ilml-plugin-linkedin 1.20.11 → 1.20.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/run.mjs CHANGED
@@ -1,13 +1,13 @@
1
- var xi=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var oe=(e,t)=>{for(var o in t)xi(e,o,{get:t[o],enumerable:!0})};import z from"fs";import pe from"path";function so(){let e=process.env.ILML_SCOPE_DIR;return e?pe.join(e,"plugins-state","linkedin","cookies.json"):Ei}function Ci(){let e=so(),t=pe.dirname(e);return t&&t!=="."&&!z.existsSync(t)&&z.mkdirSync(t,{recursive:!0}),e}function hn(e){let t=Ci();return z.writeFileSync(t,JSON.stringify(e)),t}function At(){let e=so();if(!z.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=z.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}function yn(){return z.existsSync(so())}function Ai(){let e=process.env.ILML_SCOPE_DIR;return e?pe.join(e,"plugins-state","linkedin"):"."}function gn(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function _i(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?gn(t[1]):"default"}function bn(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return z.existsSync(t)||z.mkdirSync(t,{recursive:!0}),pe.resolve(t);let o=gn(e||_i()),r=pe.join(Ai(),"chrome-profile",o);return z.existsSync(r)||z.mkdirSync(r,{recursive:!0}),pe.resolve(r)}function Sn(e){return!z.existsSync(pe.join(e,wn))}function kn(e){try{z.writeFileSync(pe.join(e,wn),new Date().toISOString())}catch{}}function vn(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{z.rmSync(pe.join(e,o),{force:!0}),t++}catch{}return t}var Ei,wn,_t=de(()=>{Ei="cookies.json";wn=".ilml-seeded"});async function w(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}async function lo(e,t,{timeout:o=45e3,poll:r=1e3,label:n="page"}={}){let i=Date.now();for(;Date.now()-i<o;){try{if(await e.evaluate(a=>!!document.querySelector(a),t)){let a=Date.now()-i;return a>6e3&&console.log(` (waited ${Math.round(a/1e3)}s for LinkedIn to finish loading ${n})`),!0}}catch{}await new Promise(s=>setTimeout(s,r))}return!1}function $t(e){return xn.test(e||"")}async function ao(e,{credentialWaitMs:t=36e4,label:o="page"}={}){console.log(` \u26A0 Auth wall on ${o} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let r=!!(process.stdin&&process.stdin.isTTY),n=r?t:Math.min(t,45e3),i=Date.now(),s=!1;for(;Date.now()-i<n;){let l="wait";try{l=await e.evaluate(c=>!new RegExp(c).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",xn.source)}catch{}if(l==="in"){try{let c=await e.cookies();if(Array.isArray(c)&&c.some(f=>f.name==="li_at")){let f=hn(c);console.log(` \u2713 Session recovered \u2014 re-saved ${c.length} cookies (${f}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(c){console.log(` \u2713 Session recovered (cookie re-save skipped: ${c.message}).`)}return!0}if(l==="creds"){if(!r){let c=new Error(`Session expired (${o}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}s||(s=!0,console.log(`
1
+ var Ti=Object.defineProperty;var oe=(e,t)=>()=>(e&&(t=e(e=0)),t);var ne=(e,t)=>{for(var o in t)Ti(e,o,{get:t[o],enumerable:!0})};import z from"fs";import pe from"path";function uo(){let e=process.env.ILML_SCOPE_DIR;return e?pe.join(e,"plugins-state","linkedin","cookies.json"):Ri}function Ii(){let e=uo(),t=pe.dirname(e);return t&&t!=="."&&!z.existsSync(t)&&z.mkdirSync(t,{recursive:!0}),e}function yn(e){let t=Ii();return z.writeFileSync(t,JSON.stringify(e)),t}function Rt(){let e=uo();if(!z.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=z.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}function gn(){return z.existsSync(uo())}function Di(){let e=process.env.ILML_SCOPE_DIR;return e?pe.join(e,"plugins-state","linkedin"):"."}function bn(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function ji(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?bn(t[1]):"default"}function wn(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return z.existsSync(t)||z.mkdirSync(t,{recursive:!0}),pe.resolve(t);let o=bn(e||ji()),r=pe.join(Di(),"chrome-profile",o);return z.existsSync(r)||z.mkdirSync(r,{recursive:!0}),pe.resolve(r)}function kn(e){return!z.existsSync(pe.join(e,Sn))}function vn(e){try{z.writeFileSync(pe.join(e,Sn),new Date().toISOString())}catch{}}function xn(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{z.rmSync(pe.join(e,o),{force:!0}),t++}catch{}return t}var Ri,Sn,It=oe(()=>{Ri="cookies.json";Sn=".ilml-seeded"});async function k(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}async function fo(e,t,{timeout:o=45e3,poll:r=1e3,label:n="page"}={}){let i=Date.now();for(;Date.now()-i<o;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-i;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${n})`),!0}}catch{}await new Promise(s=>setTimeout(s,r))}return!1}function lt(e){return An.test(e||"")}async function at(e,{credentialWaitMs:t=36e4,label:o="page"}={}){console.log(` \u26A0 Auth wall on ${o} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let r=!!(process.stdin&&process.stdin.isTTY),n=r?t:Math.min(t,45e3),i=Date.now(),s=!1;for(;Date.now()-i<n;){let l="wait";try{l=await e.evaluate(a=>!new RegExp(a).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",An.source)}catch{}if(l==="in"){try{let a=await e.cookies();if(Array.isArray(a)&&a.some(d=>d.name==="li_at")){let d=yn(a);console.log(` \u2713 Session recovered \u2014 re-saved ${a.length} cookies (${d}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(a){console.log(` \u2713 Session recovered (cookie re-save skipped: ${a.message}).`)}return!0}if(l==="creds"){if(!r){let a=new Error(`Session expired (${o}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw a.code="SESSION_EXPIRED",a}s||(s=!0,console.log(`
2
2
  \u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
3
- `))}await new Promise(c=>setTimeout(c,2500))}let a=new Error(`Session expired (${o}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw a.code="SESSION_EXPIRED",a}async function Ue(e,{readySelector:t,label:o="page",timeout:r=45e3}={}){let n=await lo(e,t,{timeout:r,label:o});if(!n&&$t(e.url())){let i=new Error(`Session expired (${o}) \u2014 redirected to login. Run: ilml linkedin login`);throw i.code="SESSION_EXPIRED",i}return n}async function co(e,t,{readySelector:o,label:r="page",timeout:n=45e3,gotoTimeout:i=6e4,autoRecover:s=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:i});try{return await Ue(e,{readySelector:o,label:r,timeout:n})}catch(a){if(s&&a.code==="SESSION_EXPIRED"){await ao(e,{label:r});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:i})}catch{}return await Ue(e,{readySelector:o,label:r,timeout:n})}throw a}}function En(e){return parseInt(e,10)||0}async function ne(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let n=r.innerText||"",i=n.includes("Premium")||n.includes("premium")||n.includes("Upgrade")||n.includes("upgrade"),s=n.includes("Try for")||n.includes("free trial")||n.includes("/month")||n.includes("per month")||n.includes("Start my")||n.includes("Subscribe"),a=n.includes("Get hired faster")||n.includes("Get hired 2x");if(i||s||a){let l=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:n.substring(0,80)};let c=r.querySelectorAll("button");for(let u of c){let f=u.innerText?.trim().toLowerCase()||"",d=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return u.click(),{dismissed:!0,matched:n.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var xn,Be=de(()=>{_t();xn=/\/authwall|\/login|\/checkpoint|\/uas\/login/});var Tn={};oe(Tn,{default:()=>Ni,getAllUnprocessedProfiles:()=>Dt,getSummary:()=>Ve,getUnprocessedProfiles:()=>It,listFiles:()=>$n,loadProfiles:()=>Rt,markProfileProcessed:()=>_n,saveProfile:()=>at,saveProfiles:()=>An});import"dotenv/config";import*as H from"fs";import*as re from"path";import{fileURLToPath as Ii}from"url";function lt(){H.existsSync(me)||H.mkdirSync(me,{recursive:!0})}function Li(e,t){try{let o=`${e}-${fo()}.json`,r=H.readdirSync(me).filter(i=>i.startsWith(e)&&i.endsWith(".json")&&i!==o),n=0;for(let i of r)JSON.parse(H.readFileSync(re.join(me,i),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function fo(){return new Date().toISOString().split("T")[0]}function po(e,t=null){let o=t||fo();return re.join(me,`${e}-${o}.json`)}function Rt(e,t=null){lt();let o=po(e,t);try{if(H.existsSync(o)){let r=H.readFileSync(o,"utf-8"),n=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${n.profiles.length} profiles from ${o}`),n.profiles}}catch(r){console.error(`Error loading profiles from ${o}:`,r.message)}return[]}function at(e,t){lt();let o=po(e),r={source:e,date:fo(),lastUpdated:new Date().toISOString(),profiles:[]};try{H.existsSync(o)&&(r=JSON.parse(H.readFileSync(o,"utf-8")))}catch(s){console.error(`Error reading ${o}:`,s.message)}if(r.profiles.some(s=>s.profileUrl===t.profileUrl))return!1;let i=Li(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:i}),r.lastUpdated=new Date().toISOString();try{H.writeFileSync(o,JSON.stringify(r,null,2));let s=i>0?` (seen ${i} day${i>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${s} (total: ${r.profiles.length})`),!0}catch(s){return console.error(`Error saving to ${o}:`,s.message),!1}}function An(e,t){let o=0;for(let r of t)at(e,r)&&o++;return o}function It(e,t=null){return Rt(e,t).filter(r=>!r.processed)}function _n(e,t,o,r=null){lt();let n=po(e,r);try{if(!H.existsSync(n))return;let i=JSON.parse(H.readFileSync(n,"utf-8")),s=i.profiles.find(a=>a.profileUrl===t);if(s){if(s.processed=!0,s.processedAt=new Date().toISOString(),typeof o=="string")s.status=o;else if(typeof o=="object"){if(s.status=o.status,o.profileInfo){let a=o.profileInfo;a.name&&(s.name=a.name),a.title&&(s.title=a.title),a.location&&(s.location=a.location),a.company&&(s.company=a.company),a.connectionDegree&&(s.connectionDegree=a.connectionDegree),a.connectionsCount&&(s.connectionsCount=a.connectionsCount),a.mutualConnections&&(s.mutualConnections=a.mutualConnections),a.photoUrl&&(s.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(s.hasVerifiedBadge=a.hasVerifiedBadge)}s.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}i.lastUpdated=new Date().toISOString(),H.writeFileSync(n,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function Ve(e){let t=Rt(e),o=t.filter(n=>n.processed),r=t.filter(n=>!n.processed);return{total:t.length,processed:o.length,unprocessed:r.length,statuses:o.reduce((n,i)=>(n[i.status]=(n[i.status]||0)+1,n),{})}}function $n(){lt();try{return H.readdirSync(me).filter(t=>t.endsWith(".json")).map(t=>{let[o,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let n=JSON.parse(H.readFileSync(re.join(me,t),"utf-8"));return{file:t,source:o,date:r,count:n.profiles?.length||0,unprocessed:n.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:o,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function Dt(e){lt();let t=[];try{let n=H.readdirSync(me).filter(i=>i.startsWith(e+"-")&&i.endsWith(".json")).sort().reverse();for(let i of n)try{let s=JSON.parse(H.readFileSync(re.join(me,i),"utf-8"));s.profiles&&t.push({file:i,date:s.date,profiles:s.profiles})}catch{}}catch{return[]}let o=new Set,r=[];for(let{date:n,profiles:i}of t)for(let s of i)!s.processed&&s.profileUrl&&!o.has(s.profileUrl)&&(o.add(s.profileUrl),r.push({...s,_fromDate:n}));return r}var Di,ji,me,Ni,mo=de(()=>{Di=Ii(import.meta.url),ji=re.dirname(re.dirname(Di)),me=process.env.DATA_DIR?re.resolve(process.env.DATA_DIR,"collected-profiles"):re.join(ji,"collected-profiles");Ni={loadProfiles:Rt,saveProfile:at,saveProfiles:An,getUnprocessedProfiles:It,getAllUnprocessedProfiles:Dt,markProfileProcessed:_n,getSummary:Ve,listFiles:$n}});import{getPluginConfig as Pi}from"@ilivemylife/graph-sdk";var Fi,Se,he,ho,yo,go=de(async()=>{Fi=await Pi();for(let[e,t]of Object.entries(Fi))process.env[e]===void 0&&(process.env[e]=t);Se=process.env.LINKEDIN_NAME,he=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ho=Object.freeze(new Set([he.DRAFT,he.CONFIRMED,he.NEEDS_REVIEW])),yo=Object.freeze(new Set([he.DRAFT,he.CONFIRMED,he.REJECTED,he.NEEDS_REVIEW]))});var Yn={};oe(Yn,{addEncounter:()=>ze,addProfileAlias:()=>Mt,atomicWriteJSON:()=>ge,canSendConnection:()=>dt,commitDataSnapshot:()=>Wn,default:()=>Ki,getAllApplications:()=>Vn,getPersonStatus:()=>Ot,getQuestionStats:()=>Gn,getQuotaStatus:()=>ft,getRecentConnections:()=>Jt,linkPersonToJob:()=>Ft,loadApplicationQuestions:()=>Co,loadConversations:()=>qn,loadJobs:()=>Lt,loadPeople:()=>X,loadProfileHistory:()=>On,loadQuota:()=>Ut,loadSyncState:()=>Bn,logApplicationQuestions:()=>Qe,migrateFromDailyFiles:()=>Un,profileSlug:()=>ke,recordConnectionSent:()=>Bt,resetCaches:()=>xo,resolveCanonicalKey:()=>ve,safeLoadJSON:()=>Le,saveConversations:()=>Mn,saveJobs:()=>Nt,savePeople:()=>Ee,saveQuota:()=>Eo,saveSyncState:()=>Jn,updateConnectionStatus:()=>qt,upsertJob:()=>Pt,upsertPerson:()=>xe});import"dotenv/config";import*as q from"fs";import*as V from"path";import{fileURLToPath as Oi}from"url";import{execSync as bo}from"child_process";function xo(){Ge=null,We=null,ye=null,je=null,Ye=null,De=null}function ee(){q.existsSync(Q)||q.mkdirSync(Q,{recursive:!0})}function ge(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";q.writeFileSync(r,o);for(let n=0;n<3;n++)try{q.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Le(e,t){if(!q.existsSync(e))return null;try{let o=JSON.parse(q.readFileSync(e,"utf-8"));try{q.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${V.resolve(e)}`);let r=e+".backup";if(q.existsSync(r))try{let n=JSON.parse(q.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{q.copyFileSync(r,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{q.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ke(){return new Date().toISOString().split("T")[0]}function ke(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Rn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function ve(e,t,o=null){if(!t||e[t])return t;let r=ke(t);if(!r)return t;let n=null;for(let[i,s]of Object.entries(e)){if(ke(s.profileUrl||i)===r)return i;!n&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}if(n){let i=Rn(o),s=Rn(e[n].name);if(i&&s&&i===s)return n}return t}function Bi(){q.existsSync(vo)||q.mkdirSync(vo,{recursive:!0})}function Fn(e){let t=ke(e);return t?V.join(vo,`${t}.json`):null}function On(e){let t=Fn(e);return t?Le(t,`profile-history/${ke(e)}.json`)||[]:[]}function Ji(e,t){let o=Fn(e);if(!o)return;Bi();let r=On(e);r.unshift(t);try{ge(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${ke(e)}: ${n.message}`)}}function In(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Dn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Hi(e,t){if(!e)return[];let o=[];for(let r of Ui){let n=e[r],i=t[r];In(n)||In(i)||Dn(n)!==Dn(i)&&o.push(r)}return o}function Vi(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[r,n]of Object.entries(e))t.has(r)||(o[r]=n);return o}function X(){return Ge||(ee(),Ge=Le(wo,"people.json")||{},Ge)}function Ee(e){ee(),Ge=e;try{ge(wo,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${V.resolve(wo)}`)}}function Lt(){return We||(ee(),We=Le(So,"jobs.json")||{},We)}function Nt(e){ee(),We=e;try{ge(So,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${V.resolve(So)}`)}}function qn(){return je||(ee(),je=Le(jt,"conversations.json")||{},Gi(je),je)}function Gi(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let n=(o.messages||[]).find(i=>i.status==="draft");n&&o.draftStatus&&o.draftStatus!=="pending"&&(n.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{ge(jt,e)}catch{}}}function Mn(e){ee(),je=e;try{ge(jt,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${V.resolve(jt)}`)}}function xe(e,t={}){if(!e)return null;let o=X(),r=Ke(),n=new Date().toISOString(),i=ve(o,e,t.name),s=o[i];if(s){let a=Hi(s,t);a.length>0&&(Ji(i,{capturedAt:n,previousLastUpdated:s.lastUpdated||null,changedFields:a,snapshot:Vi(s)}),s.lastSnapshotAt=n),s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=n,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let l of Pn)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(s[l])&&s[l].length>0)continue;s[l]=t[l]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=n)}else o[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:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return Ee(o),o[i]}function Pt(e,t={}){if(!e)return null;let o=Lt(),r=Ke(),n=o[e];if(n){let i=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let s of i)t[s]!=null&&(n[s]=t[s])}else o[e]={title:t.title||null,company:t.company||null,location:t.location||null,salary:t.salary||null,url:t.url||null,applied:t.applied||!1,appliedDate:t.appliedDate||r,recruiterUrl:t.recruiterUrl||null,firstSeen:r};return Nt(o),o[e]}function Ft(e,t){if(!e||!t)return;let o=X(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),Ee(o)))}function ze(e,t){if(!e||!t)return;let o=X(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let i={date:Ke(),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),!r.encounters.some(a=>a.date===i.date&&a.source===i.source&&a.action===i.action&&(a.jobId||"")===(i.jobId||""))&&(r.encounters.push(i),r.lastUpdated=new Date().toISOString(),Ee(o))}function Ot(e){return e&&X()[e]?.connectionStatus||null}function qt(e,t,o={}){if(!e)return;if(o.profileInfo)xe(e,o.profileInfo);else{let a=X(),l=ve(a,e,o.profileInfo?.name);a[l]||xe(e,{})}let r=X(),n=ve(r,e,o.profileInfo?.name),i=r[n];if(!i)return;let s=Ke();i.connectionStatus=t,t==="connected"?i.connectionDate=s:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=s)),i.connectionMethod=o.method||i.connectionMethod,i.messageSent=o.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),Ee(r)}function Mt(e,t,o={}){if(o.dryRun||!e||!t)return;let r=ke(t);if(!r)return;let n=X(),i=ve(n,e),s=n[i];if(!s)return;let a=ke(s.profileUrl||i);r!==a&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(r)||(s.aliases.push(r),s.lastUpdated=new Date().toISOString(),Ee(n)))}function Ut(){return ye||(ee(),ye=Le(jn,"quota.json"),(!ye||!ye.connections)&&(ye={connections:[]}),ye)}function Eo(e){ee(),ye=e;try{ge(jn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Bt(e,t="unknown"){let o=Ut(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),Eo(o)}function Jt(){let e=Ut(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function dt(){let e=Jt(),t=Ke(),o=e.filter(l=>l.date===t).length,r=e.length,n=o>=ct,i=r>=ut,s=!n&&!i,a={allowed:s,daily:{sent:o,max:ct},weekly:{sent:r,max:ut}};return s||(a.reason=n?`Daily limit reached (${o}/${ct})`:`Weekly limit reached (${r}/${ut})`),a}function ft(){let e=Jt(),t=Ke(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:ct,remaining:ct-o},weekly:{sent:r,max:ut,remaining:ut-r}}}function Wi(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function Un(){ee();let e=q.readdirSync(Q).filter(i=>i.endsWith(".json")&&i!=="people.json"&&i!=="jobs.json"&&i!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
3
+ `))}await new Promise(a=>setTimeout(a,2500))}let c=new Error(`Session expired (${o}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}async function st(e,{readySelector:t,label:o="page",timeout:r=45e3}={}){let n=await fo(e,t,{timeout:r,label:o});if(!n&&lt(e.url())){let i=new Error(`Session expired (${o}) \u2014 redirected to login. Run: ilml linkedin login`);throw i.code="SESSION_EXPIRED",i}return n}async function Be(e,t,{readySelector:o,label:r="page",timeout:n=45e3,gotoTimeout:i=6e4,autoRecover:s=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:i});try{return await st(e,{readySelector:o,label:r,timeout:n})}catch(c){if(s&&c.code==="SESSION_EXPIRED"){await at(e,{label:r});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:i})}catch{}return await st(e,{readySelector:o,label:r,timeout:n})}throw c}}function En(e){return parseInt(e,10)||0}async function re(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let n=r.innerText||"",i=n.includes("Premium")||n.includes("premium")||n.includes("Upgrade")||n.includes("upgrade"),s=n.includes("Try for")||n.includes("free trial")||n.includes("/month")||n.includes("per month")||n.includes("Start my")||n.includes("Subscribe"),c=n.includes("Get hired faster")||n.includes("Get hired 2x");if(i||s||c){let l=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:n.substring(0,80)};let a=r.querySelectorAll("button");for(let u of a){let d=u.innerText?.trim().toLowerCase()||"",f=u.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return u.click(),{dismissed:!0,matched:n.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var An,Je=oe(()=>{It();An=/\/authwall|\/login|\/checkpoint|\/uas\/login/});var In={};ne(In,{default:()=>Ui,getAllUnprocessedProfiles:()=>qt,getSummary:()=>Ge,getUnprocessedProfiles:()=>Nt,listFiles:()=>Rn,loadProfiles:()=>Lt,markProfileProcessed:()=>Tn,saveProfile:()=>dt,saveProfiles:()=>_n});import"dotenv/config";import*as Y from"fs";import*as ie from"path";import{fileURLToPath as Pi}from"url";function ut(){Y.existsSync(me)||Y.mkdirSync(me,{recursive:!0})}function Mi(e,t){try{let o=`${e}-${po()}.json`,r=Y.readdirSync(me).filter(i=>i.startsWith(e)&&i.endsWith(".json")&&i!==o),n=0;for(let i of r)JSON.parse(Y.readFileSync(ie.join(me,i),"utf-8")).profiles?.some(c=>c.profileUrl===t)&&n++;return n}catch{return 0}}function po(){return new Date().toISOString().split("T")[0]}function mo(e,t=null){let o=t||po();return ie.join(me,`${e}-${o}.json`)}function Lt(e,t=null){ut();let o=mo(e,t);try{if(Y.existsSync(o)){let r=Y.readFileSync(o,"utf-8"),n=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${n.profiles.length} profiles from ${o}`),n.profiles}}catch(r){console.error(`Error loading profiles from ${o}:`,r.message)}return[]}function dt(e,t){ut();let o=mo(e),r={source:e,date:po(),lastUpdated:new Date().toISOString(),profiles:[]};try{Y.existsSync(o)&&(r=JSON.parse(Y.readFileSync(o,"utf-8")))}catch(s){console.error(`Error reading ${o}:`,s.message)}if(r.profiles.some(s=>s.profileUrl===t.profileUrl))return!1;let i=Mi(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:i}),r.lastUpdated=new Date().toISOString();try{Y.writeFileSync(o,JSON.stringify(r,null,2));let s=i>0?` (seen ${i} day${i>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${s} (total: ${r.profiles.length})`),!0}catch(s){return console.error(`Error saving to ${o}:`,s.message),!1}}function _n(e,t){let o=0;for(let r of t)dt(e,r)&&o++;return o}function Nt(e,t=null){return Lt(e,t).filter(r=>!r.processed)}function Tn(e,t,o,r=null){ut();let n=mo(e,r);try{if(!Y.existsSync(n))return;let i=JSON.parse(Y.readFileSync(n,"utf-8")),s=i.profiles.find(c=>c.profileUrl===t);if(s){if(s.processed=!0,s.processedAt=new Date().toISOString(),typeof o=="string")s.status=o;else if(typeof o=="object"){if(s.status=o.status,o.profileInfo){let c=o.profileInfo;c.name&&(s.name=c.name),c.title&&(s.title=c.title),c.location&&(s.location=c.location),c.company&&(s.company=c.company),c.connectionDegree&&(s.connectionDegree=c.connectionDegree),c.connectionsCount&&(s.connectionsCount=c.connectionsCount),c.mutualConnections&&(s.mutualConnections=c.mutualConnections),c.photoUrl&&(s.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(s.hasVerifiedBadge=c.hasVerifiedBadge)}s.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}i.lastUpdated=new Date().toISOString(),Y.writeFileSync(n,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function Ge(e){let t=Lt(e),o=t.filter(n=>n.processed),r=t.filter(n=>!n.processed);return{total:t.length,processed:o.length,unprocessed:r.length,statuses:o.reduce((n,i)=>(n[i.status]=(n[i.status]||0)+1,n),{})}}function Rn(){ut();try{return Y.readdirSync(me).filter(t=>t.endsWith(".json")).map(t=>{let[o,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let n=JSON.parse(Y.readFileSync(ie.join(me,t),"utf-8"));return{file:t,source:o,date:r,count:n.profiles?.length||0,unprocessed:n.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:o,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function qt(e){ut();let t=[];try{let n=Y.readdirSync(me).filter(i=>i.startsWith(e+"-")&&i.endsWith(".json")).sort().reverse();for(let i of n)try{let s=JSON.parse(Y.readFileSync(ie.join(me,i),"utf-8"));s.profiles&&t.push({file:i,date:s.date,profiles:s.profiles})}catch{}}catch{return[]}let o=new Set,r=[];for(let{date:n,profiles:i}of t)for(let s of i)!s.processed&&s.profileUrl&&!o.has(s.profileUrl)&&(o.add(s.profileUrl),r.push({...s,_fromDate:n}));return r}var Oi,Fi,me,Ui,ho=oe(()=>{Oi=Pi(import.meta.url),Fi=ie.dirname(ie.dirname(Oi)),me=process.env.DATA_DIR?ie.resolve(process.env.DATA_DIR,"collected-profiles"):ie.join(Fi,"collected-profiles");Ui={loadProfiles:Lt,saveProfile:dt,saveProfiles:_n,getUnprocessedProfiles:Nt,getAllUnprocessedProfiles:qt,markProfileProcessed:Tn,getSummary:Ge,listFiles:Rn}});function Ji(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function jn(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let o=new URLSearchParams;o.set("keywords",t);let r=(e.JOB_SEARCH_LOCATION||"").trim();r&&o.set("location",r);let n=(e.JOB_SEARCH_GEO_ID||"").trim();n&&o.set("geoId",n);let i=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(i)&&i>0&&o.set("distance",String(i)),Dn(e.JOB_SEARCH_EASY_APPLY)&&o.set("f_AL","true"),Dn(e.JOB_SEARCH_IN_NETWORK)&&o.set("f_JIYN","true");let s=Ji(e.JOB_SEARCH_COMPANY_IDS);s.length&&o.set("f_C",s.join(","));let c=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();c&&o.set("f_TPR",Bi[c]||c),o.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let l="https://www.linkedin.com/jobs/search/?"+o.toString(),a=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return a&&(l+="&"+a),l}var Bi,Dn,Ln=oe(()=>{Bi={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},Dn=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim())});import{getPluginConfig as Hi}from"@ilivemylife/graph-sdk";var Gi,Nn,ke,he,yo,go,bo=oe(async()=>{Ln();Gi=await Hi();for(let[e,t]of Object.entries(Gi))process.env[e]===void 0&&(process.env[e]=t);Nn=jn(process.env);Nn&&(process.env.LINKEDIN_SEARCH_URL=Nn);ke=process.env.LINKEDIN_NAME,he=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),yo=Object.freeze(new Set([he.DRAFT,he.CONFIRMED,he.NEEDS_REVIEW])),go=Object.freeze(new Set([he.DRAFT,he.CONFIRMED,he.REJECTED,he.NEEDS_REVIEW]))});var er={};ne(er,{addEncounter:()=>ze,addProfileAlias:()=>Ht,atomicWriteJSON:()=>ge,canSendConnection:()=>mt,commitDataSnapshot:()=>Zn,default:()=>ns,getAllApplications:()=>Qn,getPersonStatus:()=>Bt,getQuestionStats:()=>Xn,getQuotaStatus:()=>ht,getRecentConnections:()=>Wt,linkPersonToJob:()=>Ut,loadApplicationQuestions:()=>Co,loadConversations:()=>Gn,loadJobs:()=>Ot,loadPeople:()=>X,loadProfileHistory:()=>Hn,loadQuota:()=>Gt,loadSyncState:()=>Yn,logApplicationQuestions:()=>Qe,migrateFromDailyFiles:()=>Wn,profileSlug:()=>ve,recordConnectionSent:()=>Vt,resetCaches:()=>Ao,resolveCanonicalKey:()=>xe,safeLoadJSON:()=>qe,saveConversations:()=>Vn,saveJobs:()=>Ft,savePeople:()=>Ee,saveQuota:()=>Eo,saveSyncState:()=>Kn,updateConnectionStatus:()=>Jt,upsertJob:()=>Mt,upsertPerson:()=>Ae});import"dotenv/config";import*as J from"fs";import*as K from"path";import{fileURLToPath as Vi}from"url";import{execSync as wo}from"child_process";function Ao(){Ve=null,We=null,ye=null,Ne=null,Ye=null,Le=null}function ee(){J.existsSync(Q)||J.mkdirSync(Q,{recursive:!0})}function ge(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";J.writeFileSync(r,o);for(let n=0;n<3;n++)try{J.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function qe(e,t){if(!J.existsSync(e))return null;try{let o=JSON.parse(J.readFileSync(e,"utf-8"));try{J.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${K.resolve(e)}`);let r=e+".backup";if(J.existsSync(r))try{let n=JSON.parse(J.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{J.copyFileSync(r,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{J.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ke(){return new Date().toISOString().split("T")[0]}function ve(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function qn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function xe(e,t,o=null){if(!t||e[t])return t;let r=ve(t);if(!r)return t;let n=null;for(let[i,s]of Object.entries(e)){if(ve(s.profileUrl||i)===r)return i;!n&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}if(n){let i=qn(o),s=qn(e[n].name);if(i&&s&&i===s)return n}return t}function zi(){J.existsSync(xo)||J.mkdirSync(xo,{recursive:!0})}function Jn(e){let t=ve(e);return t?K.join(xo,`${t}.json`):null}function Hn(e){let t=Jn(e);return t?qe(t,`profile-history/${ve(e)}.json`)||[]:[]}function Qi(e,t){let o=Jn(e);if(!o)return;zi();let r=Hn(e);r.unshift(t);try{ge(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${ve(e)}: ${n.message}`)}}function Pn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function On(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Xi(e,t){if(!e)return[];let o=[];for(let r of Ki){let n=e[r],i=t[r];Pn(n)||Pn(i)||On(n)!==On(i)&&o.push(r)}return o}function Zi(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[r,n]of Object.entries(e))t.has(r)||(o[r]=n);return o}function X(){return Ve||(ee(),Ve=qe(So,"people.json")||{},Ve)}function Ee(e){ee(),Ve=e;try{ge(So,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${K.resolve(So)}`)}}function Ot(){return We||(ee(),We=qe(ko,"jobs.json")||{},We)}function Ft(e){ee(),We=e;try{ge(ko,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${K.resolve(ko)}`)}}function Gn(){return Ne||(ee(),Ne=qe(Pt,"conversations.json")||{},es(Ne),Ne)}function es(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let n=(o.messages||[]).find(i=>i.status==="draft");n&&o.draftStatus&&o.draftStatus!=="pending"&&(n.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{ge(Pt,e)}catch{}}}function Vn(e){ee(),Ne=e;try{ge(Pt,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${K.resolve(Pt)}`)}}function Ae(e,t={}){if(!e)return null;let o=X(),r=Ke(),n=new Date().toISOString(),i=xe(o,e,t.name),s=o[i];if(s){let c=Xi(s,t);c.length>0&&(Qi(i,{capturedAt:n,previousLastUpdated:s.lastUpdated||null,changedFields:c,snapshot:Zi(s)}),s.lastSnapshotAt=n),s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=n,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let l of Bn)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(s[l])&&s[l].length>0)continue;s[l]=t[l]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=n)}else o[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:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return Ee(o),o[i]}function Mt(e,t={}){if(!e)return null;let o=Ot(),r=Ke(),n=o[e];if(n){let i=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let s of i)t[s]!=null&&(n[s]=t[s])}else o[e]={title:t.title||null,company:t.company||null,location:t.location||null,salary:t.salary||null,url:t.url||null,applied:t.applied||!1,appliedDate:t.appliedDate||r,recruiterUrl:t.recruiterUrl||null,firstSeen:r};return Ft(o),o[e]}function Ut(e,t){if(!e||!t)return;let o=X(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),Ee(o)))}function ze(e,t){if(!e||!t)return;let o=X(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let i={date:Ke(),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),!r.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(r.encounters.push(i),r.lastUpdated=new Date().toISOString(),Ee(o))}function Bt(e){return e&&X()[e]?.connectionStatus||null}function Jt(e,t,o={}){if(!e)return;if(o.profileInfo)Ae(e,o.profileInfo);else{let c=X(),l=xe(c,e,o.profileInfo?.name);c[l]||Ae(e,{})}let r=X(),n=xe(r,e,o.profileInfo?.name),i=r[n];if(!i)return;let s=Ke();i.connectionStatus=t,t==="connected"?i.connectionDate=s:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=s)),i.connectionMethod=o.method||i.connectionMethod,i.messageSent=o.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),Ee(r)}function Ht(e,t,o={}){if(o.dryRun||!e||!t)return;let r=ve(t);if(!r)return;let n=X(),i=xe(n,e),s=n[i];if(!s)return;let c=ve(s.profileUrl||i);r!==c&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(r)||(s.aliases.push(r),s.lastUpdated=new Date().toISOString(),Ee(n)))}function Gt(){return ye||(ee(),ye=qe(Fn,"quota.json"),(!ye||!ye.connections)&&(ye={connections:[]}),ye)}function Eo(e){ee(),ye=e;try{ge(Fn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Vt(e,t="unknown"){let o=Gt(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),Eo(o)}function Wt(){let e=Gt(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function mt(){let e=Wt(),t=Ke(),o=e.filter(l=>l.date===t).length,r=e.length,n=o>=ft,i=r>=pt,s=!n&&!i,c={allowed:s,daily:{sent:o,max:ft},weekly:{sent:r,max:pt}};return s||(c.reason=n?`Daily limit reached (${o}/${ft})`:`Weekly limit reached (${r}/${pt})`),c}function ht(){let e=Wt(),t=Ke(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:ft,remaining:ft-o},weekly:{sent:r,max:pt,remaining:pt-r}}}function ts(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function Wn(){ee();let e=J.readdirSync(Q).filter(i=>i.endsWith(".json")&&i!=="people.json"&&i!=="jobs.json"&&i!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
4
4
  Migrating from ${e.length} daily files...
5
- `);let t=X(),o=Lt(),r=0,n=0;e.sort();for(let i of e){let s=V.join(Q,i),a;try{a=JSON.parse(q.readFileSync(s,"utf-8"))}catch(u){console.log(` Skipping ${i}: ${u.message}`);continue}let l=a.date||i.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,c=a.source||i.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!a.profiles||!Array.isArray(a.profiles)){console.log(` Skipping ${i}: no profiles array`);continue}console.log(` ${i}: ${a.profiles.length} profiles`);for(let u of a.profiles){let f=u.profileUrl;if(!f)continue;let d=t[f];if(d){d.seenCount=(d.seenCount||1)+1,l&&(!d.lastSeen||l>d.lastSeen)&&(d.lastSeen=l),l&&(!d.firstSeen||l<d.firstSeen)&&(d.firstSeen=l),c&&!d.sources?.includes(c)&&(d.sources=d.sources||[],d.sources.push(c));for(let p of Pn)u[p]!=null&&(d[p]=u[p]);u.status&&u.processed&&(d.connectionStatus=u.status,d.connectionDate=l,u.funnelResult&&(d.connectionMethod=u.funnelResult.method||d.connectionMethod,d.messageSent=u.funnelResult.message||d.messageSent)),d.lastUpdated=new Date().toISOString()}else t[f]={name:u.name||null,title:u.title||null,location:u.location||null,company:u.company||null,connectionDegree:u.connectionDegree||null,connectionsCount:u.connectionsCount||null,mutualConnections:u.mutualConnections||null,photoUrl:u.photoUrl||null,hasVerifiedBadge:u.hasVerifiedBadge||!1,firstSeen:l,lastSeen:l,seenCount:1,sources:c?[c]:[],connectionStatus:u.processed&&u.status||null,connectionDate:u.processed?l:null,connectionMethod:u.funnelResult?.method||null,messageSent:u.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(u.fromJob?.url){let p=Wi(u.fromJob.url);p&&(t[f].jobIds||(t[f].jobIds=[]),t[f].jobIds.includes(p)||t[f].jobIds.push(p),o[p]?o[p].recruiterUrl||(o[p].recruiterUrl=f):(o[p]={title:u.fromJob.title||null,company:u.fromJob.company||null,location:null,salary:null,url:u.fromJob.url,applied:!0,appliedDate:l,recruiterUrl:f,firstSeen:l},n++))}}}return Ee(t),Nt(o),console.log(`
6
- Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(o).length} total (${n} new)`),{people:Object.keys(t).length,jobs:Object.keys(o).length}}function Bn(){return Ye||(ee(),Ye=Le(Ln,"sync-state.json")||{},Ye)}function Jn(e){ee(),Ye=e;try{ge(Ln,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Co(){if(De)return De;ee();try{q.existsSync(ko)&&(De=JSON.parse(q.readFileSync(ko,"utf-8")))}catch{}return De||(De={}),De}function Hn(e){return Array.isArray(e.applications)}function Vn(){let e=Co();if(Hn(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function Qe(e){if(!e||!e.questions||e.questions.length===0)return;let t=Co(),o=e.jobId||"unknown",n={applicationId:`${o}_${Date.now()}`,date:new Date().toISOString(),result:e.result||"submitted",formPages:e.formPages||null,duration:e.duration||null,retries:e.retries||0,failedField:e.failedField||null,questionCount:e.questions.length,questions:e.questions.map(i=>{let s={type:i.type||"input",question:i.labelText||i.question||"",answer:i.answer||""};return i.options&&(i.options.length<=Yi?s.options=i.options:s.optionsOmitted=!0),i.page&&(s.page=i.page),i.wasPreFilled&&(s.wasPreFilled=!0),i.wasRetry&&(s.wasRetry=!0),typeof i.isRequired=="boolean"&&(s.isRequired=i.isRequired),i.wasOptional&&(s.wasOptional=!0),s})};Hn(t)?(n.jobId=o,n.jobTitle=e.jobTitle||null,n.jobCompany=e.jobCompany||null,n.jobUrl=e.jobUrl||null,t.applications.push(n)):(t[o]||(t[o]={applications:[]}),t[o].applications.push(n));try{ge(ko,t)}catch(i){console.error(`[!] Failed to save application-questions.json: ${i.message}`)}}function Gn(){let e=Vn(),t=new Map;for(let i of e)for(let s of i.questions||[]){let a=s.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:s.question,count:0,answers:new Map});let l=t.get(a);l.count++;let c=(s.answer||"").trim();l.answers.set(c,(l.answers.get(c)||0)+1)}let o=[...t.values()].sort((i,s)=>s.count-i.count),r=o.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((s,a)=>a[1]-s[1])[0]?.[0]||""})),n=o.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((s,a)=>a[1]-s[1]).map(([s,a])=>`${s} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:n}}function Wn(e){if(q.existsSync(V.join(Q,".git")))try{let t={cwd:Q,stdio:"pipe",timeout:1e4};bo("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{bo("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');bo(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var qi,Mi,Q,wo,So,jn,jt,Ln,ko,vo,Nn,ct,ut,Ge,We,ye,je,Ye,De,Pn,Ui,Yi,Ki,Xe=de(async()=>{await go();qi=Oi(import.meta.url),Mi=V.dirname(V.dirname(qi)),Q=process.env.DATA_DIR?V.resolve(process.env.DATA_DIR,"collected-profiles"):V.join(Mi,"collected-profiles"),wo=V.join(Q,"people.json"),So=V.join(Q,"jobs.json"),jn=V.join(Q,"quota.json"),jt=V.join(Q,"conversations.json"),Ln=V.join(Q,"sync-state.json"),ko=V.join(Q,"application-questions.json"),vo=V.join(Q,"profile-history"),Nn=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},ct=Nn(process.env.CONNECT_MAX_DAILY,20),ut=Nn(process.env.CONNECT_MAX_WEEKLY,100),Ge=null,We=null,ye=null,je=null,Ye=null,De=null;Pn=["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"],Ui=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];Yi=50;Ki={loadPeople:X,savePeople:Ee,loadJobs:Lt,saveJobs:Nt,loadConversations:qn,saveConversations:Mn,upsertPerson:xe,upsertJob:Pt,linkPersonToJob:Ft,addEncounter:ze,getPersonStatus:Ot,updateConnectionStatus:qt,addProfileAlias:Mt,resolveCanonicalKey:ve,migrateFromDailyFiles:Un,loadQuota:Ut,saveQuota:Eo,recordConnectionSent:Bt,canSendConnection:dt,getRecentConnections:Jt,getQuotaStatus:ft,loadSyncState:Bn,saveSyncState:Jn,commitDataSnapshot:Wn,logApplicationQuestions:Qe,getQuestionStats:Gn}});var Kn={};oe(Kn,{extractCertificationsFromDetails:()=>es,extractEducationFromDetails:()=>Xi,extractExperienceFromDetails:()=>zi,extractFeaturedFromDetails:()=>Qi,extractRecommendationsFromDetails:()=>ts,extractSkillsFromDetails:()=>Zi});async function zi(e,t){let o=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await Ue(e,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await w(1e3);for(let n=0;n<5;n++)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 i of document.querySelectorAll("button"))if(/^Load more$/i.test((i.textContent||"").trim()))return i.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 n=document.querySelector("main");if(!n)return[];function i(c){let u=[];for(let f of c.querySelectorAll("div")){let d=Array.from(f.children).filter(m=>m.tagName==="DIV");if(d.length<3)continue;let p=d.filter(m=>(m.textContent||"").trim().length>50);p.length<3||(f.textContent||"").length<500||u.push({el:f,count:p.length,totalText:(f.textContent||"").length})}return u.sort((f,d)=>d.count-f.count||f.totalText-d.totalText),u[0]?.el}let s=i(n);if(!s)return[];let a=Array.from(s.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function l(c){let u=c[0]||null,f=null,d=null;if(c[1]){let A=c[1].split("\xB7").map(T=>T.trim());f=A[0]||null,A[1]&&(d=A[1])}let p=c.findIndex(A=>/(\d{4}|present)/i.test(A)&&/(-|–|—)/i.test(A)&&A.length<80),m=null,h=null;if(p>=0){let A=c[p].split("\xB7").map(T=>T.trim());m=A[0]||null,A[1]&&(h=A[1])}let g=null,y=-1;if(p>=0&&c[p+1]){let A=c[p+1],T=/^[>*\-•]|^&gt;/.test(A),j=/https?:\/\//.test(A),K=/\d{4}/.test(A),U=/,/.test(A)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(A);!T&&!j&&!K&&A.length<100&&U&&(g=A,y=p+1)}let S=null,x=-1,b=c[c.length-1];if(b&&/and\s+\+\d+\s+skills?$/i.test(b)){x=c.length-1;let A=b.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);A&&(S={listed:A[1].split(",").map(T=>T.trim()),additional:parseInt(A[2],10)})}let C=new Set([0,1,p,y,x].filter(A=>A>=0)),R=c.filter((A,T)=>!C.has(T)),L=R.length>0?R.join(`
5
+ `);let t=X(),o=Ot(),r=0,n=0;e.sort();for(let i of e){let s=K.join(Q,i),c;try{c=JSON.parse(J.readFileSync(s,"utf-8"))}catch(u){console.log(` Skipping ${i}: ${u.message}`);continue}let l=c.date||i.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,a=c.source||i.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!c.profiles||!Array.isArray(c.profiles)){console.log(` Skipping ${i}: no profiles array`);continue}console.log(` ${i}: ${c.profiles.length} profiles`);for(let u of c.profiles){let d=u.profileUrl;if(!d)continue;let f=t[d];if(f){f.seenCount=(f.seenCount||1)+1,l&&(!f.lastSeen||l>f.lastSeen)&&(f.lastSeen=l),l&&(!f.firstSeen||l<f.firstSeen)&&(f.firstSeen=l),a&&!f.sources?.includes(a)&&(f.sources=f.sources||[],f.sources.push(a));for(let p of Bn)u[p]!=null&&(f[p]=u[p]);u.status&&u.processed&&(f.connectionStatus=u.status,f.connectionDate=l,u.funnelResult&&(f.connectionMethod=u.funnelResult.method||f.connectionMethod,f.messageSent=u.funnelResult.message||f.messageSent)),f.lastUpdated=new Date().toISOString()}else t[d]={name:u.name||null,title:u.title||null,location:u.location||null,company:u.company||null,connectionDegree:u.connectionDegree||null,connectionsCount:u.connectionsCount||null,mutualConnections:u.mutualConnections||null,photoUrl:u.photoUrl||null,hasVerifiedBadge:u.hasVerifiedBadge||!1,firstSeen:l,lastSeen:l,seenCount:1,sources:a?[a]:[],connectionStatus:u.processed&&u.status||null,connectionDate:u.processed?l:null,connectionMethod:u.funnelResult?.method||null,messageSent:u.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(u.fromJob?.url){let p=ts(u.fromJob.url);p&&(t[d].jobIds||(t[d].jobIds=[]),t[d].jobIds.includes(p)||t[d].jobIds.push(p),o[p]?o[p].recruiterUrl||(o[p].recruiterUrl=d):(o[p]={title:u.fromJob.title||null,company:u.fromJob.company||null,location:null,salary:null,url:u.fromJob.url,applied:!0,appliedDate:l,recruiterUrl:d,firstSeen:l},n++))}}}return Ee(t),Ft(o),console.log(`
6
+ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(o).length} total (${n} new)`),{people:Object.keys(t).length,jobs:Object.keys(o).length}}function Yn(){return Ye||(ee(),Ye=qe(Mn,"sync-state.json")||{},Ye)}function Kn(e){ee(),Ye=e;try{ge(Mn,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Co(){if(Le)return Le;ee();try{J.existsSync(vo)&&(Le=JSON.parse(J.readFileSync(vo,"utf-8")))}catch{}return Le||(Le={}),Le}function zn(e){return Array.isArray(e.applications)}function Qn(){let e=Co();if(zn(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function Qe(e){if(!e||!e.questions||e.questions.length===0)return;let t=Co(),o=e.jobId||"unknown",n={applicationId:`${o}_${Date.now()}`,date:new Date().toISOString(),result:e.result||"submitted",formPages:e.formPages||null,duration:e.duration||null,retries:e.retries||0,failedField:e.failedField||null,questionCount:e.questions.length,questions:e.questions.map(i=>{let s={type:i.type||"input",question:i.labelText||i.question||"",answer:i.answer||""};return i.options&&(i.options.length<=os?s.options=i.options:s.optionsOmitted=!0),i.page&&(s.page=i.page),i.wasPreFilled&&(s.wasPreFilled=!0),i.wasRetry&&(s.wasRetry=!0),typeof i.isRequired=="boolean"&&(s.isRequired=i.isRequired),i.wasOptional&&(s.wasOptional=!0),s})};zn(t)?(n.jobId=o,n.jobTitle=e.jobTitle||null,n.jobCompany=e.jobCompany||null,n.jobUrl=e.jobUrl||null,t.applications.push(n)):(t[o]||(t[o]={applications:[]}),t[o].applications.push(n));try{ge(vo,t)}catch(i){console.error(`[!] Failed to save application-questions.json: ${i.message}`)}}function Xn(){let e=Qn(),t=new Map;for(let i of e)for(let s of i.questions||[]){let c=s.question.toLowerCase().trim();if(!c)continue;t.has(c)||t.set(c,{question:s.question,count:0,answers:new Map});let l=t.get(c);l.count++;let a=(s.answer||"").trim();l.answers.set(a,(l.answers.get(a)||0)+1)}let o=[...t.values()].sort((i,s)=>s.count-i.count),r=o.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((s,c)=>c[1]-s[1])[0]?.[0]||""})),n=o.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((s,c)=>c[1]-s[1]).map(([s,c])=>`${s} (${c}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:n}}function Zn(e){if(J.existsSync(K.join(Q,".git")))try{let t={cwd:Q,stdio:"pipe",timeout:1e4};wo("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{wo("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');wo(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Wi,Yi,Q,So,ko,Fn,Pt,Mn,vo,xo,Un,ft,pt,Ve,We,ye,Ne,Ye,Le,Bn,Ki,os,ns,Xe=oe(async()=>{await bo();Wi=Vi(import.meta.url),Yi=K.dirname(K.dirname(Wi)),Q=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"collected-profiles"):K.join(Yi,"collected-profiles"),So=K.join(Q,"people.json"),ko=K.join(Q,"jobs.json"),Fn=K.join(Q,"quota.json"),Pt=K.join(Q,"conversations.json"),Mn=K.join(Q,"sync-state.json"),vo=K.join(Q,"application-questions.json"),xo=K.join(Q,"profile-history"),Un=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},ft=Un(process.env.CONNECT_MAX_DAILY,20),pt=Un(process.env.CONNECT_MAX_WEEKLY,100),Ve=null,We=null,ye=null,Ne=null,Ye=null,Le=null;Bn=["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"],Ki=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];os=50;ns={loadPeople:X,savePeople:Ee,loadJobs:Ot,saveJobs:Ft,loadConversations:Gn,saveConversations:Vn,upsertPerson:Ae,upsertJob:Mt,linkPersonToJob:Ut,addEncounter:ze,getPersonStatus:Bt,updateConnectionStatus:Jt,addProfileAlias:Ht,resolveCanonicalKey:xe,migrateFromDailyFiles:Wn,loadQuota:Gt,saveQuota:Eo,recordConnectionSent:Vt,canSendConnection:mt,getRecentConnections:Wt,getQuotaStatus:ht,loadSyncState:Yn,saveSyncState:Kn,commitDataSnapshot:Zn,logApplicationQuestions:Qe,getQuestionStats:Xn}});var tr={};ne(tr,{extractCertificationsFromDetails:()=>as,extractEducationFromDetails:()=>ss,extractExperienceFromDetails:()=>rs,extractFeaturedFromDetails:()=>is,extractRecommendationsFromDetails:()=>cs,extractSkillsFromDetails:()=>ls});async function rs(e,t){let o=t.replace(/\/+$/,"")+"/details/experience/";try{await Be(e,o,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await k(1e3);let r=e.url();if(!r.toLowerCase().includes("/details/experience/"))throw new Error(`Section /details/experience/ not available on profile (landed on ${r})`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(900);await k(1e3);let n=0;for(;n<5&&await e.evaluate(()=>{for(let s of document.querySelectorAll("button"))if(/^Load more$/i.test((s.textContent||"").trim()))return s.click(),!0;return!1});)n++,await k(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function s(u){let d=[];for(let f of u.querySelectorAll("div")){let p=Array.from(f.children).filter(h=>h.tagName==="DIV");if(p.length<3)continue;let m=p.filter(h=>(h.textContent||"").trim().length>50);m.length<3||(f.textContent||"").length<500||d.push({el:f,count:m.length,totalText:(f.textContent||"").length})}return d.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),d[0]?.el}let c=s(i);if(!c)return[];let l=Array.from(c.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function a(u){let d=u[0]||null,f=null,p=null;if(u[1]){let x=u[1].split("\xB7").map(T=>T.trim());f=x[0]||null,x[1]&&(p=x[1])}let m=u.findIndex(x=>/(\d{4}|present)/i.test(x)&&/(-|–|—)/i.test(x)&&x.length<80),h=null,g=null;if(m>=0){let x=u[m].split("\xB7").map(T=>T.trim());h=x[0]||null,x[1]&&(g=x[1])}let y=null,A=-1;if(m>=0&&u[m+1]){let x=u[m+1],T=/^[>*\-•]|^&gt;/.test(x),N=/https?:\/\//.test(x),I=/\d{4}/.test(x),C=/,/.test(x)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(x);!T&&!N&&!I&&x.length<100&&C&&(y=x,A=m+1)}let E=null,b=-1,S=u[u.length-1];if(S&&/and\s+\+\d+\s+skills?$/i.test(S)){b=u.length-1;let x=S.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);x&&(E={listed:x[1].split(",").map(T=>T.trim()),additional:parseInt(x[2],10)})}let _=new Set([0,1,m,A,b].filter(x=>x>=0)),D=u.filter((x,T)=>!_.has(T)),w=D.length>0?D.join(`
7
7
 
8
- `):null;return{title:u,company:f,employmentType:d,dates:m,duration:h,location:g,description:L,skills:S,_raw:c}}return a.map(c=>{let f=(c.innerText||"").trim().split(`
9
- `).map(d=>d.trim()).filter(d=>d&&d.length<5e3);return l(f)}).filter(c=>c.title)})}catch(r){if(/session expired|bounced to|authwall|checkpoint/i.test(r.message||""))throw r;return console.error(`extractExperienceFromDetails failed for ${t}: ${r.message?.slice(0,120)}`),[]}}async function pt(e,t,o){let r=t.replace(/\/+$/,"")+`/details/${o}/`;await e.goto(r,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let n=e.url();if(/\/(login|authwall|checkpoint)/i.test(n))throw new Error(`Session expired \u2014 bounced to ${n} when fetching /details/${o}/`);if(!n.toLowerCase().includes(`/details/${o.toLowerCase()}/`))throw new Error(`Section /details/${o}/ not available on profile (landed on ${n})`);for(let s=0;s<4;s++)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 a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)i++,await w(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function ht(e,t,o,r){try{return await r()}catch(n){let i=n.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw n;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${o} failed for ${e}: ${i.slice(0,120)}`),[])}}async function Qi(e,t){return ht(t,"featured","extractFeaturedFromDetails",async()=>(await pt(e,t,"featured"),await e.evaluate(`(() => {
10
- ${mt}
8
+ `):null;return{title:d,company:f,employmentType:p,dates:h,duration:g,location:y,description:w,skills:E,_raw:u}}return l.map(u=>{let f=(u.innerText||"").trim().split(`
9
+ `).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return a(f)}).filter(u=>u.title)})}catch(r){if(r.code==="SESSION_EXPIRED"||/^session expired/i.test(r.message||""))throw r;return console.error(`extractExperienceFromDetails failed for ${t}: ${r.message?.slice(0,120)}`),[]}}async function yt(e,t,o){let r=t.replace(/\/+$/,"")+`/details/${o}/`;await Be(e,r,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:`details/${o}`}),await k(1e3);let n=e.url();if(!n.toLowerCase().includes(`/details/${o.toLowerCase()}/`))throw new Error(`Section /details/${o}/ not available on profile (landed on ${n})`);for(let s=0;s<4;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);await k(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)i++,await k(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(600)}async function bt(e,t,o,r){try{return await r()}catch(n){let i=n.message||"";if(n.code==="SESSION_EXPIRED"||/^session expired/i.test(i))throw n;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${o} failed for ${e}: ${i.slice(0,120)}`),[])}}async function is(e,t){return bt(t,"featured","extractFeaturedFromDetails",async()=>(await yt(e,t,"featured"),await e.evaluate(`(() => {
10
+ ${gt}
11
11
 
12
12
  const main = document.querySelector('main');
13
13
  if (!main) return [];
@@ -47,8 +47,8 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
47
47
  if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
48
48
  return true;
49
49
  });
50
- })()`)))}async function Xi(e,t){return ht(t,"education","extractEducationFromDetails",async()=>(await pt(e,t,"education"),await e.evaluate(`(() => {
51
- ${mt}
50
+ })()`)))}async function ss(e,t){return bt(t,"education","extractEducationFromDetails",async()=>(await yt(e,t,"education"),await e.evaluate(`(() => {
51
+ ${gt}
52
52
 
53
53
  const main = document.querySelector('main');
54
54
  if (!main) return [];
@@ -84,8 +84,8 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
84
84
  if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
85
85
  return true;
86
86
  });
87
- })()`)))}async function Zi(e,t){return ht(t,"skills","extractSkillsFromDetails",async()=>(await pt(e,t,"skills"),await e.evaluate(`(() => {
88
- ${mt}
87
+ })()`)))}async function ls(e,t){return bt(t,"skills","extractSkillsFromDetails",async()=>(await yt(e,t,"skills"),await e.evaluate(`(() => {
88
+ ${gt}
89
89
 
90
90
  const main = document.querySelector('main');
91
91
  if (!main) return [];
@@ -116,8 +116,8 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
116
116
  skills.push({ name, endorsements, _raw: lines });
117
117
  }
118
118
  return skills;
119
- })()`)))}async function es(e,t){return ht(t,"certifications","extractCertificationsFromDetails",async()=>(await pt(e,t,"certifications"),await e.evaluate(`(() => {
120
- ${mt}
119
+ })()`)))}async function as(e,t){return bt(t,"certifications","extractCertificationsFromDetails",async()=>(await yt(e,t,"certifications"),await e.evaluate(`(() => {
120
+ ${gt}
121
121
 
122
122
  const main = document.querySelector('main');
123
123
  if (!main) return [];
@@ -141,8 +141,8 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
141
141
 
142
142
  return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
143
143
  }).filter(e => e.name);
144
- })()`)))}async function ts(e,t){return ht(t,"recommendations","extractRecommendationsFromDetails",async()=>(await pt(e,t,"recommendations"),await e.evaluate(`(() => {
145
- ${mt}
144
+ })()`)))}async function cs(e,t){return bt(t,"recommendations","extractRecommendationsFromDetails",async()=>(await yt(e,t,"recommendations"),await e.evaluate(`(() => {
145
+ ${gt}
146
146
 
147
147
  const main = document.querySelector('main');
148
148
  if (!main) return [];
@@ -177,7 +177,7 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
177
177
  if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
178
178
  return true;
179
179
  });
180
- })()`)))}var mt,zn=de(()=>{Be();mt=`
180
+ })()`)))}var gt,or=oe(()=>{Je();gt=`
181
181
  function findEntryContainer(root) {
182
182
  const candidates = [];
183
183
  for (const div of root.querySelectorAll('div')) {
@@ -240,84 +240,87 @@ function findEntryContainer(root) {
240
240
  candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
241
241
  return candidates[0]?.el;
242
242
  }
243
- `});var er={};oe(er,{BLOCK_MARKERS:()=>Qn,dedupeAndCap:()=>Zn,extractSidePanelProfiles:()=>os,normalizeFundUrl:()=>Ht,normalizeProfileUrl:()=>Ze,scanRelatedBlocks:()=>Xn});function Ze(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let o=t[1].trim();return o?`https://www.linkedin.com/in/${o}/`:null}function Ht(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function Xn(e,t){let o=t||(typeof document<"u"?document:null);if(!o)return[];let r=c=>(c||"").replace(/\s+/g," ").trim(),n=c=>{let u=String(c||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},i=c=>r(c).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),s=c=>{let u=c,f=null;for(let d=0;d<6&&u.parentElement;d++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){f||(f=u);let p=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(p))return u}return f||c.parentElement},a=[],l=Array.from(o.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let c of l){let u=r(c.textContent).toLowerCase();if(!u)continue;let f=e.find(([g])=>u.includes(g));if(!f)continue;let d=f[1],p=s(c);if(!p)continue;let m=0,h=new Set;for(let g of Array.from(p.querySelectorAll('a[href*="/in/"]'))){let y=g.href||g.getAttribute("href")||"",S=n(y);if(!S)continue;let x=g.querySelector('span[aria-hidden="true"]'),b=r(x?x.textContent:g.getAttribute("aria-label")||g.textContent),C=i(b);if(!C||h.has(S))continue;h.add(S);let R="",L=b.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(L&&(R=r(L[1])),!R){let A=g.closest("li")||g.parentElement;A&&(R=Array.from(A.querySelectorAll("p, span")).map(j=>r(j.textContent)).filter(j=>j&&j!==C&&!/^view\b/i.test(j)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(j)&&/[a-z]/i.test(j)&&j.length>2)[0]||"")}a.push({href:y,name:C,headline:R,block:d,rank:m++})}}return a}function Zn(e,t={}){let o=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,r=Ze(t.seedUrl||""),n=new Map,i={};for(let s of e||[]){let a=Ze(s.href);a&&(r&&a===r||(i[s.block]=i[s.block]||0,!(i[s.block]>=o)&&(n.has(a)||(i[s.block]++,n.set(a,{url:a,name:s.name,headline:s.headline||null,block:s.block,rank:s.rank})))))}return Array.from(n.values())}async function os(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(r=>setTimeout(r,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(r=>setTimeout(r,1200))}catch{}let o;try{o=await e.evaluate(Xn,Qn)}catch{return[]}return Zn(o,t)}var Qn,Ao=de(()=>{Qn=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"]]});var sr={};oe(sr,{getJobDecision:()=>jo,getLastVisit:()=>fs,getScoutStats:()=>ps,loadCompanies:()=>Lo,loadDiscoveredPeople:()=>kt,loadJobDecisions:()=>Do,loadScoutedJobs:()=>Ro,loadVisitLog:()=>Yt,recordCompany:()=>us,recordDiscoveredEdge:()=>as,recordDiscoveredEdges:()=>cs,recordVisit:()=>ds,resetCaches:()=>To,saveCompany:()=>Wt,saveDiscoveredPerson:()=>ss,saveScoutedJob:()=>Io,setJobDecision:()=>Fe});import"dotenv/config";import*as ie from"fs";import*as te from"path";import{fileURLToPath as ns}from"url";function Ce(){ie.existsSync(Pe)||ie.mkdirSync(Pe,{recursive:!0})}function Ae(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ie.writeFileSync(r,o);for(let n=0;n<3;n++)try{ie.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function St(e){try{if(ie.existsSync(e))return JSON.parse(ie.readFileSync(e,"utf-8"))}catch{}return null}function To(){yt=null,gt=null,bt=null,wt=null,Ne=null}function Ro(){return yt||(yt=St(tr)||{},yt)}function Io(e,t){if(!e)return;Ce();let o=Ro(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[n,i]of Object.entries(t))i!=null&&(o[e][n]=i);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{Ae(tr,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}function Do(){return gt||(gt=St(nr)||{},gt)}function Fe(e,t,o={}){if(!e||!t)return;Ce();let r=Do(),n=new Date().toISOString().slice(0,10);r[e]?(r[e].status=t,r[e].updatedAt=n,o.reason&&(r[e].reason=o.reason),o.score!=null&&(r[e].score=o.score),o.source&&(r[e].source=o.source)):r[e]={status:t,decidedAt:n,updatedAt:n,reason:o.reason||null,score:o.score??null,source:o.source||null};try{Ae(nr,r)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function jo(e){return Do()[e]||null}function kt(){return bt||(bt=St(Gt)||{},bt)}function et(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function rr(e,t){let o=Ze(t)||t;if(e[o])return o;let r=et(t);if(!r)return o;let n=null;for(let[i,s]of Object.entries(e)){if(et(s&&(s.canonicalUrl||s.profileUrl)||i)===r)return i;!n&&s&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}return n||o}function ss(e,t){if(!e)return;Ce();let o=kt(),r=new Date().toISOString().slice(0,10),n=rr(o,e),i=et(e);if(o[n]){let s=o[n];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),i&&et(s.canonicalUrl||s.profileUrl||n)!==i&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(i)||s.aliases.push(i)),s.lastSeen=r,s.seenCount=(s.seenCount||1)+1}else o[n]={canonicalUrl:n,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:r,lastSeen:r,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{Ae(Gt,o)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function ls(e,t){let o=e.kind||"similar-panel";return o==="list-post"?{edge:{kind:o,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:r=>r.kind==="list-post"&&r.postUrl===(e.postUrl||null)&&r.fund===(e.fund||null)}:o==="scout"?{edge:{kind:o,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:r=>r.kind==="scout"&&r.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:r=>r.kind!=="list-post"&&r.kind!=="scout"&&r.seedUrl===(e.seedUrl||null)&&r.block===(e.block||"unknown")}}function ir(e,t,o={},r){if(!t)return;let n=et(t);t=rr(e,t);let i=o.seedUrl?{...o,seedUrl:Ze(o.seedUrl)||o.seedUrl}:o,s=r.slice(0,10),{edge:a,match:l}=ls(i,r),c=e[t];c||(c=e[t]={canonicalUrl:t,aliases:[],name:o.name||null,headline:o.headline||null,location:o.location||null,company:o.company||null,companyUrl:o.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:a.kind,sources:[],connectionsCount:o.connectionsCount??null,selectivity:o.selectivity||"unknown",connectGate:o.connectGate||"unknown",score:null,fitScore:null,isConnected:o.isConnected||!1,graphRefs:[],note:o.note||"",whyUseful:o.whyUseful||"",extra:{},source:a.kind,role:Array.isArray(o.categories)&&o.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:s,firstSeen:s,lastSeen:s}),o.name&&(c.name=o.name),o.headline&&(!c.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(c.headline))&&(c.headline=o.headline),o.location&&(c.location=c.location||o.location),o.company&&(c.company=o.company),o.companyUrl&&(c.companyUrl=c.companyUrl||o.companyUrl),o.isConnected!=null&&(c.isConnected=o.isConnected),o.connectionsCount!=null&&(c.connectionsCount=o.connectionsCount),o.selectivity&&o.selectivity!=="unknown"&&(c.selectivity=o.selectivity),o.connectGate&&o.connectGate!=="unknown"&&(c.connectGate=o.connectGate),o.note&&!c.note&&(c.note=o.note),o.whyUseful&&!c.whyUseful&&(c.whyUseful=o.whyUseful),o.extra&&typeof o.extra=="object"&&(c.extra={...c.extra||{},...o.extra}),Array.isArray(c.sources)||(c.sources=[]);let u=c.sources.find(l);if(u?(a.rank!=null&&(u.rank==null||a.rank<u.rank)&&(u.rank=a.rank),u.at=a.at):c.sources.push(a),Array.isArray(c.categories)||(c.categories=[]),Array.isArray(c.sectors)||(c.sectors=[]),Array.isArray(c.aliases)||(c.aliases=[]),Array.isArray(c.graphRefs)||(c.graphRefs=[]),_o(c.categories,o.category),Vt(c.categories,o.categories),Vt(c.sectors,o.sectors),Vt(c.aliases,o.aliases),n&&et(c.canonicalUrl||t)!==n&&_o(c.aliases,n),Vt(c.graphRefs,o.graphRefs),Array.isArray(o.affiliations)){Array.isArray(c.affiliations)||(c.affiliations=[]);for(let f of o.affiliations)!f||!f.companyKey||c.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||c.affiliations.push(f)}c.lastSeen=s,c.seenCount=(c.seenCount||0)+1}function as(e,t={}){if(!e)return;Ce();let o=kt();ir(o,e,t,new Date().toISOString());try{Ae(Gt,o)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function cs(e){if(!Array.isArray(e)||e.length===0)return;Ce();let t=kt(),o=new Date().toISOString(),r=0;for(let n of e)!n||!n.url||(ir(t,n.url,n,o),r++);if(r)try{Ae(Gt,t)}catch(n){console.error(`[!] Failed to save discovered-people.json: ${n.message}`)}}function us(e={}){if(!e||!e.name)return;Ce();let t=e.key||Ht(e.website)||Ht(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,o=Lo(),r=new Date().toISOString().slice(0,10),n=(l,c)=>{c&&Array.isArray(l)&&!l.includes(c)&&l.push(c)},i=(l,c)=>{if(Array.isArray(c))for(let u of c)n(l,u)},s=o[t];s||(s=o[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:r,lastSeen:r}),e.name&&(s.name=e.name),e.website&&(s.website=s.website||e.website),e.linkedinUrl&&(s.linkedinUrl=s.linkedinUrl||e.linkedinUrl);for(let l of["size","check","stage","location","industries","about"])e[l]&&!s[l]&&(s[l]=e[l]);e.note&&!s.note&&(s.note=e.note),e.whyUseful&&!s.whyUseful&&(s.whyUseful=e.whyUseful),e.fitScore!=null&&(s.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(s.extra={...s.extra||{},...e.extra});for(let l of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(s[l])||(s[l]=[]),i(s[l],e[l]);Array.isArray(s.people)||(s.people=[]);let a=l=>{if(!l||!l.url)return;let c=s.people.find(u=>u.url===l.url&&(u.role||null)===(l.role||null));c?l.current!=null&&(c.current=l.current):s.people.push({url:l.url,name:l.name||null,role:l.role||null,current:l.current??null,from:l.from??null,to:l.to??null})};(e.people||[]).forEach(a),(e.partners||[]).forEach(l=>a({url:l.url,name:l.name,role:"Partner",current:!0})),Array.isArray(s.portfolio)||(s.portfolio=[]);for(let l of e.portfolio||[]){let c=l&&(l.key||l.name);c&&!s.portfolio.some(u=>(u.key||u.name)===c)&&s.portfolio.push(l)}s.lastSeen=r,s.seenCount=(s.seenCount||0)+1;try{Ae($o,o)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function Lo(){return wt||(wt=St($o)||{},wt)}function Wt(e,t){if(!e)return;Ce();let o=Lo(),r=new Date().toISOString().slice(0,10);if(o[e]){let n=o[e];t.name&&(n.name=t.name),t.about&&(n.about=t.about),t.size&&(n.size=t.size),t.industries&&(n.industries=t.industries),t.jobId&&(n.jobIds||(n.jobIds=[]),n.jobIds.includes(t.jobId)||n.jobIds.push(t.jobId)),t.recruiterUrl&&(n.recruiterUrls||(n.recruiterUrls=[]),n.recruiterUrls.includes(t.recruiterUrl)||n.recruiterUrls.push(t.recruiterUrl)),n.lastSeen=r,n.jobCount=n.jobIds?.length||0}else o[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:r,lastSeen:r,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{Ae($o,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}function Yt(){return Ne||(Ne=St(or)||{visits:[]},Array.isArray(Ne.visits)||(Ne.visits=[]),Ne)}function ds(e,t={}){if(!e)return;Ce();let o=Yt();o.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let r=Date.now()-90*24*60*60*1e3;o.visits=o.visits.filter(n=>new Date(n.date).getTime()>r);try{Ae(or,o)}catch(n){console.error(`[!] Failed to save visit-log.json: ${n.message}`)}}function fs(e){let t=Yt();for(let o=t.visits.length-1;o>=0;o--)if(t.visits[o].profileUrl===e)return t.visits[o].date;return null}function ps(){let e=Ro(),t=kt(),o=Object.values(e),r=Object.values(t),n={};for(let d of o)d.company&&(n[d.company]=(n[d.company]||0)+1);let i=Object.entries(n).sort((d,p)=>p[1]-d[1]).slice(0,5).map(([d,p])=>`${d} (${p})`),s={};for(let d of o)for(let p of d.techStack||[])s[p]=(s[p]||0)+1;let a=Object.entries(s).sort((d,p)=>p[1]-d[1]).slice(0,8).map(([d,p])=>`${d} (${p})`),l=Yt(),c=new Date().toISOString().slice(0,10),u=l.visits.filter(d=>d.date.startsWith(c)).length,f=new Set(l.visits.map(d=>d.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:r.length,topCompanies:i,topTech:a,totalVisited:f,todayVisited:u,lastScoutDate:o.length>0?o.sort((d,p)=>(p.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var rs,is,Pe,tr,Gt,or,$o,nr,yt,gt,bt,_o,Vt,wt,Ne,Kt=de(()=>{Ao();rs=ns(import.meta.url),is=te.dirname(te.dirname(rs)),Pe=process.env.DATA_DIR?te.resolve(process.env.DATA_DIR,"market-research"):te.join(is,"market-research"),tr=te.join(Pe,"scouted-jobs.json"),Gt=te.join(Pe,"discovered-people.json"),or=te.join(Pe,"visit-log.json"),$o=te.join(Pe,"companies.json"),nr=te.join(Pe,"job-decisions.json");yt=null;gt=null;bt=null;_o=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Vt=(e,t)=>{if(Array.isArray(t))for(let o of t)_o(e,o)};wt=null;Ne=null});var gr={};oe(gr,{computeEngagement:()=>Po,detectCategory:()=>cr,detectCategoryFromTitle:()=>zt,determineAction:()=>hr,determineLastMessageBy:()=>dr,determineSituation:()=>ur,enrichConversation:()=>ms,enrichPerson:()=>Ss,enrichPersonContext:()=>yr,extractAutoTags:()=>pr,generateSummary:()=>fr,normPreview:()=>No});function ms(e,t,o){if(!e)return e;let n=(e.messages||[]).filter(l=>!yo.has(l.status)),i=ys(t,e.profileUrl,o),s=dr(n,t);if(e.lastMessageBy=s,e.conversationStatus=s==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=cr(n,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=ur(n,s,t),n.length>0){let l=n[n.length-1];e.lastMessageTime=l.time}if(n.length>0&&!e.initiatedBy){let l=n[0];l.sender===Se?e.initiatedBy="us":l.sender!=="Unknown"&&l.sender!==""&&(e.initiatedBy="them")}e.engagement=Po(n,t),e.personContext=yr(i),e.summary=fr(e,t,i),e.autoTags=pr(e,t,i);let a=hr(e);return e.actionNeeded=a.action,e.actionDetail=a.detail,e.suggestedPriority=hs(e),e}function cr(e,t,o){if(!e||e.length===0)return o?.title?zt(o.title):null;let r=e.filter(n=>n.sender!==Se&&n.sender!=="Unknown"&&n.sender!=="").map(n=>n.text).join(" ");for(let[n,i]of Object.entries(ar))if(i.theirMessages){for(let s of i.theirMessages)if(s.test(r))return n}if(o?.title){let n=zt(o.title);if(n)return n}return null}function zt(e){if(!e)return null;for(let[t,o]of Object.entries(ar))if(o.title){for(let r of o.title)if(r.test(e))return t}return null}function ur(e,t,o){if(!e||e.length===0)return"no_messages";let r=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return lr.test(r.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let n=[...e].reverse().find(i=>i.sender!==Se&&i.sender!=="Unknown");return lr.test(n?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function dr(e,t){if(!e||e.length===0)return"them";let o=[...e].map(n=>({m:n,t:Date.parse(n.time)})).filter(n=>Number.isFinite(n.t)).sort((n,i)=>i.t-n.t).map(n=>n.m),r=o.length>0?o:[...e].reverse();for(let n of r){let i=n.sender;if(i===Se)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function fr(e,t,o){let r=e.messages||[];if(r.length===0)return null;let n=[],i=e.category,s=o?.title,a=o?.company,l=o?.location;i==="recruiter"&&a?n.push(`Recruiter from ${a}`):i==="hiring_manager"&&a?n.push(`Hiring manager at ${a}`):i==="founder"&&a?n.push(`Founder of ${a}`):i&&s?n.push(`${Fo(i)}: ${tt(s,40)}`):s?n.push(tt(s,50)):n.push(t.split(" ")[0]);let c=r.filter(m=>m.sender!==Se&&m.sender!=="Unknown").map(m=>m.text).join(" "),u=gs(c),f=bs(c),d=ws(c),p=[];return u&&p.push(u),d&&d!==l&&p.push(d),f&&p.push(f),p.length>0&&n.push(p.join(", ")),e.situation==="they_want_to_schedule_call"?n.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?n.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?n.push("needs reply"):e.conversationStatus==="awaiting_reply"&&n.push("waiting on them"),n.join(". ").replace(/\.\./g,".")}function pr(e,t,o){let r=[],n=(e.messages||[]).filter(c=>!yo.has(c.status)),i=n.map(c=>c.text).join(" "),s=n.filter(c=>c.sender!==Se&&c.sender!=="Unknown").map(c=>c.text).join(" "),a=mr(s,o?.location);r.push(...a),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&r.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&r.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&r.push("remote"),/\b(hybrid)\b/i.test(i)&&r.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&r.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&r.push("java"),/\b(python)\b/i.test(i)&&r.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&r.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&r.push("backend"),/\b(full.?stack)\b/i.test(i)&&r.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&r.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&r.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&r.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&r.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&r.push("has-salary");let l=e.engagement||Po(n,t);return l.messageCount>=6&&r.push("active-thread"),l.theirCount===0&&l.ourCount>0&&r.push("no-response"),l.ourCount===0&&l.theirCount>0&&r.push("unanswered"),e.situation==="they_want_to_schedule_call"&&r.push("hot-lead"),(e.messages||[]).some(c=>ho.has(c.status))&&r.push("has-draft"),[...new Set(r)]}function mr(e,t){let o=[],r=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],n=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let s of r)i.includes(s)&&o.push(s.replace(/\s+/g,"-"));for(let[s,a]of n)i.includes(s)&&o.push(a);return o}function hr(e){let{category:t,situation:o,conversationStatus:r}=e;if(e.dismissedAtPreview&&No(e.lastMessagePreview)===No(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let n=(e.messages||[]).find(i=>ho.has(i.status));return n?n.status===he.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:r==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:o==="no_messages"?{action:"none",detail:"No messages read yet."}:o==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:o==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${Fo(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:o==="active_conversation_needs_our_reply"||o==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function Po(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let o=0,r=0,n=0,i=!1,s=!1,a=e.map(l=>l.text).join(" ");for(let l of e)l.sender===Se?o++:l.sender==="Unknown"||l.sender===""?n++:r++;return i=/\b(job|role|position|opening)\b/i.test(a),s=/\$[\d,]+|\d+k|\d+\/hr/i.test(a),{messageCount:e.length,theirCount:r,ourCount:o,unknownCount:n,hasJob:i,hasSalary:s}}function yr(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function hs(e){let{category:t,situation:o,engagement:r}=e;return o==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(o==="active_conversation_needs_our_reply"||o==="needs_our_reply")?r?.messageCount>=4?"high":"medium":t==="recruiter"&&o==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function ys(e,t,o){if(!o)return null;if(t&&o[t])return o[t];if(t){let n=ve(o,t,e);if(o[n])return o[n]}if(!e)return null;let r=Object.values(o).filter(n=>n.name===e);return r.length===1?r[0]:null}function No(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Fo(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function tt(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function gs(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let o=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return o?o[1]:null}function bs(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function ws(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function Ss(e,t){if(!e)return e;if(e.categorySource!=="manual"){let r=zt(e.title);r&&(e.category=r,e.categorySource=e.categorySource||"title")}ks(e),e.personSummary=vs(e),e.personAutoTags=xs(e);let o=Es(e);return e.personActionNeeded=o.action,e.personActionDetail=o.detail,e.personPriorityManual||(e.personPriority=Cs(e)),e}function ks(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(o=>o.jobTitle).sort((o,r)=>(r.date||"").localeCompare(o.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function vs(e){let t=[],o=e.category,r=e.title,n=e.company,i=e.location;if(o==="recruiter"&&n?t.push(`Recruiter at ${n}`):o==="hiring_manager"&&n?t.push(`Hiring manager at ${n}`):o==="founder"&&n?t.push(`Founder of ${n}`):r&&n?t.push(`${tt(r,40)} at ${tt(n,30)}`):r?t.push(tt(r,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let s=new Date(e.connectionDate);if(!isNaN(s)){let a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${a[s.getMonth()]} ${s.getDate()}`)}}if(e.jobCount>0){let s=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(s+=` (last: ${tt(e.lastJobTitle,30)}`,e.lastJobDate){let a=new Date(e.lastJobDate);isNaN(a)||(s+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][a.getMonth()]} ${a.getDate()}`)}s+=")"}t.push(s)}return t.join(". ").replace(/\.\./g,".")||null}function xs(e){let t=[],o=[e.title,e.company,e.location].filter(Boolean).join(" "),r=mr("",e.location);return t.push(...r),e.category&&t.push(e.category),/\b(java)\b/i.test(o)&&!/javascript/i.test(o)&&t.push("java"),/\b(python)\b/i.test(o)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(o)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(o)&&t.push("backend"),/\b(full.?stack)\b/i.test(o)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(o)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(o)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(o)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(o)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(o)&&t.push("staffing"),[...new Set(t)]}function Es(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${Fo(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function Cs(e){let t=e.category;if(!t)return null;let o=As(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&o?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&o?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function As(e,t){if(!e.connectionDate)return!1;let o=new Date(e.connectionDate);if(isNaN(o))return!1;let r=new Date;return r.setDate(r.getDate()-t),o>=r}var ar,lr,br=de(async()=>{await go();await Xe();ar={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};lr=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var Sr={};oe(Sr,{DEFAULT_PROFILE_INTERESTS:()=>wr,computeFit:()=>Ts,detectSectors:()=>$s});function $s(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),o=[];for(let[r,n]of Object.entries(_s))n.some(i=>i.test(t))&&o.push(r);return o}function Ts(e,t=wr){if(!Array.isArray(e)||e.length===0)return 0;let o=i=>typeof i=="number"&&Number.isFinite(i)?i:0,r=Math.max(1,...Object.values(t||{}).map(o)),n=0;for(let i of e){let s=o(t&&t[i]);s>n&&(n=s)}return Math.min(1,n/r)}var _s,wr,kr=de(()=>{_s={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};wr={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});Be();import ri from"puppeteer";import*as pi from"fs";import{createGraphClient as $i,resolveToken as Ti}from"@ilivemylife/graph-sdk";import{config as Ri}from"dotenv";Ri();var Cn=Ti()||process.env.TOKEN;Cn||(console.error(`
243
+ `});var sr={};ne(sr,{BLOCK_MARKERS:()=>nr,dedupeAndCap:()=>ir,extractSidePanelProfiles:()=>us,normalizeFundUrl:()=>Yt,normalizeProfileUrl:()=>Ze,scanRelatedBlocks:()=>rr});function Ze(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let o=t[1].trim();return o?`https://www.linkedin.com/in/${o}/`:null}function Yt(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function rr(e,t){let o=t||(typeof document<"u"?document:null);if(!o)return[];let r=a=>(a||"").replace(/\s+/g," ").trim(),n=a=>{let u=String(a||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},i=a=>r(a).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),s=a=>{let u=a,d=null;for(let f=0;f<6&&u.parentElement;f++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){d||(d=u);let p=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(p))return u}return d||a.parentElement},c=[],l=Array.from(o.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let a of l){let u=r(a.textContent).toLowerCase();if(!u)continue;let d=e.find(([g])=>u.includes(g));if(!d)continue;let f=d[1],p=s(a);if(!p)continue;let m=0,h=new Set;for(let g of Array.from(p.querySelectorAll('a[href*="/in/"]'))){let y=g.href||g.getAttribute("href")||"",A=n(y);if(!A)continue;let E=g.querySelector('span[aria-hidden="true"]'),b=r(E?E.textContent:g.getAttribute("aria-label")||g.textContent),S=i(b);if(!S||h.has(A))continue;h.add(A);let _="",D=b.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(D&&(_=r(D[1])),!_){let w=g.closest("li")||g.parentElement;w&&(_=Array.from(w.querySelectorAll("p, span")).map(T=>r(T.textContent)).filter(T=>T&&T!==S&&!/^view\b/i.test(T)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(T)&&/[a-z]/i.test(T)&&T.length>2)[0]||"")}c.push({href:y,name:S,headline:_,block:f,rank:m++})}}return c}function ir(e,t={}){let o=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,r=Ze(t.seedUrl||""),n=new Map,i={};for(let s of e||[]){let c=Ze(s.href);c&&(r&&c===r||(i[s.block]=i[s.block]||0,!(i[s.block]>=o)&&(n.has(c)||(i[s.block]++,n.set(c,{url:c,name:s.name,headline:s.headline||null,block:s.block,rank:s.rank})))))}return Array.from(n.values())}async function us(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(r=>setTimeout(r,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(r=>setTimeout(r,1200))}catch{}let o;try{o=await e.evaluate(rr,nr)}catch{return[]}return ir(o,t)}var nr,$o=oe(()=>{nr=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"]]});var fr={};ne(fr,{getJobDecision:()=>At,getLastVisit:()=>Ss,getScoutStats:()=>ks,loadCompanies:()=>Lo,loadDiscoveredPeople:()=>Et,loadJobDecisions:()=>jo,loadScoutedJobs:()=>Io,loadVisitLog:()=>Xt,recordCompany:()=>bs,recordDiscoveredEdge:()=>ys,recordDiscoveredEdges:()=>gs,recordVisit:()=>ws,resetCaches:()=>Ro,saveCompany:()=>Qt,saveDiscoveredPerson:()=>ms,saveScoutedJob:()=>Do,setJobDecision:()=>_e});import"dotenv/config";import*as se from"fs";import*as te from"path";import{fileURLToPath as ds}from"url";function Ce(){se.existsSync(Oe)||se.mkdirSync(Oe,{recursive:!0})}function $e(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";se.writeFileSync(r,o);for(let n=0;n<3;n++)try{se.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function xt(e){try{if(se.existsSync(e))return JSON.parse(se.readFileSync(e,"utf-8"))}catch{}return null}function Ro(){wt=null,St=null,kt=null,vt=null,Pe=null}function Io(){return wt||(wt=xt(lr)||{},wt)}function Do(e,t){if(!e)return;Ce();let o=Io(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[n,i]of Object.entries(t))i!=null&&(o[e][n]=i);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{$e(lr,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}function jo(){return St||(St=xt(cr)||{},St)}function _e(e,t,o={}){if(!e||!t)return;Ce();let r=jo(),n=new Date().toISOString().slice(0,10);r[e]?(r[e].status=t,r[e].updatedAt=n,o.reason&&(r[e].reason=o.reason),o.score!=null&&(r[e].score=o.score),o.source&&(r[e].source=o.source)):r[e]={status:t,decidedAt:n,updatedAt:n,reason:o.reason||null,score:o.score??null,source:o.source||null};try{$e(cr,r)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function At(e){return jo()[e]||null}function Et(){return kt||(kt=xt(zt)||{},kt)}function et(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function ur(e,t){let o=Ze(t)||t;if(e[o])return o;let r=et(t);if(!r)return o;let n=null;for(let[i,s]of Object.entries(e)){if(et(s&&(s.canonicalUrl||s.profileUrl)||i)===r)return i;!n&&s&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}return n||o}function ms(e,t){if(!e)return;Ce();let o=Et(),r=new Date().toISOString().slice(0,10),n=ur(o,e),i=et(e);if(o[n]){let s=o[n];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),i&&et(s.canonicalUrl||s.profileUrl||n)!==i&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(i)||s.aliases.push(i)),s.lastSeen=r,s.seenCount=(s.seenCount||1)+1}else o[n]={canonicalUrl:n,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:r,lastSeen:r,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{$e(zt,o)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function hs(e,t){let o=e.kind||"similar-panel";return o==="list-post"?{edge:{kind:o,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:r=>r.kind==="list-post"&&r.postUrl===(e.postUrl||null)&&r.fund===(e.fund||null)}:o==="scout"?{edge:{kind:o,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:r=>r.kind==="scout"&&r.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:r=>r.kind!=="list-post"&&r.kind!=="scout"&&r.seedUrl===(e.seedUrl||null)&&r.block===(e.block||"unknown")}}function dr(e,t,o={},r){if(!t)return;let n=et(t);t=ur(e,t);let i=o.seedUrl?{...o,seedUrl:Ze(o.seedUrl)||o.seedUrl}:o,s=r.slice(0,10),{edge:c,match:l}=hs(i,r),a=e[t];a||(a=e[t]={canonicalUrl:t,aliases:[],name:o.name||null,headline:o.headline||null,location:o.location||null,company:o.company||null,companyUrl:o.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:c.kind,sources:[],connectionsCount:o.connectionsCount??null,selectivity:o.selectivity||"unknown",connectGate:o.connectGate||"unknown",score:null,fitScore:null,isConnected:o.isConnected||!1,graphRefs:[],note:o.note||"",whyUseful:o.whyUseful||"",extra:{},source:c.kind,role:Array.isArray(o.categories)&&o.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:s,firstSeen:s,lastSeen:s}),o.name&&(a.name=o.name),o.headline&&(!a.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(a.headline))&&(a.headline=o.headline),o.location&&(a.location=a.location||o.location),o.company&&(a.company=o.company),o.companyUrl&&(a.companyUrl=a.companyUrl||o.companyUrl),o.isConnected!=null&&(a.isConnected=o.isConnected),o.connectionsCount!=null&&(a.connectionsCount=o.connectionsCount),o.selectivity&&o.selectivity!=="unknown"&&(a.selectivity=o.selectivity),o.connectGate&&o.connectGate!=="unknown"&&(a.connectGate=o.connectGate),o.note&&!a.note&&(a.note=o.note),o.whyUseful&&!a.whyUseful&&(a.whyUseful=o.whyUseful),o.extra&&typeof o.extra=="object"&&(a.extra={...a.extra||{},...o.extra}),Array.isArray(a.sources)||(a.sources=[]);let u=a.sources.find(l);if(u?(c.rank!=null&&(u.rank==null||c.rank<u.rank)&&(u.rank=c.rank),u.at=c.at):a.sources.push(c),Array.isArray(a.categories)||(a.categories=[]),Array.isArray(a.sectors)||(a.sectors=[]),Array.isArray(a.aliases)||(a.aliases=[]),Array.isArray(a.graphRefs)||(a.graphRefs=[]),_o(a.categories,o.category),Kt(a.categories,o.categories),Kt(a.sectors,o.sectors),Kt(a.aliases,o.aliases),n&&et(a.canonicalUrl||t)!==n&&_o(a.aliases,n),Kt(a.graphRefs,o.graphRefs),Array.isArray(o.affiliations)){Array.isArray(a.affiliations)||(a.affiliations=[]);for(let d of o.affiliations)!d||!d.companyKey||a.affiliations.some(f=>f.companyKey===d.companyKey&&f.role===d.role)||a.affiliations.push(d)}a.lastSeen=s,a.seenCount=(a.seenCount||0)+1}function ys(e,t={}){if(!e)return;Ce();let o=Et();dr(o,e,t,new Date().toISOString());try{$e(zt,o)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function gs(e){if(!Array.isArray(e)||e.length===0)return;Ce();let t=Et(),o=new Date().toISOString(),r=0;for(let n of e)!n||!n.url||(dr(t,n.url,n,o),r++);if(r)try{$e(zt,t)}catch(n){console.error(`[!] Failed to save discovered-people.json: ${n.message}`)}}function bs(e={}){if(!e||!e.name)return;Ce();let t=e.key||Yt(e.website)||Yt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,o=Lo(),r=new Date().toISOString().slice(0,10),n=(l,a)=>{a&&Array.isArray(l)&&!l.includes(a)&&l.push(a)},i=(l,a)=>{if(Array.isArray(a))for(let u of a)n(l,u)},s=o[t];s||(s=o[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:r,lastSeen:r}),e.name&&(s.name=e.name),e.website&&(s.website=s.website||e.website),e.linkedinUrl&&(s.linkedinUrl=s.linkedinUrl||e.linkedinUrl);for(let l of["size","check","stage","location","industries","about"])e[l]&&!s[l]&&(s[l]=e[l]);e.note&&!s.note&&(s.note=e.note),e.whyUseful&&!s.whyUseful&&(s.whyUseful=e.whyUseful),e.fitScore!=null&&(s.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(s.extra={...s.extra||{},...e.extra});for(let l of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(s[l])||(s[l]=[]),i(s[l],e[l]);Array.isArray(s.people)||(s.people=[]);let c=l=>{if(!l||!l.url)return;let a=s.people.find(u=>u.url===l.url&&(u.role||null)===(l.role||null));a?l.current!=null&&(a.current=l.current):s.people.push({url:l.url,name:l.name||null,role:l.role||null,current:l.current??null,from:l.from??null,to:l.to??null})};(e.people||[]).forEach(c),(e.partners||[]).forEach(l=>c({url:l.url,name:l.name,role:"Partner",current:!0})),Array.isArray(s.portfolio)||(s.portfolio=[]);for(let l of e.portfolio||[]){let a=l&&(l.key||l.name);a&&!s.portfolio.some(u=>(u.key||u.name)===a)&&s.portfolio.push(l)}s.lastSeen=r,s.seenCount=(s.seenCount||0)+1;try{$e(To,o)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function Lo(){return vt||(vt=xt(To)||{},vt)}function Qt(e,t){if(!e)return;Ce();let o=Lo(),r=new Date().toISOString().slice(0,10);if(o[e]){let n=o[e];t.name&&(n.name=t.name),t.about&&(n.about=t.about),t.size&&(n.size=t.size),t.industries&&(n.industries=t.industries),t.jobId&&(n.jobIds||(n.jobIds=[]),n.jobIds.includes(t.jobId)||n.jobIds.push(t.jobId)),t.recruiterUrl&&(n.recruiterUrls||(n.recruiterUrls=[]),n.recruiterUrls.includes(t.recruiterUrl)||n.recruiterUrls.push(t.recruiterUrl)),n.lastSeen=r,n.jobCount=n.jobIds?.length||0}else o[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:r,lastSeen:r,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{$e(To,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}function Xt(){return Pe||(Pe=xt(ar)||{visits:[]},Array.isArray(Pe.visits)||(Pe.visits=[]),Pe)}function ws(e,t={}){if(!e)return;Ce();let o=Xt();o.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let r=Date.now()-90*24*60*60*1e3;o.visits=o.visits.filter(n=>new Date(n.date).getTime()>r);try{$e(ar,o)}catch(n){console.error(`[!] Failed to save visit-log.json: ${n.message}`)}}function Ss(e){let t=Xt();for(let o=t.visits.length-1;o>=0;o--)if(t.visits[o].profileUrl===e)return t.visits[o].date;return null}function ks(){let e=Io(),t=Et(),o=Object.values(e),r=Object.values(t),n={};for(let f of o)f.company&&(n[f.company]=(n[f.company]||0)+1);let i=Object.entries(n).sort((f,p)=>p[1]-f[1]).slice(0,5).map(([f,p])=>`${f} (${p})`),s={};for(let f of o)for(let p of f.techStack||[])s[p]=(s[p]||0)+1;let c=Object.entries(s).sort((f,p)=>p[1]-f[1]).slice(0,8).map(([f,p])=>`${f} (${p})`),l=Xt(),a=new Date().toISOString().slice(0,10),u=l.visits.filter(f=>f.date.startsWith(a)).length,d=new Set(l.visits.map(f=>f.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:r.length,topCompanies:i,topTech:c,totalVisited:d,todayVisited:u,lastScoutDate:o.length>0?o.sort((f,p)=>(p.scoutedAt||"").localeCompare(f.scoutedAt||""))[0]?.scoutedAt:null}}var fs,ps,Oe,lr,zt,ar,To,cr,wt,St,kt,_o,Kt,vt,Pe,Zt=oe(()=>{$o();fs=ds(import.meta.url),ps=te.dirname(te.dirname(fs)),Oe=process.env.DATA_DIR?te.resolve(process.env.DATA_DIR,"market-research"):te.join(ps,"market-research"),lr=te.join(Oe,"scouted-jobs.json"),zt=te.join(Oe,"discovered-people.json"),ar=te.join(Oe,"visit-log.json"),To=te.join(Oe,"companies.json"),cr=te.join(Oe,"job-decisions.json");wt=null;St=null;kt=null;_o=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Kt=(e,t)=>{if(Array.isArray(t))for(let o of t)_o(e,o)};vt=null;Pe=null});var xr={};ne(xr,{computeEngagement:()=>qo,detectCategory:()=>hr,detectCategoryFromTitle:()=>eo,determineAction:()=>kr,determineLastMessageBy:()=>gr,determineSituation:()=>yr,enrichConversation:()=>vs,enrichPerson:()=>_s,enrichPersonContext:()=>vr,extractAutoTags:()=>wr,generateSummary:()=>br,normPreview:()=>No});function vs(e,t,o){if(!e)return e;let n=(e.messages||[]).filter(l=>!go.has(l.status)),i=As(t,e.profileUrl,o),s=gr(n,t);if(e.lastMessageBy=s,e.conversationStatus=s==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=hr(n,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=yr(n,s,t),n.length>0){let l=n[n.length-1];e.lastMessageTime=l.time}if(n.length>0&&!e.initiatedBy){let l=n[0];l.sender===ke?e.initiatedBy="us":l.sender!=="Unknown"&&l.sender!==""&&(e.initiatedBy="them")}e.engagement=qo(n,t),e.personContext=vr(i),e.summary=br(e,t,i),e.autoTags=wr(e,t,i);let c=kr(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=xs(e),e}function hr(e,t,o){if(!e||e.length===0)return o?.title?eo(o.title):null;let r=e.filter(n=>n.sender!==ke&&n.sender!=="Unknown"&&n.sender!=="").map(n=>n.text).join(" ");for(let[n,i]of Object.entries(mr))if(i.theirMessages){for(let s of i.theirMessages)if(s.test(r))return n}if(o?.title){let n=eo(o.title);if(n)return n}return null}function eo(e){if(!e)return null;for(let[t,o]of Object.entries(mr))if(o.title){for(let r of o.title)if(r.test(e))return t}return null}function yr(e,t,o){if(!e||e.length===0)return"no_messages";let r=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return pr.test(r.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let n=[...e].reverse().find(i=>i.sender!==ke&&i.sender!=="Unknown");return pr.test(n?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function gr(e,t){if(!e||e.length===0)return"them";let o=[...e].map(n=>({m:n,t:Date.parse(n.time)})).filter(n=>Number.isFinite(n.t)).sort((n,i)=>i.t-n.t).map(n=>n.m),r=o.length>0?o:[...e].reverse();for(let n of r){let i=n.sender;if(i===ke)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function br(e,t,o){let r=e.messages||[];if(r.length===0)return null;let n=[],i=e.category,s=o?.title,c=o?.company,l=o?.location;i==="recruiter"&&c?n.push(`Recruiter from ${c}`):i==="hiring_manager"&&c?n.push(`Hiring manager at ${c}`):i==="founder"&&c?n.push(`Founder of ${c}`):i&&s?n.push(`${Po(i)}: ${tt(s,40)}`):s?n.push(tt(s,50)):n.push(t.split(" ")[0]);let a=r.filter(m=>m.sender!==ke&&m.sender!=="Unknown").map(m=>m.text).join(" "),u=Es(a),d=Cs(a),f=$s(a),p=[];return u&&p.push(u),f&&f!==l&&p.push(f),d&&p.push(d),p.length>0&&n.push(p.join(", ")),e.situation==="they_want_to_schedule_call"?n.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?n.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?n.push("needs reply"):e.conversationStatus==="awaiting_reply"&&n.push("waiting on them"),n.join(". ").replace(/\.\./g,".")}function wr(e,t,o){let r=[],n=(e.messages||[]).filter(a=>!go.has(a.status)),i=n.map(a=>a.text).join(" "),s=n.filter(a=>a.sender!==ke&&a.sender!=="Unknown").map(a=>a.text).join(" "),c=Sr(s,o?.location);r.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&r.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&r.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&r.push("remote"),/\b(hybrid)\b/i.test(i)&&r.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&r.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&r.push("java"),/\b(python)\b/i.test(i)&&r.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&r.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&r.push("backend"),/\b(full.?stack)\b/i.test(i)&&r.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&r.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&r.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&r.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&r.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&r.push("has-salary");let l=e.engagement||qo(n,t);return l.messageCount>=6&&r.push("active-thread"),l.theirCount===0&&l.ourCount>0&&r.push("no-response"),l.ourCount===0&&l.theirCount>0&&r.push("unanswered"),e.situation==="they_want_to_schedule_call"&&r.push("hot-lead"),(e.messages||[]).some(a=>yo.has(a.status))&&r.push("has-draft"),[...new Set(r)]}function Sr(e,t){let o=[],r=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],n=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let s of r)i.includes(s)&&o.push(s.replace(/\s+/g,"-"));for(let[s,c]of n)i.includes(s)&&o.push(c);return o}function kr(e){let{category:t,situation:o,conversationStatus:r}=e;if(e.dismissedAtPreview&&No(e.lastMessagePreview)===No(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let n=(e.messages||[]).find(i=>yo.has(i.status));return n?n.status===he.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:r==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:o==="no_messages"?{action:"none",detail:"No messages read yet."}:o==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:o==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${Po(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:o==="active_conversation_needs_our_reply"||o==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function qo(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let o=0,r=0,n=0,i=!1,s=!1,c=e.map(l=>l.text).join(" ");for(let l of e)l.sender===ke?o++:l.sender==="Unknown"||l.sender===""?n++:r++;return i=/\b(job|role|position|opening)\b/i.test(c),s=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:r,ourCount:o,unknownCount:n,hasJob:i,hasSalary:s}}function vr(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function xs(e){let{category:t,situation:o,engagement:r}=e;return o==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(o==="active_conversation_needs_our_reply"||o==="needs_our_reply")?r?.messageCount>=4?"high":"medium":t==="recruiter"&&o==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function As(e,t,o){if(!o)return null;if(t&&o[t])return o[t];if(t){let n=xe(o,t,e);if(o[n])return o[n]}if(!e)return null;let r=Object.values(o).filter(n=>n.name===e);return r.length===1?r[0]:null}function No(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Po(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function tt(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Es(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let o=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return o?o[1]:null}function Cs(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function $s(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function _s(e,t){if(!e)return e;if(e.categorySource!=="manual"){let r=eo(e.title);r&&(e.category=r,e.categorySource=e.categorySource||"title")}Ts(e),e.personSummary=Rs(e),e.personAutoTags=Is(e);let o=Ds(e);return e.personActionNeeded=o.action,e.personActionDetail=o.detail,e.personPriorityManual||(e.personPriority=js(e)),e}function Ts(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(o=>o.jobTitle).sort((o,r)=>(r.date||"").localeCompare(o.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function Rs(e){let t=[],o=e.category,r=e.title,n=e.company,i=e.location;if(o==="recruiter"&&n?t.push(`Recruiter at ${n}`):o==="hiring_manager"&&n?t.push(`Hiring manager at ${n}`):o==="founder"&&n?t.push(`Founder of ${n}`):r&&n?t.push(`${tt(r,40)} at ${tt(n,30)}`):r?t.push(tt(r,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let s=new Date(e.connectionDate);if(!isNaN(s)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[s.getMonth()]} ${s.getDate()}`)}}if(e.jobCount>0){let s=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(s+=` (last: ${tt(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(s+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}s+=")"}t.push(s)}return t.join(". ").replace(/\.\./g,".")||null}function Is(e){let t=[],o=[e.title,e.company,e.location].filter(Boolean).join(" "),r=Sr("",e.location);return t.push(...r),e.category&&t.push(e.category),/\b(java)\b/i.test(o)&&!/javascript/i.test(o)&&t.push("java"),/\b(python)\b/i.test(o)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(o)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(o)&&t.push("backend"),/\b(full.?stack)\b/i.test(o)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(o)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(o)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(o)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(o)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(o)&&t.push("staffing"),[...new Set(t)]}function Ds(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${Po(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function js(e){let t=e.category;if(!t)return null;let o=Ls(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&o?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&o?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function Ls(e,t){if(!e.connectionDate)return!1;let o=new Date(e.connectionDate);if(isNaN(o))return!1;let r=new Date;return r.setDate(r.getDate()-t),o>=r}var mr,pr,Ar=oe(async()=>{await bo();await Xe();mr={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};pr=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var Cr={};ne(Cr,{DEFAULT_PROFILE_INTERESTS:()=>Er,computeFit:()=>Ps,detectSectors:()=>qs});function qs(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),o=[];for(let[r,n]of Object.entries(Ns))n.some(i=>i.test(t))&&o.push(r);return o}function Ps(e,t=Er){if(!Array.isArray(e)||e.length===0)return 0;let o=i=>typeof i=="number"&&Number.isFinite(i)?i:0,r=Math.max(1,...Object.values(t||{}).map(o)),n=0;for(let i of e){let s=o(t&&t[i]);s>n&&(n=s)}return Math.min(1,n/r)}var Ns,Er,$r=oe(()=>{Ns={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};Er={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});Je();import ui from"puppeteer";import*as bi from"fs";import{createGraphClient as Li,resolveToken as Ni}from"@ilivemylife/graph-sdk";import{config as qi}from"dotenv";qi();var Cn=Ni()||process.env.TOKEN;Cn||(console.error(`
244
244
  [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.
245
245
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
246
246
  `),console.error(` Or add ILML_TOKEN=... to .env
247
- `),process.exit(1));var Ie=$i({token:Cn});var Je=12e4;async function He(e,{retries:t=2}={}){let o=process.env.NODE_EASY_APPLY_MAIN;if(!o||o.startsWith("YOUR_"))throw new Error('NODE_EASY_APPLY_MAIN is not configured in .env. Create a node in iLiveMyLife, add "assist" tag, and set the node ID in .env. See README.md for setup instructions.');for(let r=1;r<=t;r++)try{let n=await Ie.askLifebot(o,e,{timeout:Je});return Je=Math.max(12e4,Je*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){Je=Math.min(Je*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(Je/1e3)}s...`);continue}throw n}}async function uo(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let o=`Job application form field "${e}" \u2014 reply with ONLY the value to fill in, nothing else. `;return t&&(t==="Enter a decimal number larger than 0.0"&&(t="Enter a decimal number larger than 0"),o+=`Additional info: ${t}`),await He(o)}async function Tt(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await He(o)}async function st(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await He(o)}mo();import{LIFEBOT_MESSAGE_TYPES as ii}from"@ilivemylife/graph-sdk";Be();await Xe();async function xr(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function vr(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function Rs(e,t,o={}){let{extractExperience:r=!1,extractFeatured:n=!1,extractEducation:i=!1,extractSkills:s=!1,extractRecommendations:a=!1,extractCertifications:l=!1}=o;try{await co(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await w(1500),await ne(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await xr(e,t));let u=0;for(let b=0;b<2;b++){let C=await e.evaluate(()=>document.body.scrollHeight);for(let L=1;L<=6;L++)await e.evaluate(A=>window.scrollTo(0,A),C*L/6),await w(900);let R=await e.evaluate(()=>document.body.scrollHeight);if(R===u)break;u=R}await w(800);let f=null;try{let b=e.url();b&&/\/in\/[^/?#]/.test(b)&&(f=b.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let b=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),C=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),R=$=>{let D=($||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(D)},L={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},A=document.querySelector("main");if(!A)return L;let T=[...Array.from(A.querySelectorAll("h1")),...Array.from(A.querySelectorAll("h2"))],j=Array.from(A.querySelectorAll("h2")),K=T.find($=>{let D=$.textContent&&$.textContent.trim(),N=(D||"").replace(/\s*\(\d+\)$/,"").trim();return D&&D.length>1&&D.length<100&&!b.has(N)&&!C.has(N)}),U=K?K.textContent.trim():null,_=K?K.parentElement:null;for(;_&&_!==A&&!Array.from(_.children).filter(D=>D.tagName==="P").some(D=>{let N=D.textContent&&D.textContent.trim();return N&&N.length>5&&!R(N)});)_=_.parentElement;let M=null,F=null,B=null,G=null;if(_&&_!==A){let $=Array.from(_.children).filter(N=>N.tagName==="P").filter(N=>{let we=N.textContent&&N.textContent.trim();return we&&we.length>5&&!R(we)});if($[0]&&(M=$[0].textContent.trim()),$[1]){let N=$[1].textContent.trim().split(/\s*[·•]\s*/);F=N[0]||null,N.length>1&&(B=N.slice(1).join(" \xB7 "))}let D=Array.from(_.children).filter(N=>N.tagName==="DIV");for(let N=D.length-1;N>=0;N--){let we=D[N].textContent&&D[N].textContent.trim();if(we&&!(U&&we.startsWith(U))&&(G=we.split(/[·•]/)[0].trim(),G))break}}let W=null;if(_){let $=_.querySelectorAll("p, span, div");for(let D of $){let N=(D.textContent||"").trim().replace(/^[·•]\s*/,"");if(N==="1st"||N==="2nd"||N==="3rd"){W=N;break}}}let v=!!A.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),I=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Y=I&&I.src||null,O=A.textContent||"",J=null,Te=O.match(/(\d+\+?)\s+connections\b/i);Te&&(J=Te[1]+" connections");let Re=null,an=O.match(/(\d+)\s+mutual connection/i),cn=O.match(/and\s+(\d+)\s+other mutual/i),bi=O.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);an?Re=parseInt(an[1],10):cn?Re=2+parseInt(cn[1],10):bi&&(Re=2);let un=null,dn=null,fn=j.find($=>$.textContent&&$.textContent.trim()==="About");if(fn){let $=fn.parentElement;for(;$&&$.tagName!=="SECTION";)$=$.parentElement;if($){let D=($.textContent||"").trim();D=D.replace(/^About\s*/,"").trim();let N=D.match(/Top skills\s*(.+?)$/i);if(N){let io=N[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(vi=>vi.trim()).filter(Boolean);io.length>0&&io.length<10&&(dn=io)}D=D.split(/\n?…\s*more/i)[0].trim(),D=D.split(/\n?\.\.\.\s*more/i)[0].trim(),D=D.split(/\bTop skills\b/i)[0].trim(),D=D.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),un=D||null}}let pn=null,mn=j.find($=>$.textContent&&$.textContent.trim()==="Activity");if(mn){let $=mn.parentElement;for(;$&&$.tagName!=="SECTION";)$=$.parentElement;if($){let D=($.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);D&&(pn=parseInt(D[1].replace(/,/g,""),10))}}let wi=[...new Set(j.map($=>($.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter($=>$&&$.length>1&&$.length<60&&$!==U).filter($=>b.has($)))],it=document.body.textContent||"",Si=/#OpenToWork\b/i.test(it)||/\bOpen to work\b/.test(it),ki=/#Hiring\b/i.test(it)||/\bI'?m hiring\b/i.test(it)||/\bWe are hiring\b/i.test(it);return{name:U,title:M,location:G,currentCompany:F,currentSchool:B,connectionDegree:W,hasVerifiedBadge:v,photoUrl:Y,connectionsLevel:J,mutualConnectionsCount:Re,followers:pn,openToWork:Si,hiring:ki,about:un,topSkills:dn,availableSections:wi}});console.log(`Viewed: ${d.name} - ${d.title}`);let p=null,m=null,h=null,g=null,y=null,S=null;if(r||n||i||s||a||l){let b=await Promise.resolve().then(()=>(zn(),Kn));r&&(p=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),n&&(m=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),i&&(h=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),s&&(g=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${g.length} entries`)),a&&(y=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),l&&(S=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...p!==null&&{experience:p},...m!==null&&{featured:m},...h!==null&&{education:h},...g!==null&&{skillsFull:g},...y!==null&&{recommendations:y},...S!==null&&{certifications:S}}}catch(c){console.error(`Error viewing profile ${t}:`,c.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(c.message||""))throw c;return null}}async function ot(e,{detail:t=!1}={}){let o=()=>e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=f=>f&&!f.closest(n),s=f=>Array.from(document.querySelectorAll(f)).filter(i),a=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,u={pendingCount:a.length,pendingLabels:a.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!c};return a.length>0?{status:"pending",debug:u}:l&&!c?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),r=await o();return!r.debug.pendingCount&&!r.debug.hasMessageBtn&&!r.debug.hasConnectBtn&&(await w(1500),r=await o()),console.log(" DEBUG connection status:",JSON.stringify(r.debug)),t?r:r.status}async function Oo(e){let t=null,o=await e.evaluate(()=>{let c=document.querySelector("h1")?.textContent?.trim();if(c&&!c.includes("notification"))return c;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(c=u.textContent?.trim(),c&&!c.includes("notification")))return c;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let c=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});c.count>0&&console.log(` S0: ${c.count} custom-invite links: ${JSON.stringify(c.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),p=f.toLowerCase().split(" ")[0],m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let g=h.getBoundingClientRect();if(g.width===0||g.height===0||h.closest(m))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(p))return h}return null},o);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(o){let c=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${c}"`);let u=await e.evaluate(d=>{let p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(g=>{let y=g.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&p.test(y)}).map(g=>g.getAttribute("aria-label")?.slice(0,50))},c);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let p=document.querySelectorAll("button[aria-label]"),m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',h=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of p){if(g.closest(m))continue;let y=g.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&h.test(y))return g}return null},c);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let c=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();c.includes("invite")&&!c.includes(u)&&(console.log(` Skipping primary button: wrong person (${c})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let n=o?o.split(" ")[0].toLowerCase():"",i=null;for(let c of r){let u=await e.evaluate((f,d)=>{let p=f.className.includes("muted"),m=f.className.includes("sticky-header")||f.className.includes("sticky"),h=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,g=(f.getAttribute("aria-label")||"").toLowerCase(),y=g.includes("invite"),S=d?g.includes(d):!0;return{isMuted:p,isStickyHeader:m,inRecommendations:h,hasInvite:y,matchesName:S,ariaLabel:g}},c,n);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=c;break}}for(let c of r)c!==i&&await c.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let s=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let c of a){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),p=d.width>0&&d.height>0,m=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:m,top:d.top}},c);if(u.isVisible&&!u.isInStickyHeader){s=c,console.log(" Found More button by ID pattern (main)");break}}for(let c of a)c!==s&&await c.dispose().catch(()=>{});if(!s&&a.length>0&&(s=a[a.length-1],console.log(" Found More button by ID pattern (last)")),s||(s=await e.$('button[aria-label="More actions"]'),s&&console.log(" Found More button by aria-label")),!s){let c=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(p=>{let m=p.innerText?.trim(),h=p.getAttribute("aria-label")||"",g=p.getBoundingClientRect();return g.top<100||g.top>600||g.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let p=0;p<8&&d;p++){for(let m of d.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==f)return m;d=d.parentElement}return null});s=c?.asElement?.()||null,s||await c?.dispose?.().catch(()=>{}),s&&console.log(" Found More button by text (near profile actions)")}if(s)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),s),await w(500),await e.evaluate(d=>d.click(),s),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" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let p=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let m of p){let h=m.querySelector('a[href*="custom-invite"]');if(h)return h;for(let g of m.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let m of d)for(let h of m.querySelectorAll('[role="menuitem"], a, div')){let g=h.innerText?.trim();g&&g.length<40&&p.push(g)}return[...new Set(p)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(c){console.log(" More dropdown click failed:",c.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(c=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(c||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let p=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(p))continue;let m=d.getBoundingClientRect();if(!(m.width===0||m.height===0)){if(p.includes("invite")){if(f&&p.includes(f))return d;continue}if(p==="connect")return d}}return null},o||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Is(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let o=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),n=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV",s=(o.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(s))return console.log(` \u2717 Guard: refusing a non-connect control ("${o.ariaLabel}")`),"wrong_target";if(s.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!s.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${o.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(n){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await w(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await w(3e3)):(await e.evaluate(u=>u.click(),t),await w(3e3));let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let l=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),c=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${c}`:` \u26A0 No modal after connect click \u2014 ${c}`),"success"}async function Ds(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 o=await Oo(e);if(o){await e.evaluate(n=>n.click(),o),await w(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r)return await nt(e,r)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function nt(e,t){let o='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',r=()=>e.evaluate(s=>{let a=l=>!!(l&&l.querySelector(s));return!(a(document)||a(document.querySelector("#interop-outlet")?.shadowRoot))},o),n=()=>e.evaluate(()=>{for(let s of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(s.innerText||""))return!0;return!1}),i=async()=>{let s=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(s)return s;let a=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,o);return s=a?.asElement?.()||null,s||await a?.dispose?.().catch(()=>{}),s};for(let s=0;s<2;s++){try{await t.evaluate(a=>a.click())}catch{}if(await w(3e3),await n())return!1;if(await r())return!0;if(s===0){let a=await i();if(!a)return await r();t=a,await w(600)}}return await r()}async function js(e,t,o={}){let{source:r="unknown",skipQuotaGate:n=!1,skipQuotaRecord:i=!1}=o;if(!n){let a=dt();if(!a.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${a.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:a.reason,profileInfo:null}}let s=await Ls(e,t,o);return s.connectionSent&&!i&&Bt(t,r),s}async function Ls(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,skipIfPending:i=!0,skipIfConnected:s=!0,excludeLocations:a=[]}=o,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
248
- --- Connecting: ${c} ---`),a.length>0){let y=X()[t]?.location;if(vr(y,a))return console.log(` \u26A0 Excluded location (stored): ${y}`),l.reason="excluded_location",l.profileInfo={location:y},l}try{await co(e,t,{readySelector:".pvs-profile-actions, .pv-top-card-v2-ctas, .pv-top-card, section.pv-top-card",label:"profile"})}catch(y){if(y.code==="SESSION_EXPIRED")return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),l.reason="session_expired",l.fatal=!0,l;throw y}if(await w(2e3),await ne(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await xr(e,t),await w(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(Ao(),er)),{recordDiscoveredEdges:x}=await Promise.resolve().then(()=>(Kt(),sr)),{detectCategoryFromTitle:b}=await br().then(()=>gr),{detectSectors:C}=await Promise.resolve().then(()=>(kr(),Sr)),R=S(t)||t,L=await y(e,{seedUrl:R}),A=L.map(T=>{let j=T.headline?b(T.headline):null;return{url:T.url,seedUrl:R,block:T.block,rank:T.rank,name:T.name,headline:T.headline,categories:j?[j]:[],sectors:C(T.headline||"")}});x(A),L.length&&console.log(` \xB7 discovery: harvested ${L.length} related profiles`)}catch(y){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${y.message}`)}l.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"]),S=v=>{let I=(v||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(I)},x={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},b=document.querySelector("main");if(!b)return x;let C=[...Array.from(b.querySelectorAll("h1")),...Array.from(b.querySelectorAll("h2"))],R=Array.from(b.querySelectorAll("h2")),L=C.find(v=>{let I=v.textContent&&v.textContent.trim();return I&&I.length>1&&I.length<100&&!y.has(I)&&I!=="0 notifications"}),A=L?L.textContent.trim():null,T=L?L.parentElement:null;for(;T&&T!==b&&!Array.from(T.children).filter(Y=>Y.tagName==="P").some(Y=>{let O=Y.textContent&&Y.textContent.trim();return O&&O.length>5&&!S(O)});)T=T.parentElement;let j=null,K=null,U=null;if(T&&T!==b){let v=Array.from(T.children),I=v.filter(O=>O.tagName==="P").filter(O=>{let J=O.textContent&&O.textContent.trim();return J&&J.length>5&&!S(J)});I[0]&&(j=I[0].textContent.trim()),I[1]&&(K=I[1].textContent.trim());let Y=v.filter(O=>O.tagName==="DIV");for(let O=Y.length-1;O>=0;O--){let J=Y[O].textContent&&Y[O].textContent.trim();if(J&&!(A&&J.startsWith(A))&&(U=J.split(/[·•]/)[0].trim(),U))break}}let _=null;if(T){let v=T.querySelectorAll("p, span, div");for(let I of v){let Y=(I.textContent||"").trim().replace(/^[·•]\s*/,"");if(Y==="1st"||Y==="2nd"||Y==="3rd"){_=Y;break}}}let M=null,F=R.find(v=>v.textContent&&v.textContent.trim()==="About");if(F){let v=F.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;v&&(M=(v.textContent||"").trim().replace(/^About\s*/,"").trim()||null,M&&(M=M.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let B=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),G=B&&B.src||null,W=!!b.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:A,title:j,location:U,about:M,company:K,connectionDegree:_,connectionsCount:null,mutualConnections:null,photoUrl:G,hasVerifiedBadge:W}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(l.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(a.length>0){let y=l.profileInfo?.location,S=X()[t]?.location,x=y||S;if(vr(x,a))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${x}`),l.reason="excluded_location",l;!y&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await ot(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await ne(e);let d=await Oo(e);if(d||await ne(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),d=await Oo(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!d){let y=await ot(e,{detail:!0});return s&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=d.method;let p=await Is(e,d.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let y=await ot(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await ne(e),await w(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(b=>b.scrollIntoView({behavior:"smooth",block:"center"}),S),await w(500),await S.click().catch(()=>e.evaluate(b=>b.click(),S)),await w(2e3);let x=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(x){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(R=>R.click(),x),await w(3e3);let b=e.url();if(b.includes("/premium/")||b.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),l.reason="premium_required",l;if(await ot(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),l.reason="premium_required",l}catch(x){return console.log(" More dropdown failed:",x.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of y){let x=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!x)continue;let b=(x.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(b)||x.querySelector('input[type="email"], input[name="email"]'))return!0;let C=x.querySelector('button[aria-label="Send without a note"]');if(C&&(C.disabled||C.getAttribute("aria-disabled")==="true"||(C.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let y=await e.$('button[aria-label="Dismiss"]');if(y)try{await y.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await w(500),l.reason="email_required",l}let h=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!h&&!g){let y=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let x=S.querySelector('button[aria-label="Add a note"]'),b=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!x,sendWithout:!!b}});if(y.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=S?.asElement?.()||null,h||await S.dispose().catch(()=>{})}if(y.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=S?.asElement?.()||null,g||await S.dispose().catch(()=>{})}}if(n)if(h&&r){if(console.log(" Adding personalized note..."),await h.click(),await w(1500),await e.$("div.modal-upsell")){let x=await Ds(e);return l.success=x,l.connectionSent=x,l.reason=x?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let x=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),b=r.replace("{name}",x);await S.type(b,{delay:20}),await w(500);let C=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(C)return await nt(e,C)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=b,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(g)return console.log(" Sending without note..."),await nt(e,g)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(h&&!r){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await nt(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let y=g;if(y)return await nt(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3)),await ne(e),await w(500);let S=await e.$$('button[id*="profile-overflow-action"]'),x=null;for(let b of S){let C=await e.evaluate(R=>{let L=R.getBoundingClientRect();return{visible:L.width>0&&L.height>0,inSticky:!!R.closest('.sticky-header, [class*="sticky"]')}},b);if(C.visible&&!C.inSticky){x=b;break}}!x&&S.length>0&&(x=S[S.length-1]);for(let b of S)b!==x&&await b.dispose().catch(()=>{});if(x)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),x),await w(500),await x.click().catch(()=>e.evaluate(C=>C.click(),x)),await w(2e3);let b=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(b){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(A=>A.click(),b),await w(3e3);let C=e.url();if(C.includes("/premium/")||C.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await ot(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await ot(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let L=await e.$('button[aria-label="Send without a note"]');if(L)return console.log(" Modal appeared via More dropdown, sending without note..."),await nt(e,L)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(b){console.log(" More dropdown fallback failed:",b.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(c){console.error(` \u2717 Error: ${c.message}`),l.reason="error",l.error=c.message;let u=c.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{l.fatal=!0}return l}}async function qo(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:i=20,viewOnly:s=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:l=null,excludeLocations:c=[],source:u="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
249
- === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${s?"View Only":`Connect (max ${i})`}`),s||console.log(`Custom messages: ${n?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!s){let p=ft();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let d=0;for(let p=0;p<t.length;p++){let m=t[p];try{if(e.isClosed()){console.log(`
247
+ `),process.exit(1));var Se=Li({token:Cn});var He=12e4;async function je(e,{retries:t=2}={}){let o=process.env.NODE_EASY_APPLY_MAIN;if(!o||o.startsWith("YOUR_"))throw new Error('NODE_EASY_APPLY_MAIN is not configured in .env. Create a node in iLiveMyLife, add "assist" tag, and set the node ID in .env. See README.md for setup instructions.');for(let r=1;r<=t;r++)try{let n=await Se.askLifebot(o,e,{timeout:He});return He=Math.max(12e4,He*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){He=Math.min(He*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(He/1e3)}s...`);continue}throw n}}async function Dt(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let o=`Job application form field "${e}" \u2014 reply with ONLY the value to fill in, nothing else. `;return t&&(t==="Enter a decimal number larger than 0.0"&&(t="Enter a decimal number larger than 0"),o+=`Additional info: ${t}`),await je(o)}async function jt(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await je(o)}async function ct(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await je(o)}async function $n(e,t){let o=`Select all that apply \u2014 ${e} Options: ${t.join(", ")}. Reply with ONLY the options that apply, comma-separated exactly as written, or "none".`;return await je(o)}ho();import{LIFEBOT_MESSAGE_TYPES as sn}from"@ilivemylife/graph-sdk";Je();await Xe();async function Tr(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function _r(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function Os(e,t,o={}){let{extractExperience:r=!1,extractFeatured:n=!1,extractEducation:i=!1,extractSkills:s=!1,extractRecommendations:c=!1,extractCertifications:l=!1}=o;try{await Be(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await k(1500),await re(e)&&(console.log(" Dismissed Premium overlay"),await k(1500),await Tr(e,t));let u=0;for(let b=0;b<2;b++){let S=await e.evaluate(()=>document.body.scrollHeight);for(let D=1;D<=6;D++)await e.evaluate(w=>window.scrollTo(0,w),S*D/6),await k(900);let _=await e.evaluate(()=>document.body.scrollHeight);if(_===u)break;u=_}await k(800);let d=null;try{let b=e.url();b&&/\/in\/[^/?#]/.test(b)&&(d=b.split("?")[0].replace(/\/+$/,""))}catch{}let f=await e.evaluate(()=>{let b=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),S=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"]),_=j=>{let q=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(q)},D={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:[]},w=document.querySelector("main");if(!w)return D;let x=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],T=Array.from(w.querySelectorAll("h2")),N=x.find(j=>{let q=j.textContent&&j.textContent.trim(),O=(q||"").replace(/\s*\(\d+\)$/,"").trim();return q&&q.length>1&&q.length<100&&!b.has(O)&&!S.has(O)}),I=N?N.textContent.trim():null,C=N?N.parentElement:null;for(;C&&C!==w&&!Array.from(C.children).filter(q=>q.tagName==="P").some(q=>{let O=q.textContent&&q.textContent.trim();return O&&O.length>5&&!_(O)});)C=C.parentElement;let P=null,F=null,H=null,G=null;if(C&&C!==w){let j=Array.from(C.children).filter(O=>O.tagName==="P").filter(O=>{let we=O.textContent&&O.textContent.trim();return we&&we.length>5&&!_(we)});if(j[0]&&(P=j[0].textContent.trim()),j[1]){let O=j[1].textContent.trim().split(/\s*[·•]\s*/);F=O[0]||null,O.length>1&&(H=O.slice(1).join(" \xB7 "))}let q=Array.from(C.children).filter(O=>O.tagName==="DIV");for(let O=q.length-1;O>=0;O--){let we=q[O].textContent&&q[O].textContent.trim();if(we&&!(I&&we.startsWith(I))&&(G=we.split(/[·•]/)[0].trim(),G))break}}let M=null;if(C){let j=C.querySelectorAll("p, span, div");for(let q of j){let O=(q.textContent||"").trim().replace(/^[·•]\s*/,"");if(O==="1st"||O==="2nd"||O==="3rd"){M=O;break}}}let v=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),L=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),V=L&&L.src||null,B=w.textContent||"",W=null,Ie=B.match(/(\d+\+?)\s+connections\b/i);Ie&&(W=Ie[1]+" connections");let De=null,cn=B.match(/(\d+)\s+mutual connection/i),un=B.match(/and\s+(\d+)\s+other mutual/i),Ai=B.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);cn?De=parseInt(cn[1],10):un?De=2+parseInt(un[1],10):Ai&&(De=2);let dn=null,fn=null,pn=T.find(j=>j.textContent&&j.textContent.trim()==="About");if(pn){let j=pn.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;if(j){let q=(j.textContent||"").trim();q=q.replace(/^About\s*/,"").trim();let O=q.match(/Top skills\s*(.+?)$/i);if(O){let co=O[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(_i=>_i.trim()).filter(Boolean);co.length>0&&co.length<10&&(fn=co)}q=q.split(/\n?…\s*more/i)[0].trim(),q=q.split(/\n?\.\.\.\s*more/i)[0].trim(),q=q.split(/\bTop skills\b/i)[0].trim(),q=q.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),dn=q||null}}let mn=null,hn=T.find(j=>j.textContent&&j.textContent.trim()==="Activity");if(hn){let j=hn.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;if(j){let q=(j.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);q&&(mn=parseInt(q[1].replace(/,/g,""),10))}}let Ei=[...new Set(T.map(j=>(j.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(j=>j&&j.length>1&&j.length<60&&j!==I).filter(j=>b.has(j)))],it=document.body.textContent||"",Ci=/#OpenToWork\b/i.test(it)||/\bOpen to work\b/.test(it),$i=/#Hiring\b/i.test(it)||/\bI'?m hiring\b/i.test(it)||/\bWe are hiring\b/i.test(it);return{name:I,title:P,location:G,currentCompany:F,currentSchool:H,connectionDegree:M,hasVerifiedBadge:v,photoUrl:V,connectionsLevel:W,mutualConnectionsCount:De,followers:mn,openToWork:Ci,hiring:$i,about:dn,topSkills:fn,availableSections:Ei}});console.log(`Viewed: ${f.name} - ${f.title}`);let p=null,m=null,h=null,g=null,y=null,A=null;if(r||n||i||s||c||l){let b=await Promise.resolve().then(()=>(or(),tr));r&&(p=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),n&&(m=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),i&&(h=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),s&&(g=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${g.length} entries`)),c&&(y=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),l&&(A=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${A.length} entries`))}return{...f,profileUrl:t,resolvedUrl:d,...p!==null&&{experience:p},...m!==null&&{featured:m},...h!==null&&{education:h},...g!==null&&{skillsFull:g},...y!==null&&{recommendations:y},...A!==null&&{certifications:A}}}catch(a){console.error(`Error viewing profile ${t}:`,a.message);try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(a.message||""))throw a;return null}}async function ot(e,{detail:t=!1}={}){let o=()=>e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=d=>d&&!d.closest(n),s=d=>Array.from(document.querySelectorAll(d)).filter(i),c=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,a=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:c.length,pendingLabels:c.map(d=>d.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!a};return c.length>0?{status:"pending",debug:u}:l&&!a?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),r=await o();return!r.debug.pendingCount&&!r.debug.hasMessageBtn&&!r.debug.hasConnectBtn&&(await k(1500),r=await o()),console.log(" DEBUG connection status:",JSON.stringify(r.debug)),t?r:r.status}async function Oo(e){let t=null,o=await e.evaluate(()=>{let a=document.querySelector("h1")?.textContent?.trim();if(a&&!a.includes("notification"))return a;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(a=u.textContent?.trim(),a&&!a.includes("notification")))return a;let d=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(d)return d.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let a=await e.evaluate(()=>{let d=document.querySelectorAll('a[href*="custom-invite"]');return{count:d.length,labels:Array.from(d).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});a.count>0&&console.log(` S0: ${a.count} custom-invite links: ${JSON.stringify(a.labels)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),p=d.toLowerCase().split(" ")[0],m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of f){let g=h.getBoundingClientRect();if(g.width===0||g.height===0||h.closest(m))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(p))return h}return null},o);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(o){let a=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${a}"`);let u=await e.evaluate(f=>{let p=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(g=>{let y=g.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&p.test(y)}).map(g=>g.getAttribute("aria-label")?.slice(0,50))},a);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(f=>{let p=document.querySelectorAll("button[aria-label]"),m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',h=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of p){if(g.closest(m))continue;let y=g.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&h.test(y))return g}return null},a);let d=t?.asElement?.()||null;if(d||await t?.dispose?.().catch(()=>{}),d)return console.log(" Found: button matching profile name"),{button:d,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let a=await e.evaluate(d=>(d.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();a.includes("invite")&&!a.includes(u)&&(console.log(` Skipping primary button: wrong person (${a})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let n=o?o.split(" ")[0].toLowerCase():"",i=null;for(let a of r){let u=await e.evaluate((d,f)=>{let p=d.className.includes("muted"),m=d.className.includes("sticky-header")||d.className.includes("sticky"),h=d.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,g=(d.getAttribute("aria-label")||"").toLowerCase(),y=g.includes("invite"),A=f?g.includes(f):!0;return{isMuted:p,isStickyHeader:m,inRecommendations:h,hasInvite:y,matchesName:A,ariaLabel:g}},a,n);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=a;break}}for(let a of r)a!==i&&await a.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let s=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let a of c){let u=await e.evaluate(d=>{let f=d.getBoundingClientRect(),p=f.width>0&&f.height>0,m=d.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:m,top:f.top}},a);if(u.isVisible&&!u.isInStickyHeader){s=a,console.log(" Found More button by ID pattern (main)");break}}for(let a of c)a!==s&&await a.dispose().catch(()=>{});if(!s&&c.length>0&&(s=c[c.length-1],console.log(" Found More button by ID pattern (last)")),s||(s=await e.$('button[aria-label="More actions"]'),s&&console.log(" Found More button by aria-label")),!s){let a=await e.evaluateHandle(()=>{let d=Array.from(document.querySelectorAll("button, a")).find(p=>{let m=p.innerText?.trim(),h=p.getAttribute("aria-label")||"",g=p.getBoundingClientRect();return g.top<100||g.top>600||g.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!d)return null;let f=d.parentElement;for(let p=0;p<8&&f;p++){for(let m of f.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==d)return m;f=f.parentElement}return null});s=a?.asElement?.()||null,s||await a?.dispose?.().catch(()=>{}),s&&console.log(" Found More button by text (near profile actions)")}if(s)try{if(await e.evaluate(f=>f.scrollIntoView({behavior:"smooth",block:"center"}),s),await k(500),await e.evaluate(f=>f.click(),s),await k(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let f=await e.evaluateHandle(()=>{let p=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let m of p){let h=m.querySelector('a[href*="custom-invite"]');if(h)return h;for(let g of m.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});u=f?.asElement?.()||null,u||await f?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let d=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let m of f)for(let h of m.querySelectorAll('[role="menuitem"], a, div')){let g=h.innerText?.trim();g&&g.length<40&&p.push(g)}return[...new Set(p)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(d)}`),await e.keyboard.press("Escape"),d.some(f=>/remove (your )?connection/i.test(f)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(a){console.log(" More dropdown click failed:",a.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(a=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',d=(a||"").split(" ")[0].toLowerCase();for(let f of document.querySelectorAll("button[aria-label]")){if(f.closest(u))continue;let p=(f.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(p))continue;let m=f.getBoundingClientRect();if(!(m.width===0||m.height===0)){if(p.includes("invite")){if(d&&p.includes(d))return f;continue}if(p==="connect")return f}}return null},o||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Fs(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await k(500);let o=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),n=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV",s=(o.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(s))return console.log(` \u2717 Guard: refusing a non-connect control ("${o.ariaLabel}")`),"wrong_target";if(s.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!s.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${o.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(n){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await k(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await k(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await k(3e3)):(await e.evaluate(u=>u.click(),t),await k(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let l=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),a=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${a}`:` \u26A0 No modal after connect click \u2014 ${a}`),"success"}async function Ms(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await k(1500);let o=await Oo(e);if(o){await e.evaluate(n=>n.click(),o),await k(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r)return await nt(e,r)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function nt(e,t){let o='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',r=()=>e.evaluate(s=>{let c=l=>!!(l&&l.querySelector(s));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},o),n=()=>e.evaluate(()=>{for(let s of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(s.innerText||""))return!0;return!1}),i=async()=>{let s=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(s)return s;let c=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,o);return s=c?.asElement?.()||null,s||await c?.dispose?.().catch(()=>{}),s};for(let s=0;s<2;s++){try{await t.evaluate(c=>c.click())}catch{}if(await k(3e3),await n())return!1;if(await r())return!0;if(s===0){let c=await i();if(!c)return await r();t=c,await k(600)}}return await r()}async function Us(e,t,o={}){let{source:r="unknown",skipQuotaGate:n=!1,skipQuotaRecord:i=!1}=o;if(!n){let c=mt();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 s=await Bs(e,t,o);return s.connectionSent&&!i&&Vt(t,r),s}async function Bs(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,skipIfPending:i=!0,skipIfConnected:s=!0,excludeLocations:c=[]}=o,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let a=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
248
+ --- Connecting: ${a} ---`),c.length>0){let y=X()[t]?.location;if(_r(y,c))return console.log(` \u26A0 Excluded location (stored): ${y}`),l.reason="excluded_location",l.profileInfo={location:y},l}try{await Be(e,t,{readySelector:".pvs-profile-actions, .pv-top-card-v2-ctas, .pv-top-card, section.pv-top-card",label:"profile"})}catch(y){if(y.code==="SESSION_EXPIRED")return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),l.reason="session_expired",l.fatal=!0,l;throw y}if(await k(2e3),await re(e)&&(console.log(" Dismissed Premium overlay"),await k(2e3),await Tr(e,t),await k(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:A}=await Promise.resolve().then(()=>($o(),sr)),{recordDiscoveredEdges:E}=await Promise.resolve().then(()=>(Zt(),fr)),{detectCategoryFromTitle:b}=await Ar().then(()=>xr),{detectSectors:S}=await Promise.resolve().then(()=>($r(),Cr)),_=A(t)||t,D=await y(e,{seedUrl:_}),w=D.map(x=>{let T=x.headline?b(x.headline):null;return{url:x.url,seedUrl:_,block:x.block,rank:x.rank,name:x.name,headline:x.headline,categories:T?[T]:[],sectors:S(x.headline||"")}});E(w),D.length&&console.log(` \xB7 discovery: harvested ${D.length} related profiles`)}catch(y){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${y.message}`)}l.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"]),A=v=>{let L=(v||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(L)},E={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},b=document.querySelector("main");if(!b)return E;let S=[...Array.from(b.querySelectorAll("h1")),...Array.from(b.querySelectorAll("h2"))],_=Array.from(b.querySelectorAll("h2")),D=S.find(v=>{let L=v.textContent&&v.textContent.trim();return L&&L.length>1&&L.length<100&&!y.has(L)&&L!=="0 notifications"}),w=D?D.textContent.trim():null,x=D?D.parentElement:null;for(;x&&x!==b&&!Array.from(x.children).filter(V=>V.tagName==="P").some(V=>{let B=V.textContent&&V.textContent.trim();return B&&B.length>5&&!A(B)});)x=x.parentElement;let T=null,N=null,I=null;if(x&&x!==b){let v=Array.from(x.children),L=v.filter(B=>B.tagName==="P").filter(B=>{let W=B.textContent&&B.textContent.trim();return W&&W.length>5&&!A(W)});L[0]&&(T=L[0].textContent.trim()),L[1]&&(N=L[1].textContent.trim());let V=v.filter(B=>B.tagName==="DIV");for(let B=V.length-1;B>=0;B--){let W=V[B].textContent&&V[B].textContent.trim();if(W&&!(w&&W.startsWith(w))&&(I=W.split(/[·•]/)[0].trim(),I))break}}let C=null;if(x){let v=x.querySelectorAll("p, span, div");for(let L of v){let V=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(V==="1st"||V==="2nd"||V==="3rd"){C=V;break}}}let P=null,F=_.find(v=>v.textContent&&v.textContent.trim()==="About");if(F){let v=F.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;v&&(P=(v.textContent||"").trim().replace(/^About\s*/,"").trim()||null,P&&(P=P.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let H=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),G=H&&H.src||null,M=!!b.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:w,title:T,location:I,about:P,company:N,connectionDegree:C,connectionsCount:null,mutualConnections:null,photoUrl:G,hasVerifiedBadge:M}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(l.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let y=l.profileInfo?.location,A=X()[t]?.location,E=y||A;if(_r(E,c))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${E}`),l.reason="excluded_location",l;!y&&A==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await ot(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await re(e);let f=await Oo(e);if(f||await re(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await k(2e3),f=await Oo(e)),f&&f.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!f){let y=await ot(e,{detail:!0});return s&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=f.method;let p=await Fs(e,f.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(4e3);let y=await ot(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await re(e),await k(1e3);let A=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(A)try{await e.evaluate(b=>b.scrollIntoView({behavior:"smooth",block:"center"}),A),await k(500),await A.click().catch(()=>e.evaluate(b=>b.click(),A)),await k(2e3);let E=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(E){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(_=>_.click(),E),await k(3e3);let b=e.url();if(b.includes("/premium/")||b.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),l.reason="premium_required",l;if(await ot(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await k(500),l.reason="premium_required",l}catch(E){return console.log(" More dropdown failed:",E.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let A of y){let E=A.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!E)continue;let b=(E.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(b)||E.querySelector('input[type="email"], input[name="email"]'))return!0;let S=E.querySelector('button[aria-label="Send without a note"]');if(S&&(S.disabled||S.getAttribute("aria-disabled")==="true"||(S.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let y=await e.$('button[aria-label="Dismiss"]');if(y)try{await y.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await k(500),l.reason="email_required",l}let h=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!h&&!g){let y=await e.evaluate(()=>{let A=document.querySelector("#interop-outlet")?.shadowRoot;if(!A)return{addNote:!1,sendWithout:!1};let E=A.querySelector('button[aria-label="Add a note"]'),b=A.querySelector('button[aria-label="Send without a note"]');return{addNote:!!E,sendWithout:!!b}});if(y.addNote){let A=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=A?.asElement?.()||null,h||await A.dispose().catch(()=>{})}if(y.sendWithout){let A=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=A?.asElement?.()||null,g||await A.dispose().catch(()=>{})}}if(n)if(h&&r){if(console.log(" Adding personalized note..."),await h.click(),await k(1500),await e.$("div.modal-upsell")){let E=await Ms(e);return l.success=E,l.connectionSent=E,l.reason=E?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let A=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(A){let E=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),b=r.replace("{name}",E);await A.type(b,{delay:20}),await k(500);let S=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(S)return await nt(e,S)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=b,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(g)return console.log(" Sending without note..."),await nt(e,g)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(h&&!r){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await nt(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let y=g;if(y)return await nt(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(f.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(4e3)),await re(e),await k(500);let A=await e.$$('button[id*="profile-overflow-action"]'),E=null;for(let b of A){let S=await e.evaluate(_=>{let D=_.getBoundingClientRect();return{visible:D.width>0&&D.height>0,inSticky:!!_.closest('.sticky-header, [class*="sticky"]')}},b);if(S.visible&&!S.inSticky){E=b;break}}!E&&A.length>0&&(E=A[A.length-1]);for(let b of A)b!==E&&await b.dispose().catch(()=>{});if(E)try{await e.evaluate(S=>S.scrollIntoView({behavior:"smooth",block:"center"}),E),await k(500),await E.click().catch(()=>e.evaluate(S=>S.click(),E)),await k(2e3);let b=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(b){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(w=>w.click(),b),await k(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 k(3e3),await ot(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await ot(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let D=await e.$('button[aria-label="Send without a note"]');if(D)return console.log(" Modal appeared via More dropdown, sending without note..."),await nt(e,D)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(b){console.log(" More dropdown fallback failed:",b.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(a){console.error(` \u2717 Error: ${a.message}`),l.reason="error",l.error=a.message;let u=a.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{l.fatal=!0}return l}}async function Fo(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:i=20,viewOnly:s=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:l=null,excludeLocations:a=[],source:u="unknown"}=o,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
249
+ === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${s?"View Only":`Connect (max ${i})`}`),s||console.log(`Custom messages: ${n?"Enabled":"Disabled (saving quota)"}`),a.length>0&&console.log(`Excluding locations: ${a.join(", ")}`),!s){let p=ht();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let f=0;for(let p=0;p<t.length;p++){let m=t[p];try{if(e.isClosed()){console.log(`
250
250
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
251
- \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let h=Ot(m.profileUrl);if(h==="pending"||h==="connected"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${m.name||m.profileUrl} \u2014 skipped (db: ${h})`),h==="pending"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,l&&await l(m,f,{success:!1,reason:h,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${m.name||m.profileUrl}`);let g=null;if(s){let y=await Rs(e,m.profileUrl);y?(xe(m.profileUrl,{...y,source:u}),f.viewed++,g={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(f.errors++,g={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let y=dt();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(g=await js(e,m.profileUrl,{message:r,useCustomMessage:n,excludeLocations:c,source:u,skipQuotaGate:!0}),g.success)f.connectionsSent++;else switch(g.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(g?.fatal){console.log(`
252
- \u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(g?.reason==="error"){if(d++,d>=3){console.log(`
253
- \u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(g&&g.reason&&(qt(m.profileUrl,g.reason,{method:g.method,messageSent:g.messageSent,profileInfo:g.profileInfo}),g.resolvedUrl&&Mt(m.profileUrl,g.resolvedUrl),ze(m.profileUrl,{source:u||"funnel",jobId:m.jobId||m.fromJob?.jobId||null,jobTitle:m.fromJob?.title||null,jobCompany:m.fromJob?.company||null,action:g.reason})),l&&await l(m,f,g),p<t.length-1){let y=a+Math.random()*2e3;await w(y)}}if(console.log(`
254
- === Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!s){let p=ft();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return f}await Xe();Be();async function Er(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let n=null,i=null;for(let f of r)if(n=document.querySelector(f),n){i=f;break}if(!n){let f=document.querySelector("li.scaffold-layout__list-item");if(f){let d=f.parentElement;for(;d&&d!==document.body;){if(d.scrollHeight>d.clientHeight){n=d,i="parent of li.scaffold-layout__list-item";break}d=d.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let s=n.scrollTop,a=300,l=300,c=50,u=0;for(;u<c&&(n.scrollBy(0,a),await new Promise(f=>setTimeout(f,l)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)u++;return{found:!0,usedSelector:i,initialScroll:s,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:u}},t)}async function Cr(e,{easyApplyOnly:t=!0}={}){let o=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(n=>{let s=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=n.querySelector("a.job-card-container__link");if(a){let l=a.getAttribute("href").split("?")[0],c=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),u=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),f=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),d=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:l,isEasyApply:s,applyType:s?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${l}`,jobTitle:c,companyName:u,location:f,salary:d||null,jobLink:s?a.href:null}}return{isEasyApply:!1}})});return t?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function Ar(e){let t=await e.evaluate(()=>{let o=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(o&&!o.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return o.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",t.success?t.pageState:t.reason),t.success&&await w(2e3),t.success}async function Mo(e,t){let o=e.url();if(o.includes("/jobs/"))return!1;if($t(o)){if(!await lo(e,".scaffold-layout__main, main.scaffold-layout__main, .jobs-search-results-list",{timeout:45e3,label:"job search"})&&$t(e.url())&&await ao(e,{label:"job search"}),e.url().includes("/jobs/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(2e3)),!e.url().includes("/jobs/"))throw new Error(`Session expired \u2014 could not return to job search (landed on ${e.url().slice(0,60)}). Run: ilml linkedin login`);return!0}console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();if(!r.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${r.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function _r(e,t,o,r){for(let n of t){await Mo(e,r)&&(await ne(e),await w(2e3));let s=await e.$(`a[data-control-id="${n.dataId}"]`),a="dataId";if(!s){let l=n.id?.match(/\d+/)?.[0];l&&(s=await e.$(`a[href*="/jobs/view/${l}/"]`),s&&(a="href"))}if(s){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${n.jobTitle}`);let l=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await e.evaluate(d=>d.scrollIntoView({block:"center"}),s),await w(300),await s.click(),await w(1500);let c=!1;for(let d=0;d<8;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){c=!0;break}await w(500)}if(!c){await e.evaluate(d=>d.click(),s),await w(1500);for(let d=0;d<6;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){c=!0;break}await w(500)}c||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let u=await e.evaluate(()=>{let d=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of d)for(let m of p.querySelectorAll("button")){let h=m.innerText?.trim();if(h==="Continue applying"||h==="Got it"||h==="Dismiss")return m.click(),h}return null});u&&console.log(` Dismissed popup before processing (${u})`);let{keepGoing:f}=await o(e,n);if(!f)return{keepGoing:!1}}else{let l=n.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${n.jobTitle||n.id} (dataId=${n.dataId}, jobId=${l})`)}}return{keepGoing:!0}}async function $r(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=t.querySelector(".hirer-card__hirer-information");if(o){let s=o.querySelector('a[href*="/in/"]'),a=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(s)return{name:a?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let s=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(s)return{name:r.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"poster_name"}}let n=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(n){let s=n.querySelector('a[href*="/in/"]');if(s)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"people_section"}}let i=t.querySelectorAll('a[href*="/in/"]');for(let s of i){let a=s.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:s.href?.split("?")[0],source:"details_link"}}return null})}async function Tr(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},i=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let J of i){let Te=J.querySelector(".job-criteria__subheader")?.textContent?.trim(),Re=J.querySelector(".job-criteria__text")?.textContent?.trim();Te&&Re&&(n[Te.toLowerCase()]=Re)}let s=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],a=[];for(let J of s)new RegExp("\\b"+J.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(J.replace(/\\\+/g,"+"));let c=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,f=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,d=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=d?.innerText?.trim()||null,h=(d?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",x=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,b=y.match(/(\d[\d,]*)\s+applicant/i),C=b?parseInt(b[1].replace(/,/g,"")):null,R=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),L=Array.from(R).map(J=>J.innerText?.trim()?.replace(/\s+/g," ")),T=L.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,j=L.join(" ")+" "+y,K=/\bremote\b/i.test(j)?"remote":/\bhybrid\b/i.test(j)?"hybrid":/\bon-?site\b/i.test(j)?"onsite":null,U=/\bcontract\b/i.test(j)?"contract":/\bfull-?time\b/i.test(j)?"full-time":/\bpart-?time\b/i.test(j)?"part-time":/\bfreelance\b/i.test(j)?"freelance":/\btemporary\b/i.test(j)?"temporary":null,M=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",B=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",G=(M+" "+r+" "+B).toLowerCase(),W=M.toLowerCase(),v=[];/\bremote\b/.test(G)&&v.push("remote"),/\bhybrid\b/.test(G)&&v.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(G)&&v.push("onsite"),(v.length===0||!v.includes("remote")&&!v.includes("hybrid")&&!v.includes("onsite"))&&/remote/i.test(B)&&v.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(W)&&v.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(W)&&v.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(W)&&!v.includes("managerial")&&v.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(W)?v.push("junior"):/\b(senior|sr\.?)\b/i.test(W)?v.push("senior"):/\b(staff|principal|distinguished)\b/i.test(W)?v.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(W)?v.push("executive"):/\b(lead|team lead)\b/i.test(W)&&v.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(G)&&v.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(G)&&v.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(G)&&v.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(G)&&v.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(G)&&v.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(G)&&v.push("mobile"),/\b(architect)\b/i.test(W)&&v.push("architect"),/\b(consultant|consulting)\b/i.test(W)&&v.push("consultant");let I=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(I)||/\bcontract\b/i.test(G))&&v.push("contract"),/full.?time|permanent/i.test(I)&&v.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(B)&&v.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(B)&&v.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&v.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:f,companyName:p,companyUrl:h?h.startsWith("/")?"https://www.linkedin.com"+h:h:null,aboutCompany:c,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:x,applicantCount:C,companySize:T,workplaceType:K,contractType:U,techStack:[...new Set(a)],jobTags:[...new Set(v)]}})}Kt();import"dotenv/config";import*as E from"fs";import*as Yo from"os";import*as P from"path";import{fileURLToPath as rl}from"url";var Jo={};oe(Jo,{NAME:()=>Ps,VERSION:()=>Ns,up:()=>qs});import*as se from"fs";import*as Qt from"path";var Ns=1,Ps="normalize-jobs-and-questions",Fs=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Os=50;function Uo(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function Bo(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{se.writeFileSync(r,o)}catch(n){try{se.unlinkSync(r)}catch{}throw n}try{se.renameSync(r,e)}catch(n){try{se.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function qs(e,t){let o=Qt.join(e,"jobs.json"),r=Qt.join(t,"scouted-jobs.json"),n=Qt.join(e,"application-questions.json"),i=Uo(o)||{},s=Uo(r)||{},a=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let f=s[u],d=i[u];for(let p of Fs)f[p]!=null&&d[p]==null&&(d[p]=f[p]);l.push(u),a++}a>0?(Bo(o,i),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let c=Uo(n);if(c&&Array.isArray(c.applications)){let u={},f=0;for(let d of c.applications){let p=d.jobId||"unknown";u[p]||(u[p]={applications:[]});let m=(d.questions||[]).map(h=>{let g={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=Os?g.options=h.options:(g.optionsOmitted=!0,f++)),h.page&&(g.page=h.page),h.wasPreFilled&&(g.wasPreFilled=!0),h.wasRetry&&(g.wasRetry=!0),g});u[p].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||m.length,questions:m})}Bo(n,u),console.log(` Phase 2: Rekeyed ${c.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else c&&!c.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let u of l)delete s[u];Bo(r,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Ho={};oe(Ho,{NAME:()=>Us,VERSION:()=>Ms,up:()=>Hs});import*as le from"fs";import*as Rr from"path";var Ms=2,Us="reset-unread-flags";function Bs(e){return le.existsSync(e)?JSON.parse(le.readFileSync(e,"utf-8")):null}function Js(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{le.writeFileSync(r,o)}catch(n){try{le.unlinkSync(r)}catch{}throw n}try{le.renameSync(r,e)}catch(n){try{le.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function Hs(e){let t=Rr.join(e,"conversations.json"),o=Bs(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let r=0;for(let n of Object.keys(o))o[n].unread===!0&&(o[n].unread=!1,r++);if(r===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Js(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Vo={};oe(Vo,{NAME:()=>Gs,VERSION:()=>Vs,up:()=>Qs});import*as ae from"fs";import*as Ir from"path";var Vs=3,Gs="recompute-last-message-by",Ws=new Set(["draft","confirmed","rejected","needs_review"]);function Ys(e){return ae.existsSync(e)?JSON.parse(ae.readFileSync(e,"utf-8")):null}function Ks(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ae.writeFileSync(r,o)}catch(n){try{ae.unlinkSync(r)}catch{}throw n}try{ae.renameSync(r,e)}catch(n){try{ae.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}function zs(e,t){if(!e||e.length===0)return"them";let o=e.filter(i=>!Ws.has(i.status));if(o.length===0)return"them";let r=o.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),n=r.length>0?r:[...o].reverse();for(let i of n){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function Qs(e){let t=Ir.join(e,"conversations.json"),o=Ys(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let r=process.env.LINKEDIN_NAME;if(!r||typeof r!="string"||!r.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 n=0,i=0,s=0;for(let a of Object.keys(o)){let l=o[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let c=Array.isArray(l.messages)?l.messages:[],u=zs(c,r),f=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=f,n++}if(n===0){console.log(" No conversations to recompute.");return}Ks(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${s} 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 Go={};oe(Go,{NAME:()=>Zs,VERSION:()=>Xs,up:()=>nl});import*as ce from"fs";import*as Dr from"path";var Xs=4,Zs="split-connection-timestamps",el=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function tl(e){if(!ce.existsSync(e))return null;let t=ce.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ol(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ce.writeFileSync(r,o)}catch(n){try{ce.unlinkSync(r)}catch{}throw n}try{ce.renameSync(r,e)}catch(n){try{ce.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function nl(e){let t=Dr.join(e,"people.json"),o=tl(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let r=0,n=0;for(let i of Object.keys(o)){let s=o[i];!s||typeof s!="object"||(n++,el.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,r++))}if(r===0){console.log(` Scanned ${n} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}ol(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${r} still-pending people (of ${n} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Xe();Kt();var il=rl(import.meta.url),sl=P.dirname(il),ll=P.dirname(P.dirname(sl));function al(e){return e&&(e==="~"?Yo.homedir():e.startsWith("~/")||e.startsWith("~\\")?P.join(Yo.homedir(),e.slice(2)):e)}var fe=process.env.DATA_DIR?P.resolve(al(process.env.DATA_DIR)):ll,qe=P.join(fe,"collected-profiles"),Me=P.join(fe,"market-research"),Z=P.join(fe,".schema-version"),jr=[P.join(qe,".schema-version"),P.join(Me,".schema-version")],_e=4,be=[{version:1,module:Jo},{version:2,module:Ho},{version:3,module:Vo},{version:4,module:Go}];(function(){be.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of be){if(!Number.isInteger(r.version)||r.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(r.version)} (must be positive integer)`);if(t.has(r.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${r.version}`);t.add(r.version);let n=r.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${r.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==r.version)throw new Error(`MIGRATION_REGISTRY: v${r.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=be.length?be[be.length-1].version:0;if(o!==_e)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${_e}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<be.length;r++){let n=r+1;if(be[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${be[r].version}`)}})();function Fr(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
251
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let h=Bt(m.profileUrl);if(h==="pending"||h==="connected"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${m.name||m.profileUrl} \u2014 skipped (db: ${h})`),h==="pending"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,l&&await l(m,d,{success:!1,reason:h,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${m.name||m.profileUrl}`);let g=null;if(s){let y=await Os(e,m.profileUrl);y?(Ae(m.profileUrl,{...y,source:u}),d.viewed++,g={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(d.errors++,g={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=mt();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(g=await Us(e,m.profileUrl,{message:r,useCustomMessage:n,excludeLocations:a,source:u,skipQuotaGate:!0}),g.success)d.connectionsSent++;else switch(g.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(g?.fatal){console.log(`
252
+ \u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(g?.reason==="error"){if(f++,f>=3){console.log(`
253
+ \u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(g&&g.reason&&(Jt(m.profileUrl,g.reason,{method:g.method,messageSent:g.messageSent,profileInfo:g.profileInfo}),g.resolvedUrl&&Ht(m.profileUrl,g.resolvedUrl),ze(m.profileUrl,{source:u||"funnel",jobId:m.jobId||m.fromJob?.jobId||null,jobTitle:m.fromJob?.title||null,jobCompany:m.fromJob?.company||null,action:g.reason})),l&&await l(m,d,g),p<t.length-1){let y=c+Math.random()*2e3;await k(y)}}if(console.log(`
254
+ === 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}`),!s){let p=ht();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return d}await Xe();Je();async function Rr(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let n=null,i=null;for(let d of r)if(n=document.querySelector(d),n){i=d;break}if(!n){let d=document.querySelector("li.scaffold-layout__list-item");if(d){let f=d.parentElement;for(;f&&f!==document.body;){if(f.scrollHeight>f.clientHeight){n=f,i="parent of li.scaffold-layout__list-item";break}f=f.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let s=n.scrollTop,c=300,l=300,a=50,u=0;for(;u<a&&(n.scrollBy(0,c),await new Promise(d=>setTimeout(d,l)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)u++;return{found:!0,usedSelector:i,initialScroll:s,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:u}},t)}async function Ir(e,{easyApplyOnly:t=!0}={}){let o=await e.evaluate(()=>{let n=document.querySelectorAll("li.scaffold-layout__list-item");if(n.length)return{ui:"old",jobs:Array.from(n).map(u=>{let f=(u.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),p=u.querySelector("a.job-card-container__link");if(!p)return{isEasyApply:!1};let m=p.getAttribute("href").split("?")[0];return{id:m,isEasyApply:f,applyType:f?"easy-apply":"external",dataId:p.getAttribute("data-control-id"),href:`https://linkedin.com${m}`,jobTitle:u.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),companyName:u.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),location:u.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),salary:u.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim()||null,jobLink:f?p.href:null,cardIndex:null}})};let i=Array.from(document.querySelectorAll('button[aria-label^="Dismiss"]')),s=a=>{let u=a;for(let d=0;d<14&&u&&u.parentElement;d++){u=u.parentElement;let p=Array.from(u.parentElement.children).filter(m=>{try{return m.querySelectorAll('button[aria-label^="Dismiss"]').length===1}catch{return!1}});if(p.length>=5&&p.includes(u))return u}return null},c=new Set,l=[];return i.forEach((a,u)=>{let d=s(a);if(!d||c.has(d))return;c.add(d);let f=d.innerText||"",p=d.matches&&d.matches("[componentkey]")?d:d.querySelector("[componentkey]")||d.closest("[componentkey]"),h=((p&&p.getAttribute("componentkey")||"").match(/(\d{6,})/)||[])[1]||null,g=(a.getAttribute("aria-label")||"").replace(/^Dismiss\s+/,"").replace(/\s+job$/,"").trim(),A=f.split(`
255
+ `).map(D=>D.trim()).filter(Boolean).filter(D=>D&&D!==g),E=A[0]||null,b=A.find(D=>D!==E&&/\((Remote|Hybrid|On-?site)\)|,\s*[A-Za-z]/.test(D))||A[1]||null,S=(f.match(/\$[\d,]+[^\n]*?(?:\/yr|\/hr|per year|per hour|K\b)|[\d,]+\s*(?:CAD|USD|EUR|GBP)[^\n]*?\/(?:hr|yr)/i)||[])[0]||null,_=/Easy Apply/i.test(f);l.push({id:h?`https://www.linkedin.com/jobs/view/${h}/`:null,href:h?`https://www.linkedin.com/jobs/view/${h}/`:null,jobId:h,cardIndex:u,isEasyApply:_,isApplied:/(^|\s)Applied(\s|$)/.test(f),applyType:_?"easy-apply":"external",jobTitle:g||null,companyName:E,location:b,salary:S||null,under10Applicants:/Under 10 applicants/i.test(f),activelyReviewing:/Actively reviewing/i.test(f),promoted:/Promoted/i.test(f),postedText:(f.match(/Posted[^\n]*/i)||[])[0]||null})}),{ui:"new",jobs:l}}),r=o.jobs||[];return o.ui==="new"?t?r.filter(n=>n.isEasyApply):r:t?r.filter(n=>n.isEasyApply&&n.href):r.filter(n=>n.href)}async function Js(e,t){let o=(e.url().match(/currentJobId=(\d+)/)||[])[1]||null;await e.evaluate(async c=>{let l=-1;for(let a=0;a<25;a++){let u=document.querySelectorAll('button[aria-label^="Dismiss"]');if(u.length>c||u.length===l)break;l=u.length;let d=u[u.length-1];if(d)try{d.scrollIntoView({block:"center"})}catch{}window.scrollBy(0,800),await new Promise(f=>setTimeout(f,400))}},t),await e.evaluate(c=>{let a=Array.from(document.querySelectorAll('button[aria-label^="Dismiss"]'))[c];if(!a)return;let u=a;for(let f=0;f<14&&u&&u.parentElement;f++){u=u.parentElement;let m=Array.from(u.parentElement.children).filter(h=>{try{return h.querySelectorAll('button[aria-label^="Dismiss"]').length===1}catch{return!1}});if(m.length>=5&&m.includes(u))break}if(!u)return;let d=[...u.querySelectorAll('[role="button"]')].find(f=>!/^Dismiss/i.test(f.getAttribute("aria-label")||""))||u.querySelector('a[href], [role="link"]');if(d){try{d.scrollIntoView({block:"center"})}catch{}d.click()}},t);let r=o;for(let c=0;c<12;c++){await k(500);let l=(e.url().match(/currentJobId=(\d+)/)||[])[1]||null;if(l&&(r=l),l&&l!==o)break}let n=e.url(),i=(n.match(/applicantTrackingSystemName=([^&]+)/i)||[])[1],s=!!i&&!/^linkedin$/i.test(decodeURIComponent(i));return{jobId:r,external:s,url:n}}async function Dr(e){let t=()=>parseInt((e.url().match(/[?&]start=(\d+)/)||[])[1]||"0",10),o=t(),r=await e.evaluate(()=>{let n=[...document.querySelectorAll('button[aria-label^="Page "]')],i=a=>parseInt((a.getAttribute("aria-label")||"").replace(/[^\d]/g,""),10),s=n.find(a=>a.getAttribute("aria-current")==="true"||a.getAttribute("aria-current")==="page");if(s){let a=i(s),u=n.find(d=>i(d)===a+1);return u&&!u.disabled?(u.scrollIntoView({block:"center"}),u.click(),{clicked:!0,to:`page ${a+1}`}):{clicked:!1,reason:`last page (${a})`}}let c=[...document.querySelectorAll("button")].find(a=>(/^Next$/i.test((a.innerText||"").trim())||/view next|next page/i.test(a.getAttribute("aria-label")||""))&&!a.disabled&&a.offsetParent!==null);if(c)return c.scrollIntoView({block:"center"}),c.click(),{clicked:!0,to:"next"};let l=document.querySelector('button[aria-label="View next page"], .jobs-search-pagination__button--next');return l&&!l.disabled?(l.click(),{clicked:!0,to:"legacy-next"}):{clicked:!1,reason:"No next page button found"}});if(!r.clicked)return console.log(" Pagination:",r.reason),!1;for(let n=0;n<16&&(await k(500),t()===o);n++);return await k(1500),t()===o?(console.log(" Pagination: clicked but page did not advance \u2014 stopping"),!1):(console.log(` Pagination \u2192 ${r.to}`),!0)}async function Mo(e,t){let o=e.url();if(!lt(o)&&o.includes("/jobs/"))return!1;if(lt(o)){if(!await fo(e,".scaffold-layout__main, main.scaffold-layout__main, .jobs-search-results-list",{timeout:45e3,label:"job search"})&&lt(e.url())&&await at(e,{label:"job search"}),e.url().includes("/jobs/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(2e3)),!e.url().includes("/jobs/"))throw new Error(`Session expired \u2014 could not return to job search (landed on ${e.url().slice(0,60)}). Run: ilml linkedin login`);return!0}console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let r=e.url();if(!r.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${r.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function jr(e,t,o,r){let n=r,i=t.filter(s=>s.isApplied||s.alreadyApplied).length;console.log(` \u{1F4CB} List: ${t.length} cards, ${i} already applied/dismissed (skipped), ${t.length-i} to process.`);for(let s of t){if(s.cardIndex!=null){if(s.isApplied||s.alreadyApplied){let p=s.isApplied?"list badge":"our DB";console.log(` \u2298 Already applied (${p}) \u2014 skipping without opening: ${s.jobTitle}`);continue}e.url().includes("/jobs/search")?n=e.url():(await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3));let{jobId:u,external:d}=await Js(e,s.cardIndex);if(!u){console.log(` \u26A0 Could not open card: ${s.jobTitle}`);continue}if(d){console.log(` \u21AA External ATS (not in-LinkedIn Easy Apply) \u2014 skipping: ${s.jobTitle}`);continue}s.jobId=u,s.href=`https://www.linkedin.com/jobs/view/${u}/`,s.id=s.href,await e.evaluate(()=>{for(let p of document.querySelectorAll("button")){let m=p.innerText?.trim();if(m==="Continue applying"||m==="Got it"||m==="Dismiss"){p.click();break}}}).catch(()=>{});let{keepGoing:f}=await o(e,s);if(!f)return{keepGoing:!1};continue}await Mo(e,r)&&(await re(e),await k(2e3));let l=await e.$(`a[data-control-id="${s.dataId}"]`),a="dataId";if(!l){let u=s.id?.match(/\d+/)?.[0];u&&(l=await e.$(`a[href*="/jobs/view/${u}/"]`),l&&(a="href"))}if(l){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${s.jobTitle}`);let u=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await e.evaluate(m=>m.scrollIntoView({block:"center"}),l),await k(300),await l.click(),await k(1500);let d=!1;for(let m=0;m<8;m++){let h=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(h&&h!==u){d=!0;break}await k(500)}if(!d){await e.evaluate(m=>m.click(),l),await k(1500);for(let m=0;m<6;m++){let h=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(h&&h!==u){d=!0;break}await k(500)}d||console.log(` \u26A0 Panel did not update after retry click for: ${s.jobTitle}`)}let f=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of m)for(let g of h.querySelectorAll("button")){let y=g.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return g.click(),y}return null});f&&console.log(` Dismissed popup before processing (${f})`);let{keepGoing:p}=await o(e,s);if(!p)return{keepGoing:!1}}else{let u=s.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${s.jobTitle||s.id} (dataId=${s.dataId}, jobId=${u})`)}}return{keepGoing:!0}}async function Lr(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=t.querySelector(".hirer-card__hirer-information");if(o){let s=o.querySelector('a[href*="/in/"]'),c=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(s)return{name:c?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let s=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(s)return{name:r.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"poster_name"}}let n=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(n){let s=n.querySelector('a[href*="/in/"]');if(s)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"people_section"}}let i=t.querySelectorAll('a[href*="/in/"]');for(let s of i){let c=s.textContent?.trim();if(c&&c.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(c))return{name:c,profileUrl:s.href?.split("?")[0],source:"details_link"}}return null})}async function Nr(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},i=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let W of i){let Ie=W.querySelector(".job-criteria__subheader")?.textContent?.trim(),De=W.querySelector(".job-criteria__text")?.textContent?.trim();Ie&&De&&(n[Ie.toLowerCase()]=De)}let s=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],c=[];for(let W of s)new RegExp("\\b"+W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&c.push(W.replace(/\\\+/g,"+"));let a=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,d=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,f=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=f?.innerText?.trim()||null,h=(f?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",E=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,b=y.match(/(\d[\d,]*)\s+applicant/i),S=b?parseInt(b[1].replace(/,/g,"")):null,_=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),D=Array.from(_).map(W=>W.innerText?.trim()?.replace(/\s+/g," ")),x=D.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,T=D.join(" ")+" "+y,N=/\bremote\b/i.test(T)?"remote":/\bhybrid\b/i.test(T)?"hybrid":/\bon-?site\b/i.test(T)?"onsite":null,I=/\bcontract\b/i.test(T)?"contract":/\bfull-?time\b/i.test(T)?"full-time":/\bpart-?time\b/i.test(T)?"part-time":/\bfreelance\b/i.test(T)?"freelance":/\btemporary\b/i.test(T)?"temporary":null,P=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",H=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",G=(P+" "+r+" "+H).toLowerCase(),M=P.toLowerCase(),v=[];/\bremote\b/.test(G)&&v.push("remote"),/\bhybrid\b/.test(G)&&v.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(G)&&v.push("onsite"),(v.length===0||!v.includes("remote")&&!v.includes("hybrid")&&!v.includes("onsite"))&&/remote/i.test(H)&&v.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(M)&&v.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(M)&&v.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(M)&&!v.includes("managerial")&&v.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(M)?v.push("junior"):/\b(senior|sr\.?)\b/i.test(M)?v.push("senior"):/\b(staff|principal|distinguished)\b/i.test(M)?v.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(M)?v.push("executive"):/\b(lead|team lead)\b/i.test(M)&&v.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(G)&&v.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(G)&&v.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(G)&&v.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(G)&&v.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(G)&&v.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(G)&&v.push("mobile"),/\b(architect)\b/i.test(M)&&v.push("architect"),/\b(consultant|consulting)\b/i.test(M)&&v.push("consultant");let L=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(L)||/\bcontract\b/i.test(G))&&v.push("contract"),/full.?time|permanent/i.test(L)&&v.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(H)&&v.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(H)&&v.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&v.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:d,companyName:p,companyUrl:h?h.startsWith("/")?"https://www.linkedin.com"+h:h:null,aboutCompany:a,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:E,applicantCount:S,companySize:x,workplaceType:N,contractType:I,techStack:[...new Set(c)],jobTags:[...new Set(v)]}})}Zt();import"dotenv/config";import*as R from"fs";import*as Yo from"os";import*as U from"path";import{fileURLToPath as pl}from"url";var Jo={};ne(Jo,{NAME:()=>Gs,VERSION:()=>Hs,up:()=>Ys});import*as le from"fs";import*as to from"path";var Hs=1,Gs="normalize-jobs-and-questions",Vs=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Ws=50;function Uo(e){return le.existsSync(e)?JSON.parse(le.readFileSync(e,"utf-8")):null}function Bo(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{le.writeFileSync(r,o)}catch(n){try{le.unlinkSync(r)}catch{}throw n}try{le.renameSync(r,e)}catch(n){try{le.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function Ys(e,t){let o=to.join(e,"jobs.json"),r=to.join(t,"scouted-jobs.json"),n=to.join(e,"application-questions.json"),i=Uo(o)||{},s=Uo(r)||{},c=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let d=s[u],f=i[u];for(let p of Vs)d[p]!=null&&f[p]==null&&(f[p]=d[p]);l.push(u),c++}c>0?(Bo(o,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=Uo(n);if(a&&Array.isArray(a.applications)){let u={},d=0;for(let f of a.applications){let p=f.jobId||"unknown";u[p]||(u[p]={applications:[]});let m=(f.questions||[]).map(h=>{let g={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=Ws?g.options=h.options:(g.optionsOmitted=!0,d++)),h.page&&(g.page=h.page),h.wasPreFilled&&(g.wasPreFilled=!0),h.wasRetry&&(g.wasRetry=!0),g});u[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||m.length,questions:m})}Bo(n,u),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let u of l)delete s[u];Bo(r,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Ho={};ne(Ho,{NAME:()=>zs,VERSION:()=>Ks,up:()=>Zs});import*as ae from"fs";import*as qr from"path";var Ks=2,zs="reset-unread-flags";function Qs(e){return ae.existsSync(e)?JSON.parse(ae.readFileSync(e,"utf-8")):null}function Xs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ae.writeFileSync(r,o)}catch(n){try{ae.unlinkSync(r)}catch{}throw n}try{ae.renameSync(r,e)}catch(n){try{ae.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function Zs(e){let t=qr.join(e,"conversations.json"),o=Qs(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let r=0;for(let n of Object.keys(o))o[n].unread===!0&&(o[n].unread=!1,r++);if(r===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Xs(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Go={};ne(Go,{NAME:()=>tl,VERSION:()=>el,up:()=>sl});import*as ce from"fs";import*as Pr from"path";var el=3,tl="recompute-last-message-by",ol=new Set(["draft","confirmed","rejected","needs_review"]);function nl(e){return ce.existsSync(e)?JSON.parse(ce.readFileSync(e,"utf-8")):null}function rl(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ce.writeFileSync(r,o)}catch(n){try{ce.unlinkSync(r)}catch{}throw n}try{ce.renameSync(r,e)}catch(n){try{ce.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}function il(e,t){if(!e||e.length===0)return"them";let o=e.filter(i=>!ol.has(i.status));if(o.length===0)return"them";let r=o.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),n=r.length>0?r:[...o].reverse();for(let i of n){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function sl(e){let t=Pr.join(e,"conversations.json"),o=nl(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let r=process.env.LINKEDIN_NAME;if(!r||typeof r!="string"||!r.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 n=0,i=0,s=0;for(let c of Object.keys(o)){let l=o[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let a=Array.isArray(l.messages)?l.messages:[],u=il(a,r),d=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=d,n++}if(n===0){console.log(" No conversations to recompute.");return}rl(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${s} 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 Vo={};ne(Vo,{NAME:()=>al,VERSION:()=>ll,up:()=>fl});import*as ue from"fs";import*as Or from"path";var ll=4,al="split-connection-timestamps",cl=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ul(e){if(!ue.existsSync(e))return null;let t=ue.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function dl(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ue.writeFileSync(r,o)}catch(n){try{ue.unlinkSync(r)}catch{}throw n}try{ue.renameSync(r,e)}catch(n){try{ue.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function fl(e){let t=Or.join(e,"people.json"),o=ul(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let r=0,n=0;for(let i of Object.keys(o)){let s=o[i];!s||typeof s!="object"||(n++,cl.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,r++))}if(r===0){console.log(` Scanned ${n} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}dl(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${r} still-pending people (of ${n} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Xe();Zt();var ml=pl(import.meta.url),hl=U.dirname(ml),yl=U.dirname(U.dirname(hl));function gl(e){return e&&(e==="~"?Yo.homedir():e.startsWith("~/")||e.startsWith("~\\")?U.join(Yo.homedir(),e.slice(2)):e)}var fe=process.env.DATA_DIR?U.resolve(gl(process.env.DATA_DIR)):yl,Me=U.join(fe,"collected-profiles"),Ue=U.join(fe,"market-research"),Z=U.join(fe,".schema-version"),Fr=[U.join(Me,".schema-version"),U.join(Ue,".schema-version")],Te=4,be=[{version:1,module:Jo},{version:2,module:Ho},{version:3,module:Go},{version:4,module:Vo}];(function(){be.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of be){if(!Number.isInteger(r.version)||r.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(r.version)} (must be positive integer)`);if(t.has(r.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${r.version}`);t.add(r.version);let n=r.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${r.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==r.version)throw new Error(`MIGRATION_REGISTRY: v${r.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=be.length?be[be.length-1].version:0;if(o!==Te)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${Te}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<be.length;r++){let n=r+1;if(be[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${be[r].version}`)}})();function Jr(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
255
256
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
256
- `),process.exit(1));try{E.mkdirSync(fe,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
257
+ `),process.exit(1));try{R.mkdirSync(fe,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
257
258
  [FATAL] Cannot create DATA_DIR (${fe}): ${t.message}`),console.error(` Fix the path or permissions and try again.
258
- `),process.exit(1))}let e;try{e=E.statSync(fe)}catch(t){console.error(`
259
+ `),process.exit(1))}let e;try{e=R.statSync(fe)}catch(t){console.error(`
259
260
  [FATAL] DATA_DIR (${fe}) is not accessible: ${t.message}
260
261
  `),process.exit(1)}e.isDirectory()||(console.error(`
261
262
  [FATAL] DATA_DIR (${fe}) 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.
262
- `),process.exit(1));for(let t of[qe,Me]){let o;try{o=E.lstatSync(t)}catch(r){if(r.code==="ENOENT")continue;throw r}o.isSymbolicLink()&&(console.error(`
263
+ `),process.exit(1));for(let t of[Me,Ue]){let o;try{o=R.lstatSync(t)}catch(r){if(r.code==="ENOENT")continue;throw r}o.isSymbolicLink()&&(console.error(`
263
264
  [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.
264
- `),process.exit(1))}}var Oe=P.join(fe,".migration-lock");function cl(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return E.writeFileSync(Oe,e,{flag:"wx"}),!0}catch(r){if(r.code!=="EEXIST")throw r}let t;try{t=JSON.parse(E.readFileSync(Oe,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let r=!1;try{process.kill(t.pid,0),r=!0}catch(s){s.code==="EPERM"&&(r=!0)}let n=24*60*60*1e3,i=1/0;if(t.startedAt){let s=Date.parse(t.startedAt);Number.isNaN(s)||(i=Date.now()-s)}r&&i<n&&(console.error(`
265
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Oe}
265
+ `),process.exit(1))}}var Fe=U.join(fe,".migration-lock");function bl(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return R.writeFileSync(Fe,e,{flag:"wx"}),!0}catch(r){if(r.code!=="EEXIST")throw r}let t;try{t=JSON.parse(R.readFileSync(Fe,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let r=!1;try{process.kill(t.pid,0),r=!0}catch(s){s.code==="EPERM"&&(r=!0)}let n=24*60*60*1e3,i=1/0;if(t.startedAt){let s=Date.parse(t.startedAt);Number.isNaN(s)||(i=Date.now()-s)}r&&i<n&&(console.error(`
266
+ [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}
266
267
  `),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.
267
- `),process.exit(1)),r&&i>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=Oe+".tmp";try{return E.writeFileSync(o,e),E.renameSync(o,Oe),!0}catch(r){try{E.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${r.message}`)}}function Ko(){try{if(JSON.parse(E.readFileSync(Oe,"utf-8")).pid!==process.pid)return;E.unlinkSync(Oe)}catch{}}var Lr=!1;function ul(){if(Lr)return;Lr=!0;let e=()=>{try{Ko()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function dl(){if(E.existsSync(Z))return;let e=[],t=[];for(let i of jr)if(E.existsSync(i))try{e.push({file:i,schema:Xt(i)})}catch(s){t.push({file:i,err:s.message})}if(t.length>0){console.error(`
268
+ `),process.exit(1)),r&&i>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=Fe+".tmp";try{return R.writeFileSync(o,e),R.renameSync(o,Fe),!0}catch(r){try{R.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${r.message}`)}}function Ko(){try{if(JSON.parse(R.readFileSync(Fe,"utf-8")).pid!==process.pid)return;R.unlinkSync(Fe)}catch{}}var Mr=!1;function wl(){if(Mr)return;Mr=!0;let e=()=>{try{Ko()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Sl(){if(R.existsSync(Z))return;let e=[],t=[];for(let i of Fr)if(R.existsSync(i))try{e.push({file:i,schema:oo(i)})}catch(s){t.push({file:i,err:s.message})}if(t.length>0){console.error(`
268
269
  [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(`
269
270
  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.
270
271
  `),process.exit(1)}if(e.length===0)return;let o=e.map(i=>i.schema.version);if(new Set(o).size>1){console.error(`
271
272
  [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.
272
- `),process.exit(1)}let r=e[0].schema,n=Z+".tmp";try{E.writeFileSync(n,JSON.stringify(r,null,2)),E.renameSync(n,Z)}catch(i){try{E.unlinkSync(n)}catch{}throw i}for(let i of jr)if(E.existsSync(i))try{E.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${Z}`)}function fl(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 Xt(e){let t=E.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Nr(){if(dl(),!E.existsSync(Z))return{version:0,migrations:[]};let e;try{e=Xt(Z)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
273
+ `),process.exit(1)}let r=e[0].schema,n=Z+".tmp";try{R.writeFileSync(n,JSON.stringify(r,null,2)),R.renameSync(n,Z)}catch(i){try{R.unlinkSync(n)}catch{}throw i}for(let i of Fr)if(R.existsSync(i))try{R.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${Z}`)}function kl(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 oo(e){let t=R.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Ur(){if(Sl(),!R.existsSync(Z))return{version:0,migrations:[]};let e;try{e=oo(Z)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
273
274
  [FATAL] ${Z} is not valid JSON: ${o.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
274
- `),process.exit(1)}let t=fl(e);return t===null&&(console.error(`
275
+ `),process.exit(1)}let t=kl(e);return t===null&&(console.error(`
275
276
  [FATAL] ${Z} 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.
276
- `),process.exit(1)),t}function Or(e){try{E.chmodSync(e,384)}catch{}}function pl(e){if(Fr(),E.existsSync(Z))try{if(E.lstatSync(Z).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${Z}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=Z+".tmp";try{E.writeFileSync(t,JSON.stringify(e,null,2)),Or(t),E.renameSync(t,Z)}catch(o){try{E.unlinkSync(t)}catch{}throw o}}function Pr(e,t){if(!E.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,r=E.readdirSync(e).filter(a=>{let l=a.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return E.statSync(P.join(e,a)).isFile()}catch{return!1}}),n=0,i=0,s=[];for(let a of r){let l=P.join(e,a),c=P.join(e,a+o);if(E.existsSync(c)){i++;continue}try{Mr(l,c),n++}catch(u){s.push({file:a,err:u.message})}}if(s.length>0){let a=new Error(`Failed to back up ${s.length} file(s) in ${P.basename(e)}/: `+s.map(l=>`${l.file} (${l.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(n>0||i>0){let a=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${n} files in ${P.basename(e)}/ (${o})${a}`)}}var Wo=!1;async function qr(){if(Wo)return;Fr(),bl();let t=Nr().version;if(t===_e){Wo=!0;return}ul(),cl(),process.on("exit",Ko),t>_e&&(console.error(`
277
- [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${_e}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
278
- `),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${_e}.
277
+ `),process.exit(1)),t}function Hr(e){try{R.chmodSync(e,384)}catch{}}function vl(e){if(Jr(),R.existsSync(Z))try{if(R.lstatSync(Z).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${Z}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=Z+".tmp";try{R.writeFileSync(t,JSON.stringify(e,null,2)),Hr(t),R.renameSync(t,Z)}catch(o){try{R.unlinkSync(t)}catch{}throw o}}function Br(e,t){if(!R.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,r=R.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return R.statSync(U.join(e,c)).isFile()}catch{return!1}}),n=0,i=0,s=[];for(let c of r){let l=U.join(e,c),a=U.join(e,c+o);if(R.existsSync(a)){i++;continue}try{Vr(l,a),n++}catch(u){s.push({file:c,err:u.message})}}if(s.length>0){let c=new Error(`Failed to back up ${s.length} file(s) in ${U.basename(e)}/: `+s.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(n>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${n} files in ${U.basename(e)}/ (${o})${c}`)}}var Wo=!1;async function Gr(){if(Wo)return;Jr(),$l();let t=Ur().version;if(t===Te){Wo=!0;return}wl(),bl(),process.on("exit",Ko),t>Te&&(console.error(`
278
+ [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${Te}.`),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.
279
+ `),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${Te}.
279
280
  `),process.exit(1)),console.log(`
280
- \u{1F4E6} Schema migration: v${t} \u2192 v${_e}`);let o=wl();if(!o.ok){console.error(`
281
+ \u{1F4E6} Schema migration: v${t} \u2192 v${Te}`);let o=_l();if(!o.ok){console.error(`
281
282
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let n of o.broken)console.error(` ${n.dir}/${n.file}: ${n.err}`);console.error(`
282
283
  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'.
283
284
  `),process.exit(1)}let r=be.filter(n=>n.version>t);for(let n of r){console.log(`
284
- Running migration v${String(n.version).padStart(3,"0")}...`);let i=`v${String(n.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{Pr(qe,n.version),Pr(Me,n.version)}catch(l){console.error(`
285
+ Running migration v${String(n.version).padStart(3,"0")}...`);let i=`v${String(n.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{Br(Me,n.version),Br(Ue,n.version)}catch(l){console.error(`
285
286
  [FATAL] Pre-migration backup failed for ${i}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
286
- `),process.exit(1)}let a=n.module;try{await a.up(qe,Me)}catch(l){console.error(`
287
- [FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let c=Sl(s);c.ok?(console.error(` \u2713 Auto-rollback restored ${c.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
288
- `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${c.error}`),console.error(` Manual recovery: copy *${s} files back over the originals.
289
- `))}catch(c){console.error(` [!] Auto-rollback CRASHED while restoring: ${c.message}`),console.error(` Manual recovery: copy *${s} files back over the originals.
290
- `)}process.exit(1)}try{let l=new Date().toISOString(),c={version:n.version,name:a.NAME||i,appliedAt:l},u=Nr();u.version=n.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(c),pl(u)}catch(l){console.error(`
287
+ `),process.exit(1)}let c=n.module;try{await c.up(Me,Ue)}catch(l){console.error(`
288
+ [FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let a=Tl(s);a.ok?(console.error(` \u2713 Auto-rollback restored ${a.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
289
+ `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${s} files back over the originals.
290
+ `))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${s} files back over the originals.
291
+ `)}process.exit(1)}try{let l=new Date().toISOString(),a={version:n.version,name:c.NAME||i,appliedAt:l},u=Ur();u.version=n.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(a),vl(u)}catch(l){console.error(`
291
292
  [FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${n.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.
292
- `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{xo()}catch{}try{To()}catch{}Wo=!0,Ko(),console.log(`
293
- \u2713 Schema is now at v${_e}
294
- `)}var ml=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function hl(e){let t=e.toLowerCase();return ml.some(o=>o.test(t))}var yl=6e4;function gl(){let e=Date.now(),t=[];for(let o of[fe,qe,Me]){if(!E.existsSync(o))continue;let r;try{r=E.readdirSync(o)}catch{continue}for(let n of r){if(!hl(n))continue;let i=P.join(o,n);try{let s=E.statSync(i);if(!s.isFile()||e-s.mtimeMs<yl)continue;t.push({dir:o,file:n,fullPath:i})}catch{}}}return t}function bl({verbose:e=!1}={}){let t=gl();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let r of t)try{E.unlinkSync(r.fullPath),o++,e&&console.log(` Removed orphan: ${P.basename(r.dir)}/${r.file}`)}catch(n){console.warn(` [!] Could not remove orphan ${r.fullPath}: ${n.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function wl(){let e=[];for(let t of[qe,Me]){if(!E.existsSync(t))continue;let o=E.readdirSync(t).filter(r=>{let n=r.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let r of o){let n=P.join(t,r);try{Xt(n)}catch(i){e.push({dir:P.basename(t),file:r,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Sl(e){let t=[],o=[];for(let i of[qe,Me]){if(!E.existsSync(i))continue;let s=E.readdirSync(i).filter(a=>a.endsWith(e));for(let a of s){let l=P.join(i,a),c=a.slice(0,-e.length),u=P.join(i,c);try{c.toLowerCase().endsWith(".json")?Xt(l):E.accessSync(l,E.constants.R_OK),t.push({backupPath:l,originalPath:u,fileName:a,dir:i})}catch(f){o.push(`${P.basename(i)}/${a}: ${f.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let r=0,n=[];for(let{backupPath:i,originalPath:s,fileName:a,dir:l}of t)try{Mr(i,s),r++}catch(c){n.push(`${P.basename(l)}/${a}: ${c.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:r}:{ok:!0,restored:r}}function Mr(e,t){let o=t+".tmp";try{E.copyFileSync(e,o),Or(o)}catch(r){try{E.unlinkSync(o)}catch{}throw r}try{E.renameSync(o,t)}catch(r){try{E.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let n=new Error(`File locked: ${t} (${r.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 n.code=r.code,n}throw r}}import"dotenv/config";import*as ue from"fs";import*as $e from"path";import{fileURLToPath as xl}from"url";import"dotenv/config";function kl(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),r=t%60;return r?`${o}m ${r}s`:`${o}m`}function vl({scriptName:e,mode:t,status:o,error:r,duration:n}){let i=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),a=n?` ${kl(n)}`:"",l=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",c=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${c} \u2014 ${l} \u2014 ${s}${a}`}async function Ur({scriptName:e,mode:t,status:o,summaryLines:r,error:n,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(r)||r.length===0)return;let l=`**${vl({scriptName:e,mode:t,status:o,error:n,duration:i})}**
293
+ `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{Ao()}catch{}try{Ro()}catch{}Wo=!0,Ko(),console.log(`
294
+ \u2713 Schema is now at v${Te}
295
+ `)}var xl=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Al(e){let t=e.toLowerCase();return xl.some(o=>o.test(t))}var El=6e4;function Cl(){let e=Date.now(),t=[];for(let o of[fe,Me,Ue]){if(!R.existsSync(o))continue;let r;try{r=R.readdirSync(o)}catch{continue}for(let n of r){if(!Al(n))continue;let i=U.join(o,n);try{let s=R.statSync(i);if(!s.isFile()||e-s.mtimeMs<El)continue;t.push({dir:o,file:n,fullPath:i})}catch{}}}return t}function $l({verbose:e=!1}={}){let t=Cl();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let r of t)try{R.unlinkSync(r.fullPath),o++,e&&console.log(` Removed orphan: ${U.basename(r.dir)}/${r.file}`)}catch(n){console.warn(` [!] Could not remove orphan ${r.fullPath}: ${n.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function _l(){let e=[];for(let t of[Me,Ue]){if(!R.existsSync(t))continue;let o=R.readdirSync(t).filter(r=>{let n=r.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let r of o){let n=U.join(t,r);try{oo(n)}catch(i){e.push({dir:U.basename(t),file:r,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Tl(e){let t=[],o=[];for(let i of[Me,Ue]){if(!R.existsSync(i))continue;let s=R.readdirSync(i).filter(c=>c.endsWith(e));for(let c of s){let l=U.join(i,c),a=c.slice(0,-e.length),u=U.join(i,a);try{a.toLowerCase().endsWith(".json")?oo(l):R.accessSync(l,R.constants.R_OK),t.push({backupPath:l,originalPath:u,fileName:c,dir:i})}catch(d){o.push(`${U.basename(i)}/${c}: ${d.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let r=0,n=[];for(let{backupPath:i,originalPath:s,fileName:c,dir:l}of t)try{Vr(i,s),r++}catch(a){n.push(`${U.basename(l)}/${c}: ${a.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:r}:{ok:!0,restored:r}}function Vr(e,t){let o=t+".tmp";try{R.copyFileSync(e,o),Hr(o)}catch(r){try{R.unlinkSync(o)}catch{}throw r}try{R.renameSync(o,t)}catch(r){try{R.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let n=new Error(`File locked: ${t} (${r.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 n.code=r.code,n}throw r}}import"dotenv/config";import*as de from"fs";import*as Re from"path";import{fileURLToPath as Dl}from"url";import"dotenv/config";function Rl(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),r=t%60;return r?`${o}m ${r}s`:`${o}m`}function Il({scriptName:e,mode:t,status:o,error:r,duration:n}){let i=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),c=n?` ${Rl(n)}`:"",l=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${a} \u2014 ${l} \u2014 ${s}${c}`}async function Wr({scriptName:e,mode:t,status:o,summaryLines:r,error:n,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(r)||r.length===0)return;let l=`**${Il({scriptName:e,mode:t,status:o,error:n,duration:i})}**
295
296
 
296
297
  ${r.join(`
297
- `)}`;try{await Ie.addMessage(s,l)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var El=xl(import.meta.url),Cl=$e.dirname($e.dirname(El)),zo=process.env.DATA_DIR?$e.resolve(process.env.DATA_DIR,"collected-profiles"):$e.join(Cl,"collected-profiles"),Qo=$e.join(zo,"run-log.json");function Al(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ue.writeFileSync(r,o);for(let n=0;n<3;n++)try{ue.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Br(){try{if(!ue.existsSync(Qo))return{runs:[]};let e=JSON.parse(ue.readFileSync(Qo,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Jr(e){ue.existsSync(zo)||ue.mkdirSync(zo,{recursive:!0});try{Al(Qo,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Hr(e,t="default"){let o=Br();for(let s of o.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let r=new Date,n={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(s=>new Date(s.timestamp).getTime()>i),Jr(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Vr(e,t,o=null,r=null){if(!e)return;let n=null;try{let s=Br(),a=s.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=o,a.error=r,n=a.duration;else{let l=s.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=r,n=l.duration)}Jr(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Ur({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:r,duration:n??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}_t();_t();import Xo from"fs";import _l from"path";var $l={headless:!1,defaultViewport:null,protocolTimeout:3e5},xt=new Set,Gr=!1;async function Zt(){let e=[...xt].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});xt.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Tl(){if(Gr)return;Gr=!0;let e=t=>async()=>{await Zt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Zt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Zt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Zt(),process.exit(0))}),process.on("exit",()=>{for(let t of xt)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function Zo(e){return _l.join(e,".ilml-browser-session.json")}function zr(e,t={}){try{Xo.writeFileSync(Zo(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Rl(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();zr(e,o?{wsEndpoint:o}:{})}catch{}}function Il(e){let t=Qr(e);t&&t.ownerPid===process.pid&&vt(e)}function vt(e){try{Xo.rmSync(Zo(e),{force:!0})}catch{}}function Qr(e){try{return JSON.parse(Xo.readFileSync(Zo(e),"utf-8"))}catch{return null}}function Wr(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Yr(e,t,o){let r,n=new Promise(s=>{r=setTimeout(()=>s(o),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(r),s),s=>{throw clearTimeout(r),s});return Promise.race([i,n])}async function Kr(e,t,{probeTimeoutMs:o=4e3}={}){let r=Qr(t);if(!r)return"free";if(!r.wsEndpoint)return r.ownerPid&&r.ownerPid!==process.pid&&Wr(r.ownerPid)?"live":(vt(t),"free");let n=Symbol("timeout"),i=e.connect({browserWSEndpoint:r.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await Yr(i,o,n);if(s===n)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return vt(t),"free";if(Wr(r.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Yr(s.close().then(()=>!0).catch(()=>!1),o,!1))return vt(t),"free";try{s.disconnect()}catch{}return"live"}function Dl(e,t){e&&(Tl(),xt.add(e),e.on("disconnected",()=>{xt.delete(e),t&&vt(t)}))}async function en(e,t={}){let o=bn(),r={...$l,...t,userDataDir:o},n=`Could not open the LinkedIn automation Chrome profile at ${o}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Kr(e,o)==="live")throw new Error(n);zr(o);let i;try{i=await e.launch(r)}catch{if(await Kr(e,o)==="live")throw new Error(n);vn(o);try{i=await e.launch(r)}catch(a){throw Il(o),new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${a.message})`)}}return Dl(i,o),Rl(o,i),{browser:i,profileDir:o,needsSeed:Sn(o)}}async function Xr(e,t){if(!t||!t.needsSeed)return!1;if(!yn())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(...At()),kn(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}Be();async function Et(e,t,o="op"){let r,n=new Promise((i,s)=>{r=setTimeout(()=>s(new Error(`${o} timeout after ${t}ms`)),t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}function rt(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let o=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(o)||/Target closed/i.test(o)||/Session closed/i.test(o)||/Connection closed/i.test(o)||/Most likely the page has been closed/i.test(o)||/Navigating frame was detached/i.test(o)||/Protocol error.*timed out/i.test(o)}async function Zr(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await Et(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function ei(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await Zr(e,t)?!0:(await w(o),await Zr(e,t))}async function ti(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await Et(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function oi(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){try{await Et(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let s=await e.newPage();if(i)try{await i(s)}catch{}if(n)try{let a=n();Array.isArray(a)&&a.length>0&&await s.setCookie(...a)}catch{}if(o){await s.goto(o,{waitUntil:"domcontentloaded",timeout:r});let a=s.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(a))throw new Error(`Session expired after recovery \u2014 landed on ${a}. Run: ilml linkedin login`)}return s}async function ni(e,{launchFn:t,returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");let s=null;try{s=e.process()}catch{}let a=!1;try{await Et(e.close(),5e3,"oldBrowser.close"),a=!0}catch{}if(!a&&s&&s.pid&&s.exitCode===null){try{s.kill("SIGKILL")}catch{}try{await Et(new Promise(u=>s.once("exit",u)),5e3,"oldBrowser.kill")}catch{}}let l=await t(),c=await l.newPage();if(i)try{await i(c)}catch{}if(n)try{let u=n();Array.isArray(u)&&u.length>0&&await c.setCookie(...u)}catch{}if(o){await c.goto(o,{waitUntil:"domcontentloaded",timeout:r});let u=c.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(u))throw new Error(`Session expired after browser restart \u2014 landed on ${u}. Run: ilml linkedin login`)}return{browser:l,page:c}}await qr();var ro=0,jl=process.env.FUNNEL_CONNECT_RECRUITERS==="true",Ll=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Nl=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),Pl=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",tn=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],eo=-1;async function Fl(){if(eo===-1){let e=await He("What is last counter? Answer only number!!");if(console.log(`Lifebot answered about lastIndex:${e}`),!/^\d+$/.test(e.trim()))throw new Error(`Last Counter is not a number, got: "${e}"`);eo=En(e)+1,console.log(`lastIndex initialized as: ${eo}`)}return eo++}var mi=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${mi}`);var Ol=[{label:"linkedin-session-expired",match:e=>/redirected to login|cookies expired|Session expired after recovery/i.test(e.message),severity:"fatal",instructions:"Run: ilml linkedin login"},{label:"ilml-auth-expired",match:e=>{if(e.code==="PROCESSING_ERROR"||e.constructor?.name==="LifebotProcessingError")return!1;let t=e.message||"";return/Token is invalid or expired/i.test(t)||/\b401\b/.test(t)||/Unauthorized/i.test(t)||/authentication.*(failed|required)/i.test(t)},severity:"fatal",instructions:"Run: ilml login (this is the iLiveMyLife platform login, not the LinkedIn one)"},{label:"lifebot-timeout",match:e=>e.constructor.name==="LifebotTimeoutError",severity:"transient",maxConsecutive:3,cleanup:"popup"},{label:"lifebot-provider-error",match:e=>e.code==="PROCESSING_ERROR"||e.constructor.name==="LifebotProcessingError"||/AI provider returned an unexpected error/i.test(e.message||""),severity:"transient",maxConsecutive:3,cleanup:"popup",cooldownMs:3e3,instructions:"The AI provider had a hiccup. If it keeps failing, switch the provider in your Lifebot node settings."},{label:"stale-context",match:e=>/Execution context was destroyed|Cannot find context/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3}],Ct={};function hi(e){let t=e;for(let o=0;t&&o<5;o++){let r=Ol.find(n=>{try{return n.match(t)}catch{return!1}});if(r)return r;t=t.cause}return null}function ql(e){return Ct[e]=(Ct[e]||0)+1,Ct[e]}function si(){for(let e of Object.keys(Ct))Ct[e]=0}var on=0;function Ml(){return on++,on>=mi?(console.log(`Max run counter reached with ${on}`),!1):!0}async function Ul(e){let t=await Er(e)}async function Bl(e){return Cr(e,{easyApplyOnly:!0})}async function Jl(e){return Ar(e)}async function sn(e,t){return Mo(e,t)}var nn=3,Hl=2;async function oo(e,t){let{searchUrl:o,launchFn:r,setupPage:n,cookiesProvider:i}=e.recoveryCtx,s=await ti(e.browser);if(!s||e._pageRecoveryStreak>=nn){if(k.browserRestarts>=Hl)throw new Error(`CDP unrecoverable: ${k.browserRestarts} browser restart${k.browserRestarts===1?"":"s"} and ${k.cdpRecoveries} page recover${k.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let l=s?`${nn} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${l}). Reason: ${t}`);let c=await ni(e.browser,{launchFn:r,setupPage:n,cookiesProvider:i,returnUrl:o});e.browser=c.browser,e.page=c.page,e._pageRecoveryStreak=0,k.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${k.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${nn}). Reason: ${t}`),e.page=await oi(e.browser,e.page,{returnUrl:o,cookiesProvider:i,setupPage:n}),e._pageRecoveryStreak+=1,k.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${k.cdpRecoveries}).`)}async function Vl(e){let{searchUrl:t}=e.recoveryCtx,o=3;e._pageRecoveryStreak=e._pageRecoveryStreak||0;for(let r=1;r<=o;r++){if(r>1){console.log(`
298
- --- Pass ${r}/${o}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(u){if(rt(u))await oo(e,`pass-${r} navigation: ${u.message?.slice(0,80)}`);else throw u}await w(3e3)}let n=k.submitted,i=k.cdpRecoveries+k.browserRestarts,s=!0,a=!0;for(;s&&a;){if(!await ei(e.page)){await oo(e,"liveness probe failed twice");continue}try{await sn(e.page,t);let f=await sa(e.page,gi,Ul);a=f.keepGoing;let d=f.jobsDone;if(console.log("keepGoing",a),console.log("pageDone"),console.log(d.length),!a)break;s=await Jl(e.page),e._pageRecoveryStreak=0}catch(f){if(!rt(f))throw f;await oo(e,`mid-iteration: ${f.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!a)break;let l=k.submitted-n,c=k.cdpRecoveries+k.browserRestarts-i;if(l===0){if(c>0&&r<o){console.log(`No new jobs applied in pass ${r}, but ${c} CDP recover${c===1?"y":"ies"} \u2014 pass ${r+1} will retry.`);continue}console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${l} new jobs in pass ${r}.`)}}async function li(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return _r(e,t,o,r)}async function ai(e,t){let o=t?.match(/\d+/)?.[0]||t,r=await e.$(`div[data-job-id="${o}"] button[aria-label^="Dismiss"]`);r?(await r.click(),console.log(` Dismissed job ${o} from list`)):console.log(` Dismiss button not found for ${o}`)}async function Gl(e,t){try{let o=await $r(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},at("recruiters-from-jobs",o)?(ro++,console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F3AF} RECRUITER FOUND \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Name: ${o.name?.substring(0,30).padEnd(30)} \u2502`),console.log(`\u2502 Source: ${o.source.padEnd(28)} \u2502`),console.log(`\u2502 Company: ${t.companyName?.substring(0,27).padEnd(27)} \u2502`),console.log(`\u2502 Total today: ${String(ro).padEnd(23)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")):console.log(` \u2139 Recruiter already saved: ${o.name}`),xe(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){Ft(o.profileUrl,n),ze(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let i=o.fromJob?.companyUrl;i&&Wt(i,{recruiterUrl:o.profileUrl,jobId:n})}return o}else console.log(" \u26AA No recruiter found on this job page");return null}catch(o){return console.error("Error extracting recruiter:",o.message),null}}async function no(e){return await e.evaluate(()=>{let t=document.body.innerText||"",o=document.querySelector("#interop-outlet")?.shadowRoot?.textContent||"",r=t+" "+o;return r.includes("We limit daily submissions")||r.includes("We limit Easy Apply submissions")||r.includes("Easy Apply limit")||r.includes("reached today")||r.includes("apply tomorrow")})}async function yi(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let n of o){let i=n.querySelectorAll("button");for(let s of i){let a=s.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return s.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return t&&console.log(" Daily limit popup closed"),t}catch{return!1}}async function ci(e){await e.evaluate(()=>{let s=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of s)for(let l of a.querySelectorAll("button")){let c=l.innerText?.trim();if(c==="Continue applying"||c==="Got it"||c==="Dismiss"){l.click();return}}});let t=Date.now(),o=3e3,r=null;for(;!r&&Date.now()-t<o;){if(r=await e.$(".jobs-apply-button"),r||(r=await e.$('button[aria-label*="Easy Apply"]')),r||(r=await e.$('a[aria-label*="Easy Apply"]')),r||(r=await e.$('a[href*="/apply/"]')),!r){let s=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let l of a){let c=l.innerText?.trim();if(c==="Easy Apply"||c==="Apply")return l}return null});r=s?.asElement?.()||null,r||await s.dispose().catch(()=>{})}r||await new Promise(s=>setTimeout(s,300))}let n=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${n>400?` (waited ${n}ms)`:""}`),r){if(await e.evaluate(c=>c.disabled,r))return await no(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(c=>c.tagName==="A",r)){await e.evaluate(c=>c.click(),r),await w(3e3);try{await e.waitForFunction(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[data-easy-apply-next-button], button[aria-label="Submit application"]'),{timeout:1e4})}catch{await w(2e3)}}else await r.click(),await w(1500);return await no(e)?(await yi(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await no(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function Wl(e){return await e.evaluate(async()=>{function t(){let l=document.querySelectorAll(".artdeco-inline-feedback__message");if(l.length>0)return l;let c=document.querySelector("#interop-outlet")?.shadowRoot;return c&&(l=c.querySelectorAll(".artdeco-inline-feedback__message")),l}let o=3e3,r=t();if(r?.length===0&&(await new Promise(l=>setTimeout(l,o)),r=t()),r?.length===0)return null;let n=r[0];console.log("errorMsg"),console.log(n);let i=n?.textContent.trim(),s=n.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=n.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(s),a||s){console.log("parentElement"),console.log(a);let l=a.querySelector(".artdeco-text-input--label")||a.querySelector("legend .fb-dash-form-element__label-title--is-required")||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||a.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),c=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),u=a.querySelectorAll('input[type="radio"]'),f=a.querySelector("select[data-test-text-entity-list-form-select]"),d=n.parentElement.parentElement.querySelector('input[type="file"]'),p=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(d),l&&c)return{type:"input",labelText:l.textContent.trim(),errorMsgText:i};if(l&&u.length){let m=l?l.querySelector("span:nth-of-type(1)")?.textContent.trim():null,h=Array.from(u).map(y=>{let x=(document.querySelector(`label[for="${y.id}"]`)||y.nextElementSibling)?.textContent?.trim();return{value:y.value,label:x||y.value}}),g=h.map(y=>y.label);return{type:"radio",labelText:m,errorMsgText:i,options:g,optionsData:h}}else if(f){let m=a.querySelector('label[for="'+f.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),h=m?m.querySelector("span:nth-of-type(2)")?.textContent.trim():null,g=Array.from(f.options).map(y=>y.value).filter(y=>y!=="Select an option");return{type:"select",labelText:h,errorMsgText:i,options:g}}else if(d){let m=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:i,labelText:m}}else{if(p)return{type:"datePicker",errorMsgText:i};{let m=l?l.querySelector("span:nth-of-type(2)")?.textContent.trim():null,h=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(h.length>0){let g=Array.from(h).map(y=>y.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:m,errorMsgText:i,options:g}}else return null}}}return null})}async function Yl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));l.value=n;let c=new Event("input",{bubbles:!0});if(l.dispatchEvent(c),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let u=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},f=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),f(p),await new Promise(m=>setTimeout(m,100)),u(p)})(l)}}return null},t,o)}async function Kl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('input[type="radio"]'),c=n;if(r.optionsData){let u=r.optionsData.find(f=>f.label.toLowerCase()===n.toLowerCase());u&&(c=u.value,console.log(`Radio: matched label "${n}" to value "${c}"`))}for(let u of l){let d=(document.querySelector(`label[for="${u.id}"]`)||u.nextElementSibling)?.textContent?.trim()||"";if(u.value.toLowerCase()===c.toLowerCase()||d.toLowerCase()===n.toLowerCase()){u.checked=!0;let p=new Event("change",{bubbles:!0});u.dispatchEvent(p),console.log(`Radio selected: value="${u.value}", label="${d}"`);break}}}return null},t,o)}async function zl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector("select[data-test-text-entity-list-form-select]");if(!l)return null;let c=Array.from(l.options),u=c.find(d=>d.text.toLowerCase()===n.toLowerCase())||c.find(d=>d.text.toLowerCase().includes(n.toLowerCase()));u?l.value=u.value:l.value=n;let f=new Event("change",{bubbles:!0});l.dispatchEvent(f)}return null},t,o)}async function Ql(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');l.length>0&&l.forEach(c=>{if(c.nextElementSibling.textContent.trim()===n.trim()){c.checked=!0;let u=new Event("change",{bubbles:!0});c.dispatchEvent(u)}})}return null},t,o)}async function Xl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i?.length===0)return null;let s=i[0],a=s.closest(".fb-dash-form-element"),l=s.parentElement.parentElement.querySelector('input[type="file"]');if(a&&l){async function c(u,f,d){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let m=new Blob([new Uint8Array(f)]),h=new File([m],d,{type:"application/pdf"}),g=new DataTransfer;g.items.add(h),u.files=g.files;let y=new Event("change",{bubbles:!0});u.dispatchEvent(y)}await c(l,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function ui(e){let t=await Wl(e);if(t===null)return null;if(t?.type==="input"){let n=await uo(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await Yl(e,t,n)}else if(t?.type==="radio"){let n=await Tt(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[];!i.find(a=>a.toLowerCase()===n?.toLowerCase())&&i.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await Tt(t.labelText,t.options),n=n?.trim()||n,i.find(l=>l.toLowerCase()===n?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])),t.answer=n,await Kl(e,t,n)}else if(t?.type==="select"){let n=await st(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[],s=i.find(a=>a.toLowerCase()===n?.toLowerCase());if(s)n=s;else if(i.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await st(t.labelText,t.options),n=n?.trim()||n;let a=i.find(l=>l.toLowerCase()===n?.toLowerCase());a?n=a:(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])}t.answer=n,await zl(e,t,n)}else if(t?.type==="checkbox"){let n=await st(t.labelText,t.options);t.answer=n,await Ql(e,t,n)}else if(t?.type==="file"){let n=process.env.RESUME_PDF_URL;t.answer=n;let i=await fetch(n);if(!i.ok)throw new Error("Network response was not ok");let s=await i.arrayBuffer();await Xl(e,t,s)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let o=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${o}" \u2192 ${r}`),t}async function Zl(e){return await e.evaluate(async()=>{let t=[],o=document.querySelectorAll(".fb-dash-form-element");if(!o||o.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(o=r.querySelectorAll(".fb-dash-form-element"))}if(!o||o.length===0)return[];for(let r of o){let n=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),s=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),l=r.querySelector("select[data-test-text-entity-list-form-select]"),c=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),u=r.querySelector('input[type="file"]');if(n&&s&&a.length===0){let f=n.textContent.trim();t.push({type:"input",labelText:f,answer:s.value,isRequired:i,wasPreFilled:!!s.value})}else if(n&&a.length){let f=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,d=Array.from(a).map(m=>m.value),p=(Array.from(a).find(m=>m.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:f,options:d,answer:p,isRequired:i,wasPreFilled:!!p})}else if(l){let f=r.querySelector('label[for="'+l.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),d=f?.querySelector("span:nth-of-type(2)")?.textContent.trim()||f?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||f?.querySelector("span")?.textContent.trim()||f?.textContent?.trim()||null,p=Array.from(l.options).map(h=>h.value).filter(h=>h!=="Select an option"),m=l.value!=="Select an option"?l.value:"";t.push({type:"select",labelText:d,options:p,answer:m,isRequired:i,wasPreFilled:!!m})}else if(c.length>0){let f=r.querySelector("legend span")?.textContent?.trim(),d=Array.from(c).map(h=>({label:h.nextElementSibling?.textContent?.trim()||h.value,checked:h.checked})),p=d.some(h=>h.checked),m=d.filter(h=>h.checked).map(h=>h.label).join(", ");t.push({type:"checkbox",labelText:f,options:d.map(h=>h.label),answer:m,isRequired:i,wasPreFilled:p})}else if(u){let f=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:f,answer:u.value?"uploaded":"",isRequired:i,wasPreFilled:!!u.value})}}return t})}async function ln(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelector(".artdeco-text-input--label")||s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||s.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),l=s.querySelector(".artdeco-text-input--input")||s.querySelector("input");if(a&&l&&r===a.textContent.trim()){l.value=n;let c=new Event("input",{bubbles:!0});if(l.dispatchEvent(c),r==="City"||r==="Location (city)"){let u=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},f=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),f(p),await new Promise(m=>setTimeout(m,100)),u(p)})(l)}return!0}}return!1},t,o)}async function ea(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelectorAll('input[type="radio"]');if(a.length===0)continue;let l=s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('legend [class*="fb-dash-form-element__label"]')||s.querySelector("legend span");if((l?.querySelector("span:nth-of-type(1)")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let u=(n||"").toLowerCase();for(let f of a){let d=f.getRootNode(),m=(f.id&&d.querySelector(`label[for="${f.id}"]`)||f.nextElementSibling)?.textContent?.trim()||"";if(f.value.toLowerCase()===u||m.toLowerCase()===u)return f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function ta(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelector("select[data-test-text-entity-list-form-select]");if(!a)continue;let l=s.querySelector(`label[for="${a.id}"]`)||s.querySelector(".fb-dash-form-element__label-title--is-required");if((l?.querySelector("span:nth-of-type(2)")?.textContent.trim()||l?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||l?.querySelector("span")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let u=Array.from(a.options),f=(n||"").toLowerCase(),d=u.find(p=>p.text.toLowerCase()===f)||u.find(p=>p.value.toLowerCase()===f)||u.find(p=>p.text.toLowerCase().includes(f));return d?(a.value=d.value,a.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function oa(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let a=document.querySelector("#interop-outlet")?.shadowRoot;a&&(i=a.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;let s=(n||"").split(",").map(a=>a.trim().toLowerCase()).filter(Boolean);if(s.length===0)return!1;for(let a of i){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(l.length===0||a.querySelector("legend span")?.textContent?.trim()!==r)continue;let u=!1;for(let f of l){let d=(f.nextElementSibling?.textContent||f.value||"").trim().toLowerCase();s.includes(d)&&!f.checked&&(f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),u=!0)}return u}return!1},t,o)}async function na(e,t){for(let o of t){if(!o.labelText||o.isRequired||o.wasPreFilled||o.answer||o.type==="datePicker"||o.type==="file")continue;let r="";try{if(o.type==="input")r=await uo(o.labelText,"");else if(o.type==="radio")r=await Tt(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await st(o.labelText,o.options||[]);else continue}catch(s){console.log(` \u26A0 Lifebot failed for optional "${o.labelText}": ${s.message?.slice(0,80)}`);continue}if(r=(r||"").trim(),o.wasOptional=!0,!r){o.answer="",console.log(` ? [opt ${o.type}] "${o.labelText.slice(0,55)}" \u2192 (empty)`);continue}let n=!1;try{o.type==="input"?n=await ln(e,o.labelText,r):o.type==="radio"?n=await ea(e,o.labelText,r):o.type==="select"?n=await ta(e,o.labelText,r):o.type==="checkbox"&&(n=await oa(e,o.labelText,r))}catch(s){console.log(` \u26A0 setter failed for "${o.labelText}": ${s.message?.slice(0,80)}`)}o.answer=r,console.log(` ? [${n?"opt":"opt-noapply"} ${o.type}] "${o.labelText.slice(0,55)}" \u2192 "${r.slice(0,50)}"`)}}async function di(e,t){let o=[],r=!0,n=0,i=null,s=0;for(;r;){if(n++,await no(e))return console.log(" Daily limit reached during form navigation"),await yi(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let c=(await Zl(e)).filter(p=>!o.some(m=>m.labelText===p.labelText));o.push(...c);try{let p=o.find(h=>h.labelText==="City"||h.labelText==="Location (city)"),m=o.filter(h=>h.labelText!=null).find(h=>h.labelText!==null&&h.labelText.trim()!==null&&(h.labelText.trim().toLowerCase()==="cv"||h.labelText.trim().toLowerCase()==="curriculum vitae"||h.labelText.trim().toLowerCase()==="cover letter"||h.labelText.trim().toLowerCase()==="cover"));if(p&&!p.answer){let h=process.env.City;await ln(e,p.labelText,h),p.answer=h}else if(m){let h=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!m.answer||m.answer!==h)&&(await w(1e4),await ln(e,m.labelText,h),m.answer=h,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await na(e,c)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let u=null;try{u=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(u!==null){if(u.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:u};let p=u&&o.find(h=>h.errorMsgText&&h.labelText===u.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(u,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:u};let m=o.findIndex(h=>h.labelText===u.labelText&&!h.answer);m!==-1&&o.splice(m,1),o.push(u)}let f=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of p){let h=m.querySelectorAll("button");for(let g of h){let y=g.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return g.click(),y}}return null});f&&console.log(` Dismissed safety popup (${f})`);let d=await e.evaluate(async()=>{function p(b){let C=document.querySelector(b);if(C)return C;let R=document.querySelector("#interop-outlet")?.shadowRoot;return R?R.querySelector(b):null}function m(b){let C=document.querySelectorAll(b),R=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(b);return[...C||[],...R||[]]}let h=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(b=>b.innerText?.trim()==="Next"),g=m('footer[role="presentation"] button').some(b=>b.innerText.trim()==="Review")||m("button").some(b=>b.innerText.trim()==="Review"&&b.getAttribute("aria-label")?.includes("Review")),y=p('button[aria-label="Submit application"]'),S=async()=>{let b=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(C=>C.innerText?.trim()==="Next");b?b.click():console.log("Next button not found")},x=()=>{let b=m("button").find(C=>C.innerText?.trim()==="Review");b&&b.click()};return h?(await S(),{type:"next"}):g?(await x(),{type:"review"}):y?{type:"submit"}:{type:null}});if(d==null)return{filledFields:o,formPages:n,skip:!0};if(d.type&&console.log(` \u2192 ${d.type}`),d.type===null){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of m){let g=h.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of g){let S=y.innerText||"";if(S.includes("application was sent")||S.includes("resume into a profile")||S.includes("Application submitted")||S.includes("Next best action"))for(let x of y.querySelectorAll("button")){let b=x.innerText?.trim();if(b==="Not now"||b==="Done"||b==="Dismiss"||b==="Got it")return x.click(),b}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await w(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(s===0){let m=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],y=[];for(let S of h){for(let b of S.querySelectorAll("button")){let C=b.innerText?.trim();C&&C.length<60&&g.push(C)}let x=S.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');x&&y.push(x.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(m.buttons)}`),m.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(m.modalText)}`)}}if(d.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(u===null&&d.type===i?s++:s=0,i=d.type,s>=5){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),h=[],g=[];for(let y of m){for(let S of y.querySelectorAll(".artdeco-inline-feedback__message"))h.push(S.textContent?.trim()?.slice(0,60));for(let S of y.querySelectorAll(".fb-dash-form-element")){let x=S.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),b=S.querySelector("input, select, textarea"),C=!!S.querySelector(".artdeco-inline-feedback__message");x&&(C||b&&!b.value)&&g.push({label:x.slice(0,40),hasError:C,value:b?.value?.slice(0,20)||""})}}return{errors:h,emptyRequired:g.slice(0,5)}});return console.error(` \u26A0 Stuck on "${d.type}" for ${s} iterations \u2014 form not progressing.`),p.errors.length&&console.error(` Visible errors: ${JSON.stringify(p.errors)}`),p.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(p.emptyRequired)}`),console.error(" Skipping job."),{filledFields:o,formPages:n,skip:!0,duplicateField:{labelText:`stuck_on_${d.type}`}}}await w(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function fi(e){try{await e.evaluate(()=>{let t=document.getElementById("follow-company-checkbox");t?(t.checked=!1,t.dispatchEvent(new Event("change",{bubbles:!0}))):console.warn("Unfollow checkbox not found.")})}catch(t){console.error("Error in unfollowJobCheckbox:",t)}}async function ra(e){let t=await e.$('button[aria-label="Submit application"]');if(!t){let o=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Submit application"]')||null);t=o?.asElement?.()||null,t||await o.dispose().catch(()=>{})}t&&await t.click()}async function ia(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of o){for(let i of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(i.innerText?.trim()==="Done")return i.click(),"Done";let n=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let i of n){let s=i.innerText||"";if(s.includes("application was sent")||s.includes("Application sent")||s.includes("resume into a profile")||s.includes("Next best action"))for(let a of i.querySelectorAll("button")){let l=a.innerText?.trim();if(l==="Not now"||l==="Dismiss")return a.click(),l}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await w(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function to(e){try{await e.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let t=await e.$('button[aria-label="Dismiss"]');t?(await t.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await w(1e3)):console.log("Popup \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.")}catch{console.log("closeJobApplicationPopup failed to execute: \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D \u0438\u043B\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F.")}}async function rn(e){try{await e.waitForSelector('button[data-control-name="discard_application_confirm_btn"]',{timeout:3e3});let t=await e.$('button[data-control-name="discard_application_confirm_btn"]');t&&(await t.click(),console.log("Discard confirmed"),await w(500))}catch{console.log("No discard confirmation needed")}}async function gi(e,t){let o=[],r=t._fromQueue;try{k.attempted++,console.log(`
299
- --- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&jo(n)?.status==="applied")return k.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (our DB): ${t.jobTitle} \u2014 skipping`),{keepGoing:!0};let i=null;if(!r){let d=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name")?.innerText?.trim()?.replace(/\s+/g," ")?.toLowerCase()||""),p=(t.companyName||"").replace(/\s+/g," ").toLowerCase().trim(),m=d.split(" ")[0],h=p.split(" ")[0];if(m&&h&&!d.includes(h)&&!p.includes(m))return k.mismatch++,console.log(` \u2298 MISMATCH: expected company "${t.companyName}" but panel shows "${d}"`),console.log(` job title: "${t.jobTitle}"`),{keepGoing:!0};if(await e.evaluate(()=>{let y=document.querySelector(".jobs-details__main-content, .job-details-jobs-unified-top-card");if(!y)return!1;let S=y.innerText;return/Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago/i.test(S)||S.includes("Application submitted")}))return k.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${t.jobTitle} \u2014 skipping`),n&&Fe(n,"applied",{source:"detected"}),{keepGoing:!0};try{i=await Tr(e)}catch{}}let s=await ci(e);if(s.dailyLimitReached){console.log(`
298
+ `)}`;try{await Se.addMessage(s,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var jl=Dl(import.meta.url),Ll=Re.dirname(Re.dirname(jl)),zo=process.env.DATA_DIR?Re.resolve(process.env.DATA_DIR,"collected-profiles"):Re.join(Ll,"collected-profiles"),Qo=Re.join(zo,"run-log.json");function Nl(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";de.writeFileSync(r,o);for(let n=0;n<3;n++)try{de.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Yr(){try{if(!de.existsSync(Qo))return{runs:[]};let e=JSON.parse(de.readFileSync(Qo,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Kr(e){de.existsSync(zo)||de.mkdirSync(zo,{recursive:!0});try{Nl(Qo,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function zr(e,t="default"){let o=Yr();for(let s of o.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let r=new Date,n={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(s=>new Date(s.timestamp).getTime()>i),Kr(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Qr(e,t,o=null,r=null){if(!e)return;let n=null;try{let s=Yr(),c=s.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=o,c.error=r,n=c.duration;else{let l=s.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=r,n=l.duration)}Kr(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Wr({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:r,duration:n??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}It();It();import Xo from"fs";import ql from"path";var Pl={headless:!1,defaultViewport:null,protocolTimeout:3e5},$t=new Set,Xr=!1;async function no(){let e=[...$t].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});$t.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Ol(){if(Xr)return;Xr=!0;let e=t=>async()=>{await no(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await no(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await no(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await no(),process.exit(0))}),process.on("exit",()=>{for(let t of $t)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function Zo(e){return ql.join(e,".ilml-browser-session.json")}function oi(e,t={}){try{Xo.writeFileSync(Zo(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Fl(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();oi(e,o?{wsEndpoint:o}:{})}catch{}}function Ml(e){let t=ni(e);t&&t.ownerPid===process.pid&&Ct(e)}function Ct(e){try{Xo.rmSync(Zo(e),{force:!0})}catch{}}function ni(e){try{return JSON.parse(Xo.readFileSync(Zo(e),"utf-8"))}catch{return null}}function Zr(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function ei(e,t,o){let r,n=new Promise(s=>{r=setTimeout(()=>s(o),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(r),s),s=>{throw clearTimeout(r),s});return Promise.race([i,n])}async function ti(e,t,{probeTimeoutMs:o=4e3}={}){let r=ni(t);if(!r)return"free";if(!r.wsEndpoint)return r.ownerPid&&r.ownerPid!==process.pid&&Zr(r.ownerPid)?"live":(Ct(t),"free");let n=Symbol("timeout"),i=e.connect({browserWSEndpoint:r.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await ei(i,o,n);if(s===n)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return Ct(t),"free";if(Zr(r.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await ei(s.close().then(()=>!0).catch(()=>!1),o,!1))return Ct(t),"free";try{s.disconnect()}catch{}return"live"}function Ul(e,t){e&&(Ol(),$t.add(e),e.on("disconnected",()=>{$t.delete(e),t&&Ct(t)}))}async function en(e,t={}){let o=wn(),r={...Pl,...t,userDataDir:o},n=`Could not open the LinkedIn automation Chrome profile at ${o}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await ti(e,o)==="live")throw new Error(n);oi(o);let i;try{i=await e.launch(r)}catch{if(await ti(e,o)==="live")throw new Error(n);xn(o);try{i=await e.launch(r)}catch(c){throw Ml(o),new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return Ul(i,o),Fl(o,i),{browser:i,profileDir:o,needsSeed:kn(o)}}async function ri(e,t){if(!t||!t.needsSeed)return!1;if(!gn())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...Rt()),vn(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}Je();async function _t(e,t,o="op"){let r,n=new Promise((i,s)=>{r=setTimeout(()=>s(new Error(`${o} timeout after ${t}ms`)),t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}function rt(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let o=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(o)||/Target closed/i.test(o)||/Session closed/i.test(o)||/Connection closed/i.test(o)||/Most likely the page has been closed/i.test(o)||/Navigating frame was detached/i.test(o)||/Protocol error.*timed out/i.test(o)}async function ii(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await _t(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function si(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await ii(e,t)?!0:(await k(o),await ii(e,t))}async function li(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await _t(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function ai(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){try{await _t(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let s=await e.newPage();if(i)try{await i(s)}catch{}if(n)try{let c=n();Array.isArray(c)&&c.length>0&&await s.setCookie(...c)}catch{}if(o){await s.goto(o,{waitUntil:"domcontentloaded",timeout:r});let c=s.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(c))throw new Error(`Session expired after recovery \u2014 landed on ${c}. Run: ilml linkedin login`)}return s}async function ci(e,{launchFn:t,returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");let s=null;try{s=e.process()}catch{}let c=!1;try{await _t(e.close(),5e3,"oldBrowser.close"),c=!0}catch{}if(!c&&s&&s.pid&&s.exitCode===null){try{s.kill("SIGKILL")}catch{}try{await _t(new Promise(u=>s.once("exit",u)),5e3,"oldBrowser.kill")}catch{}}let l=await t(),a=await l.newPage();if(i)try{await i(a)}catch{}if(n)try{let u=n();Array.isArray(u)&&u.length>0&&await a.setCookie(...u)}catch{}if(o){await a.goto(o,{waitUntil:"domcontentloaded",timeout:r});let u=a.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(u))throw new Error(`Session expired after browser restart \u2014 landed on ${u}. Run: ilml linkedin login`)}return{browser:l,page:a}}await Gr();var ao=0,Bl=process.env.FUNNEL_CONNECT_RECRUITERS==="true",Jl=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Hl=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),Gl=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",tn=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],ro=-1;async function Vl(){if(ro===-1){let e=await je("What is last counter? Answer only number!!");if(console.log(`Lifebot answered about lastIndex:${e}`),!/^\d+$/.test(e.trim()))throw new Error(`Last Counter is not a number, got: "${e}"`);ro=En(e)+1,console.log(`lastIndex initialized as: ${ro}`)}return ro++}var wi=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${wi}`);var Wl=[{label:"linkedin-session-expired",match:e=>/redirected to login|cookies expired|Session expired after recovery/i.test(e.message),severity:"fatal",instructions:"Run: ilml linkedin login"},{label:"ilml-auth-expired",match:e=>{if(e.code==="PROCESSING_ERROR"||e.constructor?.name==="LifebotProcessingError")return!1;let t=e.message||"";return/Token is invalid or expired/i.test(t)||/\b401\b/.test(t)||/Unauthorized/i.test(t)||/authentication.*(failed|required)/i.test(t)},severity:"fatal",instructions:"Run: ilml login (this is the iLiveMyLife platform login, not the LinkedIn one)"},{label:"lifebot-timeout",match:e=>e.constructor.name==="LifebotTimeoutError",severity:"transient",maxConsecutive:3,cleanup:"popup"},{label:"lifebot-provider-error",match:e=>e.code==="PROCESSING_ERROR"||e.constructor.name==="LifebotProcessingError"||/AI provider returned an unexpected error/i.test(e.message||""),severity:"transient",maxConsecutive:3,cleanup:"popup",cooldownMs:3e3,instructions:"The AI provider had a hiccup. If it keeps failing, switch the provider in your Lifebot node settings."},{label:"stale-context",match:e=>/Execution context was destroyed|Cannot find context/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3}],Tt={};function Si(e){let t=e;for(let o=0;t&&o<5;o++){let r=Wl.find(n=>{try{return n.match(t)}catch{return!1}});if(r)return r;t=t.cause}return null}function Yl(e){return Tt[e]=(Tt[e]||0)+1,Tt[e]}function di(){for(let e of Object.keys(Tt))Tt[e]=0}var on=0;function Kl(){return on++,on>=wi?(console.log(`Max run counter reached with ${on}`),!1):!0}async function zl(e){let t=await Rr(e)}async function Ql(e){return Ir(e,{easyApplyOnly:!0})}async function Xl(e){return Dr(e)}async function ln(e,t){return Mo(e,t)}var nn=3,Zl=2;async function so(e,t){let{searchUrl:o,launchFn:r,setupPage:n,cookiesProvider:i}=e.recoveryCtx,s=await li(e.browser);if(!s||e._pageRecoveryStreak>=nn){if($.browserRestarts>=Zl)throw new Error(`CDP unrecoverable: ${$.browserRestarts} browser restart${$.browserRestarts===1?"":"s"} and ${$.cdpRecoveries} page recover${$.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let l=s?`${nn} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${l}). Reason: ${t}`);let a=await ci(e.browser,{launchFn:r,setupPage:n,cookiesProvider:i,returnUrl:o});e.browser=a.browser,e.page=a.page,e._pageRecoveryStreak=0,$.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${$.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${nn}). Reason: ${t}`),e.page=await ai(e.browser,e.page,{returnUrl:o,cookiesProvider:i,setupPage:n}),e._pageRecoveryStreak+=1,$.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${$.cdpRecoveries}).`)}async function ea(e){let{searchUrl:t}=e.recoveryCtx,o=3;e._pageRecoveryStreak=e._pageRecoveryStreak||0;for(let r=1;r<=o;r++){if(r>1){console.log(`
299
+ --- Pass ${r}/${o}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(u){if(rt(u))await so(e,`pass-${r} navigation: ${u.message?.slice(0,80)}`);else throw u}await k(3e3)}let n=$.submitted,i=$.cdpRecoveries+$.browserRestarts,s=!0,c=!0;for(;s&&c;){if(!await si(e.page)){await so(e,"liveness probe failed twice");continue}try{await ln(e.page,t);let d=await ya(e.page,xi,zl);c=d.keepGoing;let f=d.jobsDone;if(console.log("keepGoing",c),console.log("pageDone"),console.log(f.length),!c)break;s=await Xl(e.page),e._pageRecoveryStreak=0}catch(d){if(!rt(d))throw d;await so(e,`mid-iteration: ${d.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!c)break;let l=$.submitted-n,a=$.cdpRecoveries+$.browserRestarts-i;if(l===0){if(a>0&&r<o){console.log(`No new jobs applied in pass ${r}, but ${a} CDP recover${a===1?"y":"ies"} \u2014 pass ${r+1} will retry.`);continue}console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${l} new jobs in pass ${r}.`)}}async function fi(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;for(let i of t){if(i.isApplied||i.alreadyApplied)continue;let s=i.id?.match(/\d+/)?.[0],c=s?At(s)?.status:null;(c==="applied"||c==="dismissed"||c==="skipped")&&(i.alreadyApplied=!0)}let n=await jr(e,t,o,r);try{let i=t.map(s=>s.id?.match(/\d+/)?.[0]).filter(s=>s&&At(s)?.status==="dismissed");if(i.length&&e.isConnected?.()!==!1){e.url().includes("/jobs/search")||(await e.goto(r,{waitUntil:"domcontentloaded",timeout:6e4}).catch(()=>{}),await k(2500));for(let s of i)await ki(e,s)}}catch(i){console.log(` end-of-scan dismiss skipped: ${i.message?.slice(0,60)}`)}return n}async function ki(e,t){let o=t?.match(/\d+/)?.[0]||t;if(!o){console.log(" Dismiss: no jobId");return}let r="error";try{r=await e.evaluate(n=>{let s=[...document.querySelectorAll('button[aria-label^="Dismiss"]')].find(c=>{let l=c.closest('[componentkey^="job-card-component-ref-"]');return l&&(l.getAttribute("componentkey")||"").includes(n)});return s?(s.click(),"dismissed"):"no-target"},o)}catch(n){r=`err:${n.message?.slice(0,40)}`}console.log(` Dismiss ${o}: ${r}`)}async function ta(e,t){try{let o=await Lr(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},dt("recruiters-from-jobs",o)?(ao++,console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F3AF} RECRUITER FOUND \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Name: ${o.name?.substring(0,30).padEnd(30)} \u2502`),console.log(`\u2502 Source: ${o.source.padEnd(28)} \u2502`),console.log(`\u2502 Company: ${t.companyName?.substring(0,27).padEnd(27)} \u2502`),console.log(`\u2502 Total today: ${String(ao).padEnd(23)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")):console.log(` \u2139 Recruiter already saved: ${o.name}`),Ae(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){Ut(o.profileUrl,n),ze(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let i=o.fromJob?.companyUrl;i&&Qt(i,{recruiterUrl:o.profileUrl,jobId:n})}return o}else console.log(" \u26AA No recruiter found on this job page");return null}catch(o){return console.error("Error extracting recruiter:",o.message),null}}async function lo(e){return await e.evaluate(()=>{let t=(document.body&&document.body.innerText||"")+" "+(document.querySelector("#interop-outlet")?.shadowRoot?.textContent||"");return/we limit easy apply submissions/i.test(t)||/reached today'?s easy apply limit/i.test(t)||/reached your (daily )?easy apply limit/i.test(t)||/continue applying tomorrow/i.test(t)})}async function vi(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let n of o){let i=n.querySelectorAll("button");for(let s of i){let c=s.innerText?.trim();if(c==="Got it"||c==="OK"||c==="Done")return s.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return t&&console.log(" Daily limit popup closed"),t}catch{return!1}}async function pi(e){await e.evaluate(()=>{let s=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let c of s)for(let l of c.querySelectorAll("button")){let a=l.innerText?.trim();if(a==="Continue applying"||a==="Got it"||a==="Dismiss"){l.click();return}}});let t=Date.now(),o=3e3,r=null;for(;!r&&Date.now()-t<o;){if(r=await e.$(".jobs-apply-button"),r||(r=await e.$('button[aria-label*="Easy Apply"]')),r||(r=await e.$('a[aria-label*="Easy Apply"]')),r||(r=await e.$('a[href*="/apply/"]')),!r){let s=await e.evaluateHandle(()=>{let c=document.querySelectorAll("button, a");for(let l of c){let a=l.innerText?.trim();if(a==="Easy Apply"||a==="Apply")return l}return null});r=s?.asElement?.()||null,r||await s.dispose().catch(()=>{})}r||await new Promise(s=>setTimeout(s,300))}let n=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${n>400?` (waited ${n}ms)`:""}`),r){if(await e.evaluate(a=>a.disabled,r))return await lo(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(a=>a.tagName==="A",r)){await e.evaluate(a=>a.click(),r),await k(3e3);try{await e.waitForFunction(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[data-easy-apply-next-button], button[aria-label="Submit application"]'),{timeout:1e4})}catch{await k(2e3)}}else await r.click(),await k(1500);return await lo(e)?(await vi(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await lo(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function oa(e){return await e.evaluate(async()=>{let t=document.querySelector("button[data-easy-apply-next-button]")||document.querySelector('button[aria-label="Continue to next step"]')||document.querySelector('button[aria-label="Submit application"]')||[...document.querySelectorAll("footer button, button.artdeco-button--primary")].find(d=>/^(Next|Review|Submit application)$/i.test((d.innerText||"").trim())),o=t;for(let d=0;d<15&&o&&!(o.querySelector&&o.querySelector('button[aria-label="Dismiss"]'));d++)o=o.parentElement;o&&!(o.querySelector&&o.querySelector('button[aria-label="Dismiss"]'))&&(o=null);let r=o;if(!document.querySelector(".fb-dash-form-element")&&t&&r){await new Promise(w=>setTimeout(w,300));let d=w=>(w||"").replace(/\s+/g," ").trim(),f=w=>d(w.labels&&w.labels[0]&&w.labels[0].innerText||w.getAttribute("aria-label")||""),p=w=>{let x=w.getAttribute("aria-describedby");if(!x)return!1;let T=x.split(/\s+/).map(N=>document.getElementById(N)?.innerText||"").join(" ");return/invalid input/i.test(T)},m=w=>w.required&&!d(w.value)||p(w);for(let w of r.querySelectorAll("fieldset")){let x=[...w.querySelectorAll('[role="radio"]')],T=[...w.querySelectorAll('input[type="radio"]')];if(!x.length&&!T.length)continue;let N=T.some(v=>v.checked)||x.some(v=>v.getAttribute("aria-checked")==="true"),I=T.some(v=>v.required)||p(w)||w.getAttribute("role")==="radiogroup";if(N||!I)continue;let C=x.map(v=>d(v.getAttribute("aria-label"))).filter(Boolean),P=C.length&&C.every(v=>v===C[0])?C[0]:"",F=d((w.getAttribute("aria-labelledby")||"").split(/\s+/).map(v=>document.getElementById(v)?.innerText||"").join(" ")),H=d(w.previousElementSibling?.innerText||"").replace(/\*+$/,"").trim(),G=d(w.querySelector("legend")?.innerText||"")||d(w.getAttribute("aria-label")||"")||P||F||H,M=x.map(v=>{let L=d(v.innerText);if(L)return L;let V=d(v.getAttribute("aria-label"));return V&&V!==P?V:""}).filter(Boolean);if(!(!G||M.length===0))return w.setAttribute("data-ilml-target","radio"),{type:"radio",labelText:G,errorMsgText:"",options:M,newUi:!0}}for(let w of r.querySelectorAll("select")){if(!m(w))continue;let x=f(w);if(!x)continue;let T=[...w.options].map(N=>d(N.textContent)).filter(N=>N&&!/^select an option$/i.test(N));return w.setAttribute("data-ilml-target","select"),{type:"select",labelText:x,errorMsgText:"",options:T,newUi:!0}}for(let w of r.querySelectorAll('input[type="text"],input[type="tel"],input[type="number"],input:not([type]),textarea')){let x=d(w.getAttribute("placeholder")),T=/city|location/i.test(x),N=!d(w.value);if(!m(w)&&!(T&&N))continue;let I=f(w);if(!I&&T&&(I="Location (city)"),!!I)return w.setAttribute("data-ilml-target","input"),{type:"input",labelText:I,errorMsgText:"",newUi:!0,isCity:T}}let h=w=>w.getAttribute("role")==="checkbox"?w.getAttribute("aria-checked")!=="true":!w.checked,g=w=>w.getAttribute("aria-required")==="true"||w.required||p(w)||(w.closest("fieldset")?p(w.closest("fieldset")):!1),y=w=>{let x=f(w);if(x)return x;let T=d(w.innerText);if(T&&T.length>1&&T.length<80)return T;let N=w.parentElement;for(let I=0;I<5&&N;I++){let C=d(N.innerText);if(C.length>3&&C.length<80)return C;N=N.parentElement}return""},A=w=>!!(w.getClientRects().length||w.offsetParent),E=[...r.querySelectorAll('[role="checkbox"]')],b=[...r.querySelectorAll('input[type="checkbox"]')].filter(w=>A(w)&&!w.closest('[role="checkbox"]')),S=[...E,...b].filter(h),_=S.map(w=>({el:w,label:y(w)})).filter(w=>w.label);if(_.length>=2){let w=new Set(_.map(I=>I.label)),x=_[0].el;for(let I=0;I<8&&x&&!_.every(C=>x.contains(C.el));I++)x=x.parentElement;let N=(x?[...x.querySelectorAll("legend, h2, h3, h4, label, p")].map(I=>d(I.innerText)):[]).find(I=>I&&!w.has(I)&&I.length>4&&I.length<100&&!/easy apply|^jobs$/i.test(I))||"";if(!N){let I=d(x?x.innerText:"");for(let C of w)I=I.split(C).join(" ");I=I.replace(/jobs easy apply/ig," ").trim(),N=d(I).slice(0,120)}return N||(N="Which of these apply to you?"),_.forEach((I,C)=>I.el.setAttribute("data-ilml-target","cbgroup-"+C)),{type:"checkboxGroup",labelText:N,options:_.map(I=>I.label),newUi:!0}}let D=S.find(g)||(S.length===1?S[0]:null);if(D){let w=y(D);if(w)return D.setAttribute("data-ilml-target","checkbox"),{type:"checkbox",labelText:w,errorMsgText:"",newUi:!0,isConsent:!0}}return null}function n(){let d=document.querySelectorAll(".artdeco-inline-feedback__message");if(d.length>0)return d;let f=document.querySelector("#interop-outlet")?.shadowRoot;return f&&(d=f.querySelectorAll(".artdeco-inline-feedback__message")),d}let i=3e3,s=n();if(s?.length===0&&(await new Promise(d=>setTimeout(d,i)),s=n()),s?.length===0)return null;let c=s[0];console.log("errorMsg"),console.log(c);let l=c?.textContent.trim(),a=c.parentElement.parentElement.querySelector("label")?.textContent.trim(),u=c.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(u),console.log("isUpload"),console.log(a),u||a){console.log("parentElement"),console.log(u);let d=u.querySelector(".artdeco-text-input--label")||u.querySelector("legend .fb-dash-form-element__label-title--is-required")||u.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||u.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||u.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),f=u.querySelector(".artdeco-text-input--input")||u.querySelector("input#"+u.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),p=u.querySelectorAll('input[type="radio"]'),m=u.querySelector("select[data-test-text-entity-list-form-select]"),h=c.parentElement.parentElement.querySelector('input[type="file"]'),g=u.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(h),d&&f)return{type:"input",labelText:d.textContent.trim(),errorMsgText:l};if(d&&p.length){let y=d?d.querySelector("span:nth-of-type(1)")?.textContent.trim():null,A=Array.from(p).map(b=>{let _=(document.querySelector(`label[for="${b.id}"]`)||b.nextElementSibling)?.textContent?.trim();return{value:b.value,label:_||b.value}}),E=A.map(b=>b.label);return{type:"radio",labelText:y,errorMsgText:l,options:E,optionsData:A}}else if(m){let y=u.querySelector('label[for="'+m.id+'"]')||u.querySelector(".fb-dash-form-element__label-title--is-required"),A=y?y.querySelector("span:nth-of-type(2)")?.textContent.trim():null,E=Array.from(m.options).map(b=>b.value).filter(b=>b!=="Select an option");return{type:"select",labelText:A,errorMsgText:l,options:E}}else if(h){let y=c.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:l,labelText:y}}else{if(g)return{type:"datePicker",errorMsgText:l};{let y=d?d.querySelector("span:nth-of-type(2)")?.textContent.trim():null,A=u.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(A.length>0){let E=Array.from(A).map(b=>b.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:y,errorMsgText:l,options:E}}else return null}}}return null})}async function na(e,t,o){return await e.evaluate(async(r,n)=>{if(r&&r.newUi){let l=document.querySelector('[data-ilml-target="input"]');if(!l)return null;l.removeAttribute("data-ilml-target");let a=(r.labelText||"").toLowerCase();if(l.type==="number"||/salary|compensation|desired pay|expected pay|\bpay\b/.test(a)){let p=String(n).match(/\d[\d,]*(?:\.\d+)?/);p&&(n=p[0].replace(/,/g,""))}let u=l.tagName==="TEXTAREA"?window.HTMLTextAreaElement.prototype:window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(u,"value").set;try{l.focus()}catch{}d.call(l,n),l.dispatchEvent(new Event("input",{bubbles:!0})),l.dispatchEvent(new Event("change",{bubbles:!0}));let f=(r.labelText||"").toLowerCase();return f.includes("city")||f.includes("location")?(await new Promise(p=>setTimeout(p,600)),l.dispatchEvent(new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40})),await new Promise(p=>setTimeout(p,150)),l.dispatchEvent(new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13}))):(l.dispatchEvent(new FocusEvent("blur",{bubbles:!0})),l.dispatchEvent(new FocusEvent("focusout",{bubbles:!0}))),null}let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let c=i[0].closest(".fb-dash-form-element");if(c){let l=c.querySelector(".artdeco-text-input--input")||c.querySelector("input#"+c.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));l.value=n;let a=new Event("input",{bubbles:!0});if(l.dispatchEvent(a),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let u=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},d=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),d(p),await new Promise(m=>setTimeout(m,100)),u(p)})(l)}}return null},t,o)}async function ra(e,t,o){return await e.evaluate(async(r,n)=>{if(r&&r.newUi){let l=document.querySelector('fieldset[data-ilml-target="radio"]');if(!l)return null;l.removeAttribute("data-ilml-target");let a=p=>(p||"").replace(/\s+/g," ").trim(),u=String(n).toLowerCase(),d=[...l.querySelectorAll('[role="radio"]')],f=d.find(p=>a(p.innerText).toLowerCase()===u)||d.find(p=>a(p.getAttribute("aria-label")).toLowerCase()===u)||d.find(p=>a(p.innerText).toLowerCase().includes(u))||d.find(p=>a(p.getAttribute("aria-label")).toLowerCase().includes(u));return f&&f.click(),null}let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let c=i[0].closest(".fb-dash-form-element");if(c){let l=c.querySelectorAll('input[type="radio"]'),a=n;if(r.optionsData){let u=r.optionsData.find(d=>d.label.toLowerCase()===n.toLowerCase());u&&(a=u.value,console.log(`Radio: matched label "${n}" to value "${a}"`))}for(let u of l){let f=(document.querySelector(`label[for="${u.id}"]`)||u.nextElementSibling)?.textContent?.trim()||"";if(u.value.toLowerCase()===a.toLowerCase()||f.toLowerCase()===n.toLowerCase()){u.checked=!0;let p=new Event("change",{bubbles:!0});u.dispatchEvent(p),console.log(`Radio selected: value="${u.value}", label="${f}"`);break}}}return null},t,o)}async function ia(e,t,o){let r=(o||[]).map(n=>String(n).toLowerCase().trim()).filter(Boolean);return await e.evaluate((n,i)=>((n||[]).forEach((s,c)=>{let l=document.querySelector(`[data-ilml-target="cbgroup-${c}"]`);if(!l)return;l.removeAttribute("data-ilml-target");let a=String(s).toLowerCase().trim(),u=i.some(f=>f===a||f.includes(a)||a.includes(f)),d=l.getAttribute("role")==="checkbox"?l.getAttribute("aria-checked")==="true":l.checked;u&&!d&&(l.getAttribute("role")==="checkbox"?l:l.id&&document.querySelector(`label[for="${l.id}"]`)||l.closest("label")||l).click()}),null),t.options,r)}async function sa(e,t,o){return await e.evaluate(async(r,n)=>{if(r&&r.newUi){let l=document.querySelector('select[data-ilml-target="select"]');if(!l)return null;l.removeAttribute("data-ilml-target");let a=m=>(m||"").replace(/\s+/g," ").trim(),u=a(n).toLowerCase(),d=[...l.options],f=d.find(m=>a(m.textContent).toLowerCase()===u)||d.find(m=>a(m.textContent).toLowerCase().includes(u));return Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype,"value").set.call(l,f?f.value:n),l.dispatchEvent(new Event("input",{bubbles:!0})),l.dispatchEvent(new Event("change",{bubbles:!0})),null}let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let c=i[0].closest(".fb-dash-form-element");if(c){let l=c.querySelector("select[data-test-text-entity-list-form-select]");if(!l)return null;let a=Array.from(l.options),u=a.find(f=>f.text.toLowerCase()===n.toLowerCase())||a.find(f=>f.text.toLowerCase().includes(n.toLowerCase()));u?l.value=u.value:l.value=n;let d=new Event("change",{bubbles:!0});l.dispatchEvent(d)}return null},t,o)}async function mi(e,t,o){return await e.evaluate(async(r,n)=>{if(r&&r.newUi){let l=document.querySelector('[data-ilml-target="checkbox"]');return l&&(l.removeAttribute("data-ilml-target"),(l.getAttribute("role")==="checkbox"?l:l.id&&document.querySelector(`label[for="${l.id}"]`)||l.closest("label")||l).click()),null}let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let c=i[0].closest(".fb-dash-form-element");if(c){let l=c.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');l.length>0&&l.forEach(a=>{if(a.nextElementSibling.textContent.trim()===n.trim()){a.checked=!0;let u=new Event("change",{bubbles:!0});a.dispatchEvent(u)}})}return null},t,o)}async function la(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i?.length===0)return null;let s=i[0],c=s.closest(".fb-dash-form-element"),l=s.parentElement.parentElement.querySelector('input[type="file"]');if(c&&l){async function a(u,d,f){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let m=new Blob([new Uint8Array(d)]),h=new File([m],f,{type:"application/pdf"}),g=new DataTransfer;g.items.add(h),u.files=g.files;let y=new Event("change",{bubbles:!0});u.dispatchEvent(y)}await a(l,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function hi(e){let t=await oa(e);if(t===null)return null;if(t?.type==="input"){let n;t.isCity&&process.env.City?n=process.env.City:(n=await Dt(t.labelText,t.errorMsgText),n=n?.trim()||n),t.answer=n,await na(e,t,n)}else if(t?.type==="radio"){let n=await jt(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[];!i.find(c=>c.toLowerCase()===n?.toLowerCase())&&i.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await jt(t.labelText,t.options),n=n?.trim()||n,i.find(l=>l.toLowerCase()===n?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])),t.answer=n,await ra(e,t,n)}else if(t?.type==="select"){let n=await ct(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[],s=i.find(c=>c.toLowerCase()===n?.toLowerCase());if(s)n=s;else if(i.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await ct(t.labelText,t.options),n=n?.trim()||n;let c=i.find(l=>l.toLowerCase()===n?.toLowerCase());c?n=c:(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])}t.answer=n,await sa(e,t,n)}else if(t?.type==="checkboxGroup"){let n=await $n(t.labelText,t.options);n=(n||"").trim();let s=(t.options||[]).filter(c=>n.toLowerCase().includes(c.toLowerCase()));!s.length&&!/^\s*none\b/i.test(n)&&(s=n.split(/[,;\n]+/).map(c=>c.trim()).filter(Boolean)),t.answer=s.join(", ")||"(none)",await ia(e,t,s)}else if(t?.type==="checkbox")if(t.newUi&&t.isConsent)t.answer="checked",await mi(e,t,"checked");else{let n=await ct(t.labelText,t.options);t.answer=n,await mi(e,t,n)}else if(t?.type==="file"){let n=process.env.RESUME_PDF_URL;t.answer=n;let i=await fetch(n);if(!i.ok)throw new Error("Network response was not ok");let s=await i.arrayBuffer();await la(e,t,s)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let o=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${o}" \u2192 ${r}`),t}async function aa(e){return await e.evaluate(async()=>{let t=[],o=document.querySelectorAll(".fb-dash-form-element");if(!o||o.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(o=r.querySelectorAll(".fb-dash-form-element"))}if(!o||o.length===0)return[];for(let r of o){let n=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),s=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),c=r.querySelectorAll('input[type="radio"]'),l=r.querySelector("select[data-test-text-entity-list-form-select]"),a=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),u=r.querySelector('input[type="file"]');if(n&&s&&c.length===0){let d=n.textContent.trim();t.push({type:"input",labelText:d,answer:s.value,isRequired:i,wasPreFilled:!!s.value})}else if(n&&c.length){let d=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,f=Array.from(c).map(m=>m.value),p=(Array.from(c).find(m=>m.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:d,options:f,answer:p,isRequired:i,wasPreFilled:!!p})}else if(l){let d=r.querySelector('label[for="'+l.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),f=d?.querySelector("span:nth-of-type(2)")?.textContent.trim()||d?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||d?.querySelector("span")?.textContent.trim()||d?.textContent?.trim()||null,p=Array.from(l.options).map(h=>h.value).filter(h=>h!=="Select an option"),m=l.value!=="Select an option"?l.value:"";t.push({type:"select",labelText:f,options:p,answer:m,isRequired:i,wasPreFilled:!!m})}else if(a.length>0){let d=r.querySelector("legend span")?.textContent?.trim(),f=Array.from(a).map(h=>({label:h.nextElementSibling?.textContent?.trim()||h.value,checked:h.checked})),p=f.some(h=>h.checked),m=f.filter(h=>h.checked).map(h=>h.label).join(", ");t.push({type:"checkbox",labelText:d,options:f.map(h=>h.label),answer:m,isRequired:i,wasPreFilled:p})}else if(u){let d=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:d,answer:u.value?"uploaded":"",isRequired:i,wasPreFilled:!!u.value})}}return t})}async function an(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let c=s.querySelector(".artdeco-text-input--label")||s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||s.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),l=s.querySelector(".artdeco-text-input--input")||s.querySelector("input");if(c&&l&&r===c.textContent.trim()){l.value=n;let a=new Event("input",{bubbles:!0});if(l.dispatchEvent(a),r==="City"||r==="Location (city)"){let u=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},d=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),d(p),await new Promise(m=>setTimeout(m,100)),u(p)})(l)}return!0}}return!1},t,o)}async function ca(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let c=s.querySelectorAll('input[type="radio"]');if(c.length===0)continue;let l=s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('legend [class*="fb-dash-form-element__label"]')||s.querySelector("legend span");if((l?.querySelector("span:nth-of-type(1)")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let u=(n||"").toLowerCase();for(let d of c){let f=d.getRootNode(),m=(d.id&&f.querySelector(`label[for="${d.id}"]`)||d.nextElementSibling)?.textContent?.trim()||"";if(d.value.toLowerCase()===u||m.toLowerCase()===u)return d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function ua(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let c=s.querySelector("select[data-test-text-entity-list-form-select]");if(!c)continue;let l=s.querySelector(`label[for="${c.id}"]`)||s.querySelector(".fb-dash-form-element__label-title--is-required");if((l?.querySelector("span:nth-of-type(2)")?.textContent.trim()||l?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||l?.querySelector("span")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let u=Array.from(c.options),d=(n||"").toLowerCase(),f=u.find(p=>p.text.toLowerCase()===d)||u.find(p=>p.value.toLowerCase()===d)||u.find(p=>p.text.toLowerCase().includes(d));return f?(c.value=f.value,c.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function da(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let c=document.querySelector("#interop-outlet")?.shadowRoot;c&&(i=c.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;let s=(n||"").split(",").map(c=>c.trim().toLowerCase()).filter(Boolean);if(s.length===0)return!1;for(let c of i){let l=c.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(l.length===0||c.querySelector("legend span")?.textContent?.trim()!==r)continue;let u=!1;for(let d of l){let f=(d.nextElementSibling?.textContent||d.value||"").trim().toLowerCase();s.includes(f)&&!d.checked&&(d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),u=!0)}return u}return!1},t,o)}async function fa(e,t){for(let o of t){if(!o.labelText||o.isRequired||o.wasPreFilled||o.answer||o.type==="datePicker"||o.type==="file")continue;let r="";try{if(o.type==="input")r=await Dt(o.labelText,"");else if(o.type==="radio")r=await jt(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await ct(o.labelText,o.options||[]);else continue}catch(s){console.log(` \u26A0 Lifebot failed for optional "${o.labelText}": ${s.message?.slice(0,80)}`);continue}if(r=(r||"").trim(),o.wasOptional=!0,!r){o.answer="",console.log(` ? [opt ${o.type}] "${o.labelText.slice(0,55)}" \u2192 (empty)`);continue}let n=!1;try{o.type==="input"?n=await an(e,o.labelText,r):o.type==="radio"?n=await ca(e,o.labelText,r):o.type==="select"?n=await ua(e,o.labelText,r):o.type==="checkbox"&&(n=await da(e,o.labelText,r))}catch(s){console.log(` \u26A0 setter failed for "${o.labelText}": ${s.message?.slice(0,80)}`)}o.answer=r,console.log(` ? [${n?"opt":"opt-noapply"} ${o.type}] "${o.labelText.slice(0,55)}" \u2192 "${r.slice(0,50)}"`)}}async function pa(e){let t=await e.evaluate(()=>{let r=a=>(a||"").replace(/\s+/g," ").trim(),n=document.querySelector("button[data-easy-apply-next-button]")||document.querySelector('button[aria-label="Continue to next step"]')||document.querySelector('button[aria-label="Submit application"]')||[...document.querySelectorAll("footer button, button.artdeco-button--primary")].find(a=>/^(Next|Review|Submit application)$/i.test((a.innerText||"").trim())),i=n;for(let a=0;a<12&&i&&!(i.querySelector&&i.querySelectorAll('input,select,textarea,[role="radio"],[role="checkbox"]').length>0);a++)i=i.parentElement;if(document.querySelector(".fb-dash-form-element")||!n||!i)return[];let s=a=>r(a.labels&&a.labels[0]&&a.labels[0].innerText||a.getAttribute("aria-label")||""),c=[],l=0;for(let a of i.querySelectorAll('input[type="text"],input[type="tel"],input[type="url"],input[type="email"],input[type="number"],input:not([type]),textarea')){if(a.hasAttribute("data-ilml-optdone")||a.required||r(a.value))continue;let u=s(a);u&&(a.setAttribute("data-ilml-optdone","1"),a.setAttribute("data-ilml-opt",String(l)),c.push({idx:l,labelText:u}),l++)}return c}),o=[];for(let r of t){let n="";try{n=(await Dt(r.labelText,""))?.trim()||""}catch(i){console.log(` \u26A0 optional Lifebot failed "${r.labelText.slice(0,45)}": ${i.message?.slice(0,60)}`)}n&&await e.evaluate((i,s)=>{let c=document.querySelector(`[data-ilml-opt="${i}"]`);if(!c)return;c.removeAttribute("data-ilml-opt");let l=c.tagName==="TEXTAREA"?window.HTMLTextAreaElement.prototype:window.HTMLInputElement.prototype,a=Object.getOwnPropertyDescriptor(l,"value").set;try{c.focus()}catch{}a.call(c,s),c.dispatchEvent(new Event("input",{bubbles:!0})),c.dispatchEvent(new Event("change",{bubbles:!0})),c.dispatchEvent(new Event("blur",{bubbles:!0})),c.dispatchEvent(new FocusEvent("focusout",{bubbles:!0}))},r.idx,n),console.log(` ? [opt input] "${r.labelText.slice(0,55)}" \u2192 ${n?`"${n.slice(0,50)}"`:"(empty)"}`),o.push({type:"input",labelText:r.labelText,answer:n,wasOptional:!0,newUi:!0})}return o}async function yi(e,t){let o=[],r=!0,n=0,i=null,s=0;for(;r;){if(n++,await lo(e))return console.log(" Daily limit reached during form navigation"),await vi(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let a=(await aa(e)).filter(p=>!o.some(m=>m.labelText===p.labelText));o.push(...a);try{let p=o.find(h=>h.labelText==="City"||h.labelText==="Location (city)"),m=o.filter(h=>h.labelText!=null).find(h=>h.labelText!==null&&h.labelText.trim()!==null&&(h.labelText.trim().toLowerCase()==="cv"||h.labelText.trim().toLowerCase()==="curriculum vitae"||h.labelText.trim().toLowerCase()==="cover letter"||h.labelText.trim().toLowerCase()==="cover"));if(p&&!p.answer){let h=process.env.City;await an(e,p.labelText,h),p.answer=h}else if(m){let h=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!m.answer||m.answer!==h)&&(await k(1e4),await an(e,m.labelText,h),m.answer=h,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await fa(e,a)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}try{let p=await pa(e);for(let m of p)o.some(h=>h.labelText===m.labelText)||o.push(m)}catch(p){console.error(` \u26A0 fillOptionalInputsNewUi failed: ${p.message?.slice(0,100)}`)}let u=null;try{u=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(u!==null){if(u.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:u};let p=u&&o.find(h=>(h.errorMsgText||h.newUi)&&h.labelText===u.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(u,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:u};let m=o.findIndex(h=>h.labelText===u.labelText&&!h.answer);m!==-1&&o.splice(m,1),o.push(u)}let d=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of p){let h=m.querySelectorAll("button");for(let g of h){let y=g.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return g.click(),y}}return null});d&&console.log(` Dismissed safety popup (${d})`);let f=await e.evaluate(async()=>{function p(b){let S=document.querySelector(b);if(S)return S;let _=document.querySelector("#interop-outlet")?.shadowRoot;return _?_.querySelector(b):null}function m(b){let S=document.querySelectorAll(b),_=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(b);return[...S||[],..._||[]]}let h=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(b=>b.innerText?.trim()==="Next"),g=m("button").some(b=>(b.innerText||"").trim()==="Review"||/^Review( your application)?$/i.test(b.getAttribute("aria-label")||"")),y=p('button[aria-label="Submit application"]')||m("button").find(b=>(b.innerText||"").trim()==="Submit application"),A=async()=>{let b=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(S=>S.innerText?.trim()==="Next");b?b.click():console.log("Next button not found")},E=()=>{let b=m("button").find(S=>S.innerText?.trim()==="Review");b&&b.click()};return h?(await A(),{type:"next"}):g?(await E(),{type:"review"}):y?{type:"submit"}:{type:null}});if(f==null)return{filledFields:o,formPages:n,skip:!0};if(f.type&&console.log(` \u2192 ${f.type}`),f.type===null){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of m){let g=h.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of g){let A=y.innerText||"";if(A.includes("application was sent")||A.includes("resume into a profile")||A.includes("Application submitted")||A.includes("Next best action"))for(let E of y.querySelectorAll("button")){let b=E.innerText?.trim();if(b==="Not now"||b==="Done"||b==="Dismiss"||b==="Got it")return E.click(),b}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await k(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(s===0){let m=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],y=[];for(let A of h){for(let b of A.querySelectorAll("button")){let S=b.innerText?.trim();S&&S.length<60&&g.push(S)}let E=A.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');E&&y.push(E.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(m.buttons)}`),m.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(m.modalText)}`)}}if(f.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(u===null&&f.type===i?s++:s=0,i=f.type,s>=5){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),h=[],g=[];for(let S of m){for(let _ of S.querySelectorAll(".artdeco-inline-feedback__message"))h.push(_.textContent?.trim()?.slice(0,60));for(let _ of S.querySelectorAll(".fb-dash-form-element")){let D=_.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),w=_.querySelector("input, select, textarea"),x=!!_.querySelector(".artdeco-inline-feedback__message");D&&(x||w&&!w.value)&&g.push({label:D.slice(0,40),hasError:x,value:w?.value?.slice(0,20)||""})}}let y=S=>(S||"").replace(/\s+/g," ").trim(),E=document.querySelector("button[data-easy-apply-next-button]")||document.querySelector('button[aria-label="Continue to next step"]')||[...document.querySelectorAll("footer button, button.artdeco-button--primary")].find(S=>/^(Next|Review|Submit application)$/i.test((S.innerText||"").trim()));for(let S=0;S<12&&E&&!(E.querySelector&&E.querySelectorAll('input,select,textarea,[role="radio"],[role="checkbox"]').length>0);S++)E=E.parentElement;let b=[];if(E){for(let S of E.querySelectorAll("fieldset")){let _=[...S.querySelectorAll('[role="radio"]')],D=[...S.querySelectorAll('input[type="radio"]')];!_.length&&!D.length||b.push({kind:"radiogroup",q:y(S.querySelector("legend")?.innerText||S.getAttribute("aria-label")||_[0]?.getAttribute("aria-label")).slice(0,50),opts:_.map(w=>({t:y(w.innerText).slice(0,15),aria:y(w.getAttribute("aria-label")).slice(0,15),chk:w.getAttribute("aria-checked")})),inputs:D.map(w=>({val:w.value?.slice(0,12),checked:w.checked}))})}for(let S of E.querySelectorAll('[role="checkbox"],input[type="checkbox"]'))b.push({kind:"checkbox",role:S.getAttribute("role")||S.type,ariaChecked:S.getAttribute("aria-checked"),checked:S.checked??null,required:S.required||S.getAttribute("aria-required")==="true",visible:!!(S.getClientRects().length||S.offsetParent),label:y(S.labels&&S.labels[0]?.innerText||S.getAttribute("aria-label")||S.closest("div,label,fieldset")?.innerText).slice(0,50)});for(let S of E.querySelectorAll('input[type="text"],input[type="tel"],input[type="number"],input:not([type]),textarea,select')){let _=S.getAttribute("aria-describedby"),D=_?y(_.split(/\s+/).map(w=>document.getElementById(w)?.innerText||"").join(" ")).slice(0,50):"";b.push({kind:S.tagName.toLowerCase(),label:y(S.labels&&S.labels[0]?.innerText||S.getAttribute("aria-label")).slice(0,40),value:y(S.value).slice(0,30),required:S.required,ariaInvalid:S.getAttribute("aria-invalid"),describedbyErr:D,ph:y(S.getAttribute("placeholder")).slice(0,30)})}}return{errors:h,emptyRequired:g.slice(0,5),newUi:b.slice(0,8)}});return console.error(` \u26A0 Stuck on "${f.type}" for ${s} iterations \u2014 form not progressing.`),p.errors.length&&console.error(` Visible errors: ${JSON.stringify(p.errors)}`),p.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(p.emptyRequired)}`),p.newUi?.length&&console.error(` NEW-UI fields: ${JSON.stringify(p.newUi)}`),console.error(" Skipping job."),{filledFields:o,formPages:n,skip:!0,duplicateField:{labelText:`stuck_on_${f.type}`}}}await k(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function gi(e){try{await e.evaluate(()=>{let t=document.getElementById("follow-company-checkbox");t?(t.checked=!1,t.dispatchEvent(new Event("change",{bubbles:!0}))):console.warn("Unfollow checkbox not found.")})}catch(t){console.error("Error in unfollowJobCheckbox:",t)}}async function ma(e){let t=await e.evaluateHandle(()=>{let r=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let n of r){let i=n.querySelector('button[aria-label="Submit application"]');if(i)return i;let s=[...n.querySelectorAll("button")].find(c=>(c.innerText||"").trim()==="Submit application");if(s)return s}return null}),o=t?.asElement?.()||null;o?await o.click():await t.dispose().catch(()=>{})}async function ha(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of o){for(let i of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(i.innerText?.trim()==="Done")return i.click(),"Done";let n=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let i of n){let s=i.innerText||"";if(s.includes("application was sent")||s.includes("Application sent")||s.includes("resume into a profile")||s.includes("Next best action"))for(let c of i.querySelectorAll("button")){let l=c.innerText?.trim();if(l==="Not now"||l==="Dismiss")return c.click(),l}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await k(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function io(e){try{await e.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let t=await e.$('button[aria-label="Dismiss"]');t?(await t.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await k(1e3)):console.log("Popup \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.")}catch{console.log("closeJobApplicationPopup failed to execute: \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D \u0438\u043B\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F.")}}async function rn(e){try{await e.waitForSelector('button[data-control-name="discard_application_confirm_btn"]',{timeout:3e3});let t=await e.$('button[data-control-name="discard_application_confirm_btn"]');t&&(await t.click(),console.log("Discard confirmed"),await k(500))}catch{console.log("No discard confirmation needed")}}async function xi(e,t){let o=[],r=t._fromQueue;try{$.attempted++,console.log(`
300
+ --- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&At(n)?.status==="applied")return $.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (our DB): ${t.jobTitle} \u2014 skipping`),{keepGoing:!0};let i=null;if(!r){let f=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name")?.innerText?.trim()?.replace(/\s+/g," ")?.toLowerCase()||""),p=(t.companyName||"").replace(/\s+/g," ").toLowerCase().trim(),m=f.split(" ")[0],h=p.split(" ")[0];if(m&&h&&!f.includes(h)&&!p.includes(m))return $.mismatch++,console.log(` \u2298 MISMATCH: expected company "${t.companyName}" but panel shows "${f}"`),console.log(` job title: "${t.jobTitle}"`),{keepGoing:!0};if(await e.evaluate(()=>{for(let y of document.querySelectorAll("span, div, li, strong, p")){if(y.children.length!==0||y.closest('[componentkey^="job-card-component-ref-"]'))continue;let A=(y.textContent||"").trim();if(A==="Applied"||/^Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago$/i.test(A)||/^Application submitted$/i.test(A))return!0}return!1}))return $.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${t.jobTitle} \u2014 skipping`),n&&_e(n,"applied",{source:"detected"}),{keepGoing:!0};try{i=await Nr(e)}catch{}}let s=await pi(e);if(s.dailyLimitReached){console.log(`
300
301
  ========================================`),console.log("LinkedIn daily application limit reached!"),console.log(`========================================
301
- `);let d=Ve("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${d.total}`),console.log(` - This session: ${ro}`),console.log(` - Unprocessed: ${d.unprocessed}`),k.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:d}}if(!s.clicked)return k.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${t.jobTitle} @ ${t.companyName}`),{keepGoing:!0};await fi(e);let a=await Fl();console.log(`Applying for job: ${t.id}`);let l=`### Job Information
302
- - **Counter:** ${a}
302
+ `);let f=Ge("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${f.total}`),console.log(` - This session: ${ao}`),console.log(` - Unprocessed: ${f.unprocessed}`),$.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:f}}if(!s.clicked)return $.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${t.jobTitle} @ ${t.companyName}`),{keepGoing:!0};await gi(e);let c=await Vl();console.log(`Applying for job: ${t.id}`);let l=`### Job Information
303
+ - **Counter:** ${c}
303
304
  - **Job Title:** ${t.jobTitle}
304
305
  - **Company:** ${t.companyName}
305
306
  - **Location:** ${t.location}
306
307
  - **Salary:** ${t.salary}
307
- - **Job URL:** ${t.href}`,c=process.env.NODE_EASY_APPLY_MAIN;await Ie.addMessage(c,l,{lifebot:ii.off});let u=await He("Should I apply for this job? Answer only 'yes' or 'no'!!");if(si(),console.log(`Should I apply for ${t.jobTitle} ?? `+u),u.toLowerCase()==="no"){k.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await to(e),await rn(e),await ai(e,t.id);let d=t.id?.match(/\d+/)?.[0];return Qe({jobId:d,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),Fe(d,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let f=await di(e,ui);if(f.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await ci(e)).clicked?f=await di(e,ui):(console.log(" pressApplyButton failed on retry"),f={filledFields:[],formPages:0,skip:!0,duplicateField:{labelText:"stale_popup_retry_failed"}})),console.log(`processNavigation: pages=${f.formPages}, fields=${f.filledFields?.length||0}, skip=${f.skip}${f.dailyLimitReached?", DAILY LIMIT":""}`),f.dailyLimitReached)return console.log(" Daily limit reached \u2014 stopping"),await to(e),{keepGoing:!1,dailyLimitReached:!0};if(f.skip){if(await to(e),await rn(e),f.duplicateField){await ai(e,t.id);let d=process.env.NODE_EASY_APPLY_ERRORS;await Ie.addMessage(d,`${t.href} failed at label ${f.duplicateField?.labelText}`,{lifebot:ii.off})}k.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${f.duplicateField?.labelText||"form error"}`),Qe({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"failed",formPages:f.formPages,failedField:f.duplicateField?.labelText||null,questions:f.filledFields||[]})}else{o=f.filledFields,o.length,await fi(e),await ra(e),await w(2e3),await ia(e),k.submitted++,console.log(` \u2713 APPLIED: ${t.jobTitle} @ ${t.companyName} (${f.formPages} pages, ${o.length} fields)`);let d=t.id?.match(/\d+/)?.[0];if(d&&(Pt(d,{title:t.jobTitle,company:t.companyName,location:t.location,salary:t.salary,url:t.href,applied:!0}),Io(d,{title:t.jobTitle,company:i?.companyName||t.companyName,companyUrl:i?.companyUrl,location:t.location,salary:t.salary,url:t.href,isEasyApply:!0,applyType:"easy-apply",applied:!0,appliedAt:new Date().toISOString().slice(0,10),description:i?.description,techStack:i?.techStack,jobTags:i?.jobTags,seniority:i?.seniority,employmentType:i?.employmentType,industries:i?.industries,jobFunction:i?.jobFunction,postedTime:i?.postedTime,applicantCount:i?.applicantCount,companySize:i?.companySize,workplaceType:i?.workplaceType,contractType:i?.contractType,aboutCompany:i?.aboutCompany}),Fe(d,"applied",{source:"easy-apply"}),i?.companyUrl&&Wt(i.companyUrl,{name:i.companyName||t.companyName,about:i.aboutCompany,size:i.companySize,industries:i.industries,jobId:d})),await Gl(e,t),Qe({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:f.formPages,questions:o}),!Ml())return{keepGoing:!1}}}catch(n){if(rt(n))throw console.log(`\u26A0 CDP dead during "${t.jobTitle}" \u2014 bubbling up for page recovery: ${(n.message||"").slice(0,100)}`),n;let i=hi(n);if(!i)return console.log(`\u274C Unknown error \u2014 stopping: ${(n.message||"").slice(0,120)}`),console.log(n),{keepGoing:!1};if(i.severity==="fatal")return console.log(`\u274C [${i.label}] Fatal \u2014 stopping: ${(n.message||"").slice(0,120)}`),i.instructions&&console.log(` \u2192 ${i.instructions}`),i.label==="ilml-auth-expired"?k.fatalAuthExpired="ilml":i.label==="linkedin-session-expired"&&(k.fatalAuthExpired="linkedin"),{keepGoing:!1};let s=ql(i.label);if(console.log(`\u26A0 [${i.label}] on "${t.jobTitle}" (${s}/${i.maxConsecutive} consecutive): ${(n.message||"").slice(0,120)}`),i.cleanup==="popup"){try{await to(e)}catch{}try{await rn(e)}catch{}}return s>=i.maxConsecutive?(console.log(`\u274C [${i.label}] ${i.maxConsecutive} consecutive \u2014 stopping.`),i.instructions&&console.log(` \u2192 ${i.instructions}`),{keepGoing:!1}):(i.cooldownMs&&await w(i.cooldownMs),{keepGoing:!0})}return si(),{keepGoing:!0}}async function sa(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL,n=[],i=0;for(;;){await sn(e,r)&&(await ne(e),await w(2e3));try{await e.waitForSelector("li.scaffold-layout__list-item",{timeout:3e4})}catch{}await o(e);let a=await Bl(e);if(a.length===0){if(!e.url().includes("/jobs/")){if(i++,i>3){console.log(" Too many recovery attempts \u2014 LinkedIn keeps redirecting. Stopping.");break}console.log(` No jobs found but not on /jobs/ page \u2014 recovery attempt ${i}/3...`),await sn(e,r);continue}let c=await e.evaluate(()=>({totalCards:document.querySelectorAll("li.scaffold-layout__list-item").length,hasListContainer:!!document.querySelector(".jobs-search-results-list, .scaffold-layout__list-container")}));c.totalCards===0?console.log(` \u26A0 No job cards on page (container present: ${c.hasListContainer}). Either the search returned nothing, the page never finished loading, or LinkedIn changed its markup.`):console.log(` ${c.totalCards} job card(s) on page but none are Easy Apply \u2014 nothing to apply to with this search filter.`);break}if(i=0,n.length===0){n=a;let{keepGoing:l}=await li(e,a,t);if(!l)return{keepGoing:!1,jobsDone:n}}else{let l=a.filter(u=>!n.some(f=>f.id===u.id));if(console.log(` New jobs on page: ${l.length} (page: ${a.length}, total seen: ${n.length})`),l.length===0)break;let{keepGoing:c}=await li(e,l,t);if(n=[...n,...l],!c)return{keepGoing:!1,jobsDone:n}}}return console.log(` All jobs processed. Total: ${n.length}`),{keepGoing:!0,jobsDone:n}}var k={attempted:0,submitted:0,skippedByLifebot:0,failed:0,mismatch:0,alreadyApplied:0,expired:0,noApplyButton:0,dailyLimitHit:!1,cdpRecoveries:0,browserRestarts:0,fatalAuthExpired:null};(async()=>{let e=process.argv.find(l=>l.startsWith("--job-urls=")),t=Hr("apply",e?"queue":"search"),o=null,r=null,n=[],i=async()=>(await en(ri,{devtools:!1})).browser,s=async l=>{await l.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},a=()=>At();try{let l=await en(ri,{devtools:!1});o=l.browser;let c=await o.newPage();await s(c),await Xr(c,l);let u=process.argv.find(_=>_.startsWith("--job-urls=")),f=u?u.split("=").slice(1).join("=").replace(/^@/,""):null,d=process.env.LINKEDIN_SEARCH_URL,p=f?"https://www.linkedin.com/feed/":d;try{await c.goto(p,{waitUntil:"domcontentloaded",timeout:6e4})}catch(_){console.error("\u274C Navigation error:",_.message),console.log("Trying to continue anyway..."),await w(5e3)}try{await Ue(c,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .jobs-search-results-list, li.scaffold-layout__list-item",label:"search page"})}catch(_){throw _.code==="SESSION_EXPIRED"?new Error("Not logged in (or session expired). Run: ilml linkedin login"):_}console.log("\u2713 Logged in to LinkedIn.");let m=Ve("recruiters-from-jobs");m.total>0&&console.log(`
308
+ - **Job URL:** ${t.href}`,a=process.env.NODE_EASY_APPLY_MAIN;await Se.addMessage(a,l,{lifebot:sn.off});let u=await je("Should I apply for this job? Answer only 'yes' or 'no'!!");if(di(),console.log(`Should I apply for ${t.jobTitle} ?? `+u),u.toLowerCase()==="no"){$.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await io(e),await rn(e),await ki(e,t.id);let f=t.id?.match(/\d+/)?.[0];return Qe({jobId:f,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),_e(f,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let d=await yi(e,hi);if(d.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await pi(e)).clicked?d=await yi(e,hi):(console.log(" pressApplyButton failed on retry"),d={filledFields:[],formPages:0,skip:!0,duplicateField:{labelText:"stale_popup_retry_failed"}})),console.log(`processNavigation: pages=${d.formPages}, fields=${d.filledFields?.length||0}, skip=${d.skip}${d.dailyLimitReached?", DAILY LIMIT":""}`),d.dailyLimitReached)return console.log(" Daily limit reached \u2014 stopping"),await io(e),{keepGoing:!1,dailyLimitReached:!0};if(d.skip){if(await io(e),await rn(e),d.duplicateField){let p=process.env.NODE_EASY_APPLY_ERRORS,m=`${t.href} failed at label ${d.duplicateField?.labelText}`;try{let h=d.duplicateField||{},g=[];h.type&&g.push(`type=${h.type}`),Array.isArray(h.options)&&h.options.length&&g.push(`options=${h.options.slice(0,6).join("|").slice(0,80)}`),h.answer&&g.push(`answer="${String(h.answer).slice(0,40)}"`),g.length&&(m+=` [${g.join(", ")}]`)}catch{}await Se.addMessage(p,m,{lifebot:sn.off})}$.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${d.duplicateField?.labelText||"form error"}`),Qe({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"failed",formPages:d.formPages,failedField:d.duplicateField?.labelText||null,questions:d.filledFields||[]});let f=t.id?.match(/\d+/)?.[0];f&&_e(f,"dismissed",{reason:(d.duplicateField?.labelText||"form_error").slice(0,60),source:"apply"}),$.failedFields.push(d.duplicateField?.labelText||"form_error")}else{o=d.filledFields,o.length,await gi(e),await ma(e),await k(2e3),await ha(e),$.submitted++,console.log(` \u2713 APPLIED: ${t.jobTitle} @ ${t.companyName} (${d.formPages} pages, ${o.length} fields)`);let f=t.id?.match(/\d+/)?.[0];if(f&&(Mt(f,{title:t.jobTitle,company:t.companyName,location:t.location,salary:t.salary,url:t.href,applied:!0}),Do(f,{title:t.jobTitle,company:i?.companyName||t.companyName,companyUrl:i?.companyUrl,location:t.location,salary:t.salary,url:t.href,isEasyApply:!0,applyType:"easy-apply",applied:!0,appliedAt:new Date().toISOString().slice(0,10),description:i?.description,techStack:i?.techStack,jobTags:i?.jobTags,seniority:i?.seniority,employmentType:i?.employmentType,industries:i?.industries,jobFunction:i?.jobFunction,postedTime:i?.postedTime,applicantCount:i?.applicantCount,companySize:i?.companySize,workplaceType:i?.workplaceType,contractType:i?.contractType,aboutCompany:i?.aboutCompany}),_e(f,"applied",{source:"easy-apply"}),i?.companyUrl&&Qt(i.companyUrl,{name:i.companyName||t.companyName,about:i.aboutCompany,size:i.companySize,industries:i.industries,jobId:f})),await ta(e,t),Qe({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:d.formPages,questions:o}),!Kl())return{keepGoing:!1}}}catch(n){if(rt(n))throw console.log(`\u26A0 CDP dead during "${t.jobTitle}" \u2014 bubbling up for page recovery: ${(n.message||"").slice(0,100)}`),n;let i=Si(n);if(!i)return console.log(`\u274C Unknown error \u2014 stopping: ${(n.message||"").slice(0,120)}`),console.log(n),{keepGoing:!1};if(i.severity==="fatal")return console.log(`\u274C [${i.label}] Fatal \u2014 stopping: ${(n.message||"").slice(0,120)}`),i.instructions&&console.log(` \u2192 ${i.instructions}`),i.label==="ilml-auth-expired"?$.fatalAuthExpired="ilml":i.label==="linkedin-session-expired"&&($.fatalAuthExpired="linkedin"),{keepGoing:!1};let s=Yl(i.label);if(console.log(`\u26A0 [${i.label}] on "${t.jobTitle}" (${s}/${i.maxConsecutive} consecutive): ${(n.message||"").slice(0,120)}`),i.cleanup==="popup"){try{await io(e)}catch{}try{await rn(e)}catch{}}return s>=i.maxConsecutive?(console.log(`\u274C [${i.label}] ${i.maxConsecutive} consecutive \u2014 stopping.`),i.instructions&&console.log(` \u2192 ${i.instructions}`),{keepGoing:!1}):(i.cooldownMs&&await k(i.cooldownMs),{keepGoing:!0})}return di(),{keepGoing:!0}}async function ya(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL,n=[],i=0;for(;;){await ln(e,r)&&(await re(e),await k(2e3));try{await e.waitForSelector('li.scaffold-layout__list-item, button[aria-label^="Dismiss"]',{timeout:3e4})}catch{}await o(e);let c=await Ql(e);if(c.length===0){if(!e.url().includes("/jobs/")){if(i++,i>3){console.log(" Too many recovery attempts \u2014 LinkedIn keeps redirecting. Stopping.");break}console.log(` No jobs found but not on /jobs/ page \u2014 recovery attempt ${i}/3...`),await ln(e,r);continue}let a=await e.evaluate(()=>{let u=document.querySelectorAll('button[aria-label^="Dismiss"]').length;return{totalCards:document.querySelectorAll("li.scaffold-layout__list-item").length||u,hasListContainer:!!document.querySelector(".jobs-search-results-list, .scaffold-layout__list-container")||u>0}});a.totalCards===0?console.log(` \u26A0 No job cards on page (container present: ${a.hasListContainer}). Either the search returned nothing, the page never finished loading, or LinkedIn changed its markup.`):console.log(` ${a.totalCards} job card(s) on page but none are Easy Apply \u2014 nothing to apply to with this search filter.`);break}if(i=0,n.length===0){n=c;let{keepGoing:l}=await fi(e,c,t);if(!l)return{keepGoing:!1,jobsDone:n}}else{let l=f=>{if(f.id!=null)return`id:${f.id}`;let p=(f.jobTitle||"").trim().toLowerCase(),m=(f.companyName||"").trim().toLowerCase();return p||m?`tc:${p}|${m}`:"tc:|"},a=new Set(n.map(l)),u=c.filter(f=>!a.has(l(f)));if(console.log(` New jobs on page: ${u.length} (page: ${c.length}, total seen: ${n.length})`),u.length===0)break;let{keepGoing:d}=await fi(e,u,t);if(n=[...n,...u],!d)return{keepGoing:!1,jobsDone:n}}}return console.log(` All jobs processed. Total: ${n.length}`),{keepGoing:!0,jobsDone:n}}var $={attempted:0,submitted:0,skippedByLifebot:0,failed:0,mismatch:0,alreadyApplied:0,expired:0,noApplyButton:0,dailyLimitHit:!1,cdpRecoveries:0,browserRestarts:0,fatalAuthExpired:null,failedFields:[]};(async()=>{let e=process.argv.find(l=>l.startsWith("--job-urls=")),t=zr("apply",e?"queue":"search"),o=null,r=null,n=[],i=async()=>(await en(ui,{devtools:!1})).browser,s=async l=>{await l.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},c=()=>Rt();try{let l=await en(ui,{devtools:!1});o=l.browser;let a=await o.newPage();await s(a),await ri(a,l);let u=process.argv.find(C=>C.startsWith("--job-urls=")),d=u?u.split("=").slice(1).join("=").replace(/^@/,""):null,f=process.env.LINKEDIN_SEARCH_URL,p=d?"https://www.linkedin.com/feed/":f;try{await a.goto(p,{waitUntil:"domcontentloaded",timeout:6e4})}catch(C){console.error("\u274C Navigation error:",C.message),console.log("Trying to continue anyway..."),await k(5e3)}try{await st(a,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .jobs-search-results-list, li.scaffold-layout__list-item",label:"search page"})}catch(C){if(C.code==="SESSION_EXPIRED")try{await at(a,{label:"search page"});try{await a.goto(p,{waitUntil:"domcontentloaded",timeout:6e4})}catch{}await st(a,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .jobs-search-results-list, li.scaffold-layout__list-item",label:"search page"})}catch{throw new Error("Not logged in (or session expired). Run: ilml linkedin login")}else throw C}console.log("\u2713 Logged in to LinkedIn.");let m=Ge("recruiters-from-jobs");m.total>0&&console.log(`
308
309
  \u{1F4C2} Existing recruiters for today: ${m.total} (${m.unprocessed} unprocessed)
309
- `),await w(2e3);let h={page:c,browser:o,recoveryCtx:{searchUrl:d,launchFn:i,setupPage:s,cookiesProvider:a}},g=!1;if(f)try{let _=JSON.parse(pi.readFileSync(f,"utf-8"));console.log(`
310
- \u{1F4CB} Queue mode: ${_.length} jobs from ${f}
311
- `);for(let M=0;M<_.length;M++){let F=typeof _[M]=="string"?{url:_[M]}:_[M],B=F.url,G=F.title||"Unknown",W=F.company||"";console.log(`
312
- [${M+1}/${_.length}] ${G} @ ${W}`),console.log(` ${B}`),c=h.page,o=h.browser;try{let v=B.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await c.goto(B,{waitUntil:"domcontentloaded",timeout:6e4}),await w(8e3);let I=await c.evaluate(()=>{let J=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:J.includes("Application submitted"),noLongerAccepting:J.includes("No longer accepting applications")}});if(I.alreadyApplied){console.log(" Already applied \u2014 skipping"),k.alreadyApplied++,Fe(v,"applied",{applyMethod:"detected"});continue}if(I.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),k.expired++,Fe(v,"expired",{reason:"no_longer_accepting"});continue}if(!I.hasApply){console.log(" No Easy Apply button \u2014 skipping"),k.noApplyButton++;continue}let Y={id:`/jobs/view/${v}/`,href:B,jobTitle:G,companyName:W,location:F.location||"",salary:F.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let O=await gi(c,Y);if(console.log(` Result: keepGoing=${O.keepGoing}, reason=${O.dailyLimitReached?"daily_limit":"ok"}`),!O.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),g=!0;break}}catch(v){if(rt(v))try{await oo(h,`queue job ${M+1}: ${v.message?.slice(0,80)}`),c=h.page,o=h.browser}catch(I){console.error(`\u274C Queue mode: CDP recovery failed: ${I.message}`),console.error(" Aborting queue, falling back to standard search if possible.");break}else{let I=hi(v);if(I?.severity==="fatal"){console.error(`\u274C [${I.label}] Fatal \u2014 stopping queue: ${(v.message||"").slice(0,120)}`),I.instructions&&console.error(` \u2192 ${I.instructions}`),I.label==="ilml-auth-expired"?k.fatalAuthExpired="ilml":I.label==="linkedin-session-expired"&&(k.fatalAuthExpired="linkedin");break}console.error(` Error: ${v.message?.slice(0,80)}`)}}}console.log(`
313
- Queue complete. ${g?"Daily limit hit.":"Continuing to search..."}`)}catch(_){console.error(`Failed to read job URLs file: ${_.message}`)}if(!g){if(f){console.log(`
314
- Queue done. Continuing with standard search...`);try{await c.goto(d,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3)}catch(_){console.error(" Navigation to search failed:",_.message)}}h.page=c,h.browser=o;try{await Vl(h)}catch(_){rt(_)||/CDP unrecoverable/.test(_.message||"")?(console.error(`
315
- \u274C Apply phase ended: CDP channel could not be recovered after ${k.cdpRecoveries} page recoveries and ${k.browserRestarts} browser restarts.`),console.error(` Last error: ${_.message}`)):/Session expired/i.test(_.message||"")?(console.error(`
316
- \u274C Apply phase ended: ${_.message}`),r=_):console.error(`
317
- \u26A0 Apply phase crashed: ${_.message}`)}c=h.page,o=h.browser}let y=k.submitted+k.skippedByLifebot+k.failed+k.mismatch+k.alreadyApplied+k.expired+k.noApplyButton,S=k.attempted-y,x=Ve("recruiters-from-jobs");n.push(`Jobs attempted: ${k.attempted}`),n.push(`Successfully applied: ${k.submitted}`),n.push(`Skipped by Lifebot: ${k.skippedByLifebot}`),n.push(`Failed (form errors): ${k.failed}`),k.mismatch>0&&n.push(`Mismatch (wrong panel): ${k.mismatch}`),k.alreadyApplied>0&&n.push(`Already applied: ${k.alreadyApplied}`),k.expired>0&&n.push(`Expired (closed): ${k.expired}`),k.noApplyButton>0&&n.push(`No Apply button: ${k.noApplyButton}`),S>0&&n.push(`Unaccounted: ${S}`),n.push(`Daily limit reached: ${k.dailyLimitHit?"Yes":"No"}`),k.cdpRecoveries>0&&n.push(`Page recoveries (CDP): ${k.cdpRecoveries}`),k.browserRestarts>0&&n.push(`Browser restarts: ${k.browserRestarts}`),n.push(`Recruiters found: ${ro}`),n.push(`Recruiters total: ${x.total} (${x.unprocessed} unprocessed)`),console.log(`
318
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SESSION SUMMARY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let _ of n)console.log(` ${_}`);console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let b=!!o&&o.isConnected?.()!==!1,C=jl?b?k.fatalAuthExpired==="linkedin"?"LinkedIn session expired (run: ilml linkedin login)":k.fatalAuthExpired==="ilml"?"iLiveMyLife token expired (run: ilml login)":null:"browser is not in a usable state":"recruiter auto-connect is disabled (FUNNEL_CONNECT_RECRUITERS=false)",R=!C;R||(console.log(`
319
- \u26A0 Skipping recruiter funnel \u2014 ${C}.`),console.log(` ${x.unprocessed} recruiters saved for next run.`),n.push(`Funnel: skipped (${C})`));let{markProfileProcessed:L}=await Promise.resolve().then(()=>(mo(),Tn)),{canSendConnection:A,getQuotaStatus:T}=await Xe().then(()=>Yn),j=()=>({message:Pl,useCustomMessage:Ll,maxConnections:Nl,excludeLocations:tn,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async(_,M,F)=>{L("recruiters-from-jobs",_.profileUrl,{status:F.reason,connectionSent:F.connectionSent,withCustomMessage:F.withCustomMessage,message:F.messageSent,method:F.method,reason:F.reason,error:F.error,profileInfo:F.profileInfo},_._fromDate||null)}});if(R&&x.unprocessed>0){console.log(`
320
- --- Funnel: today's recruiters (${x.unprocessed}) ---`),tn.length>0&&console.log(` Excluding locations: ${tn.join(", ")}`);let _=It("recruiters-from-jobs");await qo(c,_,j())}let K=A();if(R&&K.allowed){let _=Dt("recruiters-from-jobs"),M=new Date().toISOString().split("T")[0],F=_.filter(B=>B._fromDate!==M);if(F.length>0){let B=T();console.log(`
321
- --- Funnel: backfill from previous days (${F.length} unprocessed) ---`),console.log(` Quota remaining: ${B.daily.remaining} today, ${B.weekly.remaining} this week`),await qo(c,F,{...j(),maxConnections:B.daily.remaining})}}let U=T();console.log(`
322
- \u2705 Funnel done. Connection quota left: ${U.daily.remaining} of ${U.daily.max} today, ${U.weekly.remaining} of ${U.weekly.max} this week`),n.push(`Connection quota left: ${U.daily.remaining} of ${U.daily.max} today, ${U.weekly.remaining} of ${U.weekly.max} week`)}catch(l){r=l,console.error(`
323
- \u274C Apply session ended with error: ${l.message}`),l.stack&&console.error(l.stack)}Vr(t,r?"error":"success",{summaryLines:n,dailyLimitHit:k.dailyLimitHit,attempted:k.attempted,submitted:k.submitted,failed:k.failed,skippedByLifebot:k.skippedByLifebot},r?r.message:null);try{await o?.close()}catch{}r&&process.exit(1)})();
310
+ `),await k(2e3);let h={page:a,browser:o,recoveryCtx:{searchUrl:f,launchFn:i,setupPage:s,cookiesProvider:c}},g=!1;if(d)try{let C=JSON.parse(bi.readFileSync(d,"utf-8"));console.log(`
311
+ \u{1F4CB} Queue mode: ${C.length} jobs from ${d}
312
+ `);for(let P=0;P<C.length;P++){let F=typeof C[P]=="string"?{url:C[P]}:C[P],H=F.url,G=F.title||"Unknown",M=F.company||"";console.log(`
313
+ [${P+1}/${C.length}] ${G} @ ${M}`),console.log(` ${H}`),a=h.page,o=h.browser;try{let v=H.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await a.goto(H,{waitUntil:"domcontentloaded",timeout:6e4}),await k(8e3);let L=await a.evaluate(()=>{let W=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:W.includes("Application submitted"),noLongerAccepting:W.includes("No longer accepting applications")}});if(L.alreadyApplied){console.log(" Already applied \u2014 skipping"),$.alreadyApplied++,_e(v,"applied",{applyMethod:"detected"});continue}if(L.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),$.expired++,_e(v,"expired",{reason:"no_longer_accepting"});continue}if(!L.hasApply){console.log(" No Easy Apply button \u2014 skipping"),$.noApplyButton++;continue}let V={id:`/jobs/view/${v}/`,href:H,jobTitle:G,companyName:M,location:F.location||"",salary:F.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let B=await xi(a,V);if(console.log(` Result: keepGoing=${B.keepGoing}, reason=${B.dailyLimitReached?"daily_limit":"ok"}`),!B.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),g=!0;break}}catch(v){if(rt(v))try{await so(h,`queue job ${P+1}: ${v.message?.slice(0,80)}`),a=h.page,o=h.browser}catch(L){console.error(`\u274C Queue mode: CDP recovery failed: ${L.message}`),console.error(" Aborting queue, falling back to standard search if possible.");break}else{let L=Si(v);if(L?.severity==="fatal"){console.error(`\u274C [${L.label}] Fatal \u2014 stopping queue: ${(v.message||"").slice(0,120)}`),L.instructions&&console.error(` \u2192 ${L.instructions}`),L.label==="ilml-auth-expired"?$.fatalAuthExpired="ilml":L.label==="linkedin-session-expired"&&($.fatalAuthExpired="linkedin");break}console.error(` Error: ${v.message?.slice(0,80)}`)}}}console.log(`
314
+ Queue complete. ${g?"Daily limit hit.":"Continuing to search..."}`)}catch(C){console.error(`Failed to read job URLs file: ${C.message}`)}if(!g){if(d){console.log(`
315
+ Queue done. Continuing with standard search...`);try{await a.goto(f,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3)}catch(C){console.error(" Navigation to search failed:",C.message)}}h.page=a,h.browser=o;try{await ea(h)}catch(C){rt(C)||/CDP unrecoverable/.test(C.message||"")?(console.error(`
316
+ \u274C Apply phase ended: CDP channel could not be recovered after ${$.cdpRecoveries} page recoveries and ${$.browserRestarts} browser restarts.`),console.error(` Last error: ${C.message}`)):/Session expired/i.test(C.message||"")?(console.error(`
317
+ \u274C Apply phase ended: ${C.message}`),r=C):console.error(`
318
+ \u26A0 Apply phase crashed: ${C.message}`)}a=h.page,o=h.browser}let y=$.submitted+$.skippedByLifebot+$.failed+$.mismatch+$.alreadyApplied+$.expired+$.noApplyButton,A=$.attempted-y,E=Ge("recruiters-from-jobs");n.push(`Jobs attempted: ${$.attempted}`),n.push(`Successfully applied: ${$.submitted}`),n.push(`Skipped by Lifebot: ${$.skippedByLifebot}`),n.push(`Failed (form errors): ${$.failed}`),$.mismatch>0&&n.push(`Mismatch (wrong panel): ${$.mismatch}`),$.alreadyApplied>0&&n.push(`Already applied: ${$.alreadyApplied}`),$.expired>0&&n.push(`Expired (closed): ${$.expired}`),$.noApplyButton>0&&n.push(`No Apply button: ${$.noApplyButton}`),A>0&&n.push(`Unaccounted: ${A}`),n.push(`Daily limit reached: ${$.dailyLimitHit?"Yes":"No"}`),$.cdpRecoveries>0&&n.push(`Page recoveries (CDP): ${$.cdpRecoveries}`),$.browserRestarts>0&&n.push(`Browser restarts: ${$.browserRestarts}`),n.push(`Recruiters found: ${ao}`),n.push(`Recruiters total: ${E.total} (${E.unprocessed} unprocessed)`),console.log(`
319
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SESSION SUMMARY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let C of n)console.log(` ${C}`);console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");try{let C=process.env.NODE_EASY_APPLY_ERRORS;if(C){let P={};for(let M of $.failedFields)P[M]=(P[M]||0)+1;let F=Object.entries(P).sort((M,v)=>v[1]-M[1]).map(([M,v])=>`${M.slice(0,45)} \xD7${v}`).join(", ")||"\u2014",G=`\u{1F4CA} Apply run ${new Date().toISOString().slice(0,16).replace("T"," ")}
320
+ Applied: ${$.submitted} | Failed/dismissed: ${$.failed}${$.skippedByLifebot?` | Lifebot-skip: ${$.skippedByLifebot}`:""} | Daily limit: ${$.dailyLimitHit?"yes":"no"}
321
+ By field: ${F}`;await Se.addMessage(C,G,{lifebot:sn.off}),console.log(" \u{1F4CA} Run stats posted to monitoring node")}}catch(C){console.log(` stats post failed: ${C.message?.slice(0,60)}`)}let b=!!o&&o.isConnected?.()!==!1,S=Bl?b?$.fatalAuthExpired==="linkedin"?"LinkedIn session expired (run: ilml linkedin login)":$.fatalAuthExpired==="ilml"?"iLiveMyLife token expired (run: ilml login)":null:"browser is not in a usable state":"recruiter auto-connect is disabled (FUNNEL_CONNECT_RECRUITERS=false)",_=!S;_||(console.log(`
322
+ \u26A0 Skipping recruiter funnel \u2014 ${S}.`),console.log(` ${E.unprocessed} recruiters saved for next run.`),n.push(`Funnel: skipped (${S})`));let{markProfileProcessed:D}=await Promise.resolve().then(()=>(ho(),In)),{canSendConnection:w,getQuotaStatus:x}=await Xe().then(()=>er),T=()=>({message:Gl,useCustomMessage:Jl,maxConnections:Hl,excludeLocations:tn,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async(C,P,F)=>{D("recruiters-from-jobs",C.profileUrl,{status:F.reason,connectionSent:F.connectionSent,withCustomMessage:F.withCustomMessage,message:F.messageSent,method:F.method,reason:F.reason,error:F.error,profileInfo:F.profileInfo},C._fromDate||null)}});if(_&&E.unprocessed>0){console.log(`
323
+ --- Funnel: today's recruiters (${E.unprocessed}) ---`),tn.length>0&&console.log(` Excluding locations: ${tn.join(", ")}`);let C=Nt("recruiters-from-jobs");await Fo(a,C,T())}let N=w();if(_&&N.allowed){let C=qt("recruiters-from-jobs"),P=new Date().toISOString().split("T")[0],F=C.filter(H=>H._fromDate!==P);if(F.length>0){let H=x();console.log(`
324
+ --- Funnel: backfill from previous days (${F.length} unprocessed) ---`),console.log(` Quota remaining: ${H.daily.remaining} today, ${H.weekly.remaining} this week`),await Fo(a,F,{...T(),maxConnections:H.daily.remaining})}}let I=x();console.log(`
325
+ \u2705 Funnel done. Connection quota left: ${I.daily.remaining} of ${I.daily.max} today, ${I.weekly.remaining} of ${I.weekly.max} this week`),n.push(`Connection quota left: ${I.daily.remaining} of ${I.daily.max} today, ${I.weekly.remaining} of ${I.weekly.max} week`)}catch(l){r=l,console.error(`
326
+ \u274C Apply session ended with error: ${l.message}`),l.stack&&console.error(l.stack)}Qr(t,r?"error":"success",{summaryLines:n,dailyLimitHit:$.dailyLimitHit,attempted:$.attempted,submitted:$.submitted,failed:$.failed,skippedByLifebot:$.skippedByLifebot},r?r.message:null);try{await o?.close()}catch{}r&&process.exit(1)})();