ilml-plugin-linkedin 1.14.0 → 1.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/run.mjs CHANGED
@@ -1,10 +1,10 @@
1
- var Gn=Object.defineProperty;var Je=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{for(var o in t)Gn(e,o,{get:t[o],enumerable:!0})};async function g(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}function wo(e){return parseInt(e,10)||0}async function te(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let n=r.innerText||"",s=n.includes("Premium")||n.includes("premium")||n.includes("Upgrade")||n.includes("upgrade"),l=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(s||l||a){let i=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(i)return i.click(),{dismissed:!0,matched:n.substring(0,80)};let u=r.querySelectorAll("button");for(let c of u){let d=c.innerText?.trim().toLowerCase()||"",f=c.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return c.click(),{dismissed:!0,matched: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 Re=Je(()=>{});var $o={};Te($o,{default:()=>er,getAllUnprocessedProfiles:()=>ct,getSummary:()=>De,getUnprocessedProfiles:()=>at,listFiles:()=>xo,loadProfiles:()=>lt,markProfileProcessed:()=>vo,saveProfile:()=>Ge,saveProfiles:()=>ko});import"dotenv/config";import*as J from"fs";import*as oe from"path";import{fileURLToPath as Qn}from"url";function He(){J.existsSync(ue)||J.mkdirSync(ue,{recursive:!0})}function Zn(e,t){try{let o=`${e}-${Lt()}.json`,r=J.readdirSync(ue).filter(s=>s.startsWith(e)&&s.endsWith(".json")&&s!==o),n=0;for(let s of r)JSON.parse(J.readFileSync(oe.join(ue,s),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function Lt(){return new Date().toISOString().split("T")[0]}function Dt(e,t=null){let o=t||Lt();return oe.join(ue,`${e}-${o}.json`)}function lt(e,t=null){He();let o=Dt(e,t);try{if(J.existsSync(o)){let r=J.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 Ge(e,t){He();let o=Dt(e),r={source:e,date:Lt(),lastUpdated:new Date().toISOString(),profiles:[]};try{J.existsSync(o)&&(r=JSON.parse(J.readFileSync(o,"utf-8")))}catch(l){console.error(`Error reading ${o}:`,l.message)}if(r.profiles.some(l=>l.profileUrl===t.profileUrl))return!1;let s=Zn(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:s}),r.lastUpdated=new Date().toISOString();try{J.writeFileSync(o,JSON.stringify(r,null,2));let l=s>0?` (seen ${s} day${s>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${l} (total: ${r.profiles.length})`),!0}catch(l){return console.error(`Error saving to ${o}:`,l.message),!1}}function ko(e,t){let o=0;for(let r of t)Ge(e,r)&&o++;return o}function at(e,t=null){return lt(e,t).filter(r=>!r.processed)}function vo(e,t,o,r=null){He();let n=Dt(e,r);try{if(!J.existsSync(n))return;let s=JSON.parse(J.readFileSync(n,"utf-8")),l=s.profiles.find(a=>a.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof o=="string")l.status=o;else if(typeof o=="object"){if(l.status=o.status,o.profileInfo){let a=o.profileInfo;a.name&&(l.name=a.name),a.title&&(l.title=a.title),a.location&&(l.location=a.location),a.company&&(l.company=a.company),a.connectionDegree&&(l.connectionDegree=a.connectionDegree),a.connectionsCount&&(l.connectionsCount=a.connectionsCount),a.mutualConnections&&(l.mutualConnections=a.mutualConnections),a.photoUrl&&(l.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=a.hasVerifiedBadge)}l.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}}s.lastUpdated=new Date().toISOString(),J.writeFileSync(n,JSON.stringify(s,null,2))}}catch(s){console.error("Error marking profile processed:",s.message)}}function De(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,s)=>(n[s.status]=(n[s.status]||0)+1,n),{})}}function xo(){He();try{return J.readdirSync(ue).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(J.readFileSync(oe.join(ue,t),"utf-8"));return{file:t,source:o,date:r,count:n.profiles?.length||0,unprocessed:n.profiles?.filter(s=>!s.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 ct(e){He();let t=[];try{let n=J.readdirSync(ue).filter(s=>s.startsWith(e+"-")&&s.endsWith(".json")).sort().reverse();for(let s of n)try{let l=JSON.parse(J.readFileSync(oe.join(ue,s),"utf-8"));l.profiles&&t.push({file:s,date:l.date,profiles:l.profiles})}catch{}}catch{return[]}let o=new Set,r=[];for(let{date:n,profiles:s}of t)for(let l of s)!l.processed&&l.profileUrl&&!o.has(l.profileUrl)&&(o.add(l.profileUrl),r.push({...l,_fromDate:n}));return r}var zn,Xn,ue,er,jt=Je(()=>{zn=Qn(import.meta.url),Xn=oe.dirname(oe.dirname(zn)),ue=process.env.DATA_DIR?oe.resolve(process.env.DATA_DIR,"collected-profiles"):oe.join(Xn,"collected-profiles");er={loadProfiles:lt,saveProfile:Ge,saveProfiles:ko,getUnprocessedProfiles:at,getAllUnprocessedProfiles:ct,markProfileProcessed:vo,getSummary:De,listFiles:xo}});import{getPluginConfig as tr}from"@ilivemylife/graph-sdk";var or,li,Se,ai,ci,Eo=Je(async()=>{or=await tr();for(let[e,t]of Object.entries(or))process.env[e]===void 0&&(process.env[e]=t);li=process.env.LINKEDIN_NAME,Se=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ai=Object.freeze(new Set([Se.DRAFT,Se.CONFIRMED,Se.NEEDS_REVIEW])),ci=Object.freeze(new Set([Se.DRAFT,Se.CONFIRMED,Se.REJECTED,Se.NEEDS_REVIEW]))});var Bo={};Te(Bo,{addEncounter:()=>qe,atomicWriteJSON:()=>fe,canSendConnection:()=>Ke,commitDataSnapshot:()=>Uo,default:()=>mr,getAllApplications:()=>Po,getPersonStatus:()=>yt,getQuestionStats:()=>Mo,getQuotaStatus:()=>Qe,getRecentConnections:()=>St,linkPersonToJob:()=>ht,loadApplicationQuestions:()=>Bt,loadConversations:()=>Do,loadJobs:()=>ft,loadPeople:()=>X,loadProfileHistory:()=>Lo,loadQuota:()=>bt,loadSyncState:()=>Fo,logApplicationQuestions:()=>Pe,migrateFromDailyFiles:()=>No,profileSlug:()=>dt,recordConnectionSent:()=>wt,resetCaches:()=>Mt,safeLoadJSON:()=>xe,saveConversations:()=>jo,saveJobs:()=>pt,savePeople:()=>$e,saveQuota:()=>Ut,saveSyncState:()=>Oo,updateConnectionStatus:()=>gt,upsertJob:()=>mt,upsertPerson:()=>ye});import"dotenv/config";import*as P from"fs";import*as V from"path";import{fileURLToPath as nr}from"url";import{execSync as Nt}from"child_process";function Mt(){je=null,Ne=null,de=null,ve=null,Fe=null,ke=null}function Z(){P.existsSync(K)||P.mkdirSync(K,{recursive:!0})}function fe(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";P.writeFileSync(r,o);for(let n=0;n<3;n++)try{P.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function xe(e,t){if(!P.existsSync(e))return null;try{let o=JSON.parse(P.readFileSync(e,"utf-8"));try{P.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(P.existsSync(r))try{let n=JSON.parse(P.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{P.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{P.copyFileSync(e,e+".corrupted")}catch{}return null}}function Oe(){return new Date().toISOString().split("T")[0]}function dt(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function lr(){P.existsSync(Pt)||P.mkdirSync(Pt,{recursive:!0})}function Io(e){let t=dt(e);return t?V.join(Pt,`${t}.json`):null}function Lo(e){let t=Io(e);return t?xe(t,`profile-history/${dt(e)}.json`)||[]:[]}function ar(e,t){let o=Io(e);if(!o)return;lr();let r=Lo(e);r.unshift(t);try{fe(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${dt(e)}: ${n.message}`)}}function Co(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Ao(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function cr(e,t){if(!e)return[];let o=[];for(let r of ir){let n=e[r],s=t[r];Co(n)||Co(s)||Ao(n)!==Ao(s)&&o.push(r)}return o}function ur(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 je||(Z(),je=xe(Ft,"people.json")||{},je)}function $e(e){Z(),je=e;try{fe(Ft,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${V.resolve(Ft)}`)}}function ft(){return Ne||(Z(),Ne=xe(Ot,"jobs.json")||{},Ne)}function pt(e){Z(),Ne=e;try{fe(Ot,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${V.resolve(Ot)}`)}}function Do(){return ve||(Z(),ve=xe(ut,"conversations.json")||{},dr(ve),ve)}function dr(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(s=>s.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{fe(ut,e)}catch{}}}function jo(e){Z(),ve=e;try{fe(ut,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${V.resolve(ut)}`)}}function ye(e,t={}){if(!e)return null;let o=X(),r=Oe(),n=new Date().toISOString(),s=o[e];if(s){let l=cr(s,t);l.length>0&&(ar(e,{capturedAt:n,previousLastUpdated:s.lastUpdated||null,changedFields:l,snapshot:ur(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 a of Ro)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(s[a])&&s[a].length>0)continue;s[a]=t[a]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=n)}else o[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return $e(o),o[e]}function mt(e,t={}){if(!e)return null;let o=ft(),r=Oe(),n=o[e];if(n){let s=["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 l of s)t[l]!=null&&(n[l]=t[l])}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 pt(o),o[e]}function ht(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(),$e(o)))}function qe(e,t){if(!e||!t)return;let o=X(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let s={date:Oe(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(s.jobId=String(t.jobId)),t.jobTitle&&(s.jobTitle=t.jobTitle),t.jobCompany&&(s.jobCompany=t.jobCompany),!r.encounters.some(a=>a.date===s.date&&a.source===s.source&&a.action===s.action&&(a.jobId||"")===(s.jobId||""))&&(r.encounters.push(s),r.lastUpdated=new Date().toISOString(),$e(o))}function yt(e){return e&&X()[e]?.connectionStatus||null}function gt(e,t,o={}){if(!e)return;o.profileInfo?ye(e,o.profileInfo):X()[e]||ye(e,{});let r=X(),n=r[e];n&&(n.connectionStatus=t,n.connectionDate=Oe(),n.connectionMethod=o.method||n.connectionMethod,n.messageSent=o.messageSent||n.messageSent,n.lastUpdated=new Date().toISOString(),$e(r))}function bt(){return de||(Z(),de=xe(_o,"quota.json"),(!de||!de.connections)&&(de={connections:[]}),de)}function Ut(e){Z(),de=e;try{fe(_o,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function wt(e,t="unknown"){let o=bt(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),Ut(o)}function St(){let e=bt(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function Ke(){let e=St(),t=Oe(),o=e.filter(i=>i.date===t).length,r=e.length,n=o>=We,s=r>=Ye,l=!n&&!s,a={allowed:l,daily:{sent:o,max:We},weekly:{sent:r,max:Ye}};return l||(a.reason=n?`Daily limit reached (${o}/${We})`:`Weekly limit reached (${r}/${Ye})`),a}function Qe(){let e=St(),t=Oe(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:We,remaining:We-o},weekly:{sent:r,max:Ye,remaining:Ye-r}}}function fr(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function No(){Z();let e=P.readdirSync(K).filter(s=>s.endsWith(".json")&&s!=="people.json"&&s!=="jobs.json"&&s!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
1
+ var Wn=Object.defineProperty;var Je=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{for(var o in t)Wn(e,o,{get:t[o],enumerable:!0})};async function g(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}function wo(e){return parseInt(e,10)||0}async function te(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let n=r.innerText||"",s=n.includes("Premium")||n.includes("premium")||n.includes("Upgrade")||n.includes("upgrade"),l=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(s||l||a){let i=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(i)return i.click(),{dismissed:!0,matched:n.substring(0,80)};let u=r.querySelectorAll("button");for(let c of u){let d=c.innerText?.trim().toLowerCase()||"",f=c.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return c.click(),{dismissed:!0,matched: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 Re=Je(()=>{});var $o={};Te($o,{default:()=>tr,getAllUnprocessedProfiles:()=>ct,getSummary:()=>De,getUnprocessedProfiles:()=>at,listFiles:()=>xo,loadProfiles:()=>lt,markProfileProcessed:()=>vo,saveProfile:()=>Ge,saveProfiles:()=>ko});import"dotenv/config";import*as J from"fs";import*as oe from"path";import{fileURLToPath as zn}from"url";function He(){J.existsSync(ue)||J.mkdirSync(ue,{recursive:!0})}function er(e,t){try{let o=`${e}-${Lt()}.json`,r=J.readdirSync(ue).filter(s=>s.startsWith(e)&&s.endsWith(".json")&&s!==o),n=0;for(let s of r)JSON.parse(J.readFileSync(oe.join(ue,s),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function Lt(){return new Date().toISOString().split("T")[0]}function Dt(e,t=null){let o=t||Lt();return oe.join(ue,`${e}-${o}.json`)}function lt(e,t=null){He();let o=Dt(e,t);try{if(J.existsSync(o)){let r=J.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 Ge(e,t){He();let o=Dt(e),r={source:e,date:Lt(),lastUpdated:new Date().toISOString(),profiles:[]};try{J.existsSync(o)&&(r=JSON.parse(J.readFileSync(o,"utf-8")))}catch(l){console.error(`Error reading ${o}:`,l.message)}if(r.profiles.some(l=>l.profileUrl===t.profileUrl))return!1;let s=er(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:s}),r.lastUpdated=new Date().toISOString();try{J.writeFileSync(o,JSON.stringify(r,null,2));let l=s>0?` (seen ${s} day${s>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${l} (total: ${r.profiles.length})`),!0}catch(l){return console.error(`Error saving to ${o}:`,l.message),!1}}function ko(e,t){let o=0;for(let r of t)Ge(e,r)&&o++;return o}function at(e,t=null){return lt(e,t).filter(r=>!r.processed)}function vo(e,t,o,r=null){He();let n=Dt(e,r);try{if(!J.existsSync(n))return;let s=JSON.parse(J.readFileSync(n,"utf-8")),l=s.profiles.find(a=>a.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof o=="string")l.status=o;else if(typeof o=="object"){if(l.status=o.status,o.profileInfo){let a=o.profileInfo;a.name&&(l.name=a.name),a.title&&(l.title=a.title),a.location&&(l.location=a.location),a.company&&(l.company=a.company),a.connectionDegree&&(l.connectionDegree=a.connectionDegree),a.connectionsCount&&(l.connectionsCount=a.connectionsCount),a.mutualConnections&&(l.mutualConnections=a.mutualConnections),a.photoUrl&&(l.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=a.hasVerifiedBadge)}l.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}}s.lastUpdated=new Date().toISOString(),J.writeFileSync(n,JSON.stringify(s,null,2))}}catch(s){console.error("Error marking profile processed:",s.message)}}function De(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,s)=>(n[s.status]=(n[s.status]||0)+1,n),{})}}function xo(){He();try{return J.readdirSync(ue).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(J.readFileSync(oe.join(ue,t),"utf-8"));return{file:t,source:o,date:r,count:n.profiles?.length||0,unprocessed:n.profiles?.filter(s=>!s.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 ct(e){He();let t=[];try{let n=J.readdirSync(ue).filter(s=>s.startsWith(e+"-")&&s.endsWith(".json")).sort().reverse();for(let s of n)try{let l=JSON.parse(J.readFileSync(oe.join(ue,s),"utf-8"));l.profiles&&t.push({file:s,date:l.date,profiles:l.profiles})}catch{}}catch{return[]}let o=new Set,r=[];for(let{date:n,profiles:s}of t)for(let l of s)!l.processed&&l.profileUrl&&!o.has(l.profileUrl)&&(o.add(l.profileUrl),r.push({...l,_fromDate:n}));return r}var Xn,Zn,ue,tr,jt=Je(()=>{Xn=zn(import.meta.url),Zn=oe.dirname(oe.dirname(Xn)),ue=process.env.DATA_DIR?oe.resolve(process.env.DATA_DIR,"collected-profiles"):oe.join(Zn,"collected-profiles");tr={loadProfiles:lt,saveProfile:Ge,saveProfiles:ko,getUnprocessedProfiles:at,getAllUnprocessedProfiles:ct,markProfileProcessed:vo,getSummary:De,listFiles:xo}});import{getPluginConfig as or}from"@ilivemylife/graph-sdk";var nr,ai,Se,ci,ui,Eo=Je(async()=>{nr=await or();for(let[e,t]of Object.entries(nr))process.env[e]===void 0&&(process.env[e]=t);ai=process.env.LINKEDIN_NAME,Se=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ci=Object.freeze(new Set([Se.DRAFT,Se.CONFIRMED,Se.NEEDS_REVIEW])),ui=Object.freeze(new Set([Se.DRAFT,Se.CONFIRMED,Se.REJECTED,Se.NEEDS_REVIEW]))});var Jo={};Te(Jo,{addEncounter:()=>qe,atomicWriteJSON:()=>fe,canSendConnection:()=>Ke,commitDataSnapshot:()=>Bo,default:()=>hr,getAllApplications:()=>Mo,getPersonStatus:()=>yt,getQuestionStats:()=>Uo,getQuotaStatus:()=>Qe,getRecentConnections:()=>St,linkPersonToJob:()=>ht,loadApplicationQuestions:()=>Bt,loadConversations:()=>jo,loadJobs:()=>ft,loadPeople:()=>X,loadProfileHistory:()=>Do,loadQuota:()=>bt,loadSyncState:()=>Oo,logApplicationQuestions:()=>Pe,migrateFromDailyFiles:()=>Fo,profileSlug:()=>dt,recordConnectionSent:()=>wt,resetCaches:()=>Mt,safeLoadJSON:()=>xe,saveConversations:()=>No,saveJobs:()=>pt,savePeople:()=>$e,saveQuota:()=>Ut,saveSyncState:()=>qo,updateConnectionStatus:()=>gt,upsertJob:()=>mt,upsertPerson:()=>ye});import"dotenv/config";import*as P from"fs";import*as V from"path";import{fileURLToPath as rr}from"url";import{execSync as Nt}from"child_process";function Mt(){je=null,Ne=null,de=null,ve=null,Fe=null,ke=null}function Z(){P.existsSync(K)||P.mkdirSync(K,{recursive:!0})}function fe(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";P.writeFileSync(r,o);for(let n=0;n<3;n++)try{P.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function xe(e,t){if(!P.existsSync(e))return null;try{let o=JSON.parse(P.readFileSync(e,"utf-8"));try{P.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(P.existsSync(r))try{let n=JSON.parse(P.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{P.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{P.copyFileSync(e,e+".corrupted")}catch{}return null}}function Oe(){return new Date().toISOString().split("T")[0]}function dt(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function ar(){P.existsSync(Pt)||P.mkdirSync(Pt,{recursive:!0})}function Lo(e){let t=dt(e);return t?V.join(Pt,`${t}.json`):null}function Do(e){let t=Lo(e);return t?xe(t,`profile-history/${dt(e)}.json`)||[]:[]}function cr(e,t){let o=Lo(e);if(!o)return;ar();let r=Do(e);r.unshift(t);try{fe(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${dt(e)}: ${n.message}`)}}function Co(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Ao(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function ur(e,t){if(!e)return[];let o=[];for(let r of lr){let n=e[r],s=t[r];Co(n)||Co(s)||Ao(n)!==Ao(s)&&o.push(r)}return o}function dr(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 je||(Z(),je=xe(Ft,"people.json")||{},je)}function $e(e){Z(),je=e;try{fe(Ft,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${V.resolve(Ft)}`)}}function ft(){return Ne||(Z(),Ne=xe(Ot,"jobs.json")||{},Ne)}function pt(e){Z(),Ne=e;try{fe(Ot,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${V.resolve(Ot)}`)}}function jo(){return ve||(Z(),ve=xe(ut,"conversations.json")||{},fr(ve),ve)}function fr(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(s=>s.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{fe(ut,e)}catch{}}}function No(e){Z(),ve=e;try{fe(ut,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${V.resolve(ut)}`)}}function ye(e,t={}){if(!e)return null;let o=X(),r=Oe(),n=new Date().toISOString(),s=o[e];if(s){let l=ur(s,t);l.length>0&&(cr(e,{capturedAt:n,previousLastUpdated:s.lastUpdated||null,changedFields:l,snapshot:dr(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 a of Io)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(s[a])&&s[a].length>0)continue;s[a]=t[a]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=n)}else o[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return $e(o),o[e]}function mt(e,t={}){if(!e)return null;let o=ft(),r=Oe(),n=o[e];if(n){let s=["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 l of s)t[l]!=null&&(n[l]=t[l])}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 pt(o),o[e]}function ht(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(),$e(o)))}function qe(e,t){if(!e||!t)return;let o=X(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let s={date:Oe(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(s.jobId=String(t.jobId)),t.jobTitle&&(s.jobTitle=t.jobTitle),t.jobCompany&&(s.jobCompany=t.jobCompany),!r.encounters.some(a=>a.date===s.date&&a.source===s.source&&a.action===s.action&&(a.jobId||"")===(s.jobId||""))&&(r.encounters.push(s),r.lastUpdated=new Date().toISOString(),$e(o))}function yt(e){return e&&X()[e]?.connectionStatus||null}function gt(e,t,o={}){if(!e)return;o.profileInfo?ye(e,o.profileInfo):X()[e]||ye(e,{});let r=X(),n=r[e];n&&(n.connectionStatus=t,n.connectionDate=Oe(),n.connectionMethod=o.method||n.connectionMethod,n.messageSent=o.messageSent||n.messageSent,n.lastUpdated=new Date().toISOString(),$e(r))}function bt(){return de||(Z(),de=xe(_o,"quota.json"),(!de||!de.connections)&&(de={connections:[]}),de)}function Ut(e){Z(),de=e;try{fe(_o,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function wt(e,t="unknown"){let o=bt(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),Ut(o)}function St(){let e=bt(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function Ke(){let e=St(),t=Oe(),o=e.filter(i=>i.date===t).length,r=e.length,n=o>=We,s=r>=Ye,l=!n&&!s,a={allowed:l,daily:{sent:o,max:We},weekly:{sent:r,max:Ye}};return l||(a.reason=n?`Daily limit reached (${o}/${We})`:`Weekly limit reached (${r}/${Ye})`),a}function Qe(){let e=St(),t=Oe(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:We,remaining:We-o},weekly:{sent:r,max:Ye,remaining:Ye-r}}}function pr(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function Fo(){Z();let e=P.readdirSync(K).filter(s=>s.endsWith(".json")&&s!=="people.json"&&s!=="jobs.json"&&s!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
2
2
  Migrating from ${e.length} daily files...
3
- `);let t=X(),o=ft(),r=0,n=0;e.sort();for(let s of e){let l=V.join(K,s),a;try{a=JSON.parse(P.readFileSync(l,"utf-8"))}catch(c){console.log(` Skipping ${s}: ${c.message}`);continue}let i=a.date||s.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,u=a.source||s.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!a.profiles||!Array.isArray(a.profiles)){console.log(` Skipping ${s}: no profiles array`);continue}console.log(` ${s}: ${a.profiles.length} profiles`);for(let c of a.profiles){let d=c.profileUrl;if(!d)continue;let f=t[d];if(f){f.seenCount=(f.seenCount||1)+1,i&&(!f.lastSeen||i>f.lastSeen)&&(f.lastSeen=i),i&&(!f.firstSeen||i<f.firstSeen)&&(f.firstSeen=i),u&&!f.sources?.includes(u)&&(f.sources=f.sources||[],f.sources.push(u));for(let p of Ro)c[p]!=null&&(f[p]=c[p]);c.status&&c.processed&&(f.connectionStatus=c.status,f.connectionDate=i,c.funnelResult&&(f.connectionMethod=c.funnelResult.method||f.connectionMethod,f.messageSent=c.funnelResult.message||f.messageSent)),f.lastUpdated=new Date().toISOString()}else t[d]={name:c.name||null,title:c.title||null,location:c.location||null,company:c.company||null,connectionDegree:c.connectionDegree||null,connectionsCount:c.connectionsCount||null,mutualConnections:c.mutualConnections||null,photoUrl:c.photoUrl||null,hasVerifiedBadge:c.hasVerifiedBadge||!1,firstSeen:i,lastSeen:i,seenCount:1,sources:u?[u]:[],connectionStatus:c.processed&&c.status||null,connectionDate:c.processed?i:null,connectionMethod:c.funnelResult?.method||null,messageSent:c.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(c.fromJob?.url){let p=fr(c.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:c.fromJob.title||null,company:c.fromJob.company||null,location:null,salary:null,url:c.fromJob.url,applied:!0,appliedDate:i,recruiterUrl:d,firstSeen:i},n++))}}}return $e(t),pt(o),console.log(`
4
- 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 Fo(){return Fe||(Z(),Fe=xe(To,"sync-state.json")||{},Fe)}function Oo(e){Z(),Fe=e;try{fe(To,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Bt(){if(ke)return ke;Z();try{P.existsSync(qt)&&(ke=JSON.parse(P.readFileSync(qt,"utf-8")))}catch{}return ke||(ke={}),ke}function qo(e){return Array.isArray(e.applications)}function Po(){let e=Bt();if(qo(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function Pe(e){if(!e||!e.questions||e.questions.length===0)return;let t=Bt(),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(s=>{let l={type:s.type||"input",question:s.labelText||s.question||"",answer:s.answer||""};return s.options&&(s.options.length<=pr?l.options=s.options:l.optionsOmitted=!0),s.page&&(l.page=s.page),s.wasPreFilled&&(l.wasPreFilled=!0),s.wasRetry&&(l.wasRetry=!0),typeof s.isRequired=="boolean"&&(l.isRequired=s.isRequired),s.wasOptional&&(l.wasOptional=!0),l})};qo(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{fe(qt,t)}catch(s){console.error(`[!] Failed to save application-questions.json: ${s.message}`)}}function Mo(){let e=Po(),t=new Map;for(let s of e)for(let l of s.questions||[]){let a=l.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:l.question,count:0,answers:new Map});let i=t.get(a);i.count++;let u=(l.answer||"").trim();i.answers.set(u,(i.answers.get(u)||0)+1)}let o=[...t.values()].sort((s,l)=>l.count-s.count),r=o.slice(0,15).map(s=>({question:s.question,count:s.count,topAnswer:[...s.answers.entries()].sort((l,a)=>a[1]-l[1])[0]?.[0]||""})),n=o.filter(s=>s.answers.size>1&&s.count>=3).map(s=>({question:s.question,count:s.count,answers:[...s.answers.entries()].sort((l,a)=>a[1]-l[1]).map(([l,a])=>`${l} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:n}}function Uo(e){if(P.existsSync(V.join(K,".git")))try{let t={cwd:K,stdio:"pipe",timeout:1e4};Nt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{Nt("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');Nt(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var rr,sr,K,Ft,Ot,_o,ut,To,qt,Pt,We,Ye,je,Ne,de,ve,Fe,ke,Ro,ir,pr,mr,ze=Je(async()=>{await Eo();rr=nr(import.meta.url),sr=V.dirname(V.dirname(rr)),K=process.env.DATA_DIR?V.resolve(process.env.DATA_DIR,"collected-profiles"):V.join(sr,"collected-profiles"),Ft=V.join(K,"people.json"),Ot=V.join(K,"jobs.json"),_o=V.join(K,"quota.json"),ut=V.join(K,"conversations.json"),To=V.join(K,"sync-state.json"),qt=V.join(K,"application-questions.json"),Pt=V.join(K,"profile-history"),We=20,Ye=100,je=null,Ne=null,de=null,ve=null,Fe=null,ke=null;Ro=["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"],ir=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];pr=50;mr={loadPeople:X,savePeople:$e,loadJobs:ft,saveJobs:pt,loadConversations:Do,saveConversations:jo,upsertPerson:ye,upsertJob:mt,linkPersonToJob:ht,addEncounter:qe,getPersonStatus:yt,updateConnectionStatus:gt,migrateFromDailyFiles:No,loadQuota:bt,saveQuota:Ut,recordConnectionSent:wt,canSendConnection:Ke,getRecentConnections:St,getQuotaStatus:Qe,loadSyncState:Fo,saveSyncState:Oo,commitDataSnapshot:Uo,logApplicationQuestions:Pe,getQuestionStats:Mo}});var Jo={};Te(Jo,{extractCertificationsFromDetails:()=>wr,extractEducationFromDetails:()=>gr,extractExperienceFromDetails:()=>hr,extractFeaturedFromDetails:()=>yr,extractRecommendationsFromDetails:()=>Sr,extractSkillsFromDetails:()=>br});async function hr(e,t){let o=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/experience/`);for(let s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(900);await g(1e3);let n=0;for(;n<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)n++,await g(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function l(c){let d=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(m=>m.tagName==="DIV");if(p.length<3)continue;let h=p.filter(m=>(m.textContent||"").trim().length>50);h.length<3||(f.textContent||"").length<500||d.push({el:f,count:h.length,totalText:(f.textContent||"").length})}return d.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),d[0]?.el}let a=l(s);if(!a)return[];let i=Array.from(a.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function u(c){let d=c[0]||null,f=null,p=null;if(c[1]){let C=c[1].split("\xB7").map(N=>N.trim());f=C[0]||null,C[1]&&(p=C[1])}let h=c.findIndex(C=>/(\d{4}|present)/i.test(C)&&/(-|–|—)/i.test(C)&&C.length<80),m=null,b=null;if(h>=0){let C=c[h].split("\xB7").map(N=>N.trim());m=C[0]||null,C[1]&&(b=C[1])}let y=null,k=-1;if(h>=0&&c[h+1]){let C=c[h+1],N=/^[>*\-•]|^&gt;/.test(C),Y=/https?:\/\//.test(C),U=/\d{4}/.test(C),ae=/,/.test(C)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(C);!N&&!Y&&!U&&C.length<100&&ae&&(y=C,k=h+1)}let v=null,w=-1,E=c[c.length-1];if(E&&/and\s+\+\d+\s+skills?$/i.test(E)){w=c.length-1;let C=E.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);C&&(v={listed:C[1].split(",").map(N=>N.trim()),additional:parseInt(C[2],10)})}let O=new Set([0,1,h,k,w].filter(C=>C>=0)),L=c.filter((C,N)=>!O.has(N)),W=L.length>0?L.join(`
3
+ `);let t=X(),o=ft(),r=0,n=0;e.sort();for(let s of e){let l=V.join(K,s),a;try{a=JSON.parse(P.readFileSync(l,"utf-8"))}catch(c){console.log(` Skipping ${s}: ${c.message}`);continue}let i=a.date||s.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,u=a.source||s.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!a.profiles||!Array.isArray(a.profiles)){console.log(` Skipping ${s}: no profiles array`);continue}console.log(` ${s}: ${a.profiles.length} profiles`);for(let c of a.profiles){let d=c.profileUrl;if(!d)continue;let f=t[d];if(f){f.seenCount=(f.seenCount||1)+1,i&&(!f.lastSeen||i>f.lastSeen)&&(f.lastSeen=i),i&&(!f.firstSeen||i<f.firstSeen)&&(f.firstSeen=i),u&&!f.sources?.includes(u)&&(f.sources=f.sources||[],f.sources.push(u));for(let p of Io)c[p]!=null&&(f[p]=c[p]);c.status&&c.processed&&(f.connectionStatus=c.status,f.connectionDate=i,c.funnelResult&&(f.connectionMethod=c.funnelResult.method||f.connectionMethod,f.messageSent=c.funnelResult.message||f.messageSent)),f.lastUpdated=new Date().toISOString()}else t[d]={name:c.name||null,title:c.title||null,location:c.location||null,company:c.company||null,connectionDegree:c.connectionDegree||null,connectionsCount:c.connectionsCount||null,mutualConnections:c.mutualConnections||null,photoUrl:c.photoUrl||null,hasVerifiedBadge:c.hasVerifiedBadge||!1,firstSeen:i,lastSeen:i,seenCount:1,sources:u?[u]:[],connectionStatus:c.processed&&c.status||null,connectionDate:c.processed?i:null,connectionMethod:c.funnelResult?.method||null,messageSent:c.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(c.fromJob?.url){let p=pr(c.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:c.fromJob.title||null,company:c.fromJob.company||null,location:null,salary:null,url:c.fromJob.url,applied:!0,appliedDate:i,recruiterUrl:d,firstSeen:i},n++))}}}return $e(t),pt(o),console.log(`
4
+ 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 Oo(){return Fe||(Z(),Fe=xe(To,"sync-state.json")||{},Fe)}function qo(e){Z(),Fe=e;try{fe(To,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Bt(){if(ke)return ke;Z();try{P.existsSync(qt)&&(ke=JSON.parse(P.readFileSync(qt,"utf-8")))}catch{}return ke||(ke={}),ke}function Po(e){return Array.isArray(e.applications)}function Mo(){let e=Bt();if(Po(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function Pe(e){if(!e||!e.questions||e.questions.length===0)return;let t=Bt(),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(s=>{let l={type:s.type||"input",question:s.labelText||s.question||"",answer:s.answer||""};return s.options&&(s.options.length<=mr?l.options=s.options:l.optionsOmitted=!0),s.page&&(l.page=s.page),s.wasPreFilled&&(l.wasPreFilled=!0),s.wasRetry&&(l.wasRetry=!0),typeof s.isRequired=="boolean"&&(l.isRequired=s.isRequired),s.wasOptional&&(l.wasOptional=!0),l})};Po(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{fe(qt,t)}catch(s){console.error(`[!] Failed to save application-questions.json: ${s.message}`)}}function Uo(){let e=Mo(),t=new Map;for(let s of e)for(let l of s.questions||[]){let a=l.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:l.question,count:0,answers:new Map});let i=t.get(a);i.count++;let u=(l.answer||"").trim();i.answers.set(u,(i.answers.get(u)||0)+1)}let o=[...t.values()].sort((s,l)=>l.count-s.count),r=o.slice(0,15).map(s=>({question:s.question,count:s.count,topAnswer:[...s.answers.entries()].sort((l,a)=>a[1]-l[1])[0]?.[0]||""})),n=o.filter(s=>s.answers.size>1&&s.count>=3).map(s=>({question:s.question,count:s.count,answers:[...s.answers.entries()].sort((l,a)=>a[1]-l[1]).map(([l,a])=>`${l} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:n}}function Bo(e){if(P.existsSync(V.join(K,".git")))try{let t={cwd:K,stdio:"pipe",timeout:1e4};Nt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{Nt("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');Nt(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var sr,ir,K,Ft,Ot,_o,ut,To,qt,Pt,Ro,We,Ye,je,Ne,de,ve,Fe,ke,Io,lr,mr,hr,ze=Je(async()=>{await Eo();sr=rr(import.meta.url),ir=V.dirname(V.dirname(sr)),K=process.env.DATA_DIR?V.resolve(process.env.DATA_DIR,"collected-profiles"):V.join(ir,"collected-profiles"),Ft=V.join(K,"people.json"),Ot=V.join(K,"jobs.json"),_o=V.join(K,"quota.json"),ut=V.join(K,"conversations.json"),To=V.join(K,"sync-state.json"),qt=V.join(K,"application-questions.json"),Pt=V.join(K,"profile-history"),Ro=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},We=Ro(process.env.CONNECT_MAX_DAILY,20),Ye=Ro(process.env.CONNECT_MAX_WEEKLY,100),je=null,Ne=null,de=null,ve=null,Fe=null,ke=null;Io=["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"],lr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];mr=50;hr={loadPeople:X,savePeople:$e,loadJobs:ft,saveJobs:pt,loadConversations:jo,saveConversations:No,upsertPerson:ye,upsertJob:mt,linkPersonToJob:ht,addEncounter:qe,getPersonStatus:yt,updateConnectionStatus:gt,migrateFromDailyFiles:Fo,loadQuota:bt,saveQuota:Ut,recordConnectionSent:wt,canSendConnection:Ke,getRecentConnections:St,getQuotaStatus:Qe,loadSyncState:Oo,saveSyncState:qo,commitDataSnapshot:Bo,logApplicationQuestions:Pe,getQuestionStats:Uo}});var Vo={};Te(Vo,{extractCertificationsFromDetails:()=>Sr,extractEducationFromDetails:()=>br,extractExperienceFromDetails:()=>yr,extractFeaturedFromDetails:()=>gr,extractRecommendationsFromDetails:()=>kr,extractSkillsFromDetails:()=>wr});async function yr(e,t){let o=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/experience/`);for(let s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(900);await g(1e3);let n=0;for(;n<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)n++,await g(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function l(c){let d=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(m=>m.tagName==="DIV");if(p.length<3)continue;let h=p.filter(m=>(m.textContent||"").trim().length>50);h.length<3||(f.textContent||"").length<500||d.push({el:f,count:h.length,totalText:(f.textContent||"").length})}return d.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),d[0]?.el}let a=l(s);if(!a)return[];let i=Array.from(a.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function u(c){let d=c[0]||null,f=null,p=null;if(c[1]){let C=c[1].split("\xB7").map(N=>N.trim());f=C[0]||null,C[1]&&(p=C[1])}let h=c.findIndex(C=>/(\d{4}|present)/i.test(C)&&/(-|–|—)/i.test(C)&&C.length<80),m=null,b=null;if(h>=0){let C=c[h].split("\xB7").map(N=>N.trim());m=C[0]||null,C[1]&&(b=C[1])}let y=null,k=-1;if(h>=0&&c[h+1]){let C=c[h+1],N=/^[>*\-•]|^&gt;/.test(C),Y=/https?:\/\//.test(C),U=/\d{4}/.test(C),ae=/,/.test(C)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(C);!N&&!Y&&!U&&C.length<100&&ae&&(y=C,k=h+1)}let v=null,w=-1,E=c[c.length-1];if(E&&/and\s+\+\d+\s+skills?$/i.test(E)){w=c.length-1;let C=E.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);C&&(v={listed:C[1].split(",").map(N=>N.trim()),additional:parseInt(C[2],10)})}let O=new Set([0,1,h,k,w].filter(C=>C>=0)),L=c.filter((C,N)=>!O.has(N)),W=L.length>0?L.join(`
5
5
 
6
6
  `):null;return{title:d,company:f,employmentType:p,dates:m,duration:b,location:y,description:W,skills:v,_raw:c}}return i.map(c=>{let f=(c.innerText||"").trim().split(`
7
- `).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return u(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 Xe(e,t,o){let r=t.replace(/\/+$/,"")+`/details/${o}/`;await e.goto(r,{waitUntil:"domcontentloaded",timeout:6e4}),await g(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 l=0;l<4;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(700);await g(800);let s=0;for(;s<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});)s++,await g(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(600)}async function et(e,t,o,r){try{return await r()}catch(n){let s=n.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(s))throw n;return/not available on profile/i.test(s)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${o} failed for ${e}: ${s.slice(0,120)}`),[])}}async function yr(e,t){return et(t,"featured","extractFeaturedFromDetails",async()=>(await Xe(e,t,"featured"),await e.evaluate(`(() => {
7
+ `).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return u(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 Xe(e,t,o){let r=t.replace(/\/+$/,"")+`/details/${o}/`;await e.goto(r,{waitUntil:"domcontentloaded",timeout:6e4}),await g(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 l=0;l<4;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(700);await g(800);let s=0;for(;s<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});)s++,await g(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(600)}async function et(e,t,o,r){try{return await r()}catch(n){let s=n.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(s))throw n;return/not available on profile/i.test(s)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${o} failed for ${e}: ${s.slice(0,120)}`),[])}}async function gr(e,t){return et(t,"featured","extractFeaturedFromDetails",async()=>(await Xe(e,t,"featured"),await e.evaluate(`(() => {
8
8
  ${Ze}
9
9
 
10
10
  const main = document.querySelector('main');
@@ -45,7 +45,7 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
45
45
  if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
46
46
  return true;
47
47
  });
48
- })()`)))}async function gr(e,t){return et(t,"education","extractEducationFromDetails",async()=>(await Xe(e,t,"education"),await e.evaluate(`(() => {
48
+ })()`)))}async function br(e,t){return et(t,"education","extractEducationFromDetails",async()=>(await Xe(e,t,"education"),await e.evaluate(`(() => {
49
49
  ${Ze}
50
50
 
51
51
  const main = document.querySelector('main');
@@ -82,7 +82,7 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
82
82
  if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
83
83
  return true;
84
84
  });
85
- })()`)))}async function br(e,t){return et(t,"skills","extractSkillsFromDetails",async()=>(await Xe(e,t,"skills"),await e.evaluate(`(() => {
85
+ })()`)))}async function wr(e,t){return et(t,"skills","extractSkillsFromDetails",async()=>(await Xe(e,t,"skills"),await e.evaluate(`(() => {
86
86
  ${Ze}
87
87
 
88
88
  const main = document.querySelector('main');
@@ -114,7 +114,7 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
114
114
  skills.push({ name, endorsements, _raw: lines });
115
115
  }
116
116
  return skills;
117
- })()`)))}async function wr(e,t){return et(t,"certifications","extractCertificationsFromDetails",async()=>(await Xe(e,t,"certifications"),await e.evaluate(`(() => {
117
+ })()`)))}async function Sr(e,t){return et(t,"certifications","extractCertificationsFromDetails",async()=>(await Xe(e,t,"certifications"),await e.evaluate(`(() => {
118
118
  ${Ze}
119
119
 
120
120
  const main = document.querySelector('main');
@@ -139,7 +139,7 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
139
139
 
140
140
  return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
141
141
  }).filter(e => e.name);
142
- })()`)))}async function Sr(e,t){return et(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Xe(e,t,"recommendations"),await e.evaluate(`(() => {
142
+ })()`)))}async function kr(e,t){return et(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Xe(e,t,"recommendations"),await e.evaluate(`(() => {
143
143
  ${Ze}
144
144
 
145
145
  const main = document.querySelector('main');
@@ -175,7 +175,7 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
175
175
  if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
176
176
  return true;
177
177
  });
178
- })()`)))}var Ze,Vo=Je(()=>{Re();Ze=`
178
+ })()`)))}var Ze,Ho=Je(()=>{Re();Ze=`
179
179
  function findEntryContainer(root) {
180
180
  const candidates = [];
181
181
  for (const div of root.querySelectorAll('div')) {
@@ -238,18 +238,18 @@ function findEntryContainer(root) {
238
238
  candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
239
239
  return candidates[0]?.el;
240
240
  }
241
- `});Re();import vs from"puppeteer";import*as Fn from"fs";import{createGraphClient as Wn,resolveToken as Yn}from"@ilivemylife/graph-sdk";import{config as Kn}from"dotenv";Kn();var So=Yn()||process.env.TOKEN;So||(console.error(`
241
+ `});Re();import xs from"puppeteer";import*as On from"fs";import{createGraphClient as Yn,resolveToken as Kn}from"@ilivemylife/graph-sdk";import{config as Qn}from"dotenv";Qn();var So=Kn()||process.env.TOKEN;So||(console.error(`
242
242
  [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.
243
243
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
244
244
  `),console.error(` Or add ILML_TOKEN=... to .env
245
- `),process.exit(1));var we=Wn({token:So});var Ie=12e4;async function Le(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 we.askLifebot(o,e,{timeout:Ie});return Ie=Math.max(12e4,Ie*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){Ie=Math.min(Ie*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(Ie/1e3)}s...`);continue}throw n}}async function It(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 Le(o)}async function it(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Le(o)}async function Ve(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Le(o)}jt();import{LIFEBOT_MESSAGE_TYPES as _n}from"@ilivemylife/graph-sdk";Re();await ze();async function Go(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: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function Ho(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function kr(e,t,o={}){let{extractExperience:r=!1,extractFeatured:n=!1,extractEducation:s=!1,extractSkills:l=!1,extractRecommendations:a=!1,extractCertifications:i=!1}=o;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await te(e)&&(console.log(" Dismissed Premium overlay"),await g(1500),await Go(e,t));let c=0;for(let v=0;v<2;v++){let w=await e.evaluate(()=>document.body.scrollHeight);for(let O=1;O<=6;O++)await e.evaluate(L=>window.scrollTo(0,L),w*O/6),await g(900);let E=await e.evaluate(()=>document.body.scrollHeight);if(E===c)break;c=E}await g(800);let d=await e.evaluate(()=>{let v=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),w=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),E=A=>{let R=(A||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(R)},O={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},L=document.querySelector("main");if(!L)return O;let W=[...Array.from(L.querySelectorAll("h1")),...Array.from(L.querySelectorAll("h2"))],C=Array.from(L.querySelectorAll("h2")),N=W.find(A=>{let R=A.textContent&&A.textContent.trim(),D=(R||"").replace(/\s*\(\d+\)$/,"").trim();return R&&R.length>1&&R.length<100&&!v.has(D)&&!w.has(D)}),Y=N?N.textContent.trim():null,U=N?N.parentElement:null;for(;U&&U!==L&&!Array.from(U.children).filter(R=>R.tagName==="P").some(R=>{let D=R.textContent&&R.textContent.trim();return D&&D.length>5&&!E(D)});)U=U.parentElement;let ae=null,H=null,_=null,B=null;if(U&&U!==L){let A=Array.from(U.children).filter(D=>D.tagName==="P").filter(D=>{let he=D.textContent&&D.textContent.trim();return he&&he.length>5&&!E(he)});if(A[0]&&(ae=A[0].textContent.trim()),A[1]){let D=A[1].textContent.trim().split(/\s*[·•]\s*/);H=D[0]||null,D.length>1&&(_=D.slice(1).join(" \xB7 "))}let R=Array.from(U.children).filter(D=>D.tagName==="DIV");for(let D=R.length-1;D>=0;D--){let he=R[D].textContent&&R[D].textContent.trim();if(he&&!(Y&&he.startsWith(Y))&&(B=he.split(/[·•]/)[0].trim(),B))break}}let T=null;if(U){let A=U.querySelectorAll("p, span, div");for(let R of A){let D=(R.textContent||"").trim().replace(/^[·•]\s*/,"");if(D==="1st"||D==="2nd"||D==="3rd"){T=D;break}}}let q=!!L.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),x=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),M=x&&x.src||null,j=L.textContent||"",I=null,G=j.match(/(\d+\+?)\s+connections\b/i);G&&(I=G[1]+" connections");let z=null,me=j.match(/(\d+)\s+mutual connection/i),Tt=j.match(/and\s+(\d+)\s+other mutual/i),Un=j.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);me?z=parseInt(me[1],10):Tt?z=2+parseInt(Tt[1],10):Un&&(z=2);let mo=null,ho=null,yo=C.find(A=>A.textContent&&A.textContent.trim()==="About");if(yo){let A=yo.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let R=(A.textContent||"").trim();R=R.replace(/^About\s*/,"").trim();let D=R.match(/Top skills\s*(.+?)$/i);if(D){let Rt=D[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Hn=>Hn.trim()).filter(Boolean);Rt.length>0&&Rt.length<10&&(ho=Rt)}R=R.split(/\n?…\s*more/i)[0].trim(),R=R.split(/\n?\.\.\.\s*more/i)[0].trim(),R=R.split(/\bTop skills\b/i)[0].trim(),R=R.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),mo=R||null}}let go=null,bo=C.find(A=>A.textContent&&A.textContent.trim()==="Activity");if(bo){let A=bo.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let R=(A.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);R&&(go=parseInt(R[1].replace(/,/g,""),10))}}let Bn=[...new Set(C.map(A=>(A.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(A=>A&&A.length>1&&A.length<60&&A!==Y).filter(A=>v.has(A)))],Be=document.body.textContent||"",Jn=/#OpenToWork\b/i.test(Be)||/\bOpen to work\b/.test(Be),Vn=/#Hiring\b/i.test(Be)||/\bI'?m hiring\b/i.test(Be)||/\bWe are hiring\b/i.test(Be);return{name:Y,title:ae,location:B,currentCompany:H,currentSchool:_,connectionDegree:T,hasVerifiedBadge:q,photoUrl:M,connectionsLevel:I,mutualConnectionsCount:z,followers:go,openToWork:Jn,hiring:Vn,about:mo,topSkills:ho,availableSections:Bn}});console.log(`Viewed: ${d.name} - ${d.title}`);let f=null,p=null,h=null,m=null,b=null,y=null;if(r||n||s||l||a||i){let v=await Promise.resolve().then(()=>(Vo(),Jo));r&&(f=await v.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),n&&(p=await v.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),s&&(h=await v.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),l&&(m=await v.extractSkillsFromDetails(e,t),console.log(` + Skills: ${m.length} entries`)),a&&(b=await v.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${b.length} entries`)),i&&(y=await v.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${y.length} entries`))}return{...d,profileUrl:t,...f!==null&&{experience:f},...p!==null&&{featured:p},...h!==null&&{education:h},...m!==null&&{skillsFull:m},...b!==null&&{recommendations:b},...y!==null&&{certifications:y}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function tt(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(o).map(i=>i.getAttribute("aria-label")),n=document.querySelector('button[aria-label*="Message"]'),s=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:o.length,pendingLabels:r,hasMessageBtn:!!n,hasConnectBtn:!!s};return o.length>0?{status:"pending",debug:l}:n&&!s?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Jt(e){let t=null,o=await e.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(i=u.textContent?.trim(),i&&!i.includes("notification")))return i;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let i=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),t=await e.evaluateHandle(c=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=c.toLowerCase().split(" ")[0],p=null,h=null;for(let m of d){let b=m.getBoundingClientRect();if(b.width===0||b.height===0)continue;if((m.getAttribute("aria-label")||"").toLowerCase().includes(f)){p=m;break}h||(h=m)}return p||h||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 i=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let u=await e.evaluate(d=>{let f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let b=m.getAttribute("aria-label")||"";return(b.toLowerCase().includes("invite")||b.toLowerCase().includes("connect"))&&f.test(b)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},i);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of f){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},i);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping primary button: wrong person (${i})`),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():"",s=null;for(let i of r){let u=await e.evaluate((c,d)=>{let f=c.className.includes("muted"),p=c.className.includes("sticky-header")||c.className.includes("sticky"),h=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(c.getAttribute("aria-label")||"").toLowerCase(),b=m.includes("invite"),y=d?m.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:h,hasInvite:b,matchesName:y,ariaLabel:m}},i,n);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}s=i;break}}for(let i of r)i!==s&&await i.dispose().catch(()=>{});if(s)return console.log(" Found: secondary button"),{button:s,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let i of a){let u=await e.evaluate(c=>{let d=c.getBoundingClientRect(),f=d.width>0&&d.height>0,p=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},i);if(u.isVisible&&!u.isInStickyHeader){l=i,console.log(" Found More button by ID pattern (main)");break}}for(let i of a)i!==l&&await i.dispose().catch(()=>{});if(!l&&a.length>0&&(l=a[a.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let i=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),h=f.getAttribute("aria-label")||"",m=f.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!c)return null;let d=c.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==c)return p;d=d.parentElement}return null});l=i?.asElement?.()||null,l||await i?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),l),await g(500),await e.evaluate(c=>c.click(),l),await g(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),u||(u=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect"]')),!u){let c=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=c?.asElement?.()||null,u||await c?.dispose?.().catch(()=>{})}if(!u){let c=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&f.push(m)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(i){console.log(" More dropdown click failed:",i.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&o){let i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping generic button: wrong person (${i})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function vr(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await g(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"),s=o.tag==="DIV";if(n){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(c=>c.click(),t)]),await g(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 g(2e3),"premium_redirect"}else s?(await e.evaluate(u=>u.click(),t),await g(3e3)):(await e.evaluate(u=>u.click(),t),await g(3e3));let l=e.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),i=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${i}`:` \u26A0 No modal after connect click \u2014 ${i}`),"success"}async function xr(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 g(1500);let o=await Jt(e);if(o){await e.evaluate(n=>n.click(),o),await g(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(n=>n.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function $r(e,t,o={}){let{source:r="unknown",skipQuotaGate:n=!1,skipQuotaRecord:s=!1}=o;if(!n){let a=Ke();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 l=await Er(e,t,o);return l.connectionSent&&!s&&wt(t,r),l}async function Er(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,skipIfPending:s=!0,skipIfConnected:l=!0,excludeLocations:a=[]}=o,i={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
246
- --- Connecting: ${u} ---`),a.length>0){let y=X()[t]?.location;if(Ho(y,a))return console.log(` \u26A0 Excluded location (stored): ${y}`),i.reason="excluded_location",i.profileInfo={location:y},i}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(5e3),await te(e)&&(console.log(" Dismissed Premium overlay"),await g(2e3),await Go(e,t),await g(2e3)),i.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),k=x=>{let M=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(M)},v={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},w=document.querySelector("main");if(!w)return v;let E=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],O=Array.from(w.querySelectorAll("h2")),L=E.find(x=>{let M=x.textContent&&x.textContent.trim();return M&&M.length>1&&M.length<100&&!y.has(M)&&M!=="0 notifications"}),W=L?L.textContent.trim():null,C=L?L.parentElement:null;for(;C&&C!==w&&!Array.from(C.children).filter(j=>j.tagName==="P").some(j=>{let I=j.textContent&&j.textContent.trim();return I&&I.length>5&&!k(I)});)C=C.parentElement;let N=null,Y=null,U=null;if(C&&C!==w){let x=Array.from(C.children),M=x.filter(I=>I.tagName==="P").filter(I=>{let G=I.textContent&&I.textContent.trim();return G&&G.length>5&&!k(G)});M[0]&&(N=M[0].textContent.trim()),M[1]&&(Y=M[1].textContent.trim());let j=x.filter(I=>I.tagName==="DIV");for(let I=j.length-1;I>=0;I--){let G=j[I].textContent&&j[I].textContent.trim();if(G&&!(W&&G.startsWith(W))&&(U=G.split(/[·•]/)[0].trim(),U))break}}let ae=null;if(C){let x=C.querySelectorAll("p, span, div");for(let M of x){let j=(M.textContent||"").trim().replace(/^[·•]\s*/,"");if(j==="1st"||j==="2nd"||j==="3rd"){ae=j;break}}}let H=null,_=O.find(x=>x.textContent&&x.textContent.trim()==="About");if(_){let x=_.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;x&&(H=(x.textContent||"").trim().replace(/^About\s*/,"").trim()||null,H&&(H=H.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]'),T=B&&B.src||null,q=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:W,title:N,location:U,about:H,company:Y,connectionDegree:ae,connectionsCount:null,mutualConnections:null,photoUrl:T,hasVerifiedBadge:q}}),a.length>0){let y=i.profileInfo?.location,k=X()[t]?.location,v=y||k;if(Ho(v,a))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${v}`),i.reason="excluded_location",i;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await tt(e);if(d==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await te(e);let f=await Jt(e);if(!f&&(await te(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await g(2e3),f=await Jt(e)),!f))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;if(i.method=f.method,await vr(e,f.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3);let y=await tt(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await te(e),await g(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),k),await g(500),await k.click().catch(()=>e.evaluate(w=>w.click(),k)),await g(2e3);let v=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(v){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(O=>O.click(),v),await g(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),i.reason="premium_required",i;if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.method="more_dropdown",i.withCustomMessage=!1,i;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await g(500),i.reason="premium_required",i}catch(v){return console.log(" More dropdown failed:",v.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let y=await e.$('button[aria-label="Dismiss"]');return y&&await y.click(),await g(500),i.reason="email_required",i}let m=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!m&&!b){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let v=k.querySelector('button[aria-label="Add a note"]'),w=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!v,sendWithout:!!w}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=k?.asElement?.()||null,m||await k.dispose().catch(()=>{})}if(y.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=k?.asElement?.()||null,b||await k.dispose().catch(()=>{})}}if(n){if(m&&r){if(console.log(" Adding personalized note..."),await m.click(),await g(1500),await e.$("div.modal-upsell")){let v=await xr(e);return i.success=v,i.connectionSent=v,i.reason=v?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let v=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=r.replace("{name}",v);await k.type(w,{delay:20}),await g(500);let E=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(E){try{await E.evaluate(O=>O.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=w,i}}}else if(b){console.log(" Sending without note...");try{await b.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}else if(m&&!r){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let y=b;if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}if(f.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3)),await te(e),await g(500);let k=await e.$$('button[id*="profile-overflow-action"]'),v=null;for(let w of k){let E=await e.evaluate(O=>{let L=O.getBoundingClientRect();return{visible:L.width>0&&L.height>0,inSticky:!!O.closest('.sticky-header, [class*="sticky"]')}},w);if(E.visible&&!E.inSticky){v=w;break}}!v&&k.length>0&&(v=k[k.length-1]);for(let w of k)w!==v&&await w.dispose().catch(()=>{});if(v)try{await e.evaluate(E=>E.scrollIntoView({behavior:"smooth",block:"center"}),v),await g(500),await v.click().catch(()=>e.evaluate(E=>E.click(),v)),await g(2e3);let w=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(w){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(W=>W.click(),w),await g(3e3);let E=e.url();if(E.includes("/premium/")||E.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await tt(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(i.reason="premium_required",i);if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;let L=await e.$('button[aria-label="Send without a note"]');if(L){console.log(" Modal appeared via More dropdown, sending without note...");try{await L.evaluate(W=>W.click())}catch{}return await g(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(u){console.error(` \u2717 Error: ${u.message}`),i.reason="error",i.error=u.message;let c=u.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{i.fatal=!0}return i}}async function Vt(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:s=20,viewOnly:l=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:i=null,excludeLocations:u=[],source:c="unknown"}=o,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
245
+ `),process.exit(1));var we=Yn({token:So});var Ie=12e4;async function Le(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 we.askLifebot(o,e,{timeout:Ie});return Ie=Math.max(12e4,Ie*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){Ie=Math.min(Ie*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(Ie/1e3)}s...`);continue}throw n}}async function It(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 Le(o)}async function it(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Le(o)}async function Ve(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Le(o)}jt();import{LIFEBOT_MESSAGE_TYPES as Tn}from"@ilivemylife/graph-sdk";Re();await ze();async function Wo(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: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function Go(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function vr(e,t,o={}){let{extractExperience:r=!1,extractFeatured:n=!1,extractEducation:s=!1,extractSkills:l=!1,extractRecommendations:a=!1,extractCertifications:i=!1}=o;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await te(e)&&(console.log(" Dismissed Premium overlay"),await g(1500),await Wo(e,t));let c=0;for(let v=0;v<2;v++){let w=await e.evaluate(()=>document.body.scrollHeight);for(let O=1;O<=6;O++)await e.evaluate(L=>window.scrollTo(0,L),w*O/6),await g(900);let E=await e.evaluate(()=>document.body.scrollHeight);if(E===c)break;c=E}await g(800);let d=await e.evaluate(()=>{let v=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),w=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),E=A=>{let R=(A||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(R)},O={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},L=document.querySelector("main");if(!L)return O;let W=[...Array.from(L.querySelectorAll("h1")),...Array.from(L.querySelectorAll("h2"))],C=Array.from(L.querySelectorAll("h2")),N=W.find(A=>{let R=A.textContent&&A.textContent.trim(),D=(R||"").replace(/\s*\(\d+\)$/,"").trim();return R&&R.length>1&&R.length<100&&!v.has(D)&&!w.has(D)}),Y=N?N.textContent.trim():null,U=N?N.parentElement:null;for(;U&&U!==L&&!Array.from(U.children).filter(R=>R.tagName==="P").some(R=>{let D=R.textContent&&R.textContent.trim();return D&&D.length>5&&!E(D)});)U=U.parentElement;let ae=null,H=null,_=null,B=null;if(U&&U!==L){let A=Array.from(U.children).filter(D=>D.tagName==="P").filter(D=>{let he=D.textContent&&D.textContent.trim();return he&&he.length>5&&!E(he)});if(A[0]&&(ae=A[0].textContent.trim()),A[1]){let D=A[1].textContent.trim().split(/\s*[·•]\s*/);H=D[0]||null,D.length>1&&(_=D.slice(1).join(" \xB7 "))}let R=Array.from(U.children).filter(D=>D.tagName==="DIV");for(let D=R.length-1;D>=0;D--){let he=R[D].textContent&&R[D].textContent.trim();if(he&&!(Y&&he.startsWith(Y))&&(B=he.split(/[·•]/)[0].trim(),B))break}}let T=null;if(U){let A=U.querySelectorAll("p, span, div");for(let R of A){let D=(R.textContent||"").trim().replace(/^[·•]\s*/,"");if(D==="1st"||D==="2nd"||D==="3rd"){T=D;break}}}let q=!!L.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),x=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),M=x&&x.src||null,j=L.textContent||"",I=null,G=j.match(/(\d+\+?)\s+connections\b/i);G&&(I=G[1]+" connections");let z=null,me=j.match(/(\d+)\s+mutual connection/i),Tt=j.match(/and\s+(\d+)\s+other mutual/i),Bn=j.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);me?z=parseInt(me[1],10):Tt?z=2+parseInt(Tt[1],10):Bn&&(z=2);let mo=null,ho=null,yo=C.find(A=>A.textContent&&A.textContent.trim()==="About");if(yo){let A=yo.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let R=(A.textContent||"").trim();R=R.replace(/^About\s*/,"").trim();let D=R.match(/Top skills\s*(.+?)$/i);if(D){let Rt=D[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Gn=>Gn.trim()).filter(Boolean);Rt.length>0&&Rt.length<10&&(ho=Rt)}R=R.split(/\n?…\s*more/i)[0].trim(),R=R.split(/\n?\.\.\.\s*more/i)[0].trim(),R=R.split(/\bTop skills\b/i)[0].trim(),R=R.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),mo=R||null}}let go=null,bo=C.find(A=>A.textContent&&A.textContent.trim()==="Activity");if(bo){let A=bo.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let R=(A.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);R&&(go=parseInt(R[1].replace(/,/g,""),10))}}let Jn=[...new Set(C.map(A=>(A.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(A=>A&&A.length>1&&A.length<60&&A!==Y).filter(A=>v.has(A)))],Be=document.body.textContent||"",Vn=/#OpenToWork\b/i.test(Be)||/\bOpen to work\b/.test(Be),Hn=/#Hiring\b/i.test(Be)||/\bI'?m hiring\b/i.test(Be)||/\bWe are hiring\b/i.test(Be);return{name:Y,title:ae,location:B,currentCompany:H,currentSchool:_,connectionDegree:T,hasVerifiedBadge:q,photoUrl:M,connectionsLevel:I,mutualConnectionsCount:z,followers:go,openToWork:Vn,hiring:Hn,about:mo,topSkills:ho,availableSections:Jn}});console.log(`Viewed: ${d.name} - ${d.title}`);let f=null,p=null,h=null,m=null,b=null,y=null;if(r||n||s||l||a||i){let v=await Promise.resolve().then(()=>(Ho(),Vo));r&&(f=await v.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),n&&(p=await v.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),s&&(h=await v.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),l&&(m=await v.extractSkillsFromDetails(e,t),console.log(` + Skills: ${m.length} entries`)),a&&(b=await v.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${b.length} entries`)),i&&(y=await v.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${y.length} entries`))}return{...d,profileUrl:t,...f!==null&&{experience:f},...p!==null&&{featured:p},...h!==null&&{education:h},...m!==null&&{skillsFull:m},...b!==null&&{recommendations:b},...y!==null&&{certifications:y}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function tt(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(o).map(i=>i.getAttribute("aria-label")),n=document.querySelector('button[aria-label*="Message"]'),s=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:o.length,pendingLabels:r,hasMessageBtn:!!n,hasConnectBtn:!!s};return o.length>0?{status:"pending",debug:l}:n&&!s?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Jt(e){let t=null,o=await e.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(i=u.textContent?.trim(),i&&!i.includes("notification")))return i;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let i=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),t=await e.evaluateHandle(c=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=c.toLowerCase().split(" ")[0],p=null,h=null;for(let m of d){let b=m.getBoundingClientRect();if(b.width===0||b.height===0)continue;if((m.getAttribute("aria-label")||"").toLowerCase().includes(f)){p=m;break}h||(h=m)}return p||h||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 i=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let u=await e.evaluate(d=>{let f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let b=m.getAttribute("aria-label")||"";return(b.toLowerCase().includes("invite")||b.toLowerCase().includes("connect"))&&f.test(b)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},i);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of f){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},i);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping primary button: wrong person (${i})`),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():"",s=null;for(let i of r){let u=await e.evaluate((c,d)=>{let f=c.className.includes("muted"),p=c.className.includes("sticky-header")||c.className.includes("sticky"),h=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(c.getAttribute("aria-label")||"").toLowerCase(),b=m.includes("invite"),y=d?m.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:h,hasInvite:b,matchesName:y,ariaLabel:m}},i,n);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}s=i;break}}for(let i of r)i!==s&&await i.dispose().catch(()=>{});if(s)return console.log(" Found: secondary button"),{button:s,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let i of a){let u=await e.evaluate(c=>{let d=c.getBoundingClientRect(),f=d.width>0&&d.height>0,p=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},i);if(u.isVisible&&!u.isInStickyHeader){l=i,console.log(" Found More button by ID pattern (main)");break}}for(let i of a)i!==l&&await i.dispose().catch(()=>{});if(!l&&a.length>0&&(l=a[a.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let i=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),h=f.getAttribute("aria-label")||"",m=f.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!c)return null;let d=c.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==c)return p;d=d.parentElement}return null});l=i?.asElement?.()||null,l||await i?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),l),await g(500),await e.evaluate(c=>c.click(),l),await g(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),u||(u=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect"]')),!u){let c=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=c?.asElement?.()||null,u||await c?.dispose?.().catch(()=>{})}if(!u){let c=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&f.push(m)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(i){console.log(" More dropdown click failed:",i.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&o){let i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping generic button: wrong person (${i})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function xr(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await g(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"),s=o.tag==="DIV";if(n){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(c=>c.click(),t)]),await g(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 g(2e3),"premium_redirect"}else s?(await e.evaluate(u=>u.click(),t),await g(3e3)):(await e.evaluate(u=>u.click(),t),await g(3e3));let l=e.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),i=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${i}`:` \u26A0 No modal after connect click \u2014 ${i}`),"success"}async function $r(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 g(1500);let o=await Jt(e);if(o){await e.evaluate(n=>n.click(),o),await g(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(n=>n.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Er(e,t,o={}){let{source:r="unknown",skipQuotaGate:n=!1,skipQuotaRecord:s=!1}=o;if(!n){let a=Ke();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 l=await Cr(e,t,o);return l.connectionSent&&!s&&wt(t,r),l}async function Cr(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,skipIfPending:s=!0,skipIfConnected:l=!0,excludeLocations:a=[]}=o,i={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
246
+ --- Connecting: ${u} ---`),a.length>0){let y=X()[t]?.location;if(Go(y,a))return console.log(` \u26A0 Excluded location (stored): ${y}`),i.reason="excluded_location",i.profileInfo={location:y},i}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(5e3),await te(e)&&(console.log(" Dismissed Premium overlay"),await g(2e3),await Wo(e,t),await g(2e3)),i.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),k=x=>{let M=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(M)},v={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},w=document.querySelector("main");if(!w)return v;let E=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],O=Array.from(w.querySelectorAll("h2")),L=E.find(x=>{let M=x.textContent&&x.textContent.trim();return M&&M.length>1&&M.length<100&&!y.has(M)&&M!=="0 notifications"}),W=L?L.textContent.trim():null,C=L?L.parentElement:null;for(;C&&C!==w&&!Array.from(C.children).filter(j=>j.tagName==="P").some(j=>{let I=j.textContent&&j.textContent.trim();return I&&I.length>5&&!k(I)});)C=C.parentElement;let N=null,Y=null,U=null;if(C&&C!==w){let x=Array.from(C.children),M=x.filter(I=>I.tagName==="P").filter(I=>{let G=I.textContent&&I.textContent.trim();return G&&G.length>5&&!k(G)});M[0]&&(N=M[0].textContent.trim()),M[1]&&(Y=M[1].textContent.trim());let j=x.filter(I=>I.tagName==="DIV");for(let I=j.length-1;I>=0;I--){let G=j[I].textContent&&j[I].textContent.trim();if(G&&!(W&&G.startsWith(W))&&(U=G.split(/[·•]/)[0].trim(),U))break}}let ae=null;if(C){let x=C.querySelectorAll("p, span, div");for(let M of x){let j=(M.textContent||"").trim().replace(/^[·•]\s*/,"");if(j==="1st"||j==="2nd"||j==="3rd"){ae=j;break}}}let H=null,_=O.find(x=>x.textContent&&x.textContent.trim()==="About");if(_){let x=_.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;x&&(H=(x.textContent||"").trim().replace(/^About\s*/,"").trim()||null,H&&(H=H.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]'),T=B&&B.src||null,q=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:W,title:N,location:U,about:H,company:Y,connectionDegree:ae,connectionsCount:null,mutualConnections:null,photoUrl:T,hasVerifiedBadge:q}}),a.length>0){let y=i.profileInfo?.location,k=X()[t]?.location,v=y||k;if(Go(v,a))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${v}`),i.reason="excluded_location",i;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await tt(e);if(d==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await te(e);let f=await Jt(e);if(!f&&(await te(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await g(2e3),f=await Jt(e)),!f))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;if(i.method=f.method,await xr(e,f.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3);let y=await tt(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await te(e),await g(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),k),await g(500),await k.click().catch(()=>e.evaluate(w=>w.click(),k)),await g(2e3);let v=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(v){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(O=>O.click(),v),await g(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),i.reason="premium_required",i;if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.method="more_dropdown",i.withCustomMessage=!1,i;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await g(500),i.reason="premium_required",i}catch(v){return console.log(" More dropdown failed:",v.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let y=await e.$('button[aria-label="Dismiss"]');return y&&await y.click(),await g(500),i.reason="email_required",i}let m=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!m&&!b){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let v=k.querySelector('button[aria-label="Add a note"]'),w=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!v,sendWithout:!!w}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=k?.asElement?.()||null,m||await k.dispose().catch(()=>{})}if(y.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=k?.asElement?.()||null,b||await k.dispose().catch(()=>{})}}if(n){if(m&&r){if(console.log(" Adding personalized note..."),await m.click(),await g(1500),await e.$("div.modal-upsell")){let v=await $r(e);return i.success=v,i.connectionSent=v,i.reason=v?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let v=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=r.replace("{name}",v);await k.type(w,{delay:20}),await g(500);let E=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(E){try{await E.evaluate(O=>O.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=w,i}}}else if(b){console.log(" Sending without note...");try{await b.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}else if(m&&!r){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let y=b;if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}if(f.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3)),await te(e),await g(500);let k=await e.$$('button[id*="profile-overflow-action"]'),v=null;for(let w of k){let E=await e.evaluate(O=>{let L=O.getBoundingClientRect();return{visible:L.width>0&&L.height>0,inSticky:!!O.closest('.sticky-header, [class*="sticky"]')}},w);if(E.visible&&!E.inSticky){v=w;break}}!v&&k.length>0&&(v=k[k.length-1]);for(let w of k)w!==v&&await w.dispose().catch(()=>{});if(v)try{await e.evaluate(E=>E.scrollIntoView({behavior:"smooth",block:"center"}),v),await g(500),await v.click().catch(()=>e.evaluate(E=>E.click(),v)),await g(2e3);let w=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(w){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(W=>W.click(),w),await g(3e3);let E=e.url();if(E.includes("/premium/")||E.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await tt(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(i.reason="premium_required",i);if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;let L=await e.$('button[aria-label="Send without a note"]');if(L){console.log(" Modal appeared via More dropdown, sending without note...");try{await L.evaluate(W=>W.click())}catch{}return await g(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(u){console.error(` \u2717 Error: ${u.message}`),i.reason="error",i.error=u.message;let c=u.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{i.fatal=!0}return i}}async function Vt(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:s=20,viewOnly:l=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:i=null,excludeLocations:u=[],source:c="unknown"}=o,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
247
247
  === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${s})`}`),l||console.log(`Custom messages: ${n?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!l){let p=Qe();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let f=0;for(let p=0;p<t.length;p++){let h=t[p];try{if(e.isClosed()){console.log(`
248
248
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
249
- \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=yt(h.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,i&&await i(h,d,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl}`);let b=null;if(l){let y=await kr(e,h.profileUrl);y?(ye(h.profileUrl,{...y,source:c}),d.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y}):(d.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=s){console.log(` Max connections per session (${s}) reached`);break}let y=Ke();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(b=await $r(e,h.profileUrl,{message:r,useCustomMessage:n,excludeLocations:u,source:c,skipQuotaGate:!0}),b.success)d.connectionsSent++;else switch(b.reason){case"pending":d.skipped.pending++;break;case"connected":d.skipped.connected++;break;case"email_required":d.skipped.email++;break;case"button_not_found":d.skipped.notFound++;break;case"excluded_location":d.skipped.excludedLocation++;break;default:d.errors++}}if(b?.fatal){console.log(`
249
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=yt(h.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,i&&await i(h,d,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl}`);let b=null;if(l){let y=await vr(e,h.profileUrl);y?(ye(h.profileUrl,{...y,source:c}),d.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y}):(d.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=s){console.log(` Max connections per session (${s}) reached`);break}let y=Ke();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(b=await Er(e,h.profileUrl,{message:r,useCustomMessage:n,excludeLocations:u,source:c,skipQuotaGate:!0}),b.success)d.connectionsSent++;else switch(b.reason){case"pending":d.skipped.pending++;break;case"connected":d.skipped.connected++;break;case"email_required":d.skipped.email++;break;case"button_not_found":d.skipped.notFound++;break;case"excluded_location":d.skipped.excludedLocation++;break;default:d.errors++}}if(b?.fatal){console.log(`
250
250
  \u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(b?.reason==="error"){if(f++,f>=3){console.log(`
251
251
  \u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(b&&b.reason&&(gt(h.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),qe(h.profileUrl,{source:c||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:b.reason})),i&&await i(h,d,b),p<t.length-1){let y=a+Math.random()*2e3;await g(y)}}if(console.log(`
252
- === Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!l){let p=Qe();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return d}await ze();Re();async function Wo(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,s=null;for(let d of r)if(n=document.querySelector(d),n){s=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,s="parent of li.scaffold-layout__list-item";break}f=f.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let l=n.scrollTop,a=300,i=300,u=50,c=0;for(;c<u&&(n.scrollBy(0,a),await new Promise(d=>setTimeout(d,i)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)c++;return{found:!0,usedSelector:s,initialScroll:l,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:c}},t)}async function Yo(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 l=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=n.querySelector("a.job-card-container__link");if(a){let i=a.getAttribute("href").split("?")[0],u=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),c=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),d=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),f=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:i,isEasyApply:l,applyType:l?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${i}`,jobTitle:u,companyName:c,location:d,salary:f||null,jobLink:l?a.href:null}}return{isEasyApply:!1}})});return t?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function Ko(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 g(2e3),t.success}async function Ht(e,t){let o=e.url();if(o.includes("/jobs/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let n=e.url();if(!n.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${n.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function Qo(e,t,o,r){for(let n of t){await Ht(e,r)&&(await te(e),await g(2e3));let l=await e.$(`a[data-control-id="${n.dataId}"]`),a="dataId";if(!l){let i=n.id?.match(/\d+/)?.[0];i&&(l=await e.$(`a[href*="/jobs/view/${i}/"]`),l&&(a="href"))}if(l){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${n.jobTitle}`);let i=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(f=>f.scrollIntoView({block:"center"}),l),await g(300),await l.click(),await g(1500);let u=!1;for(let f=0;f<8;f++){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!==i){u=!0;break}await g(500)}if(!u){await e.evaluate(f=>f.click(),l),await g(1500);for(let f=0;f<6;f++){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!==i){u=!0;break}await g(500)}u||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let c=await e.evaluate(()=>{let f=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of f)for(let h of p.querySelectorAll("button")){let m=h.innerText?.trim();if(m==="Continue applying"||m==="Got it"||m==="Dismiss")return h.click(),m}return null});c&&console.log(` Dismissed popup before processing (${c})`);let{keepGoing:d}=await o(e,n);if(!d)return{keepGoing:!1}}else{let i=n.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${n.jobTitle||n.id} (dataId=${n.dataId}, jobId=${i})`)}}return{keepGoing:!0}}async function zo(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 l=o.querySelector('a[href*="/in/"]'),a=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(l)return{name:a?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let l=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(l)return{name:r.textContent?.trim(),profileUrl:l.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 l=n.querySelector('a[href*="/in/"]');if(l)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"people_section"}}let s=t.querySelectorAll('a[href*="/in/"]');for(let l of s){let a=l.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:l.href?.split("?")[0],source:"details_link"}}return null})}async function Xo(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={},s=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let G of s){let z=G.querySelector(".job-criteria__subheader")?.textContent?.trim(),me=G.querySelector(".job-criteria__text")?.textContent?.trim();z&&me&&(n[z.toLowerCase()]=me)}let l=["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 G of l)new RegExp("\\b"+G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(G.replace(/\\\+/g,"+"));let u=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,m=(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()||"",v=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,w=y.match(/(\d[\d,]*)\s+applicant/i),E=w?parseInt(w[1].replace(/,/g,"")):null,O=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),L=Array.from(O).map(G=>G.innerText?.trim()?.replace(/\s+/g," ")),C=L.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,N=L.join(" ")+" "+y,Y=/\bremote\b/i.test(N)?"remote":/\bhybrid\b/i.test(N)?"hybrid":/\bon-?site\b/i.test(N)?"onsite":null,U=/\bcontract\b/i.test(N)?"contract":/\bfull-?time\b/i.test(N)?"full-time":/\bpart-?time\b/i.test(N)?"part-time":/\bfreelance\b/i.test(N)?"freelance":/\btemporary\b/i.test(N)?"temporary":null,H=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()||"",T=(H+" "+r+" "+B).toLowerCase(),q=H.toLowerCase(),x=[];/\bremote\b/.test(T)&&x.push("remote"),/\bhybrid\b/.test(T)&&x.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(T)&&x.push("onsite"),(x.length===0||!x.includes("remote")&&!x.includes("hybrid")&&!x.includes("onsite"))&&/remote/i.test(B)&&x.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(q)&&x.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(q)&&x.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(q)&&!x.includes("managerial")&&x.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(q)?x.push("junior"):/\b(senior|sr\.?)\b/i.test(q)?x.push("senior"):/\b(staff|principal|distinguished)\b/i.test(q)?x.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(q)?x.push("executive"):/\b(lead|team lead)\b/i.test(q)&&x.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(T)&&x.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(T)&&x.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(T)&&x.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(T)&&x.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(T)&&x.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(T)&&x.push("mobile"),/\b(architect)\b/i.test(q)&&x.push("architect"),/\b(consultant|consulting)\b/i.test(q)&&x.push("consultant");let M=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(M)||/\bcontract\b/i.test(T))&&x.push("contract"),/full.?time|permanent/i.test(M)&&x.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(B)&&x.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(B)&&x.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&x.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:d,companyName:p,companyUrl:m?m.startsWith("/")?"https://www.linkedin.com"+m:m:null,aboutCompany:u,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:v,applicantCount:E,companySize:C,workplaceType:Y,contractType:U,techStack:[...new Set(a)],jobTags:[...new Set(x)]}})}import"dotenv/config";import*as ne from"fs";import*as ee from"path";import{fileURLToPath as Cr}from"url";var Ar=Cr(import.meta.url),_r=ee.dirname(ee.dirname(Ar)),Ee=process.env.DATA_DIR?ee.resolve(process.env.DATA_DIR,"market-research"):ee.join(_r,"market-research"),Zo=ee.join(Ee,"scouted-jobs.json"),$i=ee.join(Ee,"discovered-people.json"),Ei=ee.join(Ee,"visit-log.json"),en=ee.join(Ee,"companies.json"),tn=ee.join(Ee,"job-decisions.json");function Gt(){ne.existsSync(Ee)||ne.mkdirSync(Ee,{recursive:!0})}function Wt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ne.writeFileSync(r,o);for(let n=0;n<3;n++)try{ne.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function Yt(e){try{if(ne.existsSync(e))return JSON.parse(ne.readFileSync(e,"utf-8"))}catch{}return null}function on(){ot=null,nt=null,Rr=null,rt=null,Lr=null}var ot=null;function Tr(){return ot||(ot=Yt(Zo)||{},ot)}function nn(e,t){if(!e)return;Gt();let o=Tr(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[n,s]of Object.entries(t))s!=null&&(o[e][n]=s);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{Wt(Zo,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}var nt=null;function rn(){return nt||(nt=Yt(tn)||{},nt)}function Me(e,t,o={}){if(!e||!t)return;Gt();let r=rn(),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{Wt(tn,r)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function sn(e){return rn()[e]||null}var Rr=null;var rt=null;function Ir(){return rt||(rt=Yt(en)||{},rt)}function Kt(e,t){if(!e)return;Gt();let o=Ir(),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{Wt(en,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}var Lr=null;import"dotenv/config";import*as $ from"fs";import*as oo from"os";import*as F from"path";import{fileURLToPath as Qr}from"url";var Xt={};Te(Xt,{NAME:()=>jr,VERSION:()=>Dr,up:()=>Or});import*as re from"fs";import*as kt from"path";var Dr=1,jr="normalize-jobs-and-questions",Nr=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Fr=50;function Qt(e){return re.existsSync(e)?JSON.parse(re.readFileSync(e,"utf-8")):null}function zt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{re.writeFileSync(r,o)}catch(n){try{re.unlinkSync(r)}catch{}throw n}try{re.renameSync(r,e)}catch(n){try{re.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function Or(e,t){let o=kt.join(e,"jobs.json"),r=kt.join(t,"scouted-jobs.json"),n=kt.join(e,"application-questions.json"),s=Qt(o)||{},l=Qt(r)||{},a=0,i=[];for(let c of Object.keys(s)){if(!l[c])continue;let d=l[c],f=s[c];for(let p of Nr)d[p]!=null&&f[p]==null&&(f[p]=d[p]);i.push(c),a++}a>0?(zt(o,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Qt(n);if(u&&Array.isArray(u.applications)){let c={},d=0;for(let f of u.applications){let p=f.jobId||"unknown";c[p]||(c[p]={applications:[]});let h=(f.questions||[]).map(m=>{let b={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=Fr?b.options=m.options:(b.optionsOmitted=!0,d++)),m.page&&(b.page=m.page),m.wasPreFilled&&(b.wasPreFilled=!0),m.wasRetry&&(b.wasRetry=!0),b});c[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||h.length,questions:h})}zt(n,c),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(i.length>0){for(let c of i)delete l[c];zt(r,l),console.log(` Phase 3: Removed ${i.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Zt={};Te(Zt,{NAME:()=>Pr,VERSION:()=>qr,up:()=>Br});import*as se from"fs";import*as ln from"path";var qr=2,Pr="reset-unread-flags";function Mr(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function Ur(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 s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function Br(e){let t=ln.join(e,"conversations.json"),o=Mr(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}Ur(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var eo={};Te(eo,{NAME:()=>Vr,VERSION:()=>Jr,up:()=>Kr});import*as ie from"fs";import*as an from"path";var Jr=3,Vr="recompute-last-message-by",Hr=new Set(["draft","confirmed","rejected","needs_review"]);function Gr(e){return ie.existsSync(e)?JSON.parse(ie.readFileSync(e,"utf-8")):null}function Wr(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ie.writeFileSync(r,o)}catch(n){try{ie.unlinkSync(r)}catch{}throw n}try{ie.renameSync(r,e)}catch(n){try{ie.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}function Yr(e,t){if(!e||e.length===0)return"them";let o=e.filter(s=>!Hr.has(s.status));if(o.length===0)return"them";let r=o.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,l)=>l.t-s.t).map(s=>s.m),n=r.length>0?r:[...o].reverse();for(let s of n){let l=s.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function Kr(e){let t=an.join(e,"conversations.json"),o=Gr(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,s=0,l=0;for(let a of Object.keys(o)){let i=o[a];if(!i||typeof i!="object")continue;Object.prototype.hasOwnProperty.call(i,"_cardSynced")&&(delete i._cardSynced,s++);let u=Array.isArray(i.messages)?i.messages:[],c=Yr(u,r),d=c==="me"?"awaiting_reply":"unanswered_by_us";i.lastMessageBy!==c&&l++,i.lastMessageBy=c,i.conversationStatus=d,n++}if(n===0){console.log(" No conversations to recompute.");return}Wr(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${l} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}await ze();var zr=Qr(import.meta.url),Xr=F.dirname(zr),Zr=F.dirname(F.dirname(Xr));function es(e){return e&&(e==="~"?oo.homedir():e.startsWith("~/")||e.startsWith("~\\")?F.join(oo.homedir(),e.slice(2)):e)}var ce=process.env.DATA_DIR?F.resolve(es(process.env.DATA_DIR)):Zr,Ae=F.join(ce,"collected-profiles"),_e=F.join(ce,"market-research"),Q=F.join(ce,".schema-version"),cn=[F.join(Ae,".schema-version"),F.join(_e,".schema-version")],ge=3,pe=[{version:1,module:Xt},{version:2,module:Zt},{version:3,module:eo}];(function(){pe.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of pe){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=pe.length?pe[pe.length-1].version:0;if(o!==ge)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${ge}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<pe.length;r++){let n=r+1;if(pe[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${pe[r].version}`)}})();function pn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
252
+ === Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!l){let p=Qe();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return d}await ze();Re();async function Yo(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,s=null;for(let d of r)if(n=document.querySelector(d),n){s=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,s="parent of li.scaffold-layout__list-item";break}f=f.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let l=n.scrollTop,a=300,i=300,u=50,c=0;for(;c<u&&(n.scrollBy(0,a),await new Promise(d=>setTimeout(d,i)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)c++;return{found:!0,usedSelector:s,initialScroll:l,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:c}},t)}async function Ko(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 l=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=n.querySelector("a.job-card-container__link");if(a){let i=a.getAttribute("href").split("?")[0],u=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),c=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),d=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),f=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:i,isEasyApply:l,applyType:l?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${i}`,jobTitle:u,companyName:c,location:d,salary:f||null,jobLink:l?a.href:null}}return{isEasyApply:!1}})});return t?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function Qo(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 g(2e3),t.success}async function Ht(e,t){let o=e.url();if(o.includes("/jobs/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let n=e.url();if(!n.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${n.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function zo(e,t,o,r){for(let n of t){await Ht(e,r)&&(await te(e),await g(2e3));let l=await e.$(`a[data-control-id="${n.dataId}"]`),a="dataId";if(!l){let i=n.id?.match(/\d+/)?.[0];i&&(l=await e.$(`a[href*="/jobs/view/${i}/"]`),l&&(a="href"))}if(l){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${n.jobTitle}`);let i=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(f=>f.scrollIntoView({block:"center"}),l),await g(300),await l.click(),await g(1500);let u=!1;for(let f=0;f<8;f++){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!==i){u=!0;break}await g(500)}if(!u){await e.evaluate(f=>f.click(),l),await g(1500);for(let f=0;f<6;f++){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!==i){u=!0;break}await g(500)}u||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let c=await e.evaluate(()=>{let f=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of f)for(let h of p.querySelectorAll("button")){let m=h.innerText?.trim();if(m==="Continue applying"||m==="Got it"||m==="Dismiss")return h.click(),m}return null});c&&console.log(` Dismissed popup before processing (${c})`);let{keepGoing:d}=await o(e,n);if(!d)return{keepGoing:!1}}else{let i=n.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${n.jobTitle||n.id} (dataId=${n.dataId}, jobId=${i})`)}}return{keepGoing:!0}}async function Xo(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 l=o.querySelector('a[href*="/in/"]'),a=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(l)return{name:a?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let l=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(l)return{name:r.textContent?.trim(),profileUrl:l.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 l=n.querySelector('a[href*="/in/"]');if(l)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"people_section"}}let s=t.querySelectorAll('a[href*="/in/"]');for(let l of s){let a=l.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:l.href?.split("?")[0],source:"details_link"}}return null})}async function Zo(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={},s=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let G of s){let z=G.querySelector(".job-criteria__subheader")?.textContent?.trim(),me=G.querySelector(".job-criteria__text")?.textContent?.trim();z&&me&&(n[z.toLowerCase()]=me)}let l=["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 G of l)new RegExp("\\b"+G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(G.replace(/\\\+/g,"+"));let u=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,m=(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()||"",v=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,w=y.match(/(\d[\d,]*)\s+applicant/i),E=w?parseInt(w[1].replace(/,/g,"")):null,O=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),L=Array.from(O).map(G=>G.innerText?.trim()?.replace(/\s+/g," ")),C=L.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,N=L.join(" ")+" "+y,Y=/\bremote\b/i.test(N)?"remote":/\bhybrid\b/i.test(N)?"hybrid":/\bon-?site\b/i.test(N)?"onsite":null,U=/\bcontract\b/i.test(N)?"contract":/\bfull-?time\b/i.test(N)?"full-time":/\bpart-?time\b/i.test(N)?"part-time":/\bfreelance\b/i.test(N)?"freelance":/\btemporary\b/i.test(N)?"temporary":null,H=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()||"",T=(H+" "+r+" "+B).toLowerCase(),q=H.toLowerCase(),x=[];/\bremote\b/.test(T)&&x.push("remote"),/\bhybrid\b/.test(T)&&x.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(T)&&x.push("onsite"),(x.length===0||!x.includes("remote")&&!x.includes("hybrid")&&!x.includes("onsite"))&&/remote/i.test(B)&&x.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(q)&&x.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(q)&&x.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(q)&&!x.includes("managerial")&&x.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(q)?x.push("junior"):/\b(senior|sr\.?)\b/i.test(q)?x.push("senior"):/\b(staff|principal|distinguished)\b/i.test(q)?x.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(q)?x.push("executive"):/\b(lead|team lead)\b/i.test(q)&&x.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(T)&&x.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(T)&&x.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(T)&&x.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(T)&&x.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(T)&&x.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(T)&&x.push("mobile"),/\b(architect)\b/i.test(q)&&x.push("architect"),/\b(consultant|consulting)\b/i.test(q)&&x.push("consultant");let M=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(M)||/\bcontract\b/i.test(T))&&x.push("contract"),/full.?time|permanent/i.test(M)&&x.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(B)&&x.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(B)&&x.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&x.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:d,companyName:p,companyUrl:m?m.startsWith("/")?"https://www.linkedin.com"+m:m:null,aboutCompany:u,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:v,applicantCount:E,companySize:C,workplaceType:Y,contractType:U,techStack:[...new Set(a)],jobTags:[...new Set(x)]}})}import"dotenv/config";import*as ne from"fs";import*as ee from"path";import{fileURLToPath as Ar}from"url";var _r=Ar(import.meta.url),Tr=ee.dirname(ee.dirname(_r)),Ee=process.env.DATA_DIR?ee.resolve(process.env.DATA_DIR,"market-research"):ee.join(Tr,"market-research"),en=ee.join(Ee,"scouted-jobs.json"),Ei=ee.join(Ee,"discovered-people.json"),Ci=ee.join(Ee,"visit-log.json"),tn=ee.join(Ee,"companies.json"),on=ee.join(Ee,"job-decisions.json");function Gt(){ne.existsSync(Ee)||ne.mkdirSync(Ee,{recursive:!0})}function Wt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ne.writeFileSync(r,o);for(let n=0;n<3;n++)try{ne.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function Yt(e){try{if(ne.existsSync(e))return JSON.parse(ne.readFileSync(e,"utf-8"))}catch{}return null}function nn(){ot=null,nt=null,Ir=null,rt=null,Dr=null}var ot=null;function Rr(){return ot||(ot=Yt(en)||{},ot)}function rn(e,t){if(!e)return;Gt();let o=Rr(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[n,s]of Object.entries(t))s!=null&&(o[e][n]=s);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{Wt(en,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}var nt=null;function sn(){return nt||(nt=Yt(on)||{},nt)}function Me(e,t,o={}){if(!e||!t)return;Gt();let r=sn(),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{Wt(on,r)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function ln(e){return sn()[e]||null}var Ir=null;var rt=null;function Lr(){return rt||(rt=Yt(tn)||{},rt)}function Kt(e,t){if(!e)return;Gt();let o=Lr(),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{Wt(tn,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}var Dr=null;import"dotenv/config";import*as $ from"fs";import*as oo from"os";import*as F from"path";import{fileURLToPath as zr}from"url";var Xt={};Te(Xt,{NAME:()=>Nr,VERSION:()=>jr,up:()=>qr});import*as re from"fs";import*as kt from"path";var jr=1,Nr="normalize-jobs-and-questions",Fr=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Or=50;function Qt(e){return re.existsSync(e)?JSON.parse(re.readFileSync(e,"utf-8")):null}function zt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{re.writeFileSync(r,o)}catch(n){try{re.unlinkSync(r)}catch{}throw n}try{re.renameSync(r,e)}catch(n){try{re.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function qr(e,t){let o=kt.join(e,"jobs.json"),r=kt.join(t,"scouted-jobs.json"),n=kt.join(e,"application-questions.json"),s=Qt(o)||{},l=Qt(r)||{},a=0,i=[];for(let c of Object.keys(s)){if(!l[c])continue;let d=l[c],f=s[c];for(let p of Fr)d[p]!=null&&f[p]==null&&(f[p]=d[p]);i.push(c),a++}a>0?(zt(o,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Qt(n);if(u&&Array.isArray(u.applications)){let c={},d=0;for(let f of u.applications){let p=f.jobId||"unknown";c[p]||(c[p]={applications:[]});let h=(f.questions||[]).map(m=>{let b={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=Or?b.options=m.options:(b.optionsOmitted=!0,d++)),m.page&&(b.page=m.page),m.wasPreFilled&&(b.wasPreFilled=!0),m.wasRetry&&(b.wasRetry=!0),b});c[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||h.length,questions:h})}zt(n,c),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(i.length>0){for(let c of i)delete l[c];zt(r,l),console.log(` Phase 3: Removed ${i.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Zt={};Te(Zt,{NAME:()=>Mr,VERSION:()=>Pr,up:()=>Jr});import*as se from"fs";import*as an from"path";var Pr=2,Mr="reset-unread-flags";function Ur(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function Br(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 s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function Jr(e){let t=an.join(e,"conversations.json"),o=Ur(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}Br(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var eo={};Te(eo,{NAME:()=>Hr,VERSION:()=>Vr,up:()=>Qr});import*as ie from"fs";import*as cn from"path";var Vr=3,Hr="recompute-last-message-by",Gr=new Set(["draft","confirmed","rejected","needs_review"]);function Wr(e){return ie.existsSync(e)?JSON.parse(ie.readFileSync(e,"utf-8")):null}function Yr(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ie.writeFileSync(r,o)}catch(n){try{ie.unlinkSync(r)}catch{}throw n}try{ie.renameSync(r,e)}catch(n){try{ie.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}function Kr(e,t){if(!e||e.length===0)return"them";let o=e.filter(s=>!Gr.has(s.status));if(o.length===0)return"them";let r=o.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,l)=>l.t-s.t).map(s=>s.m),n=r.length>0?r:[...o].reverse();for(let s of n){let l=s.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function Qr(e){let t=cn.join(e,"conversations.json"),o=Wr(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,s=0,l=0;for(let a of Object.keys(o)){let i=o[a];if(!i||typeof i!="object")continue;Object.prototype.hasOwnProperty.call(i,"_cardSynced")&&(delete i._cardSynced,s++);let u=Array.isArray(i.messages)?i.messages:[],c=Kr(u,r),d=c==="me"?"awaiting_reply":"unanswered_by_us";i.lastMessageBy!==c&&l++,i.lastMessageBy=c,i.conversationStatus=d,n++}if(n===0){console.log(" No conversations to recompute.");return}Yr(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${l} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}await ze();var Xr=zr(import.meta.url),Zr=F.dirname(Xr),es=F.dirname(F.dirname(Zr));function ts(e){return e&&(e==="~"?oo.homedir():e.startsWith("~/")||e.startsWith("~\\")?F.join(oo.homedir(),e.slice(2)):e)}var ce=process.env.DATA_DIR?F.resolve(ts(process.env.DATA_DIR)):es,Ae=F.join(ce,"collected-profiles"),_e=F.join(ce,"market-research"),Q=F.join(ce,".schema-version"),un=[F.join(Ae,".schema-version"),F.join(_e,".schema-version")],ge=3,pe=[{version:1,module:Xt},{version:2,module:Zt},{version:3,module:eo}];(function(){pe.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of pe){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=pe.length?pe[pe.length-1].version:0;if(o!==ge)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${ge}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<pe.length;r++){let n=r+1;if(pe[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${pe[r].version}`)}})();function mn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
253
253
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
254
254
  `),process.exit(1));try{$.mkdirSync(ce,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
255
255
  [FATAL] Cannot create DATA_DIR (${ce}): ${t.message}`),console.error(` Fix the path or permissions and try again.
@@ -259,64 +259,64 @@ function findEntryContainer(root) {
259
259
  [FATAL] DATA_DIR (${ce}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
260
260
  `),process.exit(1));for(let t of[Ae,_e]){let o;try{o=$.lstatSync(t)}catch(r){if(r.code==="ENOENT")continue;throw r}o.isSymbolicLink()&&(console.error(`
261
261
  [FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
262
- `),process.exit(1))}}var Ce=F.join(ce,".migration-lock");function ts(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return $.writeFileSync(Ce,e,{flag:"wx"}),!0}catch(r){if(r.code!=="EEXIST")throw r}let t;try{t=JSON.parse($.readFileSync(Ce,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let r=!1;try{process.kill(t.pid,0),r=!0}catch(l){l.code==="EPERM"&&(r=!0)}let n=24*60*60*1e3,s=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(s=Date.now()-l)}r&&s<n&&(console.error(`
262
+ `),process.exit(1))}}var Ce=F.join(ce,".migration-lock");function os(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return $.writeFileSync(Ce,e,{flag:"wx"}),!0}catch(r){if(r.code!=="EEXIST")throw r}let t;try{t=JSON.parse($.readFileSync(Ce,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let r=!1;try{process.kill(t.pid,0),r=!0}catch(l){l.code==="EPERM"&&(r=!0)}let n=24*60*60*1e3,s=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(s=Date.now()-l)}r&&s<n&&(console.error(`
263
263
  [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Ce}
264
264
  `),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
265
- `),process.exit(1)),r&&s>=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=Ce+".tmp";try{return $.writeFileSync(o,e),$.renameSync(o,Ce),!0}catch(r){try{$.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${r.message}`)}}function no(){try{if(JSON.parse($.readFileSync(Ce,"utf-8")).pid!==process.pid)return;$.unlinkSync(Ce)}catch{}}var un=!1;function os(){if(un)return;un=!0;let e=()=>{try{no()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function ns(){if($.existsSync(Q))return;let e=[],t=[];for(let s of cn)if($.existsSync(s))try{e.push({file:s,schema:vt(s)})}catch(l){t.push({file:s,err:l.message})}if(t.length>0){console.error(`
265
+ `),process.exit(1)),r&&s>=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=Ce+".tmp";try{return $.writeFileSync(o,e),$.renameSync(o,Ce),!0}catch(r){try{$.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${r.message}`)}}function no(){try{if(JSON.parse($.readFileSync(Ce,"utf-8")).pid!==process.pid)return;$.unlinkSync(Ce)}catch{}}var dn=!1;function ns(){if(dn)return;dn=!0;let e=()=>{try{no()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function rs(){if($.existsSync(Q))return;let e=[],t=[];for(let s of un)if($.existsSync(s))try{e.push({file:s,schema:vt(s)})}catch(l){t.push({file:s,err:l.message})}if(t.length>0){console.error(`
266
266
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of t)console.error(` ${s.file}: ${s.err}`);console.error(`
267
267
  Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
268
268
  `),process.exit(1)}if(e.length===0)return;let o=e.map(s=>s.schema.version);if(new Set(o).size>1){console.error(`
269
269
  [FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
270
- `),process.exit(1)}let r=e[0].schema,n=Q+".tmp";try{$.writeFileSync(n,JSON.stringify(r,null,2)),$.renameSync(n,Q)}catch(s){try{$.unlinkSync(n)}catch{}throw s}for(let s of cn)if($.existsSync(s))try{$.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${Q}`)}function rs(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 vt(e){let t=$.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function dn(){if(ns(),!$.existsSync(Q))return{version:0,migrations:[]};let e;try{e=vt(Q)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
270
+ `),process.exit(1)}let r=e[0].schema,n=Q+".tmp";try{$.writeFileSync(n,JSON.stringify(r,null,2)),$.renameSync(n,Q)}catch(s){try{$.unlinkSync(n)}catch{}throw s}for(let s of un)if($.existsSync(s))try{$.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${Q}`)}function ss(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 vt(e){let t=$.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function fn(){if(rs(),!$.existsSync(Q))return{version:0,migrations:[]};let e;try{e=vt(Q)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
271
271
  [FATAL] ${Q} 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.
272
- `),process.exit(1)}let t=rs(e);return t===null&&(console.error(`
272
+ `),process.exit(1)}let t=ss(e);return t===null&&(console.error(`
273
273
  [FATAL] ${Q} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
274
- `),process.exit(1)),t}function mn(e){try{$.chmodSync(e,384)}catch{}}function ss(e){if(pn(),$.existsSync(Q))try{if($.lstatSync(Q).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${Q}. 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=Q+".tmp";try{$.writeFileSync(t,JSON.stringify(e,null,2)),mn(t),$.renameSync(t,Q)}catch(o){try{$.unlinkSync(t)}catch{}throw o}}function fn(e,t){if(!$.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,r=$.readdirSync(e).filter(a=>{let i=a.toLowerCase();if(i.includes(".backup")||i===".schema-version"||i.endsWith(".tmp"))return!1;try{return $.statSync(F.join(e,a)).isFile()}catch{return!1}}),n=0,s=0,l=[];for(let a of r){let i=F.join(e,a),u=F.join(e,a+o);if($.existsSync(u)){s++;continue}try{yn(i,u),n++}catch(c){l.push({file:a,err:c.message})}}if(l.length>0){let a=new Error(`Failed to back up ${l.length} file(s) in ${F.basename(e)}/: `+l.map(i=>`${i.file} (${i.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(n>0||s>0){let a=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${n} files in ${F.basename(e)}/ (${o})${a}`)}}var to=!1;async function hn(){if(to)return;pn(),us();let t=dn().version;if(t===ge){to=!0;return}os(),ts(),process.on("exit",no),t>ge&&(console.error(`
274
+ `),process.exit(1)),t}function hn(e){try{$.chmodSync(e,384)}catch{}}function is(e){if(mn(),$.existsSync(Q))try{if($.lstatSync(Q).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${Q}. 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=Q+".tmp";try{$.writeFileSync(t,JSON.stringify(e,null,2)),hn(t),$.renameSync(t,Q)}catch(o){try{$.unlinkSync(t)}catch{}throw o}}function pn(e,t){if(!$.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,r=$.readdirSync(e).filter(a=>{let i=a.toLowerCase();if(i.includes(".backup")||i===".schema-version"||i.endsWith(".tmp"))return!1;try{return $.statSync(F.join(e,a)).isFile()}catch{return!1}}),n=0,s=0,l=[];for(let a of r){let i=F.join(e,a),u=F.join(e,a+o);if($.existsSync(u)){s++;continue}try{gn(i,u),n++}catch(c){l.push({file:a,err:c.message})}}if(l.length>0){let a=new Error(`Failed to back up ${l.length} file(s) in ${F.basename(e)}/: `+l.map(i=>`${i.file} (${i.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(n>0||s>0){let a=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${n} files in ${F.basename(e)}/ (${o})${a}`)}}var to=!1;async function yn(){if(to)return;mn(),ds();let t=fn().version;if(t===ge){to=!0;return}ns(),os(),process.on("exit",no),t>ge&&(console.error(`
275
275
  [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${ge}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
276
276
  `),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${ge}.
277
277
  `),process.exit(1)),console.log(`
278
- \u{1F4E6} Schema migration: v${t} \u2192 v${ge}`);let o=ds();if(!o.ok){console.error(`
278
+ \u{1F4E6} Schema migration: v${t} \u2192 v${ge}`);let o=fs();if(!o.ok){console.error(`
279
279
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let n of o.broken)console.error(` ${n.dir}/${n.file}: ${n.err}`);console.error(`
280
280
  Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
281
281
  `),process.exit(1)}let r=pe.filter(n=>n.version>t);for(let n of r){console.log(`
282
- Running migration v${String(n.version).padStart(3,"0")}...`);let s=`v${String(n.version).padStart(3,"0")}`,l=`.pre-${s}.backup`;try{fn(Ae,n.version),fn(_e,n.version)}catch(i){console.error(`
282
+ Running migration v${String(n.version).padStart(3,"0")}...`);let s=`v${String(n.version).padStart(3,"0")}`,l=`.pre-${s}.backup`;try{pn(Ae,n.version),pn(_e,n.version)}catch(i){console.error(`
283
283
  [FATAL] Pre-migration backup failed for ${s}: ${i.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
284
284
  `),process.exit(1)}let a=n.module;try{await a.up(Ae,_e)}catch(i){console.error(`
285
- [FATAL] Migration ${s} failed: ${i.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let u=fs(l);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
285
+ [FATAL] Migration ${s} failed: ${i.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let u=ps(l);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
286
286
  `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${l} files back over the originals.
287
287
  `))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${l} files back over the originals.
288
- `)}process.exit(1)}try{let i=new Date().toISOString(),u={version:n.version,name:a.NAME||s,appliedAt:i},c=dn();c.version=n.version,c.migratedAt=i,c.migrations=c.migrations||[],c.migrations.push(u),ss(c)}catch(i){console.error(`
288
+ `)}process.exit(1)}try{let i=new Date().toISOString(),u={version:n.version,name:a.NAME||s,appliedAt:i},c=fn();c.version=n.version,c.migratedAt=i,c.migrations=c.migrations||[],c.migrations.push(u),is(c)}catch(i){console.error(`
289
289
  [FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${i.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 ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
290
- `),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{Mt()}catch{}try{on()}catch{}to=!0,no(),console.log(`
290
+ `),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{Mt()}catch{}try{nn()}catch{}to=!0,no(),console.log(`
291
291
  \u2713 Schema is now at v${ge}
292
- `)}var is=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function ls(e){let t=e.toLowerCase();return is.some(o=>o.test(t))}var as=6e4;function cs(){let e=Date.now(),t=[];for(let o of[ce,Ae,_e]){if(!$.existsSync(o))continue;let r;try{r=$.readdirSync(o)}catch{continue}for(let n of r){if(!ls(n))continue;let s=F.join(o,n);try{let l=$.statSync(s);if(!l.isFile()||e-l.mtimeMs<as)continue;t.push({dir:o,file:n,fullPath:s})}catch{}}}return t}function us({verbose:e=!1}={}){let t=cs();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let r of t)try{$.unlinkSync(r.fullPath),o++,e&&console.log(` Removed orphan: ${F.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 ds(){let e=[];for(let t of[Ae,_e]){if(!$.existsSync(t))continue;let o=$.readdirSync(t).filter(r=>{let n=r.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let r of o){let n=F.join(t,r);try{vt(n)}catch(s){e.push({dir:F.basename(t),file:r,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function fs(e){let t=[],o=[];for(let s of[Ae,_e]){if(!$.existsSync(s))continue;let l=$.readdirSync(s).filter(a=>a.endsWith(e));for(let a of l){let i=F.join(s,a),u=a.slice(0,-e.length),c=F.join(s,u);try{u.toLowerCase().endsWith(".json")?vt(i):$.accessSync(i,$.constants.R_OK),t.push({backupPath:i,originalPath:c,fileName:a,dir:s})}catch(d){o.push(`${F.basename(s)}/${a}: ${d.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let r=0,n=[];for(let{backupPath:s,originalPath:l,fileName:a,dir:i}of t)try{yn(s,l),r++}catch(u){n.push(`${F.basename(i)}/${a}: ${u.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:r}:{ok:!0,restored:r}}function yn(e,t){let o=t+".tmp";try{$.copyFileSync(e,o),mn(o)}catch(r){try{$.unlinkSync(o)}catch{}throw r}try{$.renameSync(o,t)}catch(r){try{$.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 le from"fs";import*as be from"path";import{fileURLToPath as hs}from"url";import"dotenv/config";function ps(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 ms({scriptName:e,mode:t,status:o,error:r,duration:n}){let s=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),a=n?` ${ps(n)}`:"",i=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${u} \u2014 ${i} \u2014 ${l}${a}`}async function gn({scriptName:e,mode:t,status:o,summaryLines:r,error:n,duration:s}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(r)||r.length===0)return;let i=`**${ms({scriptName:e,mode:t,status:o,error:n,duration:s})}**
292
+ `)}var ls=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function as(e){let t=e.toLowerCase();return ls.some(o=>o.test(t))}var cs=6e4;function us(){let e=Date.now(),t=[];for(let o of[ce,Ae,_e]){if(!$.existsSync(o))continue;let r;try{r=$.readdirSync(o)}catch{continue}for(let n of r){if(!as(n))continue;let s=F.join(o,n);try{let l=$.statSync(s);if(!l.isFile()||e-l.mtimeMs<cs)continue;t.push({dir:o,file:n,fullPath:s})}catch{}}}return t}function ds({verbose:e=!1}={}){let t=us();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let r of t)try{$.unlinkSync(r.fullPath),o++,e&&console.log(` Removed orphan: ${F.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 fs(){let e=[];for(let t of[Ae,_e]){if(!$.existsSync(t))continue;let o=$.readdirSync(t).filter(r=>{let n=r.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let r of o){let n=F.join(t,r);try{vt(n)}catch(s){e.push({dir:F.basename(t),file:r,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function ps(e){let t=[],o=[];for(let s of[Ae,_e]){if(!$.existsSync(s))continue;let l=$.readdirSync(s).filter(a=>a.endsWith(e));for(let a of l){let i=F.join(s,a),u=a.slice(0,-e.length),c=F.join(s,u);try{u.toLowerCase().endsWith(".json")?vt(i):$.accessSync(i,$.constants.R_OK),t.push({backupPath:i,originalPath:c,fileName:a,dir:s})}catch(d){o.push(`${F.basename(s)}/${a}: ${d.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let r=0,n=[];for(let{backupPath:s,originalPath:l,fileName:a,dir:i}of t)try{gn(s,l),r++}catch(u){n.push(`${F.basename(i)}/${a}: ${u.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:r}:{ok:!0,restored:r}}function gn(e,t){let o=t+".tmp";try{$.copyFileSync(e,o),hn(o)}catch(r){try{$.unlinkSync(o)}catch{}throw r}try{$.renameSync(o,t)}catch(r){try{$.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 le from"fs";import*as be from"path";import{fileURLToPath as ys}from"url";import"dotenv/config";function ms(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 hs({scriptName:e,mode:t,status:o,error:r,duration:n}){let s=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),a=n?` ${ms(n)}`:"",i=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${u} \u2014 ${i} \u2014 ${l}${a}`}async function bn({scriptName:e,mode:t,status:o,summaryLines:r,error:n,duration:s}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(r)||r.length===0)return;let i=`**${hs({scriptName:e,mode:t,status:o,error:n,duration:s})}**
293
293
 
294
294
  ${r.join(`
295
- `)}`;try{await we.addMessage(l,i)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var ys=hs(import.meta.url),gs=be.dirname(be.dirname(ys)),ro=process.env.DATA_DIR?be.resolve(process.env.DATA_DIR,"collected-profiles"):be.join(gs,"collected-profiles"),so=be.join(ro,"run-log.json");function bs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";le.writeFileSync(r,o);for(let n=0;n<3;n++)try{le.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function bn(){try{if(!le.existsSync(so))return{runs:[]};let e=JSON.parse(le.readFileSync(so,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function wn(e){le.existsSync(ro)||le.mkdirSync(ro,{recursive:!0});try{bs(so,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Sn(e,t="default"){let o=bn();for(let l of o.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.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 s=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(l=>new Date(l.timestamp).getTime()>s),wn(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function kn(e,t,o=null,r=null){if(!e)return;let n=null;try{let l=bn(),a=l.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 i=l.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());i&&(i.status=t,i.result=t,i.duration=Date.now()-e.startTime,i.stats=o,i.error=r,n=i.duration)}wn(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let s=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";gn({scriptName:e.script,mode:e.mode,status:l,summaryLines:s,error:r,duration:n??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import vn from"fs";import ws from"path";var Ss="cookies.json";function ks(){let e=process.env.ILML_SCOPE_DIR;return e?ws.join(e,"plugins-state","linkedin","cookies.json"):Ss}function io(){let e=ks();if(!vn.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=vn.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}Re();async function xt(e,t,o="op"){let r,n=new Promise((s,l)=>{r=setTimeout(()=>l(new Error(`${o} timeout after ${t}ms`)),t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}function Ue(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 xn(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await xt(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function $n(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await xn(e,t)?!0:(await g(o),await xn(e,t))}async function En(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await xt(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function Cn(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:s=null}={}){try{await xt(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let l=await e.newPage();if(s)try{await s(l)}catch{}if(n)try{let a=n();Array.isArray(a)&&a.length>0&&await l.setCookie(...a)}catch{}if(o){await l.goto(o,{waitUntil:"domcontentloaded",timeout:r});let a=l.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 l}async function An(e,{launchFn:t,returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:s=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");try{await xt(e.close(),5e3,"oldBrowser.close")}catch{}let l=await t(),a=await l.newPage();if(s)try{await s(a)}catch{}if(n)try{let i=n();Array.isArray(i)&&i.length>0&&await a.setCookie(...i)}catch{}if(o){await a.goto(o,{waitUntil:"domcontentloaded",timeout:r});let i=a.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(i))throw new Error(`Session expired after browser restart \u2014 landed on ${i}. Run: ilml linkedin login`)}return{browser:l,page:a}}await hn();var _t=0,xs=process.env.FUNNEL_CONNECT_RECRUITERS==="true",$s=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Es=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),Cs=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",lo=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],$t=-1;async function As(){if($t===-1){let e=await Le("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}"`);$t=wo(e)+1,console.log(`lastIndex initialized as: ${$t}`)}return $t++}var On=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${On}`);var _s=[{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}],st={};function qn(e){let t=e;for(let o=0;t&&o<5;o++){let r=_s.find(n=>{try{return n.match(t)}catch{return!1}});if(r)return r;t=t.cause}return null}function Ts(e){return st[e]=(st[e]||0)+1,st[e]}function Tn(){for(let e of Object.keys(st))st[e]=0}var ao=0;function Rs(){return ao++,ao>=On?(console.log(`Max run counter reached with ${ao}`),!1):!0}async function Is(e){let t=await Wo(e)}async function Ls(e){return Yo(e,{easyApplyOnly:!0})}async function Ds(e){return Ko(e)}async function fo(e,t){return Ht(e,t)}var co=3,js=2;async function Ct(e,t){let{searchUrl:o,launchFn:r,setupPage:n,cookiesProvider:s}=e.recoveryCtx,l=await En(e.browser);if(!l||e._pageRecoveryStreak>=co){if(S.browserRestarts>=js)throw new Error(`CDP unrecoverable: ${S.browserRestarts} browser restart${S.browserRestarts===1?"":"s"} and ${S.cdpRecoveries} page recover${S.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let i=l?`${co} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${i}). Reason: ${t}`);let u=await An(e.browser,{launchFn:r,setupPage:n,cookiesProvider:s,returnUrl:o});e.browser=u.browser,e.page=u.page,e._pageRecoveryStreak=0,S.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${S.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${co}). Reason: ${t}`),e.page=await Cn(e.browser,e.page,{returnUrl:o,cookiesProvider:s,setupPage:n}),e._pageRecoveryStreak+=1,S.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${S.cdpRecoveries}).`)}async function Ns(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(`
296
- --- Pass ${r}/${o}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(c){if(Ue(c))await Ct(e,`pass-${r} navigation: ${c.message?.slice(0,80)}`);else throw c}await g(3e3)}let n=S.submitted,s=S.cdpRecoveries+S.browserRestarts,l=!0,a=!0;for(;l&&a;){if(!await $n(e.page)){await Ct(e,"liveness probe failed twice");continue}try{await fo(e.page,t);let d=await Qs(e.page,Mn,Is);a=d.keepGoing;let f=d.jobsDone;if(console.log("keepGoing",a),console.log("pageDone"),console.log(f.length),!a)break;l=await Ds(e.page),e._pageRecoveryStreak=0}catch(d){if(!Ue(d))throw d;await Ct(e,`mid-iteration: ${d.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!a)break;let i=S.submitted-n,u=S.cdpRecoveries+S.browserRestarts-s;if(i===0){if(u>0&&r<o){console.log(`No new jobs applied in pass ${r}, but ${u} CDP recover${u===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 ${i} new jobs in pass ${r}.`)}}async function Rn(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return Qo(e,t,o,r)}async function In(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 Fs(e,t){try{let o=await zo(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},Ge("recruiters-from-jobs",o)?(_t++,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(_t).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}`),ye(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){ht(o.profileUrl,n),qe(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let s=o.fromJob?.companyUrl;s&&Kt(s,{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 At(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 Pn(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let n of o){let s=n.querySelectorAll("button");for(let l of s){let a=l.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return l.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 Ln(e){await e.evaluate(()=>{let l=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of l)for(let i of a.querySelectorAll("button")){let u=i.innerText?.trim();if(u==="Continue applying"||u==="Got it"||u==="Dismiss"){i.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 l=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let i of a){let u=i.innerText?.trim();if(u==="Easy Apply"||u==="Apply")return i}return null});r=l?.asElement?.()||null,r||await l.dispose().catch(()=>{})}r||await new Promise(l=>setTimeout(l,300))}let n=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${n>400?` (waited ${n}ms)`:""}`),r){if(await e.evaluate(u=>u.disabled,r))return await At(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(u=>u.tagName==="A",r)){await e.evaluate(u=>u.click(),r),await g(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 g(2e3)}}else await r.click(),await g(1500);return await At(e)?(await Pn(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await At(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function Os(e){return await e.evaluate(async()=>{function t(){let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length>0)return i;let u=document.querySelector("#interop-outlet")?.shadowRoot;return u&&(i=u.querySelectorAll(".artdeco-inline-feedback__message")),i}let o=3e3,r=t();if(r?.length===0&&(await new Promise(i=>setTimeout(i,o)),r=t()),r?.length===0)return null;let n=r[0];console.log("errorMsg"),console.log(n);let s=n?.textContent.trim(),l=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(l),a||l){console.log("parentElement"),console.log(a);let i=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"),u=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")),c=a.querySelectorAll('input[type="radio"]'),d=a.querySelector("select[data-test-text-entity-list-form-select]"),f=n.parentElement.parentElement.querySelector('input[type="file"]'),p=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(f),i&&u)return{type:"input",labelText:i.textContent.trim(),errorMsgText:s};if(i&&c.length){let h=i?i.querySelector("span:nth-of-type(1)")?.textContent.trim():null,m=Array.from(c).map(y=>{let v=(document.querySelector(`label[for="${y.id}"]`)||y.nextElementSibling)?.textContent?.trim();return{value:y.value,label:v||y.value}}),b=m.map(y=>y.label);return{type:"radio",labelText:h,errorMsgText:s,options:b,optionsData:m}}else if(d){let h=a.querySelector('label[for="'+d.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),m=h?h.querySelector("span:nth-of-type(2)")?.textContent.trim():null,b=Array.from(d.options).map(y=>y.value).filter(y=>y!=="Select an option");return{type:"select",labelText:m,errorMsgText:s,options:b}}else if(f){let h=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:s,labelText:h}}else{if(p)return{type:"datePicker",errorMsgText:s};{let h=i?i.querySelector("span:nth-of-type(2)")?.textContent.trim():null,m=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(m.length>0){let b=Array.from(m).map(y=>y.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:h,errorMsgText:s,options:b}}else return null}}}return null})}async function qs(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=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"));i.value=n;let u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let c=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(h)},d=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(h)};await(async p=>{await new Promise(h=>setTimeout(h,500)),d(p),await new Promise(h=>setTimeout(h,100)),c(p)})(i)}}return null},t,o)}async function Ps(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('input[type="radio"]'),u=n;if(r.optionsData){let c=r.optionsData.find(d=>d.label.toLowerCase()===n.toLowerCase());c&&(u=c.value,console.log(`Radio: matched label "${n}" to value "${u}"`))}for(let c of i){let f=(document.querySelector(`label[for="${c.id}"]`)||c.nextElementSibling)?.textContent?.trim()||"";if(c.value.toLowerCase()===u.toLowerCase()||f.toLowerCase()===n.toLowerCase()){c.checked=!0;let p=new Event("change",{bubbles:!0});c.dispatchEvent(p),console.log(`Radio selected: value="${c.value}", label="${f}"`);break}}}return null},t,o)}async function Ms(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelector("select[data-test-text-entity-list-form-select]");if(!i)return null;let u=Array.from(i.options),c=u.find(f=>f.text.toLowerCase()===n.toLowerCase())||u.find(f=>f.text.toLowerCase().includes(n.toLowerCase()));c?i.value=c.value:i.value=n;let d=new Event("change",{bubbles:!0});i.dispatchEvent(d)}return null},t,o)}async function Us(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');i.length>0&&i.forEach(u=>{if(u.nextElementSibling.textContent.trim()===n.trim()){u.checked=!0;let c=new Event("change",{bubbles:!0});u.dispatchEvent(c)}})}return null},t,o)}async function Bs(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s?.length===0)return null;let l=s[0],a=l.closest(".fb-dash-form-element"),i=l.parentElement.parentElement.querySelector('input[type="file"]');if(a&&i){async function u(c,d,f){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let h=new Blob([new Uint8Array(d)]),m=new File([h],f,{type:"application/pdf"}),b=new DataTransfer;b.items.add(m),c.files=b.files;let y=new Event("change",{bubbles:!0});c.dispatchEvent(y)}await u(i,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function Dn(e){let t=await Os(e);if(t===null)return null;if(t?.type==="input"){let n=await It(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await qs(e,t,n)}else if(t?.type==="radio"){let n=await it(t.labelText,t.options);n=n?.trim()||n;let s=t.options||[];!s.find(a=>a.toLowerCase()===n?.toLowerCase())&&s.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${n}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),n=await it(t.labelText,t.options),n=n?.trim()||n,s.find(i=>i.toLowerCase()===n?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${s[0]}"`),n=s[0])),t.answer=n,await Ps(e,t,n)}else if(t?.type==="select"){let n=await Ve(t.labelText,t.options);n=n?.trim()||n;let s=t.options||[],l=s.find(a=>a.toLowerCase()===n?.toLowerCase());if(l)n=l;else if(s.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${n}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),n=await Ve(t.labelText,t.options),n=n?.trim()||n;let a=s.find(i=>i.toLowerCase()===n?.toLowerCase());a?n=a:(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${s[0]}"`),n=s[0])}t.answer=n,await Ms(e,t,n)}else if(t?.type==="checkbox"){let n=await Ve(t.labelText,t.options);t.answer=n,await Us(e,t,n)}else if(t?.type==="file"){let n=process.env.RESUME_PDF_URL;t.answer=n;let s=await fetch(n);if(!s.ok)throw new Error("Network response was not ok");let l=await s.arrayBuffer();await Bs(e,t,l)}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 Js(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"),s=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),l=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),i=r.querySelector("select[data-test-text-entity-list-form-select]"),u=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),c=r.querySelector('input[type="file"]');if(n&&l&&a.length===0){let d=n.textContent.trim();t.push({type:"input",labelText:d,answer:l.value,isRequired:s,wasPreFilled:!!l.value})}else if(n&&a.length){let d=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,f=Array.from(a).map(h=>h.value),p=(Array.from(a).find(h=>h.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:d,options:f,answer:p,isRequired:s,wasPreFilled:!!p})}else if(i){let d=r.querySelector('label[for="'+i.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(i.options).map(m=>m.value).filter(m=>m!=="Select an option"),h=i.value!=="Select an option"?i.value:"";t.push({type:"select",labelText:f,options:p,answer:h,isRequired:s,wasPreFilled:!!h})}else if(u.length>0){let d=r.querySelector("legend span")?.textContent?.trim(),f=Array.from(u).map(m=>({label:m.nextElementSibling?.textContent?.trim()||m.value,checked:m.checked})),p=f.some(m=>m.checked),h=f.filter(m=>m.checked).map(m=>m.label).join(", ");t.push({type:"checkbox",labelText:d,options:f.map(m=>m.label),answer:h,isRequired:s,wasPreFilled:p})}else if(c){let d=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:d,answer:c.value?"uploaded":"",isRequired:s,wasPreFilled:!!c.value})}}return t})}async function po(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelector(".artdeco-text-input--label")||l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||l.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=l.querySelector(".artdeco-text-input--input")||l.querySelector("input");if(a&&i&&r===a.textContent.trim()){i.value=n;let u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r==="City"||r==="Location (city)"){let c=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(h)},d=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(h)};await(async p=>{await new Promise(h=>setTimeout(h,500)),d(p),await new Promise(h=>setTimeout(h,100)),c(p)})(i)}return!0}}return!1},t,o)}async function Vs(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelectorAll('input[type="radio"]');if(a.length===0)continue;let i=l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('legend [class*="fb-dash-form-element__label"]')||l.querySelector("legend span");if((i?.querySelector("span:nth-of-type(1)")?.textContent.trim()||i?.textContent?.trim())!==r)continue;let c=(n||"").toLowerCase();for(let d of a){let f=d.getRootNode(),h=(d.id&&f.querySelector(`label[for="${d.id}"]`)||d.nextElementSibling)?.textContent?.trim()||"";if(d.value.toLowerCase()===c||h.toLowerCase()===c)return d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function Hs(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelector("select[data-test-text-entity-list-form-select]");if(!a)continue;let i=l.querySelector(`label[for="${a.id}"]`)||l.querySelector(".fb-dash-form-element__label-title--is-required");if((i?.querySelector("span:nth-of-type(2)")?.textContent.trim()||i?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||i?.querySelector("span")?.textContent.trim()||i?.textContent?.trim())!==r)continue;let c=Array.from(a.options),d=(n||"").toLowerCase(),f=c.find(p=>p.text.toLowerCase()===d)||c.find(p=>p.value.toLowerCase()===d)||c.find(p=>p.text.toLowerCase().includes(d));return f?(a.value=f.value,a.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function Gs(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let a=document.querySelector("#interop-outlet")?.shadowRoot;a&&(s=a.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;let l=(n||"").split(",").map(a=>a.trim().toLowerCase()).filter(Boolean);if(l.length===0)return!1;for(let a of s){let i=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(i.length===0||a.querySelector("legend span")?.textContent?.trim()!==r)continue;let c=!1;for(let d of i){let f=(d.nextElementSibling?.textContent||d.value||"").trim().toLowerCase();l.includes(f)&&!d.checked&&(d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),c=!0)}return c}return!1},t,o)}async function Ws(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 It(o.labelText,"");else if(o.type==="radio")r=await it(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await Ve(o.labelText,o.options||[]);else continue}catch(l){console.log(` \u26A0 Lifebot failed for optional "${o.labelText}": ${l.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 po(e,o.labelText,r):o.type==="radio"?n=await Vs(e,o.labelText,r):o.type==="select"?n=await Hs(e,o.labelText,r):o.type==="checkbox"&&(n=await Gs(e,o.labelText,r))}catch(l){console.log(` \u26A0 setter failed for "${o.labelText}": ${l.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 jn(e,t){let o=[],r=!0,n=0,s=null,l=0;for(;r;){if(n++,await At(e))return console.log(" Daily limit reached during form navigation"),await Pn(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let u=(await Js(e)).filter(p=>!o.some(h=>h.labelText===p.labelText));o.push(...u);try{let p=o.find(m=>m.labelText==="City"||m.labelText==="Location (city)"),h=o.filter(m=>m.labelText!=null).find(m=>m.labelText!==null&&m.labelText.trim()!==null&&(m.labelText.trim().toLowerCase()==="cv"||m.labelText.trim().toLowerCase()==="curriculum vitae"||m.labelText.trim().toLowerCase()==="cover letter"||m.labelText.trim().toLowerCase()==="cover"));if(p&&!p.answer){let m=process.env.City;await po(e,p.labelText,m),p.answer=m}else if(h){let m=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!h.answer||h.answer!==m)&&(await g(1e4),await po(e,h.labelText,m),h.answer=m,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await Ws(e,u)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let c=null;try{c=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(c!==null){if(c.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:c};let p=c&&o.find(m=>m.errorMsgText&&m.labelText===c.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(c,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:c};let h=o.findIndex(m=>m.labelText===c.labelText&&!m.answer);h!==-1&&o.splice(h,1),o.push(c)}let d=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of p){let m=h.querySelectorAll("button");for(let b of m){let y=b.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return b.click(),y}}return null});d&&console.log(` Dismissed safety popup (${d})`);let f=await e.evaluate(async()=>{function p(w){let E=document.querySelector(w);if(E)return E;let O=document.querySelector("#interop-outlet")?.shadowRoot;return O?O.querySelector(w):null}function h(w){let E=document.querySelectorAll(w),O=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(w);return[...E||[],...O||[]]}let m=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||h("footer button, button.artdeco-button--primary").find(w=>w.innerText?.trim()==="Next"),b=h('footer[role="presentation"] button').some(w=>w.innerText.trim()==="Review")||h("button").some(w=>w.innerText.trim()==="Review"&&w.getAttribute("aria-label")?.includes("Review")),y=p('button[aria-label="Submit application"]'),k=async()=>{let w=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||h("footer button, button.artdeco-button--primary").find(E=>E.innerText?.trim()==="Next");w?w.click():console.log("Next button not found")},v=()=>{let w=h("button").find(E=>E.innerText?.trim()==="Review");w&&w.click()};return m?(await k(),{type:"next"}):b?(await v(),{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 h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of h){let b=m.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of b){let k=y.innerText||"";if(k.includes("application was sent")||k.includes("resume into a profile")||k.includes("Application submitted")||k.includes("Next best action"))for(let v of y.querySelectorAll("button")){let w=v.innerText?.trim();if(w==="Not now"||w==="Done"||w==="Dismiss"||w==="Got it")return v.click(),w}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await g(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(l===0){let h=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),b=[],y=[];for(let k of m){for(let w of k.querySelectorAll("button")){let E=w.innerText?.trim();E&&E.length<60&&b.push(E)}let v=k.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');v&&y.push(v.innerText?.slice(0,200))}return{buttons:b.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(h.buttons)}`),h.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(h.modalText)}`)}}if(f.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(c===null&&f.type===s?l++:l=0,s=f.type,l>=5){let p=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),m=[],b=[];for(let y of h){for(let k of y.querySelectorAll(".artdeco-inline-feedback__message"))m.push(k.textContent?.trim()?.slice(0,60));for(let k of y.querySelectorAll(".fb-dash-form-element")){let v=k.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),w=k.querySelector("input, select, textarea"),E=!!k.querySelector(".artdeco-inline-feedback__message");v&&(E||w&&!w.value)&&b.push({label:v.slice(0,40),hasError:E,value:w?.value?.slice(0,20)||""})}}return{errors:m,emptyRequired:b.slice(0,5)}});return console.error(` \u26A0 Stuck on "${f.type}" for ${l} 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_${f.type}`}}}await g(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function Nn(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 Ys(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 Ks(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of o){for(let s of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(s.innerText?.trim()==="Done")return s.click(),"Done";let n=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let s of n){let l=s.innerText||"";if(l.includes("application was sent")||l.includes("Application sent")||l.includes("resume into a profile")||l.includes("Next best action"))for(let a of s.querySelectorAll("button")){let i=a.innerText?.trim();if(i==="Not now"||i==="Dismiss")return a.click(),i}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await g(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function Et(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 g(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 uo(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 g(500))}catch{console.log("No discard confirmation needed")}}async function Mn(e,t){let o=[],r=t._fromQueue;try{S.attempted++,console.log(`
297
- --- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&sn(n)?.status==="applied")return S.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (our DB): ${t.jobTitle} \u2014 skipping`),{keepGoing:!0};let s=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(),h=f.split(" ")[0],m=p.split(" ")[0];if(h&&m&&!f.includes(m)&&!p.includes(h))return S.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(()=>{let y=document.querySelector(".jobs-details__main-content, .job-details-jobs-unified-top-card");if(!y)return!1;let k=y.innerText;return/Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago/i.test(k)||k.includes("Application submitted")}))return S.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${t.jobTitle} \u2014 skipping`),n&&Me(n,"applied",{source:"detected"}),{keepGoing:!0};try{s=await Xo(e)}catch{}}let l=await Ln(e);if(l.dailyLimitReached){console.log(`
295
+ `)}`;try{await we.addMessage(l,i)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var gs=ys(import.meta.url),bs=be.dirname(be.dirname(gs)),ro=process.env.DATA_DIR?be.resolve(process.env.DATA_DIR,"collected-profiles"):be.join(bs,"collected-profiles"),so=be.join(ro,"run-log.json");function ws(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";le.writeFileSync(r,o);for(let n=0;n<3;n++)try{le.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function wn(){try{if(!le.existsSync(so))return{runs:[]};let e=JSON.parse(le.readFileSync(so,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Sn(e){le.existsSync(ro)||le.mkdirSync(ro,{recursive:!0});try{ws(so,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function kn(e,t="default"){let o=wn();for(let l of o.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.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 s=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(l=>new Date(l.timestamp).getTime()>s),Sn(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function vn(e,t,o=null,r=null){if(!e)return;let n=null;try{let l=wn(),a=l.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 i=l.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());i&&(i.status=t,i.result=t,i.duration=Date.now()-e.startTime,i.stats=o,i.error=r,n=i.duration)}Sn(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let s=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";bn({scriptName:e.script,mode:e.mode,status:l,summaryLines:s,error:r,duration:n??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import xn from"fs";import Ss from"path";var ks="cookies.json";function vs(){let e=process.env.ILML_SCOPE_DIR;return e?Ss.join(e,"plugins-state","linkedin","cookies.json"):ks}function io(){let e=vs();if(!xn.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=xn.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}Re();async function xt(e,t,o="op"){let r,n=new Promise((s,l)=>{r=setTimeout(()=>l(new Error(`${o} timeout after ${t}ms`)),t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}function Ue(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 $n(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await xt(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function En(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await $n(e,t)?!0:(await g(o),await $n(e,t))}async function Cn(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await xt(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function An(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:s=null}={}){try{await xt(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let l=await e.newPage();if(s)try{await s(l)}catch{}if(n)try{let a=n();Array.isArray(a)&&a.length>0&&await l.setCookie(...a)}catch{}if(o){await l.goto(o,{waitUntil:"domcontentloaded",timeout:r});let a=l.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 l}async function _n(e,{launchFn:t,returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:s=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");try{await xt(e.close(),5e3,"oldBrowser.close")}catch{}let l=await t(),a=await l.newPage();if(s)try{await s(a)}catch{}if(n)try{let i=n();Array.isArray(i)&&i.length>0&&await a.setCookie(...i)}catch{}if(o){await a.goto(o,{waitUntil:"domcontentloaded",timeout:r});let i=a.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(i))throw new Error(`Session expired after browser restart \u2014 landed on ${i}. Run: ilml linkedin login`)}return{browser:l,page:a}}await yn();var _t=0,$s=process.env.FUNNEL_CONNECT_RECRUITERS==="true",Es=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Cs=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),As=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",lo=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],$t=-1;async function _s(){if($t===-1){let e=await Le("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}"`);$t=wo(e)+1,console.log(`lastIndex initialized as: ${$t}`)}return $t++}var qn=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${qn}`);var Ts=[{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}],st={};function Pn(e){let t=e;for(let o=0;t&&o<5;o++){let r=Ts.find(n=>{try{return n.match(t)}catch{return!1}});if(r)return r;t=t.cause}return null}function Rs(e){return st[e]=(st[e]||0)+1,st[e]}function Rn(){for(let e of Object.keys(st))st[e]=0}var ao=0;function Is(){return ao++,ao>=qn?(console.log(`Max run counter reached with ${ao}`),!1):!0}async function Ls(e){let t=await Yo(e)}async function Ds(e){return Ko(e,{easyApplyOnly:!0})}async function js(e){return Qo(e)}async function fo(e,t){return Ht(e,t)}var co=3,Ns=2;async function Ct(e,t){let{searchUrl:o,launchFn:r,setupPage:n,cookiesProvider:s}=e.recoveryCtx,l=await Cn(e.browser);if(!l||e._pageRecoveryStreak>=co){if(S.browserRestarts>=Ns)throw new Error(`CDP unrecoverable: ${S.browserRestarts} browser restart${S.browserRestarts===1?"":"s"} and ${S.cdpRecoveries} page recover${S.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let i=l?`${co} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${i}). Reason: ${t}`);let u=await _n(e.browser,{launchFn:r,setupPage:n,cookiesProvider:s,returnUrl:o});e.browser=u.browser,e.page=u.page,e._pageRecoveryStreak=0,S.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${S.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${co}). Reason: ${t}`),e.page=await An(e.browser,e.page,{returnUrl:o,cookiesProvider:s,setupPage:n}),e._pageRecoveryStreak+=1,S.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${S.cdpRecoveries}).`)}async function Fs(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(`
296
+ --- Pass ${r}/${o}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(c){if(Ue(c))await Ct(e,`pass-${r} navigation: ${c.message?.slice(0,80)}`);else throw c}await g(3e3)}let n=S.submitted,s=S.cdpRecoveries+S.browserRestarts,l=!0,a=!0;for(;l&&a;){if(!await En(e.page)){await Ct(e,"liveness probe failed twice");continue}try{await fo(e.page,t);let d=await zs(e.page,Un,Ls);a=d.keepGoing;let f=d.jobsDone;if(console.log("keepGoing",a),console.log("pageDone"),console.log(f.length),!a)break;l=await js(e.page),e._pageRecoveryStreak=0}catch(d){if(!Ue(d))throw d;await Ct(e,`mid-iteration: ${d.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!a)break;let i=S.submitted-n,u=S.cdpRecoveries+S.browserRestarts-s;if(i===0){if(u>0&&r<o){console.log(`No new jobs applied in pass ${r}, but ${u} CDP recover${u===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 ${i} new jobs in pass ${r}.`)}}async function In(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return zo(e,t,o,r)}async function Ln(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 Os(e,t){try{let o=await Xo(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},Ge("recruiters-from-jobs",o)?(_t++,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(_t).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}`),ye(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){ht(o.profileUrl,n),qe(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let s=o.fromJob?.companyUrl;s&&Kt(s,{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 At(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 Mn(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let n of o){let s=n.querySelectorAll("button");for(let l of s){let a=l.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return l.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 Dn(e){await e.evaluate(()=>{let l=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of l)for(let i of a.querySelectorAll("button")){let u=i.innerText?.trim();if(u==="Continue applying"||u==="Got it"||u==="Dismiss"){i.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 l=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let i of a){let u=i.innerText?.trim();if(u==="Easy Apply"||u==="Apply")return i}return null});r=l?.asElement?.()||null,r||await l.dispose().catch(()=>{})}r||await new Promise(l=>setTimeout(l,300))}let n=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${n>400?` (waited ${n}ms)`:""}`),r){if(await e.evaluate(u=>u.disabled,r))return await At(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(u=>u.tagName==="A",r)){await e.evaluate(u=>u.click(),r),await g(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 g(2e3)}}else await r.click(),await g(1500);return await At(e)?(await Mn(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await At(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function qs(e){return await e.evaluate(async()=>{function t(){let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length>0)return i;let u=document.querySelector("#interop-outlet")?.shadowRoot;return u&&(i=u.querySelectorAll(".artdeco-inline-feedback__message")),i}let o=3e3,r=t();if(r?.length===0&&(await new Promise(i=>setTimeout(i,o)),r=t()),r?.length===0)return null;let n=r[0];console.log("errorMsg"),console.log(n);let s=n?.textContent.trim(),l=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(l),a||l){console.log("parentElement"),console.log(a);let i=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"),u=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")),c=a.querySelectorAll('input[type="radio"]'),d=a.querySelector("select[data-test-text-entity-list-form-select]"),f=n.parentElement.parentElement.querySelector('input[type="file"]'),p=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(f),i&&u)return{type:"input",labelText:i.textContent.trim(),errorMsgText:s};if(i&&c.length){let h=i?i.querySelector("span:nth-of-type(1)")?.textContent.trim():null,m=Array.from(c).map(y=>{let v=(document.querySelector(`label[for="${y.id}"]`)||y.nextElementSibling)?.textContent?.trim();return{value:y.value,label:v||y.value}}),b=m.map(y=>y.label);return{type:"radio",labelText:h,errorMsgText:s,options:b,optionsData:m}}else if(d){let h=a.querySelector('label[for="'+d.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),m=h?h.querySelector("span:nth-of-type(2)")?.textContent.trim():null,b=Array.from(d.options).map(y=>y.value).filter(y=>y!=="Select an option");return{type:"select",labelText:m,errorMsgText:s,options:b}}else if(f){let h=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:s,labelText:h}}else{if(p)return{type:"datePicker",errorMsgText:s};{let h=i?i.querySelector("span:nth-of-type(2)")?.textContent.trim():null,m=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(m.length>0){let b=Array.from(m).map(y=>y.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:h,errorMsgText:s,options:b}}else return null}}}return null})}async function Ps(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=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"));i.value=n;let u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let c=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(h)},d=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(h)};await(async p=>{await new Promise(h=>setTimeout(h,500)),d(p),await new Promise(h=>setTimeout(h,100)),c(p)})(i)}}return null},t,o)}async function Ms(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('input[type="radio"]'),u=n;if(r.optionsData){let c=r.optionsData.find(d=>d.label.toLowerCase()===n.toLowerCase());c&&(u=c.value,console.log(`Radio: matched label "${n}" to value "${u}"`))}for(let c of i){let f=(document.querySelector(`label[for="${c.id}"]`)||c.nextElementSibling)?.textContent?.trim()||"";if(c.value.toLowerCase()===u.toLowerCase()||f.toLowerCase()===n.toLowerCase()){c.checked=!0;let p=new Event("change",{bubbles:!0});c.dispatchEvent(p),console.log(`Radio selected: value="${c.value}", label="${f}"`);break}}}return null},t,o)}async function Us(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelector("select[data-test-text-entity-list-form-select]");if(!i)return null;let u=Array.from(i.options),c=u.find(f=>f.text.toLowerCase()===n.toLowerCase())||u.find(f=>f.text.toLowerCase().includes(n.toLowerCase()));c?i.value=c.value:i.value=n;let d=new Event("change",{bubbles:!0});i.dispatchEvent(d)}return null},t,o)}async function Bs(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');i.length>0&&i.forEach(u=>{if(u.nextElementSibling.textContent.trim()===n.trim()){u.checked=!0;let c=new Event("change",{bubbles:!0});u.dispatchEvent(c)}})}return null},t,o)}async function Js(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s?.length===0)return null;let l=s[0],a=l.closest(".fb-dash-form-element"),i=l.parentElement.parentElement.querySelector('input[type="file"]');if(a&&i){async function u(c,d,f){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let h=new Blob([new Uint8Array(d)]),m=new File([h],f,{type:"application/pdf"}),b=new DataTransfer;b.items.add(m),c.files=b.files;let y=new Event("change",{bubbles:!0});c.dispatchEvent(y)}await u(i,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function jn(e){let t=await qs(e);if(t===null)return null;if(t?.type==="input"){let n=await It(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await Ps(e,t,n)}else if(t?.type==="radio"){let n=await it(t.labelText,t.options);n=n?.trim()||n;let s=t.options||[];!s.find(a=>a.toLowerCase()===n?.toLowerCase())&&s.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${n}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),n=await it(t.labelText,t.options),n=n?.trim()||n,s.find(i=>i.toLowerCase()===n?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${s[0]}"`),n=s[0])),t.answer=n,await Ms(e,t,n)}else if(t?.type==="select"){let n=await Ve(t.labelText,t.options);n=n?.trim()||n;let s=t.options||[],l=s.find(a=>a.toLowerCase()===n?.toLowerCase());if(l)n=l;else if(s.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${n}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),n=await Ve(t.labelText,t.options),n=n?.trim()||n;let a=s.find(i=>i.toLowerCase()===n?.toLowerCase());a?n=a:(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${s[0]}"`),n=s[0])}t.answer=n,await Us(e,t,n)}else if(t?.type==="checkbox"){let n=await Ve(t.labelText,t.options);t.answer=n,await Bs(e,t,n)}else if(t?.type==="file"){let n=process.env.RESUME_PDF_URL;t.answer=n;let s=await fetch(n);if(!s.ok)throw new Error("Network response was not ok");let l=await s.arrayBuffer();await Js(e,t,l)}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 Vs(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"),s=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),l=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),i=r.querySelector("select[data-test-text-entity-list-form-select]"),u=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),c=r.querySelector('input[type="file"]');if(n&&l&&a.length===0){let d=n.textContent.trim();t.push({type:"input",labelText:d,answer:l.value,isRequired:s,wasPreFilled:!!l.value})}else if(n&&a.length){let d=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,f=Array.from(a).map(h=>h.value),p=(Array.from(a).find(h=>h.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:d,options:f,answer:p,isRequired:s,wasPreFilled:!!p})}else if(i){let d=r.querySelector('label[for="'+i.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(i.options).map(m=>m.value).filter(m=>m!=="Select an option"),h=i.value!=="Select an option"?i.value:"";t.push({type:"select",labelText:f,options:p,answer:h,isRequired:s,wasPreFilled:!!h})}else if(u.length>0){let d=r.querySelector("legend span")?.textContent?.trim(),f=Array.from(u).map(m=>({label:m.nextElementSibling?.textContent?.trim()||m.value,checked:m.checked})),p=f.some(m=>m.checked),h=f.filter(m=>m.checked).map(m=>m.label).join(", ");t.push({type:"checkbox",labelText:d,options:f.map(m=>m.label),answer:h,isRequired:s,wasPreFilled:p})}else if(c){let d=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:d,answer:c.value?"uploaded":"",isRequired:s,wasPreFilled:!!c.value})}}return t})}async function po(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelector(".artdeco-text-input--label")||l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||l.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=l.querySelector(".artdeco-text-input--input")||l.querySelector("input");if(a&&i&&r===a.textContent.trim()){i.value=n;let u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r==="City"||r==="Location (city)"){let c=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(h)},d=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(h)};await(async p=>{await new Promise(h=>setTimeout(h,500)),d(p),await new Promise(h=>setTimeout(h,100)),c(p)})(i)}return!0}}return!1},t,o)}async function Hs(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelectorAll('input[type="radio"]');if(a.length===0)continue;let i=l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('legend [class*="fb-dash-form-element__label"]')||l.querySelector("legend span");if((i?.querySelector("span:nth-of-type(1)")?.textContent.trim()||i?.textContent?.trim())!==r)continue;let c=(n||"").toLowerCase();for(let d of a){let f=d.getRootNode(),h=(d.id&&f.querySelector(`label[for="${d.id}"]`)||d.nextElementSibling)?.textContent?.trim()||"";if(d.value.toLowerCase()===c||h.toLowerCase()===c)return d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function Gs(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelector("select[data-test-text-entity-list-form-select]");if(!a)continue;let i=l.querySelector(`label[for="${a.id}"]`)||l.querySelector(".fb-dash-form-element__label-title--is-required");if((i?.querySelector("span:nth-of-type(2)")?.textContent.trim()||i?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||i?.querySelector("span")?.textContent.trim()||i?.textContent?.trim())!==r)continue;let c=Array.from(a.options),d=(n||"").toLowerCase(),f=c.find(p=>p.text.toLowerCase()===d)||c.find(p=>p.value.toLowerCase()===d)||c.find(p=>p.text.toLowerCase().includes(d));return f?(a.value=f.value,a.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function Ws(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let a=document.querySelector("#interop-outlet")?.shadowRoot;a&&(s=a.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;let l=(n||"").split(",").map(a=>a.trim().toLowerCase()).filter(Boolean);if(l.length===0)return!1;for(let a of s){let i=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(i.length===0||a.querySelector("legend span")?.textContent?.trim()!==r)continue;let c=!1;for(let d of i){let f=(d.nextElementSibling?.textContent||d.value||"").trim().toLowerCase();l.includes(f)&&!d.checked&&(d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),c=!0)}return c}return!1},t,o)}async function Ys(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 It(o.labelText,"");else if(o.type==="radio")r=await it(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await Ve(o.labelText,o.options||[]);else continue}catch(l){console.log(` \u26A0 Lifebot failed for optional "${o.labelText}": ${l.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 po(e,o.labelText,r):o.type==="radio"?n=await Hs(e,o.labelText,r):o.type==="select"?n=await Gs(e,o.labelText,r):o.type==="checkbox"&&(n=await Ws(e,o.labelText,r))}catch(l){console.log(` \u26A0 setter failed for "${o.labelText}": ${l.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 Nn(e,t){let o=[],r=!0,n=0,s=null,l=0;for(;r;){if(n++,await At(e))return console.log(" Daily limit reached during form navigation"),await Mn(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let u=(await Vs(e)).filter(p=>!o.some(h=>h.labelText===p.labelText));o.push(...u);try{let p=o.find(m=>m.labelText==="City"||m.labelText==="Location (city)"),h=o.filter(m=>m.labelText!=null).find(m=>m.labelText!==null&&m.labelText.trim()!==null&&(m.labelText.trim().toLowerCase()==="cv"||m.labelText.trim().toLowerCase()==="curriculum vitae"||m.labelText.trim().toLowerCase()==="cover letter"||m.labelText.trim().toLowerCase()==="cover"));if(p&&!p.answer){let m=process.env.City;await po(e,p.labelText,m),p.answer=m}else if(h){let m=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!h.answer||h.answer!==m)&&(await g(1e4),await po(e,h.labelText,m),h.answer=m,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await Ys(e,u)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let c=null;try{c=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(c!==null){if(c.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:c};let p=c&&o.find(m=>m.errorMsgText&&m.labelText===c.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(c,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:c};let h=o.findIndex(m=>m.labelText===c.labelText&&!m.answer);h!==-1&&o.splice(h,1),o.push(c)}let d=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of p){let m=h.querySelectorAll("button");for(let b of m){let y=b.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return b.click(),y}}return null});d&&console.log(` Dismissed safety popup (${d})`);let f=await e.evaluate(async()=>{function p(w){let E=document.querySelector(w);if(E)return E;let O=document.querySelector("#interop-outlet")?.shadowRoot;return O?O.querySelector(w):null}function h(w){let E=document.querySelectorAll(w),O=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(w);return[...E||[],...O||[]]}let m=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||h("footer button, button.artdeco-button--primary").find(w=>w.innerText?.trim()==="Next"),b=h('footer[role="presentation"] button').some(w=>w.innerText.trim()==="Review")||h("button").some(w=>w.innerText.trim()==="Review"&&w.getAttribute("aria-label")?.includes("Review")),y=p('button[aria-label="Submit application"]'),k=async()=>{let w=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||h("footer button, button.artdeco-button--primary").find(E=>E.innerText?.trim()==="Next");w?w.click():console.log("Next button not found")},v=()=>{let w=h("button").find(E=>E.innerText?.trim()==="Review");w&&w.click()};return m?(await k(),{type:"next"}):b?(await v(),{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 h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of h){let b=m.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of b){let k=y.innerText||"";if(k.includes("application was sent")||k.includes("resume into a profile")||k.includes("Application submitted")||k.includes("Next best action"))for(let v of y.querySelectorAll("button")){let w=v.innerText?.trim();if(w==="Not now"||w==="Done"||w==="Dismiss"||w==="Got it")return v.click(),w}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await g(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(l===0){let h=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),b=[],y=[];for(let k of m){for(let w of k.querySelectorAll("button")){let E=w.innerText?.trim();E&&E.length<60&&b.push(E)}let v=k.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');v&&y.push(v.innerText?.slice(0,200))}return{buttons:b.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(h.buttons)}`),h.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(h.modalText)}`)}}if(f.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(c===null&&f.type===s?l++:l=0,s=f.type,l>=5){let p=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),m=[],b=[];for(let y of h){for(let k of y.querySelectorAll(".artdeco-inline-feedback__message"))m.push(k.textContent?.trim()?.slice(0,60));for(let k of y.querySelectorAll(".fb-dash-form-element")){let v=k.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),w=k.querySelector("input, select, textarea"),E=!!k.querySelector(".artdeco-inline-feedback__message");v&&(E||w&&!w.value)&&b.push({label:v.slice(0,40),hasError:E,value:w?.value?.slice(0,20)||""})}}return{errors:m,emptyRequired:b.slice(0,5)}});return console.error(` \u26A0 Stuck on "${f.type}" for ${l} 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_${f.type}`}}}await g(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function Fn(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 Ks(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 Qs(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of o){for(let s of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(s.innerText?.trim()==="Done")return s.click(),"Done";let n=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let s of n){let l=s.innerText||"";if(l.includes("application was sent")||l.includes("Application sent")||l.includes("resume into a profile")||l.includes("Next best action"))for(let a of s.querySelectorAll("button")){let i=a.innerText?.trim();if(i==="Not now"||i==="Dismiss")return a.click(),i}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await g(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function Et(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 g(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 uo(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 g(500))}catch{console.log("No discard confirmation needed")}}async function Un(e,t){let o=[],r=t._fromQueue;try{S.attempted++,console.log(`
297
+ --- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&ln(n)?.status==="applied")return S.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (our DB): ${t.jobTitle} \u2014 skipping`),{keepGoing:!0};let s=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(),h=f.split(" ")[0],m=p.split(" ")[0];if(h&&m&&!f.includes(m)&&!p.includes(h))return S.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(()=>{let y=document.querySelector(".jobs-details__main-content, .job-details-jobs-unified-top-card");if(!y)return!1;let k=y.innerText;return/Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago/i.test(k)||k.includes("Application submitted")}))return S.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${t.jobTitle} \u2014 skipping`),n&&Me(n,"applied",{source:"detected"}),{keepGoing:!0};try{s=await Zo(e)}catch{}}let l=await Dn(e);if(l.dailyLimitReached){console.log(`
298
298
  ========================================`),console.log("LinkedIn daily application limit reached!"),console.log(`========================================
299
- `);let f=De("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${f.total}`),console.log(` - This session: ${_t}`),console.log(` - Unprocessed: ${f.unprocessed}`),S.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:f}}if(!l.clicked)return S.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${t.jobTitle} @ ${t.companyName}`),{keepGoing:!0};await Nn(e);let a=await As();console.log(`Applying for job: ${t.id}`);let i=`### Job Information
299
+ `);let f=De("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${f.total}`),console.log(` - This session: ${_t}`),console.log(` - Unprocessed: ${f.unprocessed}`),S.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:f}}if(!l.clicked)return S.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${t.jobTitle} @ ${t.companyName}`),{keepGoing:!0};await Fn(e);let a=await _s();console.log(`Applying for job: ${t.id}`);let i=`### Job Information
300
300
  - **Counter:** ${a}
301
301
  - **Job Title:** ${t.jobTitle}
302
302
  - **Company:** ${t.companyName}
303
303
  - **Location:** ${t.location}
304
304
  - **Salary:** ${t.salary}
305
- - **Job URL:** ${t.href}`,u=process.env.NODE_EASY_APPLY_MAIN;await we.addMessage(u,i,{lifebot:_n.off});let c=await Le("Should I apply for this job? Answer only 'yes' or 'no'!!");if(Tn(),console.log(`Should I apply for ${t.jobTitle} ?? `+c),c.toLowerCase()==="no"){S.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await Et(e),await uo(e),await In(e,t.id);let f=t.id?.match(/\d+/)?.[0];return Pe({jobId:f,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),Me(f,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let d=await jn(e,Dn);if(d.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await Ln(e)).clicked?d=await jn(e,Dn):(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 Et(e),{keepGoing:!1,dailyLimitReached:!0};if(d.skip){if(await Et(e),await uo(e),d.duplicateField){await In(e,t.id);let f=process.env.NODE_EASY_APPLY_ERRORS;await we.addMessage(f,`${t.href} failed at label ${d.duplicateField?.labelText}`,{lifebot:_n.off})}S.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${d.duplicateField?.labelText||"form error"}`),Pe({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||[]})}else{o=d.filledFields,o.length,await Nn(e),await Ys(e),await g(2e3),await Ks(e),S.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}),nn(f,{title:t.jobTitle,company:s?.companyName||t.companyName,companyUrl:s?.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:s?.description,techStack:s?.techStack,jobTags:s?.jobTags,seniority:s?.seniority,employmentType:s?.employmentType,industries:s?.industries,jobFunction:s?.jobFunction,postedTime:s?.postedTime,applicantCount:s?.applicantCount,companySize:s?.companySize,workplaceType:s?.workplaceType,contractType:s?.contractType,aboutCompany:s?.aboutCompany}),Me(f,"applied",{source:"easy-apply"}),s?.companyUrl&&Kt(s.companyUrl,{name:s.companyName||t.companyName,about:s.aboutCompany,size:s.companySize,industries:s.industries,jobId:f})),await Fs(e,t),Pe({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:d.formPages,questions:o}),!Rs())return{keepGoing:!1}}}catch(n){if(Ue(n))throw console.log(`\u26A0 CDP dead during "${t.jobTitle}" \u2014 bubbling up for page recovery: ${(n.message||"").slice(0,100)}`),n;let s=qn(n);if(!s)return console.log(`\u274C Unknown error \u2014 stopping: ${(n.message||"").slice(0,120)}`),console.log(n),{keepGoing:!1};if(s.severity==="fatal")return console.log(`\u274C [${s.label}] Fatal \u2014 stopping: ${(n.message||"").slice(0,120)}`),s.instructions&&console.log(` \u2192 ${s.instructions}`),s.label==="ilml-auth-expired"?S.fatalAuthExpired="ilml":s.label==="linkedin-session-expired"&&(S.fatalAuthExpired="linkedin"),{keepGoing:!1};let l=Ts(s.label);if(console.log(`\u26A0 [${s.label}] on "${t.jobTitle}" (${l}/${s.maxConsecutive} consecutive): ${(n.message||"").slice(0,120)}`),s.cleanup==="popup"){try{await Et(e)}catch{}try{await uo(e)}catch{}}return l>=s.maxConsecutive?(console.log(`\u274C [${s.label}] ${s.maxConsecutive} consecutive \u2014 stopping.`),s.instructions&&console.log(` \u2192 ${s.instructions}`),{keepGoing:!1}):(s.cooldownMs&&await g(s.cooldownMs),{keepGoing:!0})}return Tn(),{keepGoing:!0}}async function Qs(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL,n=[],s=0;for(;;){await fo(e,r)&&(await te(e),await g(2e3));try{await e.waitForSelector("li.scaffold-layout__list-item",{timeout:3e4})}catch{}await o(e);let a=await Ls(e);if(a.length===0){if(!e.url().includes("/jobs/")){if(s++,s>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 ${s}/3...`),await fo(e,r);continue}let u=await e.evaluate(()=>({totalCards:document.querySelectorAll("li.scaffold-layout__list-item").length,hasListContainer:!!document.querySelector(".jobs-search-results-list, .scaffold-layout__list-container")}));u.totalCards===0?console.log(` \u26A0 No job cards on page (container present: ${u.hasListContainer}). Either the search returned nothing, the page never finished loading, or LinkedIn changed its markup.`):console.log(` ${u.totalCards} job card(s) on page but none are Easy Apply \u2014 nothing to apply to with this search filter.`);break}if(s=0,n.length===0){n=a;let{keepGoing:i}=await Rn(e,a,t);if(!i)return{keepGoing:!1,jobsDone:n}}else{let i=a.filter(c=>!n.some(d=>d.id===c.id));if(console.log(` New jobs on page: ${i.length} (page: ${a.length}, total seen: ${n.length})`),i.length===0)break;let{keepGoing:u}=await Rn(e,i,t);if(n=[...n,...i],!u)return{keepGoing:!1,jobsDone:n}}}return console.log(` All jobs processed. Total: ${n.length}`),{keepGoing:!0,jobsDone:n}}var S={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(i=>i.startsWith("--job-urls=")),t=Sn("apply",e?"queue":"search"),o=null,r=null,n=[],s=async()=>vs.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),l=async i=>{await i.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},a=()=>io();try{o=await s();let i=async()=>{console.log(`
305
+ - **Job URL:** ${t.href}`,u=process.env.NODE_EASY_APPLY_MAIN;await we.addMessage(u,i,{lifebot:Tn.off});let c=await Le("Should I apply for this job? Answer only 'yes' or 'no'!!");if(Rn(),console.log(`Should I apply for ${t.jobTitle} ?? `+c),c.toLowerCase()==="no"){S.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await Et(e),await uo(e),await Ln(e,t.id);let f=t.id?.match(/\d+/)?.[0];return Pe({jobId:f,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),Me(f,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let d=await Nn(e,jn);if(d.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await Dn(e)).clicked?d=await Nn(e,jn):(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 Et(e),{keepGoing:!1,dailyLimitReached:!0};if(d.skip){if(await Et(e),await uo(e),d.duplicateField){await Ln(e,t.id);let f=process.env.NODE_EASY_APPLY_ERRORS;await we.addMessage(f,`${t.href} failed at label ${d.duplicateField?.labelText}`,{lifebot:Tn.off})}S.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${d.duplicateField?.labelText||"form error"}`),Pe({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||[]})}else{o=d.filledFields,o.length,await Fn(e),await Ks(e),await g(2e3),await Qs(e),S.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}),rn(f,{title:t.jobTitle,company:s?.companyName||t.companyName,companyUrl:s?.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:s?.description,techStack:s?.techStack,jobTags:s?.jobTags,seniority:s?.seniority,employmentType:s?.employmentType,industries:s?.industries,jobFunction:s?.jobFunction,postedTime:s?.postedTime,applicantCount:s?.applicantCount,companySize:s?.companySize,workplaceType:s?.workplaceType,contractType:s?.contractType,aboutCompany:s?.aboutCompany}),Me(f,"applied",{source:"easy-apply"}),s?.companyUrl&&Kt(s.companyUrl,{name:s.companyName||t.companyName,about:s.aboutCompany,size:s.companySize,industries:s.industries,jobId:f})),await Os(e,t),Pe({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:d.formPages,questions:o}),!Is())return{keepGoing:!1}}}catch(n){if(Ue(n))throw console.log(`\u26A0 CDP dead during "${t.jobTitle}" \u2014 bubbling up for page recovery: ${(n.message||"").slice(0,100)}`),n;let s=Pn(n);if(!s)return console.log(`\u274C Unknown error \u2014 stopping: ${(n.message||"").slice(0,120)}`),console.log(n),{keepGoing:!1};if(s.severity==="fatal")return console.log(`\u274C [${s.label}] Fatal \u2014 stopping: ${(n.message||"").slice(0,120)}`),s.instructions&&console.log(` \u2192 ${s.instructions}`),s.label==="ilml-auth-expired"?S.fatalAuthExpired="ilml":s.label==="linkedin-session-expired"&&(S.fatalAuthExpired="linkedin"),{keepGoing:!1};let l=Rs(s.label);if(console.log(`\u26A0 [${s.label}] on "${t.jobTitle}" (${l}/${s.maxConsecutive} consecutive): ${(n.message||"").slice(0,120)}`),s.cleanup==="popup"){try{await Et(e)}catch{}try{await uo(e)}catch{}}return l>=s.maxConsecutive?(console.log(`\u274C [${s.label}] ${s.maxConsecutive} consecutive \u2014 stopping.`),s.instructions&&console.log(` \u2192 ${s.instructions}`),{keepGoing:!1}):(s.cooldownMs&&await g(s.cooldownMs),{keepGoing:!0})}return Rn(),{keepGoing:!0}}async function zs(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL,n=[],s=0;for(;;){await fo(e,r)&&(await te(e),await g(2e3));try{await e.waitForSelector("li.scaffold-layout__list-item",{timeout:3e4})}catch{}await o(e);let a=await Ds(e);if(a.length===0){if(!e.url().includes("/jobs/")){if(s++,s>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 ${s}/3...`),await fo(e,r);continue}let u=await e.evaluate(()=>({totalCards:document.querySelectorAll("li.scaffold-layout__list-item").length,hasListContainer:!!document.querySelector(".jobs-search-results-list, .scaffold-layout__list-container")}));u.totalCards===0?console.log(` \u26A0 No job cards on page (container present: ${u.hasListContainer}). Either the search returned nothing, the page never finished loading, or LinkedIn changed its markup.`):console.log(` ${u.totalCards} job card(s) on page but none are Easy Apply \u2014 nothing to apply to with this search filter.`);break}if(s=0,n.length===0){n=a;let{keepGoing:i}=await In(e,a,t);if(!i)return{keepGoing:!1,jobsDone:n}}else{let i=a.filter(c=>!n.some(d=>d.id===c.id));if(console.log(` New jobs on page: ${i.length} (page: ${a.length}, total seen: ${n.length})`),i.length===0)break;let{keepGoing:u}=await In(e,i,t);if(n=[...n,...i],!u)return{keepGoing:!1,jobsDone:n}}}return console.log(` All jobs processed. Total: ${n.length}`),{keepGoing:!0,jobsDone:n}}var S={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(i=>i.startsWith("--job-urls=")),t=kn("apply",e?"queue":"search"),o=null,r=null,n=[],s=async()=>xs.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),l=async i=>{await i.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},a=()=>io();try{o=await s();let i=async()=>{console.log(`
306
306
  Closing browser...`);try{await o.close()}catch{}process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i);let u=await o.newPage();await l(u);let c=io();await u.setCookie(...c);let d=process.argv.find(_=>_.startsWith("--job-urls=")),f=d?d.split("=").slice(1).join("=").replace(/^@/,""):null,p=process.env.LINKEDIN_SEARCH_URL,h=f?"https://www.linkedin.com/feed/":p;try{await u.goto(h,{waitUntil:"domcontentloaded",timeout:6e4})}catch(_){console.error("\u274C Navigation error:",_.message),console.log("Trying to continue anyway..."),await g(5e3)}let m=u.url();if(m.includes("/login")||m.includes("/checkpoint"))throw new Error("Not logged in \u2014 cookies expired, run: npm run login");console.log("\u2713 \u0417\u0430\u043B\u043E\u0433\u0438\u043D\u0435\u043D\u044B \u043D\u0430 LinkedIn!");let b=De("recruiters-from-jobs");b.total>0&&console.log(`
307
307
  \u{1F4C2} Existing recruiters for today: ${b.total} (${b.unprocessed} unprocessed)
308
- `),await g(2e3);let y={page:u,browser:o,recoveryCtx:{searchUrl:p,launchFn:s,setupPage:l,cookiesProvider:a}},k=!1;if(f)try{let _=JSON.parse(Fn.readFileSync(f,"utf-8"));console.log(`
308
+ `),await g(2e3);let y={page:u,browser:o,recoveryCtx:{searchUrl:p,launchFn:s,setupPage:l,cookiesProvider:a}},k=!1;if(f)try{let _=JSON.parse(On.readFileSync(f,"utf-8"));console.log(`
309
309
  \u{1F4CB} Queue mode: ${_.length} jobs from ${f}
310
310
  `);for(let B=0;B<_.length;B++){let T=typeof _[B]=="string"?{url:_[B]}:_[B],q=T.url,x=T.title||"Unknown",M=T.company||"";console.log(`
311
- [${B+1}/${_.length}] ${x} @ ${M}`),console.log(` ${q}`),u=y.page,o=y.browser;try{let j=q.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await u.goto(q,{waitUntil:"domcontentloaded",timeout:6e4}),await g(8e3);let I=await u.evaluate(()=>{let me=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:me.includes("Application submitted"),noLongerAccepting:me.includes("No longer accepting applications")}});if(I.alreadyApplied){console.log(" Already applied \u2014 skipping"),S.alreadyApplied++,Me(j,"applied",{applyMethod:"detected"});continue}if(I.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),S.expired++,Me(j,"expired",{reason:"no_longer_accepting"});continue}if(!I.hasApply){console.log(" No Easy Apply button \u2014 skipping"),S.noApplyButton++;continue}let G={id:`/jobs/view/${j}/`,href:q,jobTitle:x,companyName:M,location:T.location||"",salary:T.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let z=await Mn(u,G);if(console.log(` Result: keepGoing=${z.keepGoing}, reason=${z.dailyLimitReached?"daily_limit":"ok"}`),!z.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),k=!0;break}}catch(j){if(Ue(j))try{await Ct(y,`queue job ${B+1}: ${j.message?.slice(0,80)}`),u=y.page,o=y.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=qn(j);if(I?.severity==="fatal"){console.error(`\u274C [${I.label}] Fatal \u2014 stopping queue: ${(j.message||"").slice(0,120)}`),I.instructions&&console.error(` \u2192 ${I.instructions}`),I.label==="ilml-auth-expired"?S.fatalAuthExpired="ilml":I.label==="linkedin-session-expired"&&(S.fatalAuthExpired="linkedin");break}console.error(` Error: ${j.message?.slice(0,80)}`)}}}console.log(`
311
+ [${B+1}/${_.length}] ${x} @ ${M}`),console.log(` ${q}`),u=y.page,o=y.browser;try{let j=q.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await u.goto(q,{waitUntil:"domcontentloaded",timeout:6e4}),await g(8e3);let I=await u.evaluate(()=>{let me=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:me.includes("Application submitted"),noLongerAccepting:me.includes("No longer accepting applications")}});if(I.alreadyApplied){console.log(" Already applied \u2014 skipping"),S.alreadyApplied++,Me(j,"applied",{applyMethod:"detected"});continue}if(I.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),S.expired++,Me(j,"expired",{reason:"no_longer_accepting"});continue}if(!I.hasApply){console.log(" No Easy Apply button \u2014 skipping"),S.noApplyButton++;continue}let G={id:`/jobs/view/${j}/`,href:q,jobTitle:x,companyName:M,location:T.location||"",salary:T.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let z=await Un(u,G);if(console.log(` Result: keepGoing=${z.keepGoing}, reason=${z.dailyLimitReached?"daily_limit":"ok"}`),!z.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),k=!0;break}}catch(j){if(Ue(j))try{await Ct(y,`queue job ${B+1}: ${j.message?.slice(0,80)}`),u=y.page,o=y.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=Pn(j);if(I?.severity==="fatal"){console.error(`\u274C [${I.label}] Fatal \u2014 stopping queue: ${(j.message||"").slice(0,120)}`),I.instructions&&console.error(` \u2192 ${I.instructions}`),I.label==="ilml-auth-expired"?S.fatalAuthExpired="ilml":I.label==="linkedin-session-expired"&&(S.fatalAuthExpired="linkedin");break}console.error(` Error: ${j.message?.slice(0,80)}`)}}}console.log(`
312
312
  Queue complete. ${k?"Daily limit hit.":"Continuing to search..."}`)}catch(_){console.error(`Failed to read job URLs file: ${_.message}`)}if(!k){if(f){console.log(`
313
- Queue done. Continuing with standard search...`);try{await u.goto(p,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3)}catch(_){console.error(" Navigation to search failed:",_.message)}}y.page=u,y.browser=o;try{await Ns(y)}catch(_){Ue(_)||/CDP unrecoverable/.test(_.message||"")?(console.error(`
313
+ Queue done. Continuing with standard search...`);try{await u.goto(p,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3)}catch(_){console.error(" Navigation to search failed:",_.message)}}y.page=u,y.browser=o;try{await Fs(y)}catch(_){Ue(_)||/CDP unrecoverable/.test(_.message||"")?(console.error(`
314
314
  \u274C Apply phase ended: CDP channel could not be recovered after ${S.cdpRecoveries} page recoveries and ${S.browserRestarts} browser restarts.`),console.error(` Last error: ${_.message}`)):/Session expired/i.test(_.message||"")?(console.error(`
315
315
  \u274C Apply phase ended: ${_.message}`),r=_):console.error(`
316
316
  \u26A0 Apply phase crashed: ${_.message}`)}u=y.page,o=y.browser}let v=S.submitted+S.skippedByLifebot+S.failed+S.mismatch+S.alreadyApplied+S.expired+S.noApplyButton,w=S.attempted-v,E=De("recruiters-from-jobs");n.push(`Jobs attempted: ${S.attempted}`),n.push(`Successfully applied: ${S.submitted}`),n.push(`Skipped by Lifebot: ${S.skippedByLifebot}`),n.push(`Failed (form errors): ${S.failed}`),S.mismatch>0&&n.push(`Mismatch (wrong panel): ${S.mismatch}`),S.alreadyApplied>0&&n.push(`Already applied: ${S.alreadyApplied}`),S.expired>0&&n.push(`Expired (closed): ${S.expired}`),S.noApplyButton>0&&n.push(`No Apply button: ${S.noApplyButton}`),w>0&&n.push(`Unaccounted: ${w}`),n.push(`Daily limit reached: ${S.dailyLimitHit?"Yes":"No"}`),S.cdpRecoveries>0&&n.push(`Page recoveries (CDP): ${S.cdpRecoveries}`),S.browserRestarts>0&&n.push(`Browser restarts: ${S.browserRestarts}`),n.push(`Recruiters found: ${_t}`),n.push(`Recruiters total: ${E.total} (${E.unprocessed} unprocessed)`),console.log(`
317
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 O=!!o&&o.isConnected?.()!==!1,L=xs?O?S.fatalAuthExpired==="linkedin"?"LinkedIn session expired (run: ilml linkedin login)":S.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)",W=!L;W||(console.log(`
318
- \u26A0 Skipping recruiter funnel \u2014 ${L}.`),console.log(` ${E.unprocessed} recruiters saved for next run.`),n.push(`Funnel: skipped (${L})`));let{markProfileProcessed:C}=await Promise.resolve().then(()=>(jt(),$o)),{canSendConnection:N,getQuotaStatus:Y}=await ze().then(()=>Bo),U=()=>({message:Cs,useCustomMessage:$s,maxConnections:Es,excludeLocations:lo,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async(_,B,T)=>{C("recruiters-from-jobs",_.profileUrl,{status:T.reason,connectionSent:T.connectionSent,withCustomMessage:T.withCustomMessage,message:T.messageSent,method:T.method,reason:T.reason,error:T.error,profileInfo:T.profileInfo},_._fromDate||null)}});if(W&&E.unprocessed>0){console.log(`
317
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 O=!!o&&o.isConnected?.()!==!1,L=$s?O?S.fatalAuthExpired==="linkedin"?"LinkedIn session expired (run: ilml linkedin login)":S.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)",W=!L;W||(console.log(`
318
+ \u26A0 Skipping recruiter funnel \u2014 ${L}.`),console.log(` ${E.unprocessed} recruiters saved for next run.`),n.push(`Funnel: skipped (${L})`));let{markProfileProcessed:C}=await Promise.resolve().then(()=>(jt(),$o)),{canSendConnection:N,getQuotaStatus:Y}=await ze().then(()=>Jo),U=()=>({message:As,useCustomMessage:Es,maxConnections:Cs,excludeLocations:lo,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async(_,B,T)=>{C("recruiters-from-jobs",_.profileUrl,{status:T.reason,connectionSent:T.connectionSent,withCustomMessage:T.withCustomMessage,message:T.messageSent,method:T.method,reason:T.reason,error:T.error,profileInfo:T.profileInfo},_._fromDate||null)}});if(W&&E.unprocessed>0){console.log(`
319
319
  --- Funnel: today's recruiters (${E.unprocessed}) ---`),lo.length>0&&console.log(` Excluding locations: ${lo.join(", ")}`);let _=at("recruiters-from-jobs");await Vt(u,_,U())}let ae=N();if(W&&ae.allowed){let _=ct("recruiters-from-jobs"),B=new Date().toISOString().split("T")[0],T=_.filter(q=>q._fromDate!==B);if(T.length>0){let q=Y();console.log(`
320
320
  --- Funnel: backfill from previous days (${T.length} unprocessed) ---`),console.log(` Quota remaining: ${q.daily.remaining} today, ${q.weekly.remaining} this week`),await Vt(u,T,{...U(),maxConnections:q.daily.remaining})}}let H=Y();console.log(`
321
321
  \u2705 Funnel done. Connection quota left: ${H.daily.remaining} of ${H.daily.max} today, ${H.weekly.remaining} of ${H.weekly.max} this week`),n.push(`Connection quota left: ${H.daily.remaining} of ${H.daily.max} today, ${H.weekly.remaining} of ${H.weekly.max} week`)}catch(i){r=i,console.error(`
322
- \u274C Apply session ended with error: ${i.message}`),i.stack&&console.error(i.stack)}kn(t,r?"error":"success",{summaryLines:n,dailyLimitHit:S.dailyLimitHit,attempted:S.attempted,submitted:S.submitted,failed:S.failed,skippedByLifebot:S.skippedByLifebot},r?r.message:null);try{await o?.close()}catch{}r&&process.exit(1)})();
322
+ \u274C Apply session ended with error: ${i.message}`),i.stack&&console.error(i.stack)}vn(t,r?"error":"success",{summaryLines:n,dailyLimitHit:S.dailyLimitHit,attempted:S.attempted,submitted:S.submitted,failed:S.failed,skippedByLifebot:S.skippedByLifebot},r?r.message:null);try{await o?.close()}catch{}r&&process.exit(1)})();