ilml-plugin-linkedin 1.20.3 → 1.20.4

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,7 +1,7 @@
1
- var hi=Object.defineProperty;var pe=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{for(var o in t)hi(e,o,{get:t[o],enumerable:!0})};async function w(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}function an(e){return parseInt(e,10)||0}async function oe(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let n=r.innerText||"",i=n.includes("Premium")||n.includes("premium")||n.includes("Upgrade")||n.includes("upgrade"),s=n.includes("Try for")||n.includes("free trial")||n.includes("/month")||n.includes("per month")||n.includes("Start my")||n.includes("Subscribe"),a=n.includes("Get hired faster")||n.includes("Get hired 2x");if(i||s||a){let l=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:n.substring(0,80)};let c=r.querySelectorAll("button");for(let u of c){let f=u.innerText?.trim().toLowerCase()||"",d=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return u.click(),{dismissed:!0,matched:n.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var Ue=pe(()=>{});var pn={};te(pn,{default:()=>xi,getAllUnprocessedProfiles:()=>_t,getSummary:()=>He,getUnprocessedProfiles:()=>$t,listFiles:()=>fn,loadProfiles:()=>At,markProfileProcessed:()=>dn,saveProfile:()=>lt,saveProfiles:()=>un});import"dotenv/config";import*as H from"fs";import*as ne from"path";import{fileURLToPath as wi}from"url";function st(){H.existsSync(me)||H.mkdirSync(me,{recursive:!0})}function vi(e,t){try{let o=`${e}-${ro()}.json`,r=H.readdirSync(me).filter(i=>i.startsWith(e)&&i.endsWith(".json")&&i!==o),n=0;for(let i of r)JSON.parse(H.readFileSync(ne.join(me,i),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function ro(){return new Date().toISOString().split("T")[0]}function io(e,t=null){let o=t||ro();return ne.join(me,`${e}-${o}.json`)}function At(e,t=null){st();let o=io(e,t);try{if(H.existsSync(o)){let r=H.readFileSync(o,"utf-8"),n=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${n.profiles.length} profiles from ${o}`),n.profiles}}catch(r){console.error(`Error loading profiles from ${o}:`,r.message)}return[]}function lt(e,t){st();let o=io(e),r={source:e,date:ro(),lastUpdated:new Date().toISOString(),profiles:[]};try{H.existsSync(o)&&(r=JSON.parse(H.readFileSync(o,"utf-8")))}catch(s){console.error(`Error reading ${o}:`,s.message)}if(r.profiles.some(s=>s.profileUrl===t.profileUrl))return!1;let i=vi(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:i}),r.lastUpdated=new Date().toISOString();try{H.writeFileSync(o,JSON.stringify(r,null,2));let s=i>0?` (seen ${i} day${i>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${s} (total: ${r.profiles.length})`),!0}catch(s){return console.error(`Error saving to ${o}:`,s.message),!1}}function un(e,t){let o=0;for(let r of t)lt(e,r)&&o++;return o}function $t(e,t=null){return At(e,t).filter(r=>!r.processed)}function dn(e,t,o,r=null){st();let n=io(e,r);try{if(!H.existsSync(n))return;let i=JSON.parse(H.readFileSync(n,"utf-8")),s=i.profiles.find(a=>a.profileUrl===t);if(s){if(s.processed=!0,s.processedAt=new Date().toISOString(),typeof o=="string")s.status=o;else if(typeof o=="object"){if(s.status=o.status,o.profileInfo){let a=o.profileInfo;a.name&&(s.name=a.name),a.title&&(s.title=a.title),a.location&&(s.location=a.location),a.company&&(s.company=a.company),a.connectionDegree&&(s.connectionDegree=a.connectionDegree),a.connectionsCount&&(s.connectionsCount=a.connectionsCount),a.mutualConnections&&(s.mutualConnections=a.mutualConnections),a.photoUrl&&(s.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(s.hasVerifiedBadge=a.hasVerifiedBadge)}s.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}i.lastUpdated=new Date().toISOString(),H.writeFileSync(n,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function He(e){let t=At(e),o=t.filter(n=>n.processed),r=t.filter(n=>!n.processed);return{total:t.length,processed:o.length,unprocessed:r.length,statuses:o.reduce((n,i)=>(n[i.status]=(n[i.status]||0)+1,n),{})}}function fn(){st();try{return H.readdirSync(me).filter(t=>t.endsWith(".json")).map(t=>{let[o,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let n=JSON.parse(H.readFileSync(ne.join(me,t),"utf-8"));return{file:t,source:o,date:r,count:n.profiles?.length||0,unprocessed:n.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:o,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function _t(e){st();let t=[];try{let n=H.readdirSync(me).filter(i=>i.startsWith(e+"-")&&i.endsWith(".json")).sort().reverse();for(let i of n)try{let s=JSON.parse(H.readFileSync(ne.join(me,i),"utf-8"));s.profiles&&t.push({file:i,date:s.date,profiles:s.profiles})}catch{}}catch{return[]}let o=new Set,r=[];for(let{date:n,profiles:i}of t)for(let s of i)!s.processed&&s.profileUrl&&!o.has(s.profileUrl)&&(o.add(s.profileUrl),r.push({...s,_fromDate:n}));return r}var Si,ki,me,xi,so=pe(()=>{Si=wi(import.meta.url),ki=ne.dirname(ne.dirname(Si)),me=process.env.DATA_DIR?ne.resolve(process.env.DATA_DIR,"collected-profiles"):ne.join(ki,"collected-profiles");xi={loadProfiles:At,saveProfile:lt,saveProfiles:un,getUnprocessedProfiles:$t,getAllUnprocessedProfiles:_t,markProfileProcessed:dn,getSummary:He,listFiles:fn}});import{getPluginConfig as Ci}from"@ilivemylife/graph-sdk";var Ei,ke,he,lo,ao,co=pe(async()=>{Ei=await Ci();for(let[e,t]of Object.entries(Ei))process.env[e]===void 0&&(process.env[e]=t);ke=process.env.LINKEDIN_NAME,he=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),lo=Object.freeze(new Set([he.DRAFT,he.CONFIRMED,he.NEEDS_REVIEW])),ao=Object.freeze(new Set([he.DRAFT,he.CONFIRMED,he.REJECTED,he.NEEDS_REVIEW]))});var jn={};te(jn,{addEncounter:()=>Ke,addProfileAlias:()=>Pt,atomicWriteJSON:()=>ge,canSendConnection:()=>ut,commitDataSnapshot:()=>In,default:()=>Fi,getAllApplications:()=>Tn,getPersonStatus:()=>Lt,getQuestionStats:()=>Rn,getQuotaStatus:()=>dt,getRecentConnections:()=>qt,linkPersonToJob:()=>Dt,loadApplicationQuestions:()=>bo,loadConversations:()=>xn,loadJobs:()=>Rt,loadPeople:()=>Q,loadProfileHistory:()=>vn,loadQuota:()=>Ft,loadSyncState:()=>An,logApplicationQuestions:()=>ze,migrateFromDailyFiles:()=>En,profileSlug:()=>ve,recordConnectionSent:()=>Ot,resetCaches:()=>yo,resolveCanonicalKey:()=>xe,safeLoadJSON:()=>Le,saveConversations:()=>Cn,saveJobs:()=>It,savePeople:()=>Ee,saveQuota:()=>go,saveSyncState:()=>$n,updateConnectionStatus:()=>Nt,upsertJob:()=>jt,upsertPerson:()=>Ce});import"dotenv/config";import*as U from"fs";import*as V from"path";import{fileURLToPath as Ai}from"url";import{execSync as uo}from"child_process";function yo(){Ve=null,Ge=null,ye=null,De=null,We=null,je=null}function Z(){U.existsSync(z)||U.mkdirSync(z,{recursive:!0})}function ge(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";U.writeFileSync(r,o);for(let n=0;n<3;n++)try{U.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Le(e,t){if(!U.existsSync(e))return null;try{let o=JSON.parse(U.readFileSync(e,"utf-8"));try{U.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(U.existsSync(r))try{let n=JSON.parse(U.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{U.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{U.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ye(){return new Date().toISOString().split("T")[0]}function ve(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function mn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function xe(e,t,o=null){if(!t||e[t])return t;let r=ve(t);if(!r)return t;let n=null;for(let[i,s]of Object.entries(e)){if(ve(s.profileUrl||i)===r)return i;!n&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}if(n){let i=mn(o),s=mn(e[n].name);if(i&&s&&i===s)return n}return t}function Ri(){U.existsSync(ho)||U.mkdirSync(ho,{recursive:!0})}function kn(e){let t=ve(e);return t?V.join(ho,`${t}.json`):null}function vn(e){let t=kn(e);return t?Le(t,`profile-history/${ve(e)}.json`)||[]:[]}function Ii(e,t){let o=kn(e);if(!o)return;Ri();let r=vn(e);r.unshift(t);try{ge(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${ve(e)}: ${n.message}`)}}function hn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function yn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function ji(e,t){if(!e)return[];let o=[];for(let r of Ti){let n=e[r],i=t[r];hn(n)||hn(i)||yn(n)!==yn(i)&&o.push(r)}return o}function Di(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 Q(){return Ve||(Z(),Ve=Le(fo,"people.json")||{},Ve)}function Ee(e){Z(),Ve=e;try{ge(fo,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${V.resolve(fo)}`)}}function Rt(){return Ge||(Z(),Ge=Le(po,"jobs.json")||{},Ge)}function It(e){Z(),Ge=e;try{ge(po,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${V.resolve(po)}`)}}function xn(){return De||(Z(),De=Le(Tt,"conversations.json")||{},Li(De),De)}function Li(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let n=(o.messages||[]).find(i=>i.status==="draft");n&&o.draftStatus&&o.draftStatus!=="pending"&&(n.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{ge(Tt,e)}catch{}}}function Cn(e){Z(),De=e;try{ge(Tt,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${V.resolve(Tt)}`)}}function Ce(e,t={}){if(!e)return null;let o=Q(),r=Ye(),n=new Date().toISOString(),i=xe(o,e,t.name),s=o[i];if(s){let a=ji(s,t);a.length>0&&(Ii(i,{capturedAt:n,previousLastUpdated:s.lastUpdated||null,changedFields:a,snapshot:Di(s)}),s.lastSnapshotAt=n),s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=n,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let l of Sn)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(s[l])&&s[l].length>0)continue;s[l]=t[l]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=n)}else o[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return Ee(o),o[i]}function jt(e,t={}){if(!e)return null;let o=Rt(),r=Ye(),n=o[e];if(n){let i=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let s of i)t[s]!=null&&(n[s]=t[s])}else o[e]={title:t.title||null,company:t.company||null,location:t.location||null,salary:t.salary||null,url:t.url||null,applied:t.applied||!1,appliedDate:t.appliedDate||r,recruiterUrl:t.recruiterUrl||null,firstSeen:r};return It(o),o[e]}function Dt(e,t){if(!e||!t)return;let o=Q(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),Ee(o)))}function Ke(e,t){if(!e||!t)return;let o=Q(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let i={date:Ye(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!r.encounters.some(a=>a.date===i.date&&a.source===i.source&&a.action===i.action&&(a.jobId||"")===(i.jobId||""))&&(r.encounters.push(i),r.lastUpdated=new Date().toISOString(),Ee(o))}function Lt(e){return e&&Q()[e]?.connectionStatus||null}function Nt(e,t,o={}){if(!e)return;if(o.profileInfo)Ce(e,o.profileInfo);else{let a=Q(),l=xe(a,e,o.profileInfo?.name);a[l]||Ce(e,{})}let r=Q(),n=xe(r,e,o.profileInfo?.name),i=r[n];if(!i)return;let s=Ye();i.connectionStatus=t,t==="connected"?i.connectionDate=s:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=s)),i.connectionMethod=o.method||i.connectionMethod,i.messageSent=o.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),Ee(r)}function Pt(e,t,o={}){if(o.dryRun||!e||!t)return;let r=ve(t);if(!r)return;let n=Q(),i=xe(n,e),s=n[i];if(!s)return;let a=ve(s.profileUrl||i);r!==a&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(r)||(s.aliases.push(r),s.lastUpdated=new Date().toISOString(),Ee(n)))}function Ft(){return ye||(Z(),ye=Le(gn,"quota.json"),(!ye||!ye.connections)&&(ye={connections:[]}),ye)}function go(e){Z(),ye=e;try{ge(gn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Ot(e,t="unknown"){let o=Ft(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),go(o)}function qt(){let e=Ft(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function ut(){let e=qt(),t=Ye(),o=e.filter(l=>l.date===t).length,r=e.length,n=o>=at,i=r>=ct,s=!n&&!i,a={allowed:s,daily:{sent:o,max:at},weekly:{sent:r,max:ct}};return s||(a.reason=n?`Daily limit reached (${o}/${at})`:`Weekly limit reached (${r}/${ct})`),a}function dt(){let e=qt(),t=Ye(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:at,remaining:at-o},weekly:{sent:r,max:ct,remaining:ct-r}}}function Ni(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function En(){Z();let e=U.readdirSync(z).filter(i=>i.endsWith(".json")&&i!=="people.json"&&i!=="jobs.json"&&i!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
1
+ var hi=Object.defineProperty;var pe=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{for(var o in t)hi(e,o,{get:t[o],enumerable:!0})};async function w(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}function an(e){return parseInt(e,10)||0}async function oe(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let n=r.innerText||"",i=n.includes("Premium")||n.includes("premium")||n.includes("Upgrade")||n.includes("upgrade"),s=n.includes("Try for")||n.includes("free trial")||n.includes("/month")||n.includes("per month")||n.includes("Start my")||n.includes("Subscribe"),a=n.includes("Get hired faster")||n.includes("Get hired 2x");if(i||s||a){let l=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:n.substring(0,80)};let c=r.querySelectorAll("button");for(let u of c){let f=u.innerText?.trim().toLowerCase()||"",d=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return u.click(),{dismissed:!0,matched:n.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var Ue=pe(()=>{});var pn={};te(pn,{default:()=>xi,getAllUnprocessedProfiles:()=>_t,getSummary:()=>He,getUnprocessedProfiles:()=>$t,listFiles:()=>fn,loadProfiles:()=>At,markProfileProcessed:()=>dn,saveProfile:()=>lt,saveProfiles:()=>un});import"dotenv/config";import*as H from"fs";import*as ne from"path";import{fileURLToPath as wi}from"url";function st(){H.existsSync(me)||H.mkdirSync(me,{recursive:!0})}function vi(e,t){try{let o=`${e}-${ro()}.json`,r=H.readdirSync(me).filter(i=>i.startsWith(e)&&i.endsWith(".json")&&i!==o),n=0;for(let i of r)JSON.parse(H.readFileSync(ne.join(me,i),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function ro(){return new Date().toISOString().split("T")[0]}function io(e,t=null){let o=t||ro();return ne.join(me,`${e}-${o}.json`)}function At(e,t=null){st();let o=io(e,t);try{if(H.existsSync(o)){let r=H.readFileSync(o,"utf-8"),n=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${n.profiles.length} profiles from ${o}`),n.profiles}}catch(r){console.error(`Error loading profiles from ${o}:`,r.message)}return[]}function lt(e,t){st();let o=io(e),r={source:e,date:ro(),lastUpdated:new Date().toISOString(),profiles:[]};try{H.existsSync(o)&&(r=JSON.parse(H.readFileSync(o,"utf-8")))}catch(s){console.error(`Error reading ${o}:`,s.message)}if(r.profiles.some(s=>s.profileUrl===t.profileUrl))return!1;let i=vi(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:i}),r.lastUpdated=new Date().toISOString();try{H.writeFileSync(o,JSON.stringify(r,null,2));let s=i>0?` (seen ${i} day${i>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${s} (total: ${r.profiles.length})`),!0}catch(s){return console.error(`Error saving to ${o}:`,s.message),!1}}function un(e,t){let o=0;for(let r of t)lt(e,r)&&o++;return o}function $t(e,t=null){return At(e,t).filter(r=>!r.processed)}function dn(e,t,o,r=null){st();let n=io(e,r);try{if(!H.existsSync(n))return;let i=JSON.parse(H.readFileSync(n,"utf-8")),s=i.profiles.find(a=>a.profileUrl===t);if(s){if(s.processed=!0,s.processedAt=new Date().toISOString(),typeof o=="string")s.status=o;else if(typeof o=="object"){if(s.status=o.status,o.profileInfo){let a=o.profileInfo;a.name&&(s.name=a.name),a.title&&(s.title=a.title),a.location&&(s.location=a.location),a.company&&(s.company=a.company),a.connectionDegree&&(s.connectionDegree=a.connectionDegree),a.connectionsCount&&(s.connectionsCount=a.connectionsCount),a.mutualConnections&&(s.mutualConnections=a.mutualConnections),a.photoUrl&&(s.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(s.hasVerifiedBadge=a.hasVerifiedBadge)}s.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}i.lastUpdated=new Date().toISOString(),H.writeFileSync(n,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function He(e){let t=At(e),o=t.filter(n=>n.processed),r=t.filter(n=>!n.processed);return{total:t.length,processed:o.length,unprocessed:r.length,statuses:o.reduce((n,i)=>(n[i.status]=(n[i.status]||0)+1,n),{})}}function fn(){st();try{return H.readdirSync(me).filter(t=>t.endsWith(".json")).map(t=>{let[o,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let n=JSON.parse(H.readFileSync(ne.join(me,t),"utf-8"));return{file:t,source:o,date:r,count:n.profiles?.length||0,unprocessed:n.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:o,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function _t(e){st();let t=[];try{let n=H.readdirSync(me).filter(i=>i.startsWith(e+"-")&&i.endsWith(".json")).sort().reverse();for(let i of n)try{let s=JSON.parse(H.readFileSync(ne.join(me,i),"utf-8"));s.profiles&&t.push({file:i,date:s.date,profiles:s.profiles})}catch{}}catch{return[]}let o=new Set,r=[];for(let{date:n,profiles:i}of t)for(let s of i)!s.processed&&s.profileUrl&&!o.has(s.profileUrl)&&(o.add(s.profileUrl),r.push({...s,_fromDate:n}));return r}var Si,ki,me,xi,so=pe(()=>{Si=wi(import.meta.url),ki=ne.dirname(ne.dirname(Si)),me=process.env.DATA_DIR?ne.resolve(process.env.DATA_DIR,"collected-profiles"):ne.join(ki,"collected-profiles");xi={loadProfiles:At,saveProfile:lt,saveProfiles:un,getUnprocessedProfiles:$t,getAllUnprocessedProfiles:_t,markProfileProcessed:dn,getSummary:He,listFiles:fn}});import{getPluginConfig as Ci}from"@ilivemylife/graph-sdk";var Ei,ke,he,lo,ao,co=pe(async()=>{Ei=await Ci();for(let[e,t]of Object.entries(Ei))process.env[e]===void 0&&(process.env[e]=t);ke=process.env.LINKEDIN_NAME,he=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),lo=Object.freeze(new Set([he.DRAFT,he.CONFIRMED,he.NEEDS_REVIEW])),ao=Object.freeze(new Set([he.DRAFT,he.CONFIRMED,he.REJECTED,he.NEEDS_REVIEW]))});var Dn={};te(Dn,{addEncounter:()=>Ke,addProfileAlias:()=>Pt,atomicWriteJSON:()=>ge,canSendConnection:()=>ut,commitDataSnapshot:()=>In,default:()=>Fi,getAllApplications:()=>Tn,getPersonStatus:()=>Lt,getQuestionStats:()=>Rn,getQuotaStatus:()=>dt,getRecentConnections:()=>qt,linkPersonToJob:()=>jt,loadApplicationQuestions:()=>bo,loadConversations:()=>xn,loadJobs:()=>Rt,loadPeople:()=>Q,loadProfileHistory:()=>vn,loadQuota:()=>Ft,loadSyncState:()=>An,logApplicationQuestions:()=>ze,migrateFromDailyFiles:()=>En,profileSlug:()=>ve,recordConnectionSent:()=>Ot,resetCaches:()=>yo,resolveCanonicalKey:()=>xe,safeLoadJSON:()=>Le,saveConversations:()=>Cn,saveJobs:()=>It,savePeople:()=>Ee,saveQuota:()=>go,saveSyncState:()=>$n,updateConnectionStatus:()=>Nt,upsertJob:()=>Dt,upsertPerson:()=>Ce});import"dotenv/config";import*as U from"fs";import*as V from"path";import{fileURLToPath as Ai}from"url";import{execSync as uo}from"child_process";function yo(){Ve=null,Ge=null,ye=null,je=null,We=null,De=null}function Z(){U.existsSync(z)||U.mkdirSync(z,{recursive:!0})}function ge(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";U.writeFileSync(r,o);for(let n=0;n<3;n++)try{U.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Le(e,t){if(!U.existsSync(e))return null;try{let o=JSON.parse(U.readFileSync(e,"utf-8"));try{U.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(U.existsSync(r))try{let n=JSON.parse(U.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{U.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{U.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ye(){return new Date().toISOString().split("T")[0]}function ve(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function mn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function xe(e,t,o=null){if(!t||e[t])return t;let r=ve(t);if(!r)return t;let n=null;for(let[i,s]of Object.entries(e)){if(ve(s.profileUrl||i)===r)return i;!n&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}if(n){let i=mn(o),s=mn(e[n].name);if(i&&s&&i===s)return n}return t}function Ri(){U.existsSync(ho)||U.mkdirSync(ho,{recursive:!0})}function kn(e){let t=ve(e);return t?V.join(ho,`${t}.json`):null}function vn(e){let t=kn(e);return t?Le(t,`profile-history/${ve(e)}.json`)||[]:[]}function Ii(e,t){let o=kn(e);if(!o)return;Ri();let r=vn(e);r.unshift(t);try{ge(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${ve(e)}: ${n.message}`)}}function hn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function yn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Di(e,t){if(!e)return[];let o=[];for(let r of Ti){let n=e[r],i=t[r];hn(n)||hn(i)||yn(n)!==yn(i)&&o.push(r)}return o}function ji(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 Q(){return Ve||(Z(),Ve=Le(fo,"people.json")||{},Ve)}function Ee(e){Z(),Ve=e;try{ge(fo,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${V.resolve(fo)}`)}}function Rt(){return Ge||(Z(),Ge=Le(po,"jobs.json")||{},Ge)}function It(e){Z(),Ge=e;try{ge(po,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${V.resolve(po)}`)}}function xn(){return je||(Z(),je=Le(Tt,"conversations.json")||{},Li(je),je)}function Li(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let n=(o.messages||[]).find(i=>i.status==="draft");n&&o.draftStatus&&o.draftStatus!=="pending"&&(n.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{ge(Tt,e)}catch{}}}function Cn(e){Z(),je=e;try{ge(Tt,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${V.resolve(Tt)}`)}}function Ce(e,t={}){if(!e)return null;let o=Q(),r=Ye(),n=new Date().toISOString(),i=xe(o,e,t.name),s=o[i];if(s){let a=Di(s,t);a.length>0&&(Ii(i,{capturedAt:n,previousLastUpdated:s.lastUpdated||null,changedFields:a,snapshot:ji(s)}),s.lastSnapshotAt=n),s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=n,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let l of Sn)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(s[l])&&s[l].length>0)continue;s[l]=t[l]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=n)}else o[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return Ee(o),o[i]}function Dt(e,t={}){if(!e)return null;let o=Rt(),r=Ye(),n=o[e];if(n){let i=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let s of i)t[s]!=null&&(n[s]=t[s])}else o[e]={title:t.title||null,company:t.company||null,location:t.location||null,salary:t.salary||null,url:t.url||null,applied:t.applied||!1,appliedDate:t.appliedDate||r,recruiterUrl:t.recruiterUrl||null,firstSeen:r};return It(o),o[e]}function jt(e,t){if(!e||!t)return;let o=Q(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),Ee(o)))}function Ke(e,t){if(!e||!t)return;let o=Q(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let i={date:Ye(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!r.encounters.some(a=>a.date===i.date&&a.source===i.source&&a.action===i.action&&(a.jobId||"")===(i.jobId||""))&&(r.encounters.push(i),r.lastUpdated=new Date().toISOString(),Ee(o))}function Lt(e){return e&&Q()[e]?.connectionStatus||null}function Nt(e,t,o={}){if(!e)return;if(o.profileInfo)Ce(e,o.profileInfo);else{let a=Q(),l=xe(a,e,o.profileInfo?.name);a[l]||Ce(e,{})}let r=Q(),n=xe(r,e,o.profileInfo?.name),i=r[n];if(!i)return;let s=Ye();i.connectionStatus=t,t==="connected"?i.connectionDate=s:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=s)),i.connectionMethod=o.method||i.connectionMethod,i.messageSent=o.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),Ee(r)}function Pt(e,t,o={}){if(o.dryRun||!e||!t)return;let r=ve(t);if(!r)return;let n=Q(),i=xe(n,e),s=n[i];if(!s)return;let a=ve(s.profileUrl||i);r!==a&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(r)||(s.aliases.push(r),s.lastUpdated=new Date().toISOString(),Ee(n)))}function Ft(){return ye||(Z(),ye=Le(gn,"quota.json"),(!ye||!ye.connections)&&(ye={connections:[]}),ye)}function go(e){Z(),ye=e;try{ge(gn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Ot(e,t="unknown"){let o=Ft(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),go(o)}function qt(){let e=Ft(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function ut(){let e=qt(),t=Ye(),o=e.filter(l=>l.date===t).length,r=e.length,n=o>=at,i=r>=ct,s=!n&&!i,a={allowed:s,daily:{sent:o,max:at},weekly:{sent:r,max:ct}};return s||(a.reason=n?`Daily limit reached (${o}/${at})`:`Weekly limit reached (${r}/${ct})`),a}function dt(){let e=qt(),t=Ye(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:at,remaining:at-o},weekly:{sent:r,max:ct,remaining:ct-r}}}function Ni(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function En(){Z();let e=U.readdirSync(z).filter(i=>i.endsWith(".json")&&i!=="people.json"&&i!=="jobs.json"&&i!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
2
2
  Migrating from ${e.length} daily files...
3
3
  `);let t=Q(),o=Rt(),r=0,n=0;e.sort();for(let i of e){let s=V.join(z,i),a;try{a=JSON.parse(U.readFileSync(s,"utf-8"))}catch(u){console.log(` Skipping ${i}: ${u.message}`);continue}let l=a.date||i.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,c=a.source||i.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!a.profiles||!Array.isArray(a.profiles)){console.log(` Skipping ${i}: no profiles array`);continue}console.log(` ${i}: ${a.profiles.length} profiles`);for(let u of a.profiles){let f=u.profileUrl;if(!f)continue;let d=t[f];if(d){d.seenCount=(d.seenCount||1)+1,l&&(!d.lastSeen||l>d.lastSeen)&&(d.lastSeen=l),l&&(!d.firstSeen||l<d.firstSeen)&&(d.firstSeen=l),c&&!d.sources?.includes(c)&&(d.sources=d.sources||[],d.sources.push(c));for(let p of Sn)u[p]!=null&&(d[p]=u[p]);u.status&&u.processed&&(d.connectionStatus=u.status,d.connectionDate=l,u.funnelResult&&(d.connectionMethod=u.funnelResult.method||d.connectionMethod,d.messageSent=u.funnelResult.message||d.messageSent)),d.lastUpdated=new Date().toISOString()}else t[f]={name:u.name||null,title:u.title||null,location:u.location||null,company:u.company||null,connectionDegree:u.connectionDegree||null,connectionsCount:u.connectionsCount||null,mutualConnections:u.mutualConnections||null,photoUrl:u.photoUrl||null,hasVerifiedBadge:u.hasVerifiedBadge||!1,firstSeen:l,lastSeen:l,seenCount:1,sources:c?[c]:[],connectionStatus:u.processed&&u.status||null,connectionDate:u.processed?l:null,connectionMethod:u.funnelResult?.method||null,messageSent:u.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(u.fromJob?.url){let p=Ni(u.fromJob.url);p&&(t[f].jobIds||(t[f].jobIds=[]),t[f].jobIds.includes(p)||t[f].jobIds.push(p),o[p]?o[p].recruiterUrl||(o[p].recruiterUrl=f):(o[p]={title:u.fromJob.title||null,company:u.fromJob.company||null,location:null,salary:null,url:u.fromJob.url,applied:!0,appliedDate:l,recruiterUrl:f,firstSeen:l},n++))}}}return Ee(t),It(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 An(){return We||(Z(),We=Le(bn,"sync-state.json")||{},We)}function $n(e){Z(),We=e;try{ge(bn,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function bo(){if(je)return je;Z();try{U.existsSync(mo)&&(je=JSON.parse(U.readFileSync(mo,"utf-8")))}catch{}return je||(je={}),je}function _n(e){return Array.isArray(e.applications)}function Tn(){let e=bo();if(_n(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function ze(e){if(!e||!e.questions||e.questions.length===0)return;let t=bo(),o=e.jobId||"unknown",n={applicationId:`${o}_${Date.now()}`,date:new Date().toISOString(),result:e.result||"submitted",formPages:e.formPages||null,duration:e.duration||null,retries:e.retries||0,failedField:e.failedField||null,questionCount:e.questions.length,questions:e.questions.map(i=>{let s={type:i.type||"input",question:i.labelText||i.question||"",answer:i.answer||""};return i.options&&(i.options.length<=Pi?s.options=i.options:s.optionsOmitted=!0),i.page&&(s.page=i.page),i.wasPreFilled&&(s.wasPreFilled=!0),i.wasRetry&&(s.wasRetry=!0),typeof i.isRequired=="boolean"&&(s.isRequired=i.isRequired),i.wasOptional&&(s.wasOptional=!0),s})};_n(t)?(n.jobId=o,n.jobTitle=e.jobTitle||null,n.jobCompany=e.jobCompany||null,n.jobUrl=e.jobUrl||null,t.applications.push(n)):(t[o]||(t[o]={applications:[]}),t[o].applications.push(n));try{ge(mo,t)}catch(i){console.error(`[!] Failed to save application-questions.json: ${i.message}`)}}function Rn(){let e=Tn(),t=new Map;for(let i of e)for(let s of i.questions||[]){let a=s.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:s.question,count:0,answers:new Map});let l=t.get(a);l.count++;let c=(s.answer||"").trim();l.answers.set(c,(l.answers.get(c)||0)+1)}let o=[...t.values()].sort((i,s)=>s.count-i.count),r=o.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((s,a)=>a[1]-s[1])[0]?.[0]||""})),n=o.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((s,a)=>a[1]-s[1]).map(([s,a])=>`${s} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:n}}function In(e){if(U.existsSync(V.join(z,".git")))try{let t={cwd:z,stdio:"pipe",timeout:1e4};uo("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{uo("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');uo(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var $i,_i,z,fo,po,gn,Tt,bn,mo,ho,wn,at,ct,Ve,Ge,ye,De,We,je,Sn,Ti,Pi,Fi,Qe=pe(async()=>{await co();$i=Ai(import.meta.url),_i=V.dirname(V.dirname($i)),z=process.env.DATA_DIR?V.resolve(process.env.DATA_DIR,"collected-profiles"):V.join(_i,"collected-profiles"),fo=V.join(z,"people.json"),po=V.join(z,"jobs.json"),gn=V.join(z,"quota.json"),Tt=V.join(z,"conversations.json"),bn=V.join(z,"sync-state.json"),mo=V.join(z,"application-questions.json"),ho=V.join(z,"profile-history"),wn=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},at=wn(process.env.CONNECT_MAX_DAILY,20),ct=wn(process.env.CONNECT_MAX_WEEKLY,100),Ve=null,Ge=null,ye=null,De=null,We=null,je=null;Sn=["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"],Ti=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];Pi=50;Fi={loadPeople:Q,savePeople:Ee,loadJobs:Rt,saveJobs:It,loadConversations:xn,saveConversations:Cn,upsertPerson:Ce,upsertJob:jt,linkPersonToJob:Dt,addEncounter:Ke,getPersonStatus:Lt,updateConnectionStatus:Nt,addProfileAlias:Pt,resolveCanonicalKey:xe,migrateFromDailyFiles:En,loadQuota:Ft,saveQuota:go,recordConnectionSent:Ot,canSendConnection:ut,getRecentConnections:qt,getQuotaStatus:dt,loadSyncState:An,saveSyncState:$n,commitDataSnapshot:In,logApplicationQuestions:ze,getQuestionStats:Rn}});var Dn={};te(Dn,{extractCertificationsFromDetails:()=>Bi,extractEducationFromDetails:()=>Mi,extractExperienceFromDetails:()=>Oi,extractFeaturedFromDetails:()=>qi,extractRecommendationsFromDetails:()=>Ji,extractSkillsFromDetails:()=>Ui});async function Oi(e,t){let o=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(900);await w(1e3);let n=0;for(;n<5&&await e.evaluate(()=>{for(let s of document.querySelectorAll("button"))if(/^Load more$/i.test((s.textContent||"").trim()))return s.click(),!0;return!1});)n++,await w(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function s(u){let f=[];for(let d of u.querySelectorAll("div")){let p=Array.from(d.children).filter(h=>h.tagName==="DIV");if(p.length<3)continue;let m=p.filter(h=>(h.textContent||"").trim().length>50);m.length<3||(d.textContent||"").length<500||f.push({el:d,count:m.length,totalText:(d.textContent||"").length})}return f.sort((d,p)=>p.count-d.count||d.totalText-p.totalText),f[0]?.el}let a=s(i);if(!a)return[];let l=Array.from(a.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function c(u){let f=u[0]||null,d=null,p=null;if(u[1]){let A=u[1].split("\xB7").map(T=>T.trim());d=A[0]||null,A[1]&&(p=A[1])}let m=u.findIndex(A=>/(\d{4}|present)/i.test(A)&&/(-|–|—)/i.test(A)&&A.length<80),h=null,g=null;if(m>=0){let A=u[m].split("\xB7").map(T=>T.trim());h=A[0]||null,A[1]&&(g=A[1])}let y=null,S=-1;if(m>=0&&u[m+1]){let A=u[m+1],T=/^[>*\-•]|^&gt;/.test(A),Y=/https?:\/\//.test(A),K=/\d{4}/.test(A),M=/,/.test(A)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(A);!T&&!Y&&!K&&A.length<100&&M&&(y=A,S=m+1)}let v=null,b=-1,E=u[u.length-1];if(E&&/and\s+\+\d+\s+skills?$/i.test(E)){b=u.length-1;let A=E.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);A&&(v={listed:A[1].split(",").map(T=>T.trim()),additional:parseInt(A[2],10)})}let R=new Set([0,1,m,S,b].filter(A=>A>=0)),I=u.filter((A,T)=>!R.has(T)),O=I.length>0?I.join(`
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 An(){return We||(Z(),We=Le(bn,"sync-state.json")||{},We)}function $n(e){Z(),We=e;try{ge(bn,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function bo(){if(De)return De;Z();try{U.existsSync(mo)&&(De=JSON.parse(U.readFileSync(mo,"utf-8")))}catch{}return De||(De={}),De}function _n(e){return Array.isArray(e.applications)}function Tn(){let e=bo();if(_n(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function ze(e){if(!e||!e.questions||e.questions.length===0)return;let t=bo(),o=e.jobId||"unknown",n={applicationId:`${o}_${Date.now()}`,date:new Date().toISOString(),result:e.result||"submitted",formPages:e.formPages||null,duration:e.duration||null,retries:e.retries||0,failedField:e.failedField||null,questionCount:e.questions.length,questions:e.questions.map(i=>{let s={type:i.type||"input",question:i.labelText||i.question||"",answer:i.answer||""};return i.options&&(i.options.length<=Pi?s.options=i.options:s.optionsOmitted=!0),i.page&&(s.page=i.page),i.wasPreFilled&&(s.wasPreFilled=!0),i.wasRetry&&(s.wasRetry=!0),typeof i.isRequired=="boolean"&&(s.isRequired=i.isRequired),i.wasOptional&&(s.wasOptional=!0),s})};_n(t)?(n.jobId=o,n.jobTitle=e.jobTitle||null,n.jobCompany=e.jobCompany||null,n.jobUrl=e.jobUrl||null,t.applications.push(n)):(t[o]||(t[o]={applications:[]}),t[o].applications.push(n));try{ge(mo,t)}catch(i){console.error(`[!] Failed to save application-questions.json: ${i.message}`)}}function Rn(){let e=Tn(),t=new Map;for(let i of e)for(let s of i.questions||[]){let a=s.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:s.question,count:0,answers:new Map});let l=t.get(a);l.count++;let c=(s.answer||"").trim();l.answers.set(c,(l.answers.get(c)||0)+1)}let o=[...t.values()].sort((i,s)=>s.count-i.count),r=o.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((s,a)=>a[1]-s[1])[0]?.[0]||""})),n=o.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((s,a)=>a[1]-s[1]).map(([s,a])=>`${s} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:n}}function In(e){if(U.existsSync(V.join(z,".git")))try{let t={cwd:z,stdio:"pipe",timeout:1e4};uo("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{uo("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');uo(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var $i,_i,z,fo,po,gn,Tt,bn,mo,ho,wn,at,ct,Ve,Ge,ye,je,We,De,Sn,Ti,Pi,Fi,Qe=pe(async()=>{await co();$i=Ai(import.meta.url),_i=V.dirname(V.dirname($i)),z=process.env.DATA_DIR?V.resolve(process.env.DATA_DIR,"collected-profiles"):V.join(_i,"collected-profiles"),fo=V.join(z,"people.json"),po=V.join(z,"jobs.json"),gn=V.join(z,"quota.json"),Tt=V.join(z,"conversations.json"),bn=V.join(z,"sync-state.json"),mo=V.join(z,"application-questions.json"),ho=V.join(z,"profile-history"),wn=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},at=wn(process.env.CONNECT_MAX_DAILY,20),ct=wn(process.env.CONNECT_MAX_WEEKLY,100),Ve=null,Ge=null,ye=null,je=null,We=null,De=null;Sn=["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"],Ti=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];Pi=50;Fi={loadPeople:Q,savePeople:Ee,loadJobs:Rt,saveJobs:It,loadConversations:xn,saveConversations:Cn,upsertPerson:Ce,upsertJob:Dt,linkPersonToJob:jt,addEncounter:Ke,getPersonStatus:Lt,updateConnectionStatus:Nt,addProfileAlias:Pt,resolveCanonicalKey:xe,migrateFromDailyFiles:En,loadQuota:Ft,saveQuota:go,recordConnectionSent:Ot,canSendConnection:ut,getRecentConnections:qt,getQuotaStatus:dt,loadSyncState:An,saveSyncState:$n,commitDataSnapshot:In,logApplicationQuestions:ze,getQuestionStats:Rn}});var jn={};te(jn,{extractCertificationsFromDetails:()=>Bi,extractEducationFromDetails:()=>Mi,extractExperienceFromDetails:()=>Oi,extractFeaturedFromDetails:()=>qi,extractRecommendationsFromDetails:()=>Ji,extractSkillsFromDetails:()=>Ui});async function Oi(e,t){let o=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(900);await w(1e3);let n=0;for(;n<5&&await e.evaluate(()=>{for(let s of document.querySelectorAll("button"))if(/^Load more$/i.test((s.textContent||"").trim()))return s.click(),!0;return!1});)n++,await w(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function s(u){let f=[];for(let d of u.querySelectorAll("div")){let p=Array.from(d.children).filter(h=>h.tagName==="DIV");if(p.length<3)continue;let m=p.filter(h=>(h.textContent||"").trim().length>50);m.length<3||(d.textContent||"").length<500||f.push({el:d,count:m.length,totalText:(d.textContent||"").length})}return f.sort((d,p)=>p.count-d.count||d.totalText-p.totalText),f[0]?.el}let a=s(i);if(!a)return[];let l=Array.from(a.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function c(u){let f=u[0]||null,d=null,p=null;if(u[1]){let A=u[1].split("\xB7").map(T=>T.trim());d=A[0]||null,A[1]&&(p=A[1])}let m=u.findIndex(A=>/(\d{4}|present)/i.test(A)&&/(-|–|—)/i.test(A)&&A.length<80),h=null,g=null;if(m>=0){let A=u[m].split("\xB7").map(T=>T.trim());h=A[0]||null,A[1]&&(g=A[1])}let y=null,S=-1;if(m>=0&&u[m+1]){let A=u[m+1],T=/^[>*\-•]|^&gt;/.test(A),Y=/https?:\/\//.test(A),K=/\d{4}/.test(A),M=/,/.test(A)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(A);!T&&!Y&&!K&&A.length<100&&M&&(y=A,S=m+1)}let v=null,b=-1,E=u[u.length-1];if(E&&/and\s+\+\d+\s+skills?$/i.test(E)){b=u.length-1;let A=E.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);A&&(v={listed:A[1].split(",").map(T=>T.trim()),additional:parseInt(A[2],10)})}let R=new Set([0,1,m,S,b].filter(A=>A>=0)),I=u.filter((A,T)=>!R.has(T)),O=I.length>0?I.join(`
5
5
 
6
6
  `):null;return{title:f,company:d,employmentType:p,dates:h,duration:g,location:y,description:O,skills:v,_raw:u}}return l.map(u=>{let d=(u.innerText||"").trim().split(`
7
7
  `).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return c(d)}).filter(u=>u.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 ft(e,t,o){let r=t.replace(/\/+$/,"")+`/details/${o}/`;await e.goto(r,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let n=e.url();if(/\/(login|authwall|checkpoint)/i.test(n))throw new Error(`Session expired \u2014 bounced to ${n} when fetching /details/${o}/`);if(!n.toLowerCase().includes(`/details/${o.toLowerCase()}/`))throw new Error(`Section /details/${o}/ not available on profile (landed on ${n})`);for(let s=0;s<4;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);await w(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)i++,await w(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function mt(e,t,o,r){try{return await r()}catch(n){let i=n.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw n;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${o} failed for ${e}: ${i.slice(0,120)}`),[])}}async function qi(e,t){return mt(t,"featured","extractFeaturedFromDetails",async()=>(await ft(e,t,"featured"),await e.evaluate(`(() => {
@@ -242,14 +242,14 @@ function findEntryContainer(root) {
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 Ie=yi({token:cn});var Be=12e4;async function Je(e,{retries:t=2}={}){let o=process.env.NODE_EASY_APPLY_MAIN;if(!o||o.startsWith("YOUR_"))throw new Error('NODE_EASY_APPLY_MAIN is not configured in .env. Create a node in iLiveMyLife, add "assist" tag, and set the node ID in .env. See README.md for setup instructions.');for(let r=1;r<=t;r++)try{let n=await Ie.askLifebot(o,e,{timeout:Be});return Be=Math.max(12e4,Be*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){Be=Math.min(Be*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(Be/1e3)}s...`);continue}throw n}}async function no(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let o=`Job application form field "${e}" \u2014 reply with ONLY the value to fill in, nothing else. `;return t&&(t==="Enter a decimal number larger than 0.0"&&(t="Enter a decimal number larger than 0"),o+=`Additional info: ${t}`),await Je(o)}async function Et(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Je(o)}async function it(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Je(o)}so();import{LIFEBOT_MESSAGE_TYPES as Qr}from"@ilivemylife/graph-sdk";Ue();await Qe();async function lr(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function sr(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function bs(e,t,o={}){let{extractExperience:r=!1,extractFeatured:n=!1,extractEducation:i=!1,extractSkills:s=!1,extractRecommendations:a=!1,extractCertifications:l=!1}=o;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await oe(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await lr(e,t));let u=0;for(let b=0;b<2;b++){let E=await e.evaluate(()=>document.body.scrollHeight);for(let I=1;I<=6;I++)await e.evaluate(O=>window.scrollTo(0,O),E*I/6),await w(900);let R=await e.evaluate(()=>document.body.scrollHeight);if(R===u)break;u=R}await w(800);let f=null;try{let b=e.url();b&&/\/in\/[^/?#]/.test(b)&&(f=b.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let b=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),E=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),R=_=>{let j=(_||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(j)},I={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:[]},O=document.querySelector("main");if(!O)return I;let A=[...Array.from(O.querySelectorAll("h1")),...Array.from(O.querySelectorAll("h2"))],T=Array.from(O.querySelectorAll("h2")),Y=A.find(_=>{let j=_.textContent&&_.textContent.trim(),L=(j||"").replace(/\s*\(\d+\)$/,"").trim();return j&&j.length>1&&j.length<100&&!b.has(L)&&!E.has(L)}),K=Y?Y.textContent.trim():null,M=Y?Y.parentElement:null;for(;M&&M!==O&&!Array.from(M.children).filter(j=>j.tagName==="P").some(j=>{let L=j.textContent&&j.textContent.trim();return L&&L.length>5&&!R(L)});)M=M.parentElement;let $=null,W=null,N=null,q=null;if(M&&M!==O){let _=Array.from(M.children).filter(L=>L.tagName==="P").filter(L=>{let Se=L.textContent&&L.textContent.trim();return Se&&Se.length>5&&!R(Se)});if(_[0]&&($=_[0].textContent.trim()),_[1]){let L=_[1].textContent.trim().split(/\s*[·•]\s*/);W=L[0]||null,L.length>1&&(N=L.slice(1).join(" \xB7 "))}let j=Array.from(M.children).filter(L=>L.tagName==="DIV");for(let L=j.length-1;L>=0;L--){let Se=j[L].textContent&&j[L].textContent.trim();if(Se&&!(K&&Se.startsWith(K))&&(q=Se.split(/[·•]/)[0].trim(),q))break}}let G=null;if(M){let _=M.querySelectorAll("p, span, div");for(let j of _){let L=(j.textContent||"").trim().replace(/^[·•]\s*/,"");if(L==="1st"||L==="2nd"||L==="3rd"){G=L;break}}}let x=!!O.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),D=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=D&&D.src||null,B=O.textContent||"",J=null,fe=B.match(/(\d+\+?)\s+connections\b/i);fe&&(J=fe[1]+" connections");let we=null,en=B.match(/(\d+)\s+mutual connection/i),tn=B.match(/and\s+(\d+)\s+other mutual/i),ui=B.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);en?we=parseInt(en[1],10):tn?we=2+parseInt(tn[1],10):ui&&(we=2);let on=null,nn=null,rn=T.find(_=>_.textContent&&_.textContent.trim()==="About");if(rn){let _=rn.parentElement;for(;_&&_.tagName!=="SECTION";)_=_.parentElement;if(_){let j=(_.textContent||"").trim();j=j.replace(/^About\s*/,"").trim();let L=j.match(/Top skills\s*(.+?)$/i);if(L){let oo=L[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(mi=>mi.trim()).filter(Boolean);oo.length>0&&oo.length<10&&(nn=oo)}j=j.split(/\n?…\s*more/i)[0].trim(),j=j.split(/\n?\.\.\.\s*more/i)[0].trim(),j=j.split(/\bTop skills\b/i)[0].trim(),j=j.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),on=j||null}}let sn=null,ln=T.find(_=>_.textContent&&_.textContent.trim()==="Activity");if(ln){let _=ln.parentElement;for(;_&&_.tagName!=="SECTION";)_=_.parentElement;if(_){let j=(_.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);j&&(sn=parseInt(j[1].replace(/,/g,""),10))}}let di=[...new Set(T.map(_=>(_.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(_=>_&&_.length>1&&_.length<60&&_!==K).filter(_=>b.has(_)))],rt=document.body.textContent||"",fi=/#OpenToWork\b/i.test(rt)||/\bOpen to work\b/.test(rt),pi=/#Hiring\b/i.test(rt)||/\bI'?m hiring\b/i.test(rt)||/\bWe are hiring\b/i.test(rt);return{name:K,title:$,location:q,currentCompany:W,currentSchool:N,connectionDegree:G,hasVerifiedBadge:x,photoUrl:P,connectionsLevel:J,mutualConnectionsCount:we,followers:sn,openToWork:fi,hiring:pi,about:on,topSkills:nn,availableSections:di}});console.log(`Viewed: ${d.name} - ${d.title}`);let p=null,m=null,h=null,g=null,y=null,S=null;if(r||n||i||s||a||l){let b=await Promise.resolve().then(()=>(Ln(),Dn));r&&(p=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),n&&(m=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),i&&(h=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),s&&(g=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${g.length} entries`)),a&&(y=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),l&&(S=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...p!==null&&{experience:p},...m!==null&&{featured:m},...h!==null&&{education:h},...g!==null&&{skillsFull:g},...y!==null&&{recommendations:y},...S!==null&&{certifications:S}}}catch(c){console.error(`Error viewing profile ${t}:`,c.message);try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(c.message||""))throw c;return null}}async function tt(e,{detail:t=!1}={}){let o=()=>e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=f=>f&&!f.closest(n),s=f=>Array.from(document.querySelectorAll(f)).filter(i),a=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,c=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:a.length,pendingLabels:a.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!c};return a.length>0?{status:"pending",debug:u}:l&&!c?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),r=await o();return!r.debug.pendingCount&&!r.debug.hasMessageBtn&&!r.debug.hasConnectBtn&&(await w(1500),r=await o()),console.log(" DEBUG connection status:",JSON.stringify(r.debug)),t?r:r.status}async function Io(e){let t=null,o=await e.evaluate(()=>{let c=document.querySelector("h1")?.textContent?.trim();if(c&&!c.includes("notification"))return c;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(c=u.textContent?.trim(),c&&!c.includes("notification")))return c;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let c=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});c.count>0&&console.log(` S0: ${c.count} custom-invite links: ${JSON.stringify(c.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),p=f.toLowerCase().split(" ")[0],m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let g=h.getBoundingClientRect();if(g.width===0||g.height===0||h.closest(m))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(p))return h}return null},o);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(o){let c=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${c}"`);let u=await e.evaluate(d=>{let p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(g=>{let y=g.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&p.test(y)}).map(g=>g.getAttribute("aria-label")?.slice(0,50))},c);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let p=document.querySelectorAll("button[aria-label]"),m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',h=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of p){if(g.closest(m))continue;let y=g.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&h.test(y))return g}return null},c);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let c=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();c.includes("invite")&&!c.includes(u)&&(console.log(` Skipping primary button: wrong person (${c})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let n=o?o.split(" ")[0].toLowerCase():"",i=null;for(let c of r){let u=await e.evaluate((f,d)=>{let p=f.className.includes("muted"),m=f.className.includes("sticky-header")||f.className.includes("sticky"),h=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,g=(f.getAttribute("aria-label")||"").toLowerCase(),y=g.includes("invite"),S=d?g.includes(d):!0;return{isMuted:p,isStickyHeader:m,inRecommendations:h,hasInvite:y,matchesName:S,ariaLabel:g}},c,n);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=c;break}}for(let c of r)c!==i&&await c.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let s=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let c of a){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),p=d.width>0&&d.height>0,m=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:m,top:d.top}},c);if(u.isVisible&&!u.isInStickyHeader){s=c,console.log(" Found More button by ID pattern (main)");break}}for(let c of a)c!==s&&await c.dispose().catch(()=>{});if(!s&&a.length>0&&(s=a[a.length-1],console.log(" Found More button by ID pattern (last)")),s||(s=await e.$('button[aria-label="More actions"]'),s&&console.log(" Found More button by aria-label")),!s){let c=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(p=>{let m=p.innerText?.trim(),h=p.getAttribute("aria-label")||"",g=p.getBoundingClientRect();return g.top<100||g.top>600||g.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let p=0;p<8&&d;p++){for(let m of d.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==f)return m;d=d.parentElement}return null});s=c?.asElement?.()||null,s||await c?.dispose?.().catch(()=>{}),s&&console.log(" Found More button by text (near profile actions)")}if(s)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),s),await w(500),await e.evaluate(d=>d.click(),s),await w(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let p=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let m of p){let h=m.querySelector('a[href*="custom-invite"]');if(h)return h;for(let g of m.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let m of d)for(let h of m.querySelectorAll('[role="menuitem"], a, div')){let g=h.innerText?.trim();g&&g.length<40&&p.push(g)}return[...new Set(p)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(c){console.log(" More dropdown click failed:",c.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(c=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(c||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let p=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(p))continue;let m=d.getBoundingClientRect();if(!(m.width===0||m.height===0)){if(p.includes("invite")){if(f&&p.includes(f))return d;continue}if(p==="connect")return d}}return null},o||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function ws(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let o=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),n=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV",s=(o.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(s))return console.log(` \u2717 Guard: refusing a non-connect control ("${o.ariaLabel}")`),"wrong_target";if(s.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!s.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${o.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(n){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await w(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await w(3e3)):(await e.evaluate(u=>u.click(),t),await w(3e3));let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let l=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),c=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${c}`:` \u26A0 No modal after connect click \u2014 ${c}`),"success"}async function Ss(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await w(1500);let o=await Io(e);if(o){await e.evaluate(n=>n.click(),o),await w(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r)return await ot(e,r)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function ot(e,t){let o='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',r=()=>e.evaluate(s=>{let a=l=>!!(l&&l.querySelector(s));return!(a(document)||a(document.querySelector("#interop-outlet")?.shadowRoot))},o),n=()=>e.evaluate(()=>{for(let s of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(s.innerText||""))return!0;return!1}),i=async()=>{let s=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(s)return s;let a=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,o);return s=a?.asElement?.()||null,s||await a?.dispose?.().catch(()=>{}),s};for(let s=0;s<2;s++){try{await t.evaluate(a=>a.click())}catch{}if(await w(3e3),await n())return!1;if(await r())return!0;if(s===0){let a=await i();if(!a)return await r();t=a,await w(600)}}return await r()}async function ks(e,t,o={}){let{source:r="unknown",skipQuotaGate:n=!1,skipQuotaRecord:i=!1}=o;if(!n){let a=ut();if(!a.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${a.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:a.reason,profileInfo:null}}let s=await vs(e,t,o);return s.connectionSent&&!i&&Ot(t,r),s}async function vs(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,skipIfPending:i=!0,skipIfConnected:s=!0,excludeLocations:a=[]}=o,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
246
- --- Connecting: ${c} ---`),a.length>0){let y=Q()[t]?.location;if(sr(y,a))return console.log(` \u26A0 Excluded location (stored): ${y}`),l.reason="excluded_location",l.profileInfo={location:y},l}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(5e3),await oe(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await lr(e,t),await w(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(wo(),On)),{recordDiscoveredEdges:v}=await Promise.resolve().then(()=>(Vt(),Hn)),{detectCategoryFromTitle:b}=await or().then(()=>tr),{detectSectors:E}=await Promise.resolve().then(()=>(ir(),rr)),R=S(t)||t,I=await y(e,{seedUrl:R}),O=I.map(A=>{let T=A.headline?b(A.headline):null;return{url:A.url,seedUrl:R,block:A.block,rank:A.rank,name:A.name,headline:A.headline,categories:T?[T]:[],sectors:E(A.headline||"")}});v(O),I.length&&console.log(` \xB7 discovery: harvested ${I.length} related profiles`)}catch(y){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${y.message}`)}l.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),S=x=>{let D=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(D)},v={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},b=document.querySelector("main");if(!b)return v;let E=[...Array.from(b.querySelectorAll("h1")),...Array.from(b.querySelectorAll("h2"))],R=Array.from(b.querySelectorAll("h2")),I=E.find(x=>{let D=x.textContent&&x.textContent.trim();return D&&D.length>1&&D.length<100&&!y.has(D)&&D!=="0 notifications"}),O=I?I.textContent.trim():null,A=I?I.parentElement:null;for(;A&&A!==b&&!Array.from(A.children).filter(P=>P.tagName==="P").some(P=>{let B=P.textContent&&P.textContent.trim();return B&&B.length>5&&!S(B)});)A=A.parentElement;let T=null,Y=null,K=null;if(A&&A!==b){let x=Array.from(A.children),D=x.filter(B=>B.tagName==="P").filter(B=>{let J=B.textContent&&B.textContent.trim();return J&&J.length>5&&!S(J)});D[0]&&(T=D[0].textContent.trim()),D[1]&&(Y=D[1].textContent.trim());let P=x.filter(B=>B.tagName==="DIV");for(let B=P.length-1;B>=0;B--){let J=P[B].textContent&&P[B].textContent.trim();if(J&&!(O&&J.startsWith(O))&&(K=J.split(/[·•]/)[0].trim(),K))break}}let M=null;if(A){let x=A.querySelectorAll("p, span, div");for(let D of x){let P=(D.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){M=P;break}}}let $=null,W=R.find(x=>x.textContent&&x.textContent.trim()==="About");if(W){let x=W.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;x&&($=(x.textContent||"").trim().replace(/^About\s*/,"").trim()||null,$&&($=$.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let N=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),q=N&&N.src||null,G=!!b.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:O,title:T,location:K,about:$,company:Y,connectionDegree:M,connectionsCount:null,mutualConnections:null,photoUrl:q,hasVerifiedBadge:G}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(l.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(a.length>0){let y=l.profileInfo?.location,S=Q()[t]?.location,v=y||S;if(sr(v,a))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${v}`),l.reason="excluded_location",l;!y&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await tt(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await oe(e);let d=await Io(e);if(d||await oe(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),d=await Io(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!d){let y=await tt(e,{detail:!0});return s&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=d.method;let p=await ws(e,d.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let y=await tt(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await oe(e),await w(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(b=>b.scrollIntoView({behavior:"smooth",block:"center"}),S),await w(500),await S.click().catch(()=>e.evaluate(b=>b.click(),S)),await w(2e3);let v=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(v){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(R=>R.click(),v),await w(3e3);let b=e.url();if(b.includes("/premium/")||b.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),l.reason="premium_required",l;if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),l.reason="premium_required",l}catch(v){return console.log(" More dropdown failed:",v.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of y){let v=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!v)continue;let b=(v.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(b)||v.querySelector('input[type="email"], input[name="email"]'))return!0;let E=v.querySelector('button[aria-label="Send without a note"]');if(E&&(E.disabled||E.getAttribute("aria-disabled")==="true"||(E.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let y=await e.$('button[aria-label="Dismiss"]');if(y)try{await y.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await w(500),l.reason="email_required",l}let h=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!h&&!g){let y=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let v=S.querySelector('button[aria-label="Add a note"]'),b=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!v,sendWithout:!!b}});if(y.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=S?.asElement?.()||null,h||await S.dispose().catch(()=>{})}if(y.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=S?.asElement?.()||null,g||await S.dispose().catch(()=>{})}}if(n)if(h&&r){if(console.log(" Adding personalized note..."),await h.click(),await w(1500),await e.$("div.modal-upsell")){let v=await Ss(e);return l.success=v,l.connectionSent=v,l.reason=v?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let v=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),b=r.replace("{name}",v);await S.type(b,{delay:20}),await w(500);let E=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(E)return await ot(e,E)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=b,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(g)return console.log(" Sending without note..."),await ot(e,g)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(h&&!r){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await ot(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let y=g;if(y)return await ot(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3)),await oe(e),await w(500);let S=await e.$$('button[id*="profile-overflow-action"]'),v=null;for(let b of S){let E=await e.evaluate(R=>{let I=R.getBoundingClientRect();return{visible:I.width>0&&I.height>0,inSticky:!!R.closest('.sticky-header, [class*="sticky"]')}},b);if(E.visible&&!E.inSticky){v=b;break}}!v&&S.length>0&&(v=S[S.length-1]);for(let b of S)b!==v&&await b.dispose().catch(()=>{});if(v)try{await e.evaluate(E=>E.scrollIntoView({behavior:"smooth",block:"center"}),v),await w(500),await v.click().catch(()=>e.evaluate(E=>E.click(),v)),await w(2e3);let b=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(b){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(O=>O.click(),b),await w(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 w(3e3),await tt(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let I=await e.$('button[aria-label="Send without a note"]');if(I)return console.log(" Modal appeared via More dropdown, sending without note..."),await ot(e,I)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(b){console.log(" More dropdown fallback failed:",b.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(c){console.error(` \u2717 Error: ${c.message}`),l.reason="error",l.error=c.message;let u=c.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{l.fatal=!0}return l}}async function jo(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:i=20,viewOnly:s=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:l=null,excludeLocations:c=[],source:u="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
245
+ `),process.exit(1));var Ie=yi({token:cn});var Be=12e4;async function Je(e,{retries:t=2}={}){let o=process.env.NODE_EASY_APPLY_MAIN;if(!o||o.startsWith("YOUR_"))throw new Error('NODE_EASY_APPLY_MAIN is not configured in .env. Create a node in iLiveMyLife, add "assist" tag, and set the node ID in .env. See README.md for setup instructions.');for(let r=1;r<=t;r++)try{let n=await Ie.askLifebot(o,e,{timeout:Be});return Be=Math.max(12e4,Be*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){Be=Math.min(Be*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(Be/1e3)}s...`);continue}throw n}}async function no(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let o=`Job application form field "${e}" \u2014 reply with ONLY the value to fill in, nothing else. `;return t&&(t==="Enter a decimal number larger than 0.0"&&(t="Enter a decimal number larger than 0"),o+=`Additional info: ${t}`),await Je(o)}async function Et(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Je(o)}async function it(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Je(o)}so();import{LIFEBOT_MESSAGE_TYPES as Qr}from"@ilivemylife/graph-sdk";Ue();await Qe();async function lr(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function sr(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function bs(e,t,o={}){let{extractExperience:r=!1,extractFeatured:n=!1,extractEducation:i=!1,extractSkills:s=!1,extractRecommendations:a=!1,extractCertifications:l=!1}=o;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await oe(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await lr(e,t));let u=0;for(let b=0;b<2;b++){let E=await e.evaluate(()=>document.body.scrollHeight);for(let I=1;I<=6;I++)await e.evaluate(O=>window.scrollTo(0,O),E*I/6),await w(900);let R=await e.evaluate(()=>document.body.scrollHeight);if(R===u)break;u=R}await w(800);let f=null;try{let b=e.url();b&&/\/in\/[^/?#]/.test(b)&&(f=b.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let b=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),E=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),R=_=>{let D=(_||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(D)},I={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:[]},O=document.querySelector("main");if(!O)return I;let A=[...Array.from(O.querySelectorAll("h1")),...Array.from(O.querySelectorAll("h2"))],T=Array.from(O.querySelectorAll("h2")),Y=A.find(_=>{let D=_.textContent&&_.textContent.trim(),L=(D||"").replace(/\s*\(\d+\)$/,"").trim();return D&&D.length>1&&D.length<100&&!b.has(L)&&!E.has(L)}),K=Y?Y.textContent.trim():null,M=Y?Y.parentElement:null;for(;M&&M!==O&&!Array.from(M.children).filter(D=>D.tagName==="P").some(D=>{let L=D.textContent&&D.textContent.trim();return L&&L.length>5&&!R(L)});)M=M.parentElement;let $=null,W=null,N=null,q=null;if(M&&M!==O){let _=Array.from(M.children).filter(L=>L.tagName==="P").filter(L=>{let Se=L.textContent&&L.textContent.trim();return Se&&Se.length>5&&!R(Se)});if(_[0]&&($=_[0].textContent.trim()),_[1]){let L=_[1].textContent.trim().split(/\s*[·•]\s*/);W=L[0]||null,L.length>1&&(N=L.slice(1).join(" \xB7 "))}let D=Array.from(M.children).filter(L=>L.tagName==="DIV");for(let L=D.length-1;L>=0;L--){let Se=D[L].textContent&&D[L].textContent.trim();if(Se&&!(K&&Se.startsWith(K))&&(q=Se.split(/[·•]/)[0].trim(),q))break}}let G=null;if(M){let _=M.querySelectorAll("p, span, div");for(let D of _){let L=(D.textContent||"").trim().replace(/^[·•]\s*/,"");if(L==="1st"||L==="2nd"||L==="3rd"){G=L;break}}}let x=!!O.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),j=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=j&&j.src||null,B=O.textContent||"",J=null,fe=B.match(/(\d+\+?)\s+connections\b/i);fe&&(J=fe[1]+" connections");let we=null,en=B.match(/(\d+)\s+mutual connection/i),tn=B.match(/and\s+(\d+)\s+other mutual/i),ui=B.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);en?we=parseInt(en[1],10):tn?we=2+parseInt(tn[1],10):ui&&(we=2);let on=null,nn=null,rn=T.find(_=>_.textContent&&_.textContent.trim()==="About");if(rn){let _=rn.parentElement;for(;_&&_.tagName!=="SECTION";)_=_.parentElement;if(_){let D=(_.textContent||"").trim();D=D.replace(/^About\s*/,"").trim();let L=D.match(/Top skills\s*(.+?)$/i);if(L){let oo=L[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(mi=>mi.trim()).filter(Boolean);oo.length>0&&oo.length<10&&(nn=oo)}D=D.split(/\n?…\s*more/i)[0].trim(),D=D.split(/\n?\.\.\.\s*more/i)[0].trim(),D=D.split(/\bTop skills\b/i)[0].trim(),D=D.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),on=D||null}}let sn=null,ln=T.find(_=>_.textContent&&_.textContent.trim()==="Activity");if(ln){let _=ln.parentElement;for(;_&&_.tagName!=="SECTION";)_=_.parentElement;if(_){let D=(_.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);D&&(sn=parseInt(D[1].replace(/,/g,""),10))}}let di=[...new Set(T.map(_=>(_.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(_=>_&&_.length>1&&_.length<60&&_!==K).filter(_=>b.has(_)))],rt=document.body.textContent||"",fi=/#OpenToWork\b/i.test(rt)||/\bOpen to work\b/.test(rt),pi=/#Hiring\b/i.test(rt)||/\bI'?m hiring\b/i.test(rt)||/\bWe are hiring\b/i.test(rt);return{name:K,title:$,location:q,currentCompany:W,currentSchool:N,connectionDegree:G,hasVerifiedBadge:x,photoUrl:P,connectionsLevel:J,mutualConnectionsCount:we,followers:sn,openToWork:fi,hiring:pi,about:on,topSkills:nn,availableSections:di}});console.log(`Viewed: ${d.name} - ${d.title}`);let p=null,m=null,h=null,g=null,y=null,S=null;if(r||n||i||s||a||l){let b=await Promise.resolve().then(()=>(Ln(),jn));r&&(p=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),n&&(m=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),i&&(h=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),s&&(g=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${g.length} entries`)),a&&(y=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),l&&(S=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...p!==null&&{experience:p},...m!==null&&{featured:m},...h!==null&&{education:h},...g!==null&&{skillsFull:g},...y!==null&&{recommendations:y},...S!==null&&{certifications:S}}}catch(c){console.error(`Error viewing profile ${t}:`,c.message);try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(c.message||""))throw c;return null}}async function tt(e,{detail:t=!1}={}){let o=()=>e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=f=>f&&!f.closest(n),s=f=>Array.from(document.querySelectorAll(f)).filter(i),a=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,c=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:a.length,pendingLabels:a.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!c};return a.length>0?{status:"pending",debug:u}:l&&!c?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),r=await o();return!r.debug.pendingCount&&!r.debug.hasMessageBtn&&!r.debug.hasConnectBtn&&(await w(1500),r=await o()),console.log(" DEBUG connection status:",JSON.stringify(r.debug)),t?r:r.status}async function Io(e){let t=null,o=await e.evaluate(()=>{let c=document.querySelector("h1")?.textContent?.trim();if(c&&!c.includes("notification"))return c;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(c=u.textContent?.trim(),c&&!c.includes("notification")))return c;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let c=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});c.count>0&&console.log(` S0: ${c.count} custom-invite links: ${JSON.stringify(c.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),p=f.toLowerCase().split(" ")[0],m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let g=h.getBoundingClientRect();if(g.width===0||g.height===0||h.closest(m))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(p))return h}return null},o);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(o){let c=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${c}"`);let u=await e.evaluate(d=>{let p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(g=>{let y=g.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&p.test(y)}).map(g=>g.getAttribute("aria-label")?.slice(0,50))},c);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let p=document.querySelectorAll("button[aria-label]"),m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',h=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of p){if(g.closest(m))continue;let y=g.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&h.test(y))return g}return null},c);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let c=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();c.includes("invite")&&!c.includes(u)&&(console.log(` Skipping primary button: wrong person (${c})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let n=o?o.split(" ")[0].toLowerCase():"",i=null;for(let c of r){let u=await e.evaluate((f,d)=>{let p=f.className.includes("muted"),m=f.className.includes("sticky-header")||f.className.includes("sticky"),h=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,g=(f.getAttribute("aria-label")||"").toLowerCase(),y=g.includes("invite"),S=d?g.includes(d):!0;return{isMuted:p,isStickyHeader:m,inRecommendations:h,hasInvite:y,matchesName:S,ariaLabel:g}},c,n);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=c;break}}for(let c of r)c!==i&&await c.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let s=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let c of a){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),p=d.width>0&&d.height>0,m=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:m,top:d.top}},c);if(u.isVisible&&!u.isInStickyHeader){s=c,console.log(" Found More button by ID pattern (main)");break}}for(let c of a)c!==s&&await c.dispose().catch(()=>{});if(!s&&a.length>0&&(s=a[a.length-1],console.log(" Found More button by ID pattern (last)")),s||(s=await e.$('button[aria-label="More actions"]'),s&&console.log(" Found More button by aria-label")),!s){let c=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(p=>{let m=p.innerText?.trim(),h=p.getAttribute("aria-label")||"",g=p.getBoundingClientRect();return g.top<100||g.top>600||g.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let p=0;p<8&&d;p++){for(let m of d.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==f)return m;d=d.parentElement}return null});s=c?.asElement?.()||null,s||await c?.dispose?.().catch(()=>{}),s&&console.log(" Found More button by text (near profile actions)")}if(s)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),s),await w(500),await e.evaluate(d=>d.click(),s),await w(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let p=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let m of p){let h=m.querySelector('a[href*="custom-invite"]');if(h)return h;for(let g of m.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let m of d)for(let h of m.querySelectorAll('[role="menuitem"], a, div')){let g=h.innerText?.trim();g&&g.length<40&&p.push(g)}return[...new Set(p)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(c){console.log(" More dropdown click failed:",c.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(c=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(c||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let p=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(p))continue;let m=d.getBoundingClientRect();if(!(m.width===0||m.height===0)){if(p.includes("invite")){if(f&&p.includes(f))return d;continue}if(p==="connect")return d}}return null},o||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function ws(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let o=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),n=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV",s=(o.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(s))return console.log(` \u2717 Guard: refusing a non-connect control ("${o.ariaLabel}")`),"wrong_target";if(s.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!s.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${o.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(n){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await w(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await w(3e3)):(await e.evaluate(u=>u.click(),t),await w(3e3));let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let l=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),c=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${c}`:` \u26A0 No modal after connect click \u2014 ${c}`),"success"}async function Ss(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await w(1500);let o=await Io(e);if(o){await e.evaluate(n=>n.click(),o),await w(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r)return await ot(e,r)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function ot(e,t){let o='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',r=()=>e.evaluate(s=>{let a=l=>!!(l&&l.querySelector(s));return!(a(document)||a(document.querySelector("#interop-outlet")?.shadowRoot))},o),n=()=>e.evaluate(()=>{for(let s of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(s.innerText||""))return!0;return!1}),i=async()=>{let s=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(s)return s;let a=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,o);return s=a?.asElement?.()||null,s||await a?.dispose?.().catch(()=>{}),s};for(let s=0;s<2;s++){try{await t.evaluate(a=>a.click())}catch{}if(await w(3e3),await n())return!1;if(await r())return!0;if(s===0){let a=await i();if(!a)return await r();t=a,await w(600)}}return await r()}async function ks(e,t,o={}){let{source:r="unknown",skipQuotaGate:n=!1,skipQuotaRecord:i=!1}=o;if(!n){let a=ut();if(!a.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${a.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:a.reason,profileInfo:null}}let s=await vs(e,t,o);return s.connectionSent&&!i&&Ot(t,r),s}async function vs(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,skipIfPending:i=!0,skipIfConnected:s=!0,excludeLocations:a=[]}=o,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
246
+ --- Connecting: ${c} ---`),a.length>0){let y=Q()[t]?.location;if(sr(y,a))return console.log(` \u26A0 Excluded location (stored): ${y}`),l.reason="excluded_location",l.profileInfo={location:y},l}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(5e3),await oe(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await lr(e,t),await w(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(wo(),On)),{recordDiscoveredEdges:v}=await Promise.resolve().then(()=>(Vt(),Hn)),{detectCategoryFromTitle:b}=await or().then(()=>tr),{detectSectors:E}=await Promise.resolve().then(()=>(ir(),rr)),R=S(t)||t,I=await y(e,{seedUrl:R}),O=I.map(A=>{let T=A.headline?b(A.headline):null;return{url:A.url,seedUrl:R,block:A.block,rank:A.rank,name:A.name,headline:A.headline,categories:T?[T]:[],sectors:E(A.headline||"")}});v(O),I.length&&console.log(` \xB7 discovery: harvested ${I.length} related profiles`)}catch(y){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${y.message}`)}l.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),S=x=>{let j=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(j)},v={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},b=document.querySelector("main");if(!b)return v;let E=[...Array.from(b.querySelectorAll("h1")),...Array.from(b.querySelectorAll("h2"))],R=Array.from(b.querySelectorAll("h2")),I=E.find(x=>{let j=x.textContent&&x.textContent.trim();return j&&j.length>1&&j.length<100&&!y.has(j)&&j!=="0 notifications"}),O=I?I.textContent.trim():null,A=I?I.parentElement:null;for(;A&&A!==b&&!Array.from(A.children).filter(P=>P.tagName==="P").some(P=>{let B=P.textContent&&P.textContent.trim();return B&&B.length>5&&!S(B)});)A=A.parentElement;let T=null,Y=null,K=null;if(A&&A!==b){let x=Array.from(A.children),j=x.filter(B=>B.tagName==="P").filter(B=>{let J=B.textContent&&B.textContent.trim();return J&&J.length>5&&!S(J)});j[0]&&(T=j[0].textContent.trim()),j[1]&&(Y=j[1].textContent.trim());let P=x.filter(B=>B.tagName==="DIV");for(let B=P.length-1;B>=0;B--){let J=P[B].textContent&&P[B].textContent.trim();if(J&&!(O&&J.startsWith(O))&&(K=J.split(/[·•]/)[0].trim(),K))break}}let M=null;if(A){let x=A.querySelectorAll("p, span, div");for(let j of x){let P=(j.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){M=P;break}}}let $=null,W=R.find(x=>x.textContent&&x.textContent.trim()==="About");if(W){let x=W.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;x&&($=(x.textContent||"").trim().replace(/^About\s*/,"").trim()||null,$&&($=$.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let N=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),q=N&&N.src||null,G=!!b.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:O,title:T,location:K,about:$,company:Y,connectionDegree:M,connectionsCount:null,mutualConnections:null,photoUrl:q,hasVerifiedBadge:G}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(l.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(a.length>0){let y=l.profileInfo?.location,S=Q()[t]?.location,v=y||S;if(sr(v,a))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${v}`),l.reason="excluded_location",l;!y&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await tt(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await oe(e);let d=await Io(e);if(d||await oe(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),d=await Io(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!d){let y=await tt(e,{detail:!0});return s&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=d.method;let p=await ws(e,d.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let y=await tt(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await oe(e),await w(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(b=>b.scrollIntoView({behavior:"smooth",block:"center"}),S),await w(500),await S.click().catch(()=>e.evaluate(b=>b.click(),S)),await w(2e3);let v=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(v){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(R=>R.click(),v),await w(3e3);let b=e.url();if(b.includes("/premium/")||b.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),l.reason="premium_required",l;if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),l.reason="premium_required",l}catch(v){return console.log(" More dropdown failed:",v.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of y){let v=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!v)continue;let b=(v.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(b)||v.querySelector('input[type="email"], input[name="email"]'))return!0;let E=v.querySelector('button[aria-label="Send without a note"]');if(E&&(E.disabled||E.getAttribute("aria-disabled")==="true"||(E.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let y=await e.$('button[aria-label="Dismiss"]');if(y)try{await y.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await w(500),l.reason="email_required",l}let h=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!h&&!g){let y=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let v=S.querySelector('button[aria-label="Add a note"]'),b=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!v,sendWithout:!!b}});if(y.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=S?.asElement?.()||null,h||await S.dispose().catch(()=>{})}if(y.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=S?.asElement?.()||null,g||await S.dispose().catch(()=>{})}}if(n)if(h&&r){if(console.log(" Adding personalized note..."),await h.click(),await w(1500),await e.$("div.modal-upsell")){let v=await Ss(e);return l.success=v,l.connectionSent=v,l.reason=v?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let v=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),b=r.replace("{name}",v);await S.type(b,{delay:20}),await w(500);let E=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(E)return await ot(e,E)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=b,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(g)return console.log(" Sending without note..."),await ot(e,g)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(h&&!r){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await ot(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let y=g;if(y)return await ot(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3)),await oe(e),await w(500);let S=await e.$$('button[id*="profile-overflow-action"]'),v=null;for(let b of S){let E=await e.evaluate(R=>{let I=R.getBoundingClientRect();return{visible:I.width>0&&I.height>0,inSticky:!!R.closest('.sticky-header, [class*="sticky"]')}},b);if(E.visible&&!E.inSticky){v=b;break}}!v&&S.length>0&&(v=S[S.length-1]);for(let b of S)b!==v&&await b.dispose().catch(()=>{});if(v)try{await e.evaluate(E=>E.scrollIntoView({behavior:"smooth",block:"center"}),v),await w(500),await v.click().catch(()=>e.evaluate(E=>E.click(),v)),await w(2e3);let b=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(b){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(O=>O.click(),b),await w(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 w(3e3),await tt(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let I=await e.$('button[aria-label="Send without a note"]');if(I)return console.log(" Modal appeared via More dropdown, sending without note..."),await ot(e,I)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(b){console.log(" More dropdown fallback failed:",b.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(c){console.error(` \u2717 Error: ${c.message}`),l.reason="error",l.error=c.message;let u=c.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{l.fatal=!0}return l}}async function Do(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:i=20,viewOnly:s=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:l=null,excludeLocations:c=[],source:u="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
247
247
  === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${s?"View Only":`Connect (max ${i})`}`),s||console.log(`Custom messages: ${n?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!s){let p=dt();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let d=0;for(let p=0;p<t.length;p++){let m=t[p];try{if(e.isClosed()){console.log(`
248
248
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
249
249
  \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let h=Lt(m.profileUrl);if(h==="pending"||h==="connected"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${m.name||m.profileUrl} \u2014 skipped (db: ${h})`),h==="pending"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,l&&await l(m,f,{success:!1,reason:h,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${m.name||m.profileUrl}`);let g=null;if(s){let y=await bs(e,m.profileUrl);y?(Ce(m.profileUrl,{...y,source:u}),f.viewed++,g={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(f.errors++,g={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let y=ut();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(g=await ks(e,m.profileUrl,{message:r,useCustomMessage:n,excludeLocations:c,source:u,skipQuotaGate:!0}),g.success)f.connectionsSent++;else switch(g.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(g?.fatal){console.log(`
250
250
  \u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(g?.reason==="error"){if(d++,d>=3){console.log(`
251
251
  \u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(g&&g.reason&&(Nt(m.profileUrl,g.reason,{method:g.method,messageSent:g.messageSent,profileInfo:g.profileInfo}),g.resolvedUrl&&Pt(m.profileUrl,g.resolvedUrl),Ke(m.profileUrl,{source:u||"funnel",jobId:m.jobId||m.fromJob?.jobId||null,jobTitle:m.fromJob?.title||null,jobCompany:m.fromJob?.company||null,action:g.reason})),l&&await l(m,f,g),p<t.length-1){let y=a+Math.random()*2e3;await w(y)}}if(console.log(`
252
- === Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!s){let p=dt();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return f}await Qe();Ue();async function ar(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let n=null,i=null;for(let f of r)if(n=document.querySelector(f),n){i=f;break}if(!n){let f=document.querySelector("li.scaffold-layout__list-item");if(f){let d=f.parentElement;for(;d&&d!==document.body;){if(d.scrollHeight>d.clientHeight){n=d,i="parent of li.scaffold-layout__list-item";break}d=d.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let s=n.scrollTop,a=300,l=300,c=50,u=0;for(;u<c&&(n.scrollBy(0,a),await new Promise(f=>setTimeout(f,l)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)u++;return{found:!0,usedSelector:i,initialScroll:s,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:u}},t)}async function cr(e,{easyApplyOnly:t=!0}={}){let o=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(n=>{let s=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=n.querySelector("a.job-card-container__link");if(a){let l=a.getAttribute("href").split("?")[0],c=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),u=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),f=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),d=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:l,isEasyApply:s,applyType:s?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${l}`,jobTitle:c,companyName:u,location:f,salary:d||null,jobLink:s?a.href:null}}return{isEasyApply:!1}})});return t?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function ur(e){let t=await e.evaluate(()=>{let o=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(o&&!o.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return o.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",t.success?t.pageState:t.reason),t.success&&await w(2e3),t.success}async function Do(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: ilml linkedin 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 w(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 dr(e,t,o,r){for(let n of t){await Do(e,r)&&(await oe(e),await w(2e3));let s=await e.$(`a[data-control-id="${n.dataId}"]`),a="dataId";if(!s){let l=n.id?.match(/\d+/)?.[0];l&&(s=await e.$(`a[href*="/jobs/view/${l}/"]`),s&&(a="href"))}if(s){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${n.jobTitle}`);let l=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await e.evaluate(d=>d.scrollIntoView({block:"center"}),s),await w(300),await s.click(),await w(1500);let c=!1;for(let d=0;d<8;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){c=!0;break}await w(500)}if(!c){await e.evaluate(d=>d.click(),s),await w(1500);for(let d=0;d<6;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){c=!0;break}await w(500)}c||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let u=await e.evaluate(()=>{let d=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of d)for(let m of p.querySelectorAll("button")){let h=m.innerText?.trim();if(h==="Continue applying"||h==="Got it"||h==="Dismiss")return m.click(),h}return null});u&&console.log(` Dismissed popup before processing (${u})`);let{keepGoing:f}=await o(e,n);if(!f)return{keepGoing:!1}}else{let l=n.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${n.jobTitle||n.id} (dataId=${n.dataId}, jobId=${l})`)}}return{keepGoing:!0}}async function fr(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=t.querySelector(".hirer-card__hirer-information");if(o){let s=o.querySelector('a[href*="/in/"]'),a=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(s)return{name:a?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let s=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(s)return{name:r.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"poster_name"}}let n=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(n){let s=n.querySelector('a[href*="/in/"]');if(s)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"people_section"}}let i=t.querySelectorAll('a[href*="/in/"]');for(let s of i){let a=s.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:s.href?.split("?")[0],source:"details_link"}}return null})}async function pr(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},i=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let J of i){let fe=J.querySelector(".job-criteria__subheader")?.textContent?.trim(),we=J.querySelector(".job-criteria__text")?.textContent?.trim();fe&&we&&(n[fe.toLowerCase()]=we)}let s=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],a=[];for(let J of s)new RegExp("\\b"+J.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(J.replace(/\\\+/g,"+"));let c=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,f=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,d=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=d?.innerText?.trim()||null,h=(d?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",v=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,b=y.match(/(\d[\d,]*)\s+applicant/i),E=b?parseInt(b[1].replace(/,/g,"")):null,R=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),I=Array.from(R).map(J=>J.innerText?.trim()?.replace(/\s+/g," ")),A=I.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,T=I.join(" ")+" "+y,Y=/\bremote\b/i.test(T)?"remote":/\bhybrid\b/i.test(T)?"hybrid":/\bon-?site\b/i.test(T)?"onsite":null,K=/\bcontract\b/i.test(T)?"contract":/\bfull-?time\b/i.test(T)?"full-time":/\bpart-?time\b/i.test(T)?"part-time":/\bfreelance\b/i.test(T)?"freelance":/\btemporary\b/i.test(T)?"temporary":null,$=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",N=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",q=($+" "+r+" "+N).toLowerCase(),G=$.toLowerCase(),x=[];/\bremote\b/.test(q)&&x.push("remote"),/\bhybrid\b/.test(q)&&x.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(q)&&x.push("onsite"),(x.length===0||!x.includes("remote")&&!x.includes("hybrid")&&!x.includes("onsite"))&&/remote/i.test(N)&&x.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(G)&&x.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(G)&&x.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(G)&&!x.includes("managerial")&&x.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(G)?x.push("junior"):/\b(senior|sr\.?)\b/i.test(G)?x.push("senior"):/\b(staff|principal|distinguished)\b/i.test(G)?x.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(G)?x.push("executive"):/\b(lead|team lead)\b/i.test(G)&&x.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(q)&&x.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(q)&&x.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(q)&&x.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(q)&&x.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(q)&&x.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(q)&&x.push("mobile"),/\b(architect)\b/i.test(G)&&x.push("architect"),/\b(consultant|consulting)\b/i.test(G)&&x.push("consultant");let D=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(D)||/\bcontract\b/i.test(q))&&x.push("contract"),/full.?time|permanent/i.test(D)&&x.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(N)&&x.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(N)&&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:f,companyName:p,companyUrl:h?h.startsWith("/")?"https://www.linkedin.com"+h:h:null,aboutCompany:c,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:v,applicantCount:E,companySize:A,workplaceType:Y,contractType:K,techStack:[...new Set(a)],jobTags:[...new Set(x)]}})}Vt();import"dotenv/config";import*as C from"fs";import*as Uo from"os";import*as F from"path";import{fileURLToPath as Gs}from"url";var Po={};te(Po,{NAME:()=>Cs,VERSION:()=>xs,up:()=>$s});import*as ie from"fs";import*as Wt from"path";var xs=1,Cs="normalize-jobs-and-questions",Es=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],As=50;function Lo(e){return ie.existsSync(e)?JSON.parse(ie.readFileSync(e,"utf-8")):null}function No(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 i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function $s(e,t){let o=Wt.join(e,"jobs.json"),r=Wt.join(t,"scouted-jobs.json"),n=Wt.join(e,"application-questions.json"),i=Lo(o)||{},s=Lo(r)||{},a=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let f=s[u],d=i[u];for(let p of Es)f[p]!=null&&d[p]==null&&(d[p]=f[p]);l.push(u),a++}a>0?(No(o,i),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let c=Lo(n);if(c&&Array.isArray(c.applications)){let u={},f=0;for(let d of c.applications){let p=d.jobId||"unknown";u[p]||(u[p]={applications:[]});let m=(d.questions||[]).map(h=>{let g={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=As?g.options=h.options:(g.optionsOmitted=!0,f++)),h.page&&(g.page=h.page),h.wasPreFilled&&(g.wasPreFilled=!0),h.wasRetry&&(g.wasRetry=!0),g});u[p].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||m.length,questions:m})}No(n,u),console.log(` Phase 2: Rekeyed ${c.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else c&&!c.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let u of l)delete s[u];No(r,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Fo={};te(Fo,{NAME:()=>Ts,VERSION:()=>_s,up:()=>js});import*as se from"fs";import*as mr from"path";var _s=2,Ts="reset-unread-flags";function Rs(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function Is(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{se.writeFileSync(r,o)}catch(n){try{se.unlinkSync(r)}catch{}throw n}try{se.renameSync(r,e)}catch(n){try{se.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function js(e){let t=mr.join(e,"conversations.json"),o=Rs(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}Is(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Oo={};te(Oo,{NAME:()=>Ls,VERSION:()=>Ds,up:()=>qs});import*as le from"fs";import*as hr from"path";var Ds=3,Ls="recompute-last-message-by",Ns=new Set(["draft","confirmed","rejected","needs_review"]);function Ps(e){return le.existsSync(e)?JSON.parse(le.readFileSync(e,"utf-8")):null}function Fs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{le.writeFileSync(r,o)}catch(n){try{le.unlinkSync(r)}catch{}throw n}try{le.renameSync(r,e)}catch(n){try{le.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}function Os(e,t){if(!e||e.length===0)return"them";let o=e.filter(i=>!Ns.has(i.status));if(o.length===0)return"them";let r=o.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),n=r.length>0?r:[...o].reverse();for(let i of n){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function qs(e){let t=hr.join(e,"conversations.json"),o=Ps(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let r=process.env.LINKEDIN_NAME;if(!r||typeof r!="string"||!r.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let n=0,i=0,s=0;for(let a of Object.keys(o)){let l=o[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let c=Array.isArray(l.messages)?l.messages:[],u=Os(c,r),f=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=f,n++}if(n===0){console.log(" No conversations to recompute.");return}Fs(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var qo={};te(qo,{NAME:()=>Us,VERSION:()=>Ms,up:()=>Vs});import*as ae from"fs";import*as yr from"path";var Ms=4,Us="split-connection-timestamps",Bs=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Js(e){if(!ae.existsSync(e))return null;let t=ae.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Hs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ae.writeFileSync(r,o)}catch(n){try{ae.unlinkSync(r)}catch{}throw n}try{ae.renameSync(r,e)}catch(n){try{ae.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function Vs(e){let t=yr.join(e,"people.json"),o=Js(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let r=0,n=0;for(let i of Object.keys(o)){let s=o[i];!s||typeof s!="object"||(n++,Bs.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,r++))}if(r===0){console.log(` Scanned ${n} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Hs(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${r} still-pending people (of ${n} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Qe();Vt();var Ws=Gs(import.meta.url),Ys=F.dirname(Ws),Ks=F.dirname(F.dirname(Ys));function zs(e){return e&&(e==="~"?Uo.homedir():e.startsWith("~/")||e.startsWith("~\\")?F.join(Uo.homedir(),e.slice(2)):e)}var ue=process.env.DATA_DIR?F.resolve(zs(process.env.DATA_DIR)):Ks,qe=F.join(ue,"collected-profiles"),Me=F.join(ue,"market-research"),X=F.join(ue,".schema-version"),gr=[F.join(qe,".schema-version"),F.join(Me,".schema-version")],_e=4,be=[{version:1,module:Po},{version:2,module:Fo},{version:3,module:Oo},{version:4,module:qo}];(function(){be.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of be){if(!Number.isInteger(r.version)||r.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(r.version)} (must be positive integer)`);if(t.has(r.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${r.version}`);t.add(r.version);let n=r.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${r.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==r.version)throw new Error(`MIGRATION_REGISTRY: v${r.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=be.length?be[be.length-1].version:0;if(o!==_e)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${_e}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<be.length;r++){let n=r+1;if(be[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${be[r].version}`)}})();function kr(){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: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!s){let p=dt();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return f}await Qe();Ue();async function ar(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let n=null,i=null;for(let f of r)if(n=document.querySelector(f),n){i=f;break}if(!n){let f=document.querySelector("li.scaffold-layout__list-item");if(f){let d=f.parentElement;for(;d&&d!==document.body;){if(d.scrollHeight>d.clientHeight){n=d,i="parent of li.scaffold-layout__list-item";break}d=d.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let s=n.scrollTop,a=300,l=300,c=50,u=0;for(;u<c&&(n.scrollBy(0,a),await new Promise(f=>setTimeout(f,l)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)u++;return{found:!0,usedSelector:i,initialScroll:s,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:u}},t)}async function cr(e,{easyApplyOnly:t=!0}={}){let o=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(n=>{let s=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=n.querySelector("a.job-card-container__link");if(a){let l=a.getAttribute("href").split("?")[0],c=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),u=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),f=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),d=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:l,isEasyApply:s,applyType:s?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${l}`,jobTitle:c,companyName:u,location:f,salary:d||null,jobLink:s?a.href:null}}return{isEasyApply:!1}})});return t?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function ur(e){let t=await e.evaluate(()=>{let o=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(o&&!o.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return o.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",t.success?t.pageState:t.reason),t.success&&await w(2e3),t.success}async function jo(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: ilml linkedin 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 w(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 dr(e,t,o,r){for(let n of t){await jo(e,r)&&(await oe(e),await w(2e3));let s=await e.$(`a[data-control-id="${n.dataId}"]`),a="dataId";if(!s){let l=n.id?.match(/\d+/)?.[0];l&&(s=await e.$(`a[href*="/jobs/view/${l}/"]`),s&&(a="href"))}if(s){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${n.jobTitle}`);let l=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await e.evaluate(d=>d.scrollIntoView({block:"center"}),s),await w(300),await s.click(),await w(1500);let c=!1;for(let d=0;d<8;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){c=!0;break}await w(500)}if(!c){await e.evaluate(d=>d.click(),s),await w(1500);for(let d=0;d<6;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){c=!0;break}await w(500)}c||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let u=await e.evaluate(()=>{let d=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of d)for(let m of p.querySelectorAll("button")){let h=m.innerText?.trim();if(h==="Continue applying"||h==="Got it"||h==="Dismiss")return m.click(),h}return null});u&&console.log(` Dismissed popup before processing (${u})`);let{keepGoing:f}=await o(e,n);if(!f)return{keepGoing:!1}}else{let l=n.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${n.jobTitle||n.id} (dataId=${n.dataId}, jobId=${l})`)}}return{keepGoing:!0}}async function fr(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=t.querySelector(".hirer-card__hirer-information");if(o){let s=o.querySelector('a[href*="/in/"]'),a=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(s)return{name:a?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let s=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(s)return{name:r.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"poster_name"}}let n=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(n){let s=n.querySelector('a[href*="/in/"]');if(s)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"people_section"}}let i=t.querySelectorAll('a[href*="/in/"]');for(let s of i){let a=s.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:s.href?.split("?")[0],source:"details_link"}}return null})}async function pr(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},i=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let J of i){let fe=J.querySelector(".job-criteria__subheader")?.textContent?.trim(),we=J.querySelector(".job-criteria__text")?.textContent?.trim();fe&&we&&(n[fe.toLowerCase()]=we)}let s=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],a=[];for(let J of s)new RegExp("\\b"+J.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(J.replace(/\\\+/g,"+"));let c=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,f=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,d=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=d?.innerText?.trim()||null,h=(d?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",v=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,b=y.match(/(\d[\d,]*)\s+applicant/i),E=b?parseInt(b[1].replace(/,/g,"")):null,R=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),I=Array.from(R).map(J=>J.innerText?.trim()?.replace(/\s+/g," ")),A=I.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,T=I.join(" ")+" "+y,Y=/\bremote\b/i.test(T)?"remote":/\bhybrid\b/i.test(T)?"hybrid":/\bon-?site\b/i.test(T)?"onsite":null,K=/\bcontract\b/i.test(T)?"contract":/\bfull-?time\b/i.test(T)?"full-time":/\bpart-?time\b/i.test(T)?"part-time":/\bfreelance\b/i.test(T)?"freelance":/\btemporary\b/i.test(T)?"temporary":null,$=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",N=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",q=($+" "+r+" "+N).toLowerCase(),G=$.toLowerCase(),x=[];/\bremote\b/.test(q)&&x.push("remote"),/\bhybrid\b/.test(q)&&x.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(q)&&x.push("onsite"),(x.length===0||!x.includes("remote")&&!x.includes("hybrid")&&!x.includes("onsite"))&&/remote/i.test(N)&&x.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(G)&&x.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(G)&&x.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(G)&&!x.includes("managerial")&&x.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(G)?x.push("junior"):/\b(senior|sr\.?)\b/i.test(G)?x.push("senior"):/\b(staff|principal|distinguished)\b/i.test(G)?x.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(G)?x.push("executive"):/\b(lead|team lead)\b/i.test(G)&&x.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(q)&&x.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(q)&&x.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(q)&&x.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(q)&&x.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(q)&&x.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(q)&&x.push("mobile"),/\b(architect)\b/i.test(G)&&x.push("architect"),/\b(consultant|consulting)\b/i.test(G)&&x.push("consultant");let j=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(j)||/\bcontract\b/i.test(q))&&x.push("contract"),/full.?time|permanent/i.test(j)&&x.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(N)&&x.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(N)&&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:f,companyName:p,companyUrl:h?h.startsWith("/")?"https://www.linkedin.com"+h:h:null,aboutCompany:c,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:v,applicantCount:E,companySize:A,workplaceType:Y,contractType:K,techStack:[...new Set(a)],jobTags:[...new Set(x)]}})}Vt();import"dotenv/config";import*as C from"fs";import*as Uo from"os";import*as F from"path";import{fileURLToPath as Gs}from"url";var Po={};te(Po,{NAME:()=>Cs,VERSION:()=>xs,up:()=>$s});import*as ie from"fs";import*as Wt from"path";var xs=1,Cs="normalize-jobs-and-questions",Es=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],As=50;function Lo(e){return ie.existsSync(e)?JSON.parse(ie.readFileSync(e,"utf-8")):null}function No(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 i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function $s(e,t){let o=Wt.join(e,"jobs.json"),r=Wt.join(t,"scouted-jobs.json"),n=Wt.join(e,"application-questions.json"),i=Lo(o)||{},s=Lo(r)||{},a=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let f=s[u],d=i[u];for(let p of Es)f[p]!=null&&d[p]==null&&(d[p]=f[p]);l.push(u),a++}a>0?(No(o,i),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let c=Lo(n);if(c&&Array.isArray(c.applications)){let u={},f=0;for(let d of c.applications){let p=d.jobId||"unknown";u[p]||(u[p]={applications:[]});let m=(d.questions||[]).map(h=>{let g={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=As?g.options=h.options:(g.optionsOmitted=!0,f++)),h.page&&(g.page=h.page),h.wasPreFilled&&(g.wasPreFilled=!0),h.wasRetry&&(g.wasRetry=!0),g});u[p].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||m.length,questions:m})}No(n,u),console.log(` Phase 2: Rekeyed ${c.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else c&&!c.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let u of l)delete s[u];No(r,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Fo={};te(Fo,{NAME:()=>Ts,VERSION:()=>_s,up:()=>Ds});import*as se from"fs";import*as mr from"path";var _s=2,Ts="reset-unread-flags";function Rs(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function Is(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{se.writeFileSync(r,o)}catch(n){try{se.unlinkSync(r)}catch{}throw n}try{se.renameSync(r,e)}catch(n){try{se.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function Ds(e){let t=mr.join(e,"conversations.json"),o=Rs(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}Is(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Oo={};te(Oo,{NAME:()=>Ls,VERSION:()=>js,up:()=>qs});import*as le from"fs";import*as hr from"path";var js=3,Ls="recompute-last-message-by",Ns=new Set(["draft","confirmed","rejected","needs_review"]);function Ps(e){return le.existsSync(e)?JSON.parse(le.readFileSync(e,"utf-8")):null}function Fs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{le.writeFileSync(r,o)}catch(n){try{le.unlinkSync(r)}catch{}throw n}try{le.renameSync(r,e)}catch(n){try{le.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}function Os(e,t){if(!e||e.length===0)return"them";let o=e.filter(i=>!Ns.has(i.status));if(o.length===0)return"them";let r=o.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),n=r.length>0?r:[...o].reverse();for(let i of n){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function qs(e){let t=hr.join(e,"conversations.json"),o=Ps(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let r=process.env.LINKEDIN_NAME;if(!r||typeof r!="string"||!r.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let n=0,i=0,s=0;for(let a of Object.keys(o)){let l=o[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let c=Array.isArray(l.messages)?l.messages:[],u=Os(c,r),f=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=f,n++}if(n===0){console.log(" No conversations to recompute.");return}Fs(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var qo={};te(qo,{NAME:()=>Us,VERSION:()=>Ms,up:()=>Vs});import*as ae from"fs";import*as yr from"path";var Ms=4,Us="split-connection-timestamps",Bs=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Js(e){if(!ae.existsSync(e))return null;let t=ae.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Hs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ae.writeFileSync(r,o)}catch(n){try{ae.unlinkSync(r)}catch{}throw n}try{ae.renameSync(r,e)}catch(n){try{ae.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function Vs(e){let t=yr.join(e,"people.json"),o=Js(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let r=0,n=0;for(let i of Object.keys(o)){let s=o[i];!s||typeof s!="object"||(n++,Bs.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,r++))}if(r===0){console.log(` Scanned ${n} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Hs(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${r} still-pending people (of ${n} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Qe();Vt();var Ws=Gs(import.meta.url),Ys=F.dirname(Ws),Ks=F.dirname(F.dirname(Ys));function zs(e){return e&&(e==="~"?Uo.homedir():e.startsWith("~/")||e.startsWith("~\\")?F.join(Uo.homedir(),e.slice(2)):e)}var ue=process.env.DATA_DIR?F.resolve(zs(process.env.DATA_DIR)):Ks,qe=F.join(ue,"collected-profiles"),Me=F.join(ue,"market-research"),X=F.join(ue,".schema-version"),gr=[F.join(qe,".schema-version"),F.join(Me,".schema-version")],_e=4,be=[{version:1,module:Po},{version:2,module:Fo},{version:3,module:Oo},{version:4,module:qo}];(function(){be.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of be){if(!Number.isInteger(r.version)||r.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(r.version)} (must be positive integer)`);if(t.has(r.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${r.version}`);t.add(r.version);let n=r.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${r.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==r.version)throw new Error(`MIGRATION_REGISTRY: v${r.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=be.length?be[be.length-1].version:0;if(o!==_e)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${_e}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<be.length;r++){let n=r+1;if(be[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${be[r].version}`)}})();function kr(){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{C.mkdirSync(ue,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
255
255
  [FATAL] Cannot create DATA_DIR (${ue}): ${t.message}`),console.error(` Fix the path or permissions and try again.
@@ -292,8 +292,8 @@ function findEntryContainer(root) {
292
292
  `)}var ol=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function nl(e){let t=e.toLowerCase();return ol.some(o=>o.test(t))}var rl=6e4;function il(){let e=Date.now(),t=[];for(let o of[ue,qe,Me]){if(!C.existsSync(o))continue;let r;try{r=C.readdirSync(o)}catch{continue}for(let n of r){if(!nl(n))continue;let i=F.join(o,n);try{let s=C.statSync(i);if(!s.isFile()||e-s.mtimeMs<rl)continue;t.push({dir:o,file:n,fullPath:i})}catch{}}}return t}function sl({verbose:e=!1}={}){let t=il();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let r of t)try{C.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 ll(){let e=[];for(let t of[qe,Me]){if(!C.existsSync(t))continue;let o=C.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{Yt(n)}catch(i){e.push({dir:F.basename(t),file:r,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function al(e){let t=[],o=[];for(let i of[qe,Me]){if(!C.existsSync(i))continue;let s=C.readdirSync(i).filter(a=>a.endsWith(e));for(let a of s){let l=F.join(i,a),c=a.slice(0,-e.length),u=F.join(i,c);try{c.toLowerCase().endsWith(".json")?Yt(l):C.accessSync(l,C.constants.R_OK),t.push({backupPath:l,originalPath:u,fileName:a,dir:i})}catch(f){o.push(`${F.basename(i)}/${a}: ${f.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let r=0,n=[];for(let{backupPath:i,originalPath:s,fileName:a,dir:l}of t)try{Cr(i,s),r++}catch(c){n.push(`${F.basename(l)}/${a}: ${c.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:r}:{ok:!0,restored:r}}function Cr(e,t){let o=t+".tmp";try{C.copyFileSync(e,o),vr(o)}catch(r){try{C.unlinkSync(o)}catch{}throw r}try{C.renameSync(o,t)}catch(r){try{C.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 ce from"fs";import*as Te from"path";import{fileURLToPath as dl}from"url";import"dotenv/config";function cl(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 ul({scriptName:e,mode:t,status:o,error:r,duration:n}){let i=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),a=n?` ${cl(n)}`:"",l=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",c=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${c} \u2014 ${l} \u2014 ${s}${a}`}async function Er({scriptName:e,mode:t,status:o,summaryLines:r,error:n,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(r)||r.length===0)return;let l=`**${ul({scriptName:e,mode:t,status:o,error:n,duration:i})}**
293
293
 
294
294
  ${r.join(`
295
- `)}`;try{await Ie.addMessage(s,l)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var fl=dl(import.meta.url),pl=Te.dirname(Te.dirname(fl)),Jo=process.env.DATA_DIR?Te.resolve(process.env.DATA_DIR,"collected-profiles"):Te.join(pl,"collected-profiles"),Ho=Te.join(Jo,"run-log.json");function ml(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ce.writeFileSync(r,o);for(let n=0;n<3;n++)try{ce.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Ar(){try{if(!ce.existsSync(Ho))return{runs:[]};let e=JSON.parse(ce.readFileSync(Ho,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function $r(e){ce.existsSync(Jo)||ce.mkdirSync(Jo,{recursive:!0});try{ml(Ho,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function _r(e,t="default"){let o=Ar();for(let s of o.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let r=new Date,n={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(s=>new Date(s.timestamp).getTime()>i),$r(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Tr(e,t,o=null,r=null){if(!e)return;let n=null;try{let s=Ar(),a=s.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=o,a.error=r,n=a.duration;else{let l=s.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=r,n=l.duration)}$r(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Er({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:r,duration:n??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import de from"fs";import Re from"path";var hl="cookies.json";function Rr(){let e=process.env.ILML_SCOPE_DIR;return e?Re.join(e,"plugins-state","linkedin","cookies.json"):hl}function Kt(){let e=Rr();if(!de.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=de.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}function Ir(){return de.existsSync(Rr())}function yl(){let e=process.env.ILML_SCOPE_DIR;return e?Re.join(e,"plugins-state","linkedin"):"."}function jr(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function gl(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?jr(t[1]):"default"}function Dr(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return de.existsSync(t)||de.mkdirSync(t,{recursive:!0}),Re.resolve(t);let o=jr(e||gl()),r=Re.join(yl(),"chrome-profile",o);return de.existsSync(r)||de.mkdirSync(r,{recursive:!0}),Re.resolve(r)}var Lr=".ilml-seeded";function Nr(e){return!de.existsSync(Re.join(e,Lr))}function Pr(e){try{de.writeFileSync(Re.join(e,Lr),new Date().toISOString())}catch{}}function Fr(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{de.rmSync(Re.join(e,o),{force:!0}),t++}catch{}return t}import Vo from"fs";import bl from"path";var wl={headless:!1,defaultViewport:null,protocolTimeout:3e5},vt=new Set,Or=!1;async function zt(){let e=[...vt].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});vt.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Sl(){if(Or)return;Or=!0;let e=t=>async()=>{await zt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await zt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await zt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await zt(),process.exit(0))}),process.on("exit",()=>{for(let t of vt)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function Go(e){return bl.join(e,".ilml-browser-session.json")}function Br(e,t={}){try{Vo.writeFileSync(Go(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function kl(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();Br(e,o?{wsEndpoint:o}:{})}catch{}}function vl(e){let t=Jr(e);t&&t.ownerPid===process.pid&&kt(e)}function kt(e){try{Vo.rmSync(Go(e),{force:!0})}catch{}}function Jr(e){try{return JSON.parse(Vo.readFileSync(Go(e),"utf-8"))}catch{return null}}function qr(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Mr(e,t,o){let r,n=new Promise(s=>{r=setTimeout(()=>s(o),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(r),s),s=>{throw clearTimeout(r),s});return Promise.race([i,n])}async function Ur(e,t,{probeTimeoutMs:o=4e3}={}){let r=Jr(t);if(!r)return"free";if(!r.wsEndpoint)return r.ownerPid&&r.ownerPid!==process.pid&&qr(r.ownerPid)?"live":(kt(t),"free");let n=Symbol("timeout"),i=e.connect({browserWSEndpoint:r.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await Mr(i,o,n);if(s===n)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return kt(t),"free";if(qr(r.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Mr(s.close().then(()=>!0).catch(()=>!1),o,!1))return kt(t),"free";try{s.disconnect()}catch{}return"live"}function xl(e,t){e&&(Sl(),vt.add(e),e.on("disconnected",()=>{vt.delete(e),t&&kt(t)}))}async function Wo(e,t={}){let o=Dr(),r={...wl,...t,userDataDir:o},n=`Could not open the LinkedIn automation Chrome profile at ${o}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Ur(e,o)==="live")throw new Error(n);Br(o);let i;try{i=await e.launch(r)}catch{if(await Ur(e,o)==="live")throw new Error(n);Fr(o);try{i=await e.launch(r)}catch(a){throw vl(o),new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${a.message})`)}}return xl(i,o),kl(o,i),{browser:i,profileDir:o,needsSeed:Nr(o)}}async function Hr(e,t){if(!t||!t.needsSeed)return!1;if(!Ir())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...Kt()),Pr(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}Ue();async function xt(e,t,o="op"){let r,n=new Promise((i,s)=>{r=setTimeout(()=>s(new Error(`${o} timeout after ${t}ms`)),t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}function nt(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 Vr(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await xt(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function Gr(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await Vr(e,t)?!0:(await w(o),await Vr(e,t))}async function Wr(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 Yr(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){try{await xt(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let s=await e.newPage();if(i)try{await i(s)}catch{}if(n)try{let a=n();Array.isArray(a)&&a.length>0&&await s.setCookie(...a)}catch{}if(o){await s.goto(o,{waitUntil:"domcontentloaded",timeout:r});let a=s.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(a))throw new Error(`Session expired after recovery \u2014 landed on ${a}. Run: ilml linkedin login`)}return s}async function Kr(e,{launchFn:t,returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");let s=null;try{s=e.process()}catch{}let a=!1;try{await xt(e.close(),5e3,"oldBrowser.close"),a=!0}catch{}if(!a&&s&&s.pid&&s.exitCode===null){try{s.kill("SIGKILL")}catch{}try{await xt(new Promise(u=>s.once("exit",u)),5e3,"oldBrowser.kill")}catch{}}let l=await t(),c=await l.newPage();if(i)try{await i(c)}catch{}if(n)try{let u=n();Array.isArray(u)&&u.length>0&&await c.setCookie(...u)}catch{}if(o){await c.goto(o,{waitUntil:"domcontentloaded",timeout:r});let u=c.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(u))throw new Error(`Session expired after browser restart \u2014 landed on ${u}. Run: ilml linkedin login`)}return{browser:l,page:c}}await xr();var to=0,Cl=process.env.FUNNEL_CONNECT_RECRUITERS==="true",El=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Al=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),$l=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",Yo=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],Qt=-1;async function _l(){if(Qt===-1){let e=await Je("What is last counter? Answer only number!!");if(console.log(`Lifebot answered about lastIndex:${e}`),!/^\d+$/.test(e.trim()))throw new Error(`Last Counter is not a number, got: "${e}"`);Qt=an(e)+1,console.log(`lastIndex initialized as: ${Qt}`)}return Qt++}var si=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${si}`);var Tl=[{label:"linkedin-session-expired",match:e=>/redirected to login|cookies expired|Session expired after recovery/i.test(e.message),severity:"fatal",instructions:"Run: ilml linkedin login"},{label:"ilml-auth-expired",match:e=>{if(e.code==="PROCESSING_ERROR"||e.constructor?.name==="LifebotProcessingError")return!1;let t=e.message||"";return/Token is invalid or expired/i.test(t)||/\b401\b/.test(t)||/Unauthorized/i.test(t)||/authentication.*(failed|required)/i.test(t)},severity:"fatal",instructions:"Run: ilml login (this is the iLiveMyLife platform login, not the LinkedIn one)"},{label:"lifebot-timeout",match:e=>e.constructor.name==="LifebotTimeoutError",severity:"transient",maxConsecutive:3,cleanup:"popup"},{label:"lifebot-provider-error",match:e=>e.code==="PROCESSING_ERROR"||e.constructor.name==="LifebotProcessingError"||/AI provider returned an unexpected error/i.test(e.message||""),severity:"transient",maxConsecutive:3,cleanup:"popup",cooldownMs:3e3,instructions:"The AI provider had a hiccup. If it keeps failing, switch the provider in your Lifebot node settings."},{label:"stale-context",match:e=>/Execution context was destroyed|Cannot find context/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3}],Ct={};function li(e){let t=e;for(let o=0;t&&o<5;o++){let r=Tl.find(n=>{try{return n.match(t)}catch{return!1}});if(r)return r;t=t.cause}return null}function Rl(e){return Ct[e]=(Ct[e]||0)+1,Ct[e]}function Xr(){for(let e of Object.keys(Ct))Ct[e]=0}var Ko=0;function Il(){return Ko++,Ko>=si?(console.log(`Max run counter reached with ${Ko}`),!1):!0}async function jl(e){let t=await ar(e)}async function Dl(e){return cr(e,{easyApplyOnly:!0})}async function Ll(e){return ur(e)}async function Xo(e,t){return Do(e,t)}var zo=3,Nl=2;async function Zt(e,t){let{searchUrl:o,launchFn:r,setupPage:n,cookiesProvider:i}=e.recoveryCtx,s=await Wr(e.browser);if(!s||e._pageRecoveryStreak>=zo){if(k.browserRestarts>=Nl)throw new Error(`CDP unrecoverable: ${k.browserRestarts} browser restart${k.browserRestarts===1?"":"s"} and ${k.cdpRecoveries} page recover${k.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let l=s?`${zo} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${l}). Reason: ${t}`);let c=await Kr(e.browser,{launchFn:r,setupPage:n,cookiesProvider:i,returnUrl:o});e.browser=c.browser,e.page=c.page,e._pageRecoveryStreak=0,k.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${k.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${zo}). Reason: ${t}`),e.page=await Yr(e.browser,e.page,{returnUrl:o,cookiesProvider:i,setupPage:n}),e._pageRecoveryStreak+=1,k.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${k.cdpRecoveries}).`)}async function Pl(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(u){if(nt(u))await Zt(e,`pass-${r} navigation: ${u.message?.slice(0,80)}`);else throw u}await w(3e3)}let n=k.submitted,i=k.cdpRecoveries+k.browserRestarts,s=!0,a=!0;for(;s&&a;){if(!await Gr(e.page)){await Zt(e,"liveness probe failed twice");continue}try{await Xo(e.page,t);let f=await Ql(e.page,ci,jl);a=f.keepGoing;let d=f.jobsDone;if(console.log("keepGoing",a),console.log("pageDone"),console.log(d.length),!a)break;s=await Ll(e.page),e._pageRecoveryStreak=0}catch(f){if(!nt(f))throw f;await Zt(e,`mid-iteration: ${f.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!a)break;let l=k.submitted-n,c=k.cdpRecoveries+k.browserRestarts-i;if(l===0){if(c>0&&r<o){console.log(`No new jobs applied in pass ${r}, but ${c} CDP recover${c===1?"y":"ies"} \u2014 pass ${r+1} will retry.`);continue}console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${l} new jobs in pass ${r}.`)}}async function Zr(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return dr(e,t,o,r)}async function ei(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 Fl(e,t){try{let o=await fr(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},lt("recruiters-from-jobs",o)?(to++,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(to).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}`),Ce(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){Dt(o.profileUrl,n),Ke(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let i=o.fromJob?.companyUrl;i&&Jt(i,{recruiterUrl:o.profileUrl,jobId:n})}return o}else console.log(" \u26AA No recruiter found on this job page");return null}catch(o){return console.error("Error extracting recruiter:",o.message),null}}async function eo(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 ai(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let n of o){let i=n.querySelectorAll("button");for(let s of i){let a=s.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return s.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return t&&console.log(" Daily limit popup closed"),t}catch{return!1}}async function ti(e){await e.evaluate(()=>{let s=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of s)for(let l of a.querySelectorAll("button")){let c=l.innerText?.trim();if(c==="Continue applying"||c==="Got it"||c==="Dismiss"){l.click();return}}});let t=Date.now(),o=3e3,r=null;for(;!r&&Date.now()-t<o;){if(r=await e.$(".jobs-apply-button"),r||(r=await e.$('button[aria-label*="Easy Apply"]')),r||(r=await e.$('a[aria-label*="Easy Apply"]')),r||(r=await e.$('a[href*="/apply/"]')),!r){let s=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let l of a){let c=l.innerText?.trim();if(c==="Easy Apply"||c==="Apply")return l}return null});r=s?.asElement?.()||null,r||await s.dispose().catch(()=>{})}r||await new Promise(s=>setTimeout(s,300))}let n=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${n>400?` (waited ${n}ms)`:""}`),r){if(await e.evaluate(c=>c.disabled,r))return await eo(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(c=>c.tagName==="A",r)){await e.evaluate(c=>c.click(),r),await w(3e3);try{await e.waitForFunction(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[data-easy-apply-next-button], button[aria-label="Submit application"]'),{timeout:1e4})}catch{await w(2e3)}}else await r.click(),await w(1500);return await eo(e)?(await ai(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await eo(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function Ol(e){return await e.evaluate(async()=>{function t(){let l=document.querySelectorAll(".artdeco-inline-feedback__message");if(l.length>0)return l;let c=document.querySelector("#interop-outlet")?.shadowRoot;return c&&(l=c.querySelectorAll(".artdeco-inline-feedback__message")),l}let o=3e3,r=t();if(r?.length===0&&(await new Promise(l=>setTimeout(l,o)),r=t()),r?.length===0)return null;let n=r[0];console.log("errorMsg"),console.log(n);let i=n?.textContent.trim(),s=n.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=n.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(s),a||s){console.log("parentElement"),console.log(a);let l=a.querySelector(".artdeco-text-input--label")||a.querySelector("legend .fb-dash-form-element__label-title--is-required")||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||a.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),c=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),u=a.querySelectorAll('input[type="radio"]'),f=a.querySelector("select[data-test-text-entity-list-form-select]"),d=n.parentElement.parentElement.querySelector('input[type="file"]'),p=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(d),l&&c)return{type:"input",labelText:l.textContent.trim(),errorMsgText:i};if(l&&u.length){let m=l?l.querySelector("span:nth-of-type(1)")?.textContent.trim():null,h=Array.from(u).map(y=>{let v=(document.querySelector(`label[for="${y.id}"]`)||y.nextElementSibling)?.textContent?.trim();return{value:y.value,label:v||y.value}}),g=h.map(y=>y.label);return{type:"radio",labelText:m,errorMsgText:i,options:g,optionsData:h}}else if(f){let m=a.querySelector('label[for="'+f.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),h=m?m.querySelector("span:nth-of-type(2)")?.textContent.trim():null,g=Array.from(f.options).map(y=>y.value).filter(y=>y!=="Select an option");return{type:"select",labelText:h,errorMsgText:i,options:g}}else if(d){let m=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:i,labelText:m}}else{if(p)return{type:"datePicker",errorMsgText:i};{let m=l?l.querySelector("span:nth-of-type(2)")?.textContent.trim():null,h=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(h.length>0){let g=Array.from(h).map(y=>y.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:m,errorMsgText:i,options:g}}else return null}}}return null})}async function ql(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));l.value=n;let c=new Event("input",{bubbles:!0});if(l.dispatchEvent(c),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let u=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},f=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),f(p),await new Promise(m=>setTimeout(m,100)),u(p)})(l)}}return null},t,o)}async function Ml(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('input[type="radio"]'),c=n;if(r.optionsData){let u=r.optionsData.find(f=>f.label.toLowerCase()===n.toLowerCase());u&&(c=u.value,console.log(`Radio: matched label "${n}" to value "${c}"`))}for(let u of l){let d=(document.querySelector(`label[for="${u.id}"]`)||u.nextElementSibling)?.textContent?.trim()||"";if(u.value.toLowerCase()===c.toLowerCase()||d.toLowerCase()===n.toLowerCase()){u.checked=!0;let p=new Event("change",{bubbles:!0});u.dispatchEvent(p),console.log(`Radio selected: value="${u.value}", label="${d}"`);break}}}return null},t,o)}async function Ul(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector("select[data-test-text-entity-list-form-select]");if(!l)return null;let c=Array.from(l.options),u=c.find(d=>d.text.toLowerCase()===n.toLowerCase())||c.find(d=>d.text.toLowerCase().includes(n.toLowerCase()));u?l.value=u.value:l.value=n;let f=new Event("change",{bubbles:!0});l.dispatchEvent(f)}return null},t,o)}async function Bl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');l.length>0&&l.forEach(c=>{if(c.nextElementSibling.textContent.trim()===n.trim()){c.checked=!0;let u=new Event("change",{bubbles:!0});c.dispatchEvent(u)}})}return null},t,o)}async function Jl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i?.length===0)return null;let s=i[0],a=s.closest(".fb-dash-form-element"),l=s.parentElement.parentElement.querySelector('input[type="file"]');if(a&&l){async function c(u,f,d){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let m=new Blob([new Uint8Array(f)]),h=new File([m],d,{type:"application/pdf"}),g=new DataTransfer;g.items.add(h),u.files=g.files;let y=new Event("change",{bubbles:!0});u.dispatchEvent(y)}await c(l,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function oi(e){let t=await Ol(e);if(t===null)return null;if(t?.type==="input"){let n=await no(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await ql(e,t,n)}else if(t?.type==="radio"){let n=await Et(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[];!i.find(a=>a.toLowerCase()===n?.toLowerCase())&&i.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await Et(t.labelText,t.options),n=n?.trim()||n,i.find(l=>l.toLowerCase()===n?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])),t.answer=n,await Ml(e,t,n)}else if(t?.type==="select"){let n=await it(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[],s=i.find(a=>a.toLowerCase()===n?.toLowerCase());if(s)n=s;else if(i.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await it(t.labelText,t.options),n=n?.trim()||n;let a=i.find(l=>l.toLowerCase()===n?.toLowerCase());a?n=a:(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])}t.answer=n,await Ul(e,t,n)}else if(t?.type==="checkbox"){let n=await it(t.labelText,t.options);t.answer=n,await Bl(e,t,n)}else if(t?.type==="file"){let n=process.env.RESUME_PDF_URL;t.answer=n;let i=await fetch(n);if(!i.ok)throw new Error("Network response was not ok");let s=await i.arrayBuffer();await Jl(e,t,s)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let o=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${o}" \u2192 ${r}`),t}async function Hl(e){return await e.evaluate(async()=>{let t=[],o=document.querySelectorAll(".fb-dash-form-element");if(!o||o.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(o=r.querySelectorAll(".fb-dash-form-element"))}if(!o||o.length===0)return[];for(let r of o){let n=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),s=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),l=r.querySelector("select[data-test-text-entity-list-form-select]"),c=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),u=r.querySelector('input[type="file"]');if(n&&s&&a.length===0){let f=n.textContent.trim();t.push({type:"input",labelText:f,answer:s.value,isRequired:i,wasPreFilled:!!s.value})}else if(n&&a.length){let f=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,d=Array.from(a).map(m=>m.value),p=(Array.from(a).find(m=>m.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:f,options:d,answer:p,isRequired:i,wasPreFilled:!!p})}else if(l){let f=r.querySelector('label[for="'+l.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),d=f?.querySelector("span:nth-of-type(2)")?.textContent.trim()||f?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||f?.querySelector("span")?.textContent.trim()||f?.textContent?.trim()||null,p=Array.from(l.options).map(h=>h.value).filter(h=>h!=="Select an option"),m=l.value!=="Select an option"?l.value:"";t.push({type:"select",labelText:d,options:p,answer:m,isRequired:i,wasPreFilled:!!m})}else if(c.length>0){let f=r.querySelector("legend span")?.textContent?.trim(),d=Array.from(c).map(h=>({label:h.nextElementSibling?.textContent?.trim()||h.value,checked:h.checked})),p=d.some(h=>h.checked),m=d.filter(h=>h.checked).map(h=>h.label).join(", ");t.push({type:"checkbox",labelText:f,options:d.map(h=>h.label),answer:m,isRequired:i,wasPreFilled:p})}else if(u){let f=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:f,answer:u.value?"uploaded":"",isRequired:i,wasPreFilled:!!u.value})}}return t})}async function Zo(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelector(".artdeco-text-input--label")||s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||s.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),l=s.querySelector(".artdeco-text-input--input")||s.querySelector("input");if(a&&l&&r===a.textContent.trim()){l.value=n;let c=new Event("input",{bubbles:!0});if(l.dispatchEvent(c),r==="City"||r==="Location (city)"){let u=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},f=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),f(p),await new Promise(m=>setTimeout(m,100)),u(p)})(l)}return!0}}return!1},t,o)}async function Vl(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelectorAll('input[type="radio"]');if(a.length===0)continue;let l=s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('legend [class*="fb-dash-form-element__label"]')||s.querySelector("legend span");if((l?.querySelector("span:nth-of-type(1)")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let u=(n||"").toLowerCase();for(let f of a){let d=f.getRootNode(),m=(f.id&&d.querySelector(`label[for="${f.id}"]`)||f.nextElementSibling)?.textContent?.trim()||"";if(f.value.toLowerCase()===u||m.toLowerCase()===u)return f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function Gl(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelector("select[data-test-text-entity-list-form-select]");if(!a)continue;let l=s.querySelector(`label[for="${a.id}"]`)||s.querySelector(".fb-dash-form-element__label-title--is-required");if((l?.querySelector("span:nth-of-type(2)")?.textContent.trim()||l?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||l?.querySelector("span")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let u=Array.from(a.options),f=(n||"").toLowerCase(),d=u.find(p=>p.text.toLowerCase()===f)||u.find(p=>p.value.toLowerCase()===f)||u.find(p=>p.text.toLowerCase().includes(f));return d?(a.value=d.value,a.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function Wl(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let a=document.querySelector("#interop-outlet")?.shadowRoot;a&&(i=a.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;let s=(n||"").split(",").map(a=>a.trim().toLowerCase()).filter(Boolean);if(s.length===0)return!1;for(let a of i){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(l.length===0||a.querySelector("legend span")?.textContent?.trim()!==r)continue;let u=!1;for(let f of l){let d=(f.nextElementSibling?.textContent||f.value||"").trim().toLowerCase();s.includes(d)&&!f.checked&&(f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),u=!0)}return u}return!1},t,o)}async function Yl(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 no(o.labelText,"");else if(o.type==="radio")r=await Et(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await it(o.labelText,o.options||[]);else continue}catch(s){console.log(` \u26A0 Lifebot failed for optional "${o.labelText}": ${s.message?.slice(0,80)}`);continue}if(r=(r||"").trim(),o.wasOptional=!0,!r){o.answer="",console.log(` ? [opt ${o.type}] "${o.labelText.slice(0,55)}" \u2192 (empty)`);continue}let n=!1;try{o.type==="input"?n=await Zo(e,o.labelText,r):o.type==="radio"?n=await Vl(e,o.labelText,r):o.type==="select"?n=await Gl(e,o.labelText,r):o.type==="checkbox"&&(n=await Wl(e,o.labelText,r))}catch(s){console.log(` \u26A0 setter failed for "${o.labelText}": ${s.message?.slice(0,80)}`)}o.answer=r,console.log(` ? [${n?"opt":"opt-noapply"} ${o.type}] "${o.labelText.slice(0,55)}" \u2192 "${r.slice(0,50)}"`)}}async function ni(e,t){let o=[],r=!0,n=0,i=null,s=0;for(;r;){if(n++,await eo(e))return console.log(" Daily limit reached during form navigation"),await ai(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let c=(await Hl(e)).filter(p=>!o.some(m=>m.labelText===p.labelText));o.push(...c);try{let p=o.find(h=>h.labelText==="City"||h.labelText==="Location (city)"),m=o.filter(h=>h.labelText!=null).find(h=>h.labelText!==null&&h.labelText.trim()!==null&&(h.labelText.trim().toLowerCase()==="cv"||h.labelText.trim().toLowerCase()==="curriculum vitae"||h.labelText.trim().toLowerCase()==="cover letter"||h.labelText.trim().toLowerCase()==="cover"));if(p&&!p.answer){let h=process.env.City;await Zo(e,p.labelText,h),p.answer=h}else if(m){let h=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!m.answer||m.answer!==h)&&(await w(1e4),await Zo(e,m.labelText,h),m.answer=h,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await Yl(e,c)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let u=null;try{u=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(u!==null){if(u.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:u};let p=u&&o.find(h=>h.errorMsgText&&h.labelText===u.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(u,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:u};let m=o.findIndex(h=>h.labelText===u.labelText&&!h.answer);m!==-1&&o.splice(m,1),o.push(u)}let f=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of p){let h=m.querySelectorAll("button");for(let g of h){let y=g.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return g.click(),y}}return null});f&&console.log(` Dismissed safety popup (${f})`);let d=await e.evaluate(async()=>{function p(b){let E=document.querySelector(b);if(E)return E;let R=document.querySelector("#interop-outlet")?.shadowRoot;return R?R.querySelector(b):null}function m(b){let E=document.querySelectorAll(b),R=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(b);return[...E||[],...R||[]]}let h=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(b=>b.innerText?.trim()==="Next"),g=m('footer[role="presentation"] button').some(b=>b.innerText.trim()==="Review")||m("button").some(b=>b.innerText.trim()==="Review"&&b.getAttribute("aria-label")?.includes("Review")),y=p('button[aria-label="Submit application"]'),S=async()=>{let b=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(E=>E.innerText?.trim()==="Next");b?b.click():console.log("Next button not found")},v=()=>{let b=m("button").find(E=>E.innerText?.trim()==="Review");b&&b.click()};return h?(await S(),{type:"next"}):g?(await v(),{type:"review"}):y?{type:"submit"}:{type:null}});if(d==null)return{filledFields:o,formPages:n,skip:!0};if(d.type&&console.log(` \u2192 ${d.type}`),d.type===null){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of m){let g=h.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of g){let S=y.innerText||"";if(S.includes("application was sent")||S.includes("resume into a profile")||S.includes("Application submitted")||S.includes("Next best action"))for(let v of y.querySelectorAll("button")){let b=v.innerText?.trim();if(b==="Not now"||b==="Done"||b==="Dismiss"||b==="Got it")return v.click(),b}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await w(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(s===0){let m=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],y=[];for(let S of h){for(let b of S.querySelectorAll("button")){let E=b.innerText?.trim();E&&E.length<60&&g.push(E)}let v=S.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');v&&y.push(v.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(m.buttons)}`),m.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(m.modalText)}`)}}if(d.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(u===null&&d.type===i?s++:s=0,i=d.type,s>=5){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),h=[],g=[];for(let y of m){for(let S of y.querySelectorAll(".artdeco-inline-feedback__message"))h.push(S.textContent?.trim()?.slice(0,60));for(let S of y.querySelectorAll(".fb-dash-form-element")){let v=S.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),b=S.querySelector("input, select, textarea"),E=!!S.querySelector(".artdeco-inline-feedback__message");v&&(E||b&&!b.value)&&g.push({label:v.slice(0,40),hasError:E,value:b?.value?.slice(0,20)||""})}}return{errors:h,emptyRequired:g.slice(0,5)}});return console.error(` \u26A0 Stuck on "${d.type}" for ${s} iterations \u2014 form not progressing.`),p.errors.length&&console.error(` Visible errors: ${JSON.stringify(p.errors)}`),p.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(p.emptyRequired)}`),console.error(" Skipping job."),{filledFields:o,formPages:n,skip:!0,duplicateField:{labelText:`stuck_on_${d.type}`}}}await w(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function ri(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 Kl(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 zl(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of o){for(let i of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(i.innerText?.trim()==="Done")return i.click(),"Done";let n=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let i of n){let s=i.innerText||"";if(s.includes("application was sent")||s.includes("Application sent")||s.includes("resume into a profile")||s.includes("Next best action"))for(let a of i.querySelectorAll("button")){let l=a.innerText?.trim();if(l==="Not now"||l==="Dismiss")return a.click(),l}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await w(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function Xt(e){try{await e.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let t=await e.$('button[aria-label="Dismiss"]');t?(await t.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await w(1e3)):console.log("Popup \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.")}catch{console.log("closeJobApplicationPopup failed to execute: \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D \u0438\u043B\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F.")}}async function Qo(e){try{await e.waitForSelector('button[data-control-name="discard_application_confirm_btn"]',{timeout:3e3});let t=await e.$('button[data-control-name="discard_application_confirm_btn"]');t&&(await t.click(),console.log("Discard confirmed"),await w(500))}catch{console.log("No discard confirmation needed")}}async function ci(e,t){let o=[],r=t._fromQueue;try{k.attempted++,console.log(`
295
+ `)}`;try{await Ie.addMessage(s,l)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var fl=dl(import.meta.url),pl=Te.dirname(Te.dirname(fl)),Jo=process.env.DATA_DIR?Te.resolve(process.env.DATA_DIR,"collected-profiles"):Te.join(pl,"collected-profiles"),Ho=Te.join(Jo,"run-log.json");function ml(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ce.writeFileSync(r,o);for(let n=0;n<3;n++)try{ce.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Ar(){try{if(!ce.existsSync(Ho))return{runs:[]};let e=JSON.parse(ce.readFileSync(Ho,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function $r(e){ce.existsSync(Jo)||ce.mkdirSync(Jo,{recursive:!0});try{ml(Ho,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function _r(e,t="default"){let o=Ar();for(let s of o.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let r=new Date,n={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(s=>new Date(s.timestamp).getTime()>i),$r(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Tr(e,t,o=null,r=null){if(!e)return;let n=null;try{let s=Ar(),a=s.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=o,a.error=r,n=a.duration;else{let l=s.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=r,n=l.duration)}$r(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Er({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:r,duration:n??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import de from"fs";import Re from"path";var hl="cookies.json";function Rr(){let e=process.env.ILML_SCOPE_DIR;return e?Re.join(e,"plugins-state","linkedin","cookies.json"):hl}function Kt(){let e=Rr();if(!de.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=de.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}function Ir(){return de.existsSync(Rr())}function yl(){let e=process.env.ILML_SCOPE_DIR;return e?Re.join(e,"plugins-state","linkedin"):"."}function Dr(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function gl(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Dr(t[1]):"default"}function jr(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return de.existsSync(t)||de.mkdirSync(t,{recursive:!0}),Re.resolve(t);let o=Dr(e||gl()),r=Re.join(yl(),"chrome-profile",o);return de.existsSync(r)||de.mkdirSync(r,{recursive:!0}),Re.resolve(r)}var Lr=".ilml-seeded";function Nr(e){return!de.existsSync(Re.join(e,Lr))}function Pr(e){try{de.writeFileSync(Re.join(e,Lr),new Date().toISOString())}catch{}}function Fr(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{de.rmSync(Re.join(e,o),{force:!0}),t++}catch{}return t}import Vo from"fs";import bl from"path";var wl={headless:!1,defaultViewport:null,protocolTimeout:3e5},vt=new Set,Or=!1;async function zt(){let e=[...vt].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});vt.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Sl(){if(Or)return;Or=!0;let e=t=>async()=>{await zt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await zt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await zt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await zt(),process.exit(0))}),process.on("exit",()=>{for(let t of vt)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function Go(e){return bl.join(e,".ilml-browser-session.json")}function Br(e,t={}){try{Vo.writeFileSync(Go(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function kl(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();Br(e,o?{wsEndpoint:o}:{})}catch{}}function vl(e){let t=Jr(e);t&&t.ownerPid===process.pid&&kt(e)}function kt(e){try{Vo.rmSync(Go(e),{force:!0})}catch{}}function Jr(e){try{return JSON.parse(Vo.readFileSync(Go(e),"utf-8"))}catch{return null}}function qr(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Mr(e,t,o){let r,n=new Promise(s=>{r=setTimeout(()=>s(o),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(r),s),s=>{throw clearTimeout(r),s});return Promise.race([i,n])}async function Ur(e,t,{probeTimeoutMs:o=4e3}={}){let r=Jr(t);if(!r)return"free";if(!r.wsEndpoint)return r.ownerPid&&r.ownerPid!==process.pid&&qr(r.ownerPid)?"live":(kt(t),"free");let n=Symbol("timeout"),i=e.connect({browserWSEndpoint:r.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await Mr(i,o,n);if(s===n)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return kt(t),"free";if(qr(r.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Mr(s.close().then(()=>!0).catch(()=>!1),o,!1))return kt(t),"free";try{s.disconnect()}catch{}return"live"}function xl(e,t){e&&(Sl(),vt.add(e),e.on("disconnected",()=>{vt.delete(e),t&&kt(t)}))}async function Wo(e,t={}){let o=jr(),r={...wl,...t,userDataDir:o},n=`Could not open the LinkedIn automation Chrome profile at ${o}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Ur(e,o)==="live")throw new Error(n);Br(o);let i;try{i=await e.launch(r)}catch{if(await Ur(e,o)==="live")throw new Error(n);Fr(o);try{i=await e.launch(r)}catch(a){throw vl(o),new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${a.message})`)}}return xl(i,o),kl(o,i),{browser:i,profileDir:o,needsSeed:Nr(o)}}async function Hr(e,t){if(!t||!t.needsSeed)return!1;if(!Ir())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...Kt()),Pr(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}Ue();async function xt(e,t,o="op"){let r,n=new Promise((i,s)=>{r=setTimeout(()=>s(new Error(`${o} timeout after ${t}ms`)),t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}function nt(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 Vr(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await xt(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function Gr(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await Vr(e,t)?!0:(await w(o),await Vr(e,t))}async function Wr(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 Yr(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){try{await xt(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let s=await e.newPage();if(i)try{await i(s)}catch{}if(n)try{let a=n();Array.isArray(a)&&a.length>0&&await s.setCookie(...a)}catch{}if(o){await s.goto(o,{waitUntil:"domcontentloaded",timeout:r});let a=s.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(a))throw new Error(`Session expired after recovery \u2014 landed on ${a}. Run: ilml linkedin login`)}return s}async function Kr(e,{launchFn:t,returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");let s=null;try{s=e.process()}catch{}let a=!1;try{await xt(e.close(),5e3,"oldBrowser.close"),a=!0}catch{}if(!a&&s&&s.pid&&s.exitCode===null){try{s.kill("SIGKILL")}catch{}try{await xt(new Promise(u=>s.once("exit",u)),5e3,"oldBrowser.kill")}catch{}}let l=await t(),c=await l.newPage();if(i)try{await i(c)}catch{}if(n)try{let u=n();Array.isArray(u)&&u.length>0&&await c.setCookie(...u)}catch{}if(o){await c.goto(o,{waitUntil:"domcontentloaded",timeout:r});let u=c.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(u))throw new Error(`Session expired after browser restart \u2014 landed on ${u}. Run: ilml linkedin login`)}return{browser:l,page:c}}await xr();var to=0,Cl=process.env.FUNNEL_CONNECT_RECRUITERS==="true",El=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Al=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),$l=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",Yo=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],Qt=-1;async function _l(){if(Qt===-1){let e=await Je("What is last counter? Answer only number!!");if(console.log(`Lifebot answered about lastIndex:${e}`),!/^\d+$/.test(e.trim()))throw new Error(`Last Counter is not a number, got: "${e}"`);Qt=an(e)+1,console.log(`lastIndex initialized as: ${Qt}`)}return Qt++}var si=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${si}`);var Tl=[{label:"linkedin-session-expired",match:e=>/redirected to login|cookies expired|Session expired after recovery/i.test(e.message),severity:"fatal",instructions:"Run: ilml linkedin login"},{label:"ilml-auth-expired",match:e=>{if(e.code==="PROCESSING_ERROR"||e.constructor?.name==="LifebotProcessingError")return!1;let t=e.message||"";return/Token is invalid or expired/i.test(t)||/\b401\b/.test(t)||/Unauthorized/i.test(t)||/authentication.*(failed|required)/i.test(t)},severity:"fatal",instructions:"Run: ilml login (this is the iLiveMyLife platform login, not the LinkedIn one)"},{label:"lifebot-timeout",match:e=>e.constructor.name==="LifebotTimeoutError",severity:"transient",maxConsecutive:3,cleanup:"popup"},{label:"lifebot-provider-error",match:e=>e.code==="PROCESSING_ERROR"||e.constructor.name==="LifebotProcessingError"||/AI provider returned an unexpected error/i.test(e.message||""),severity:"transient",maxConsecutive:3,cleanup:"popup",cooldownMs:3e3,instructions:"The AI provider had a hiccup. If it keeps failing, switch the provider in your Lifebot node settings."},{label:"stale-context",match:e=>/Execution context was destroyed|Cannot find context/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3}],Ct={};function li(e){let t=e;for(let o=0;t&&o<5;o++){let r=Tl.find(n=>{try{return n.match(t)}catch{return!1}});if(r)return r;t=t.cause}return null}function Rl(e){return Ct[e]=(Ct[e]||0)+1,Ct[e]}function Xr(){for(let e of Object.keys(Ct))Ct[e]=0}var Ko=0;function Il(){return Ko++,Ko>=si?(console.log(`Max run counter reached with ${Ko}`),!1):!0}async function Dl(e){let t=await ar(e)}async function jl(e){return cr(e,{easyApplyOnly:!0})}async function Ll(e){return ur(e)}async function Xo(e,t){return jo(e,t)}var zo=3,Nl=2;async function Zt(e,t){let{searchUrl:o,launchFn:r,setupPage:n,cookiesProvider:i}=e.recoveryCtx,s=await Wr(e.browser);if(!s||e._pageRecoveryStreak>=zo){if(k.browserRestarts>=Nl)throw new Error(`CDP unrecoverable: ${k.browserRestarts} browser restart${k.browserRestarts===1?"":"s"} and ${k.cdpRecoveries} page recover${k.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let l=s?`${zo} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${l}). Reason: ${t}`);let c=await Kr(e.browser,{launchFn:r,setupPage:n,cookiesProvider:i,returnUrl:o});e.browser=c.browser,e.page=c.page,e._pageRecoveryStreak=0,k.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${k.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${zo}). Reason: ${t}`),e.page=await Yr(e.browser,e.page,{returnUrl:o,cookiesProvider:i,setupPage:n}),e._pageRecoveryStreak+=1,k.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${k.cdpRecoveries}).`)}async function Pl(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(u){if(nt(u))await Zt(e,`pass-${r} navigation: ${u.message?.slice(0,80)}`);else throw u}await w(3e3)}let n=k.submitted,i=k.cdpRecoveries+k.browserRestarts,s=!0,a=!0;for(;s&&a;){if(!await Gr(e.page)){await Zt(e,"liveness probe failed twice");continue}try{await Xo(e.page,t);let f=await Ql(e.page,ci,Dl);a=f.keepGoing;let d=f.jobsDone;if(console.log("keepGoing",a),console.log("pageDone"),console.log(d.length),!a)break;s=await Ll(e.page),e._pageRecoveryStreak=0}catch(f){if(!nt(f))throw f;await Zt(e,`mid-iteration: ${f.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!a)break;let l=k.submitted-n,c=k.cdpRecoveries+k.browserRestarts-i;if(l===0){if(c>0&&r<o){console.log(`No new jobs applied in pass ${r}, but ${c} CDP recover${c===1?"y":"ies"} \u2014 pass ${r+1} will retry.`);continue}console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${l} new jobs in pass ${r}.`)}}async function Zr(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return dr(e,t,o,r)}async function ei(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 Fl(e,t){try{let o=await fr(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},lt("recruiters-from-jobs",o)?(to++,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(to).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}`),Ce(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){jt(o.profileUrl,n),Ke(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let i=o.fromJob?.companyUrl;i&&Jt(i,{recruiterUrl:o.profileUrl,jobId:n})}return o}else console.log(" \u26AA No recruiter found on this job page");return null}catch(o){return console.error("Error extracting recruiter:",o.message),null}}async function eo(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 ai(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let n of o){let i=n.querySelectorAll("button");for(let s of i){let a=s.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return s.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return t&&console.log(" Daily limit popup closed"),t}catch{return!1}}async function ti(e){await e.evaluate(()=>{let s=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of s)for(let l of a.querySelectorAll("button")){let c=l.innerText?.trim();if(c==="Continue applying"||c==="Got it"||c==="Dismiss"){l.click();return}}});let t=Date.now(),o=3e3,r=null;for(;!r&&Date.now()-t<o;){if(r=await e.$(".jobs-apply-button"),r||(r=await e.$('button[aria-label*="Easy Apply"]')),r||(r=await e.$('a[aria-label*="Easy Apply"]')),r||(r=await e.$('a[href*="/apply/"]')),!r){let s=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let l of a){let c=l.innerText?.trim();if(c==="Easy Apply"||c==="Apply")return l}return null});r=s?.asElement?.()||null,r||await s.dispose().catch(()=>{})}r||await new Promise(s=>setTimeout(s,300))}let n=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${n>400?` (waited ${n}ms)`:""}`),r){if(await e.evaluate(c=>c.disabled,r))return await eo(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(c=>c.tagName==="A",r)){await e.evaluate(c=>c.click(),r),await w(3e3);try{await e.waitForFunction(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[data-easy-apply-next-button], button[aria-label="Submit application"]'),{timeout:1e4})}catch{await w(2e3)}}else await r.click(),await w(1500);return await eo(e)?(await ai(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await eo(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function Ol(e){return await e.evaluate(async()=>{function t(){let l=document.querySelectorAll(".artdeco-inline-feedback__message");if(l.length>0)return l;let c=document.querySelector("#interop-outlet")?.shadowRoot;return c&&(l=c.querySelectorAll(".artdeco-inline-feedback__message")),l}let o=3e3,r=t();if(r?.length===0&&(await new Promise(l=>setTimeout(l,o)),r=t()),r?.length===0)return null;let n=r[0];console.log("errorMsg"),console.log(n);let i=n?.textContent.trim(),s=n.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=n.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(s),a||s){console.log("parentElement"),console.log(a);let l=a.querySelector(".artdeco-text-input--label")||a.querySelector("legend .fb-dash-form-element__label-title--is-required")||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||a.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),c=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),u=a.querySelectorAll('input[type="radio"]'),f=a.querySelector("select[data-test-text-entity-list-form-select]"),d=n.parentElement.parentElement.querySelector('input[type="file"]'),p=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(d),l&&c)return{type:"input",labelText:l.textContent.trim(),errorMsgText:i};if(l&&u.length){let m=l?l.querySelector("span:nth-of-type(1)")?.textContent.trim():null,h=Array.from(u).map(y=>{let v=(document.querySelector(`label[for="${y.id}"]`)||y.nextElementSibling)?.textContent?.trim();return{value:y.value,label:v||y.value}}),g=h.map(y=>y.label);return{type:"radio",labelText:m,errorMsgText:i,options:g,optionsData:h}}else if(f){let m=a.querySelector('label[for="'+f.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),h=m?m.querySelector("span:nth-of-type(2)")?.textContent.trim():null,g=Array.from(f.options).map(y=>y.value).filter(y=>y!=="Select an option");return{type:"select",labelText:h,errorMsgText:i,options:g}}else if(d){let m=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:i,labelText:m}}else{if(p)return{type:"datePicker",errorMsgText:i};{let m=l?l.querySelector("span:nth-of-type(2)")?.textContent.trim():null,h=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(h.length>0){let g=Array.from(h).map(y=>y.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:m,errorMsgText:i,options:g}}else return null}}}return null})}async function ql(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));l.value=n;let c=new Event("input",{bubbles:!0});if(l.dispatchEvent(c),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let u=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},f=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),f(p),await new Promise(m=>setTimeout(m,100)),u(p)})(l)}}return null},t,o)}async function Ml(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('input[type="radio"]'),c=n;if(r.optionsData){let u=r.optionsData.find(f=>f.label.toLowerCase()===n.toLowerCase());u&&(c=u.value,console.log(`Radio: matched label "${n}" to value "${c}"`))}for(let u of l){let d=(document.querySelector(`label[for="${u.id}"]`)||u.nextElementSibling)?.textContent?.trim()||"";if(u.value.toLowerCase()===c.toLowerCase()||d.toLowerCase()===n.toLowerCase()){u.checked=!0;let p=new Event("change",{bubbles:!0});u.dispatchEvent(p),console.log(`Radio selected: value="${u.value}", label="${d}"`);break}}}return null},t,o)}async function Ul(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector("select[data-test-text-entity-list-form-select]");if(!l)return null;let c=Array.from(l.options),u=c.find(d=>d.text.toLowerCase()===n.toLowerCase())||c.find(d=>d.text.toLowerCase().includes(n.toLowerCase()));u?l.value=u.value:l.value=n;let f=new Event("change",{bubbles:!0});l.dispatchEvent(f)}return null},t,o)}async function Bl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');l.length>0&&l.forEach(c=>{if(c.nextElementSibling.textContent.trim()===n.trim()){c.checked=!0;let u=new Event("change",{bubbles:!0});c.dispatchEvent(u)}})}return null},t,o)}async function Jl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i?.length===0)return null;let s=i[0],a=s.closest(".fb-dash-form-element"),l=s.parentElement.parentElement.querySelector('input[type="file"]');if(a&&l){async function c(u,f,d){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let m=new Blob([new Uint8Array(f)]),h=new File([m],d,{type:"application/pdf"}),g=new DataTransfer;g.items.add(h),u.files=g.files;let y=new Event("change",{bubbles:!0});u.dispatchEvent(y)}await c(l,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function oi(e){let t=await Ol(e);if(t===null)return null;if(t?.type==="input"){let n=await no(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await ql(e,t,n)}else if(t?.type==="radio"){let n=await Et(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[];!i.find(a=>a.toLowerCase()===n?.toLowerCase())&&i.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await Et(t.labelText,t.options),n=n?.trim()||n,i.find(l=>l.toLowerCase()===n?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])),t.answer=n,await Ml(e,t,n)}else if(t?.type==="select"){let n=await it(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[],s=i.find(a=>a.toLowerCase()===n?.toLowerCase());if(s)n=s;else if(i.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await it(t.labelText,t.options),n=n?.trim()||n;let a=i.find(l=>l.toLowerCase()===n?.toLowerCase());a?n=a:(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])}t.answer=n,await Ul(e,t,n)}else if(t?.type==="checkbox"){let n=await it(t.labelText,t.options);t.answer=n,await Bl(e,t,n)}else if(t?.type==="file"){let n=process.env.RESUME_PDF_URL;t.answer=n;let i=await fetch(n);if(!i.ok)throw new Error("Network response was not ok");let s=await i.arrayBuffer();await Jl(e,t,s)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let o=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${o}" \u2192 ${r}`),t}async function Hl(e){return await e.evaluate(async()=>{let t=[],o=document.querySelectorAll(".fb-dash-form-element");if(!o||o.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(o=r.querySelectorAll(".fb-dash-form-element"))}if(!o||o.length===0)return[];for(let r of o){let n=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),s=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),l=r.querySelector("select[data-test-text-entity-list-form-select]"),c=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),u=r.querySelector('input[type="file"]');if(n&&s&&a.length===0){let f=n.textContent.trim();t.push({type:"input",labelText:f,answer:s.value,isRequired:i,wasPreFilled:!!s.value})}else if(n&&a.length){let f=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,d=Array.from(a).map(m=>m.value),p=(Array.from(a).find(m=>m.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:f,options:d,answer:p,isRequired:i,wasPreFilled:!!p})}else if(l){let f=r.querySelector('label[for="'+l.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),d=f?.querySelector("span:nth-of-type(2)")?.textContent.trim()||f?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||f?.querySelector("span")?.textContent.trim()||f?.textContent?.trim()||null,p=Array.from(l.options).map(h=>h.value).filter(h=>h!=="Select an option"),m=l.value!=="Select an option"?l.value:"";t.push({type:"select",labelText:d,options:p,answer:m,isRequired:i,wasPreFilled:!!m})}else if(c.length>0){let f=r.querySelector("legend span")?.textContent?.trim(),d=Array.from(c).map(h=>({label:h.nextElementSibling?.textContent?.trim()||h.value,checked:h.checked})),p=d.some(h=>h.checked),m=d.filter(h=>h.checked).map(h=>h.label).join(", ");t.push({type:"checkbox",labelText:f,options:d.map(h=>h.label),answer:m,isRequired:i,wasPreFilled:p})}else if(u){let f=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:f,answer:u.value?"uploaded":"",isRequired:i,wasPreFilled:!!u.value})}}return t})}async function Zo(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelector(".artdeco-text-input--label")||s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||s.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),l=s.querySelector(".artdeco-text-input--input")||s.querySelector("input");if(a&&l&&r===a.textContent.trim()){l.value=n;let c=new Event("input",{bubbles:!0});if(l.dispatchEvent(c),r==="City"||r==="Location (city)"){let u=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},f=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),f(p),await new Promise(m=>setTimeout(m,100)),u(p)})(l)}return!0}}return!1},t,o)}async function Vl(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelectorAll('input[type="radio"]');if(a.length===0)continue;let l=s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('legend [class*="fb-dash-form-element__label"]')||s.querySelector("legend span");if((l?.querySelector("span:nth-of-type(1)")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let u=(n||"").toLowerCase();for(let f of a){let d=f.getRootNode(),m=(f.id&&d.querySelector(`label[for="${f.id}"]`)||f.nextElementSibling)?.textContent?.trim()||"";if(f.value.toLowerCase()===u||m.toLowerCase()===u)return f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function Gl(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelector("select[data-test-text-entity-list-form-select]");if(!a)continue;let l=s.querySelector(`label[for="${a.id}"]`)||s.querySelector(".fb-dash-form-element__label-title--is-required");if((l?.querySelector("span:nth-of-type(2)")?.textContent.trim()||l?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||l?.querySelector("span")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let u=Array.from(a.options),f=(n||"").toLowerCase(),d=u.find(p=>p.text.toLowerCase()===f)||u.find(p=>p.value.toLowerCase()===f)||u.find(p=>p.text.toLowerCase().includes(f));return d?(a.value=d.value,a.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function Wl(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let a=document.querySelector("#interop-outlet")?.shadowRoot;a&&(i=a.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;let s=(n||"").split(",").map(a=>a.trim().toLowerCase()).filter(Boolean);if(s.length===0)return!1;for(let a of i){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(l.length===0||a.querySelector("legend span")?.textContent?.trim()!==r)continue;let u=!1;for(let f of l){let d=(f.nextElementSibling?.textContent||f.value||"").trim().toLowerCase();s.includes(d)&&!f.checked&&(f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),u=!0)}return u}return!1},t,o)}async function Yl(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 no(o.labelText,"");else if(o.type==="radio")r=await Et(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await it(o.labelText,o.options||[]);else continue}catch(s){console.log(` \u26A0 Lifebot failed for optional "${o.labelText}": ${s.message?.slice(0,80)}`);continue}if(r=(r||"").trim(),o.wasOptional=!0,!r){o.answer="",console.log(` ? [opt ${o.type}] "${o.labelText.slice(0,55)}" \u2192 (empty)`);continue}let n=!1;try{o.type==="input"?n=await Zo(e,o.labelText,r):o.type==="radio"?n=await Vl(e,o.labelText,r):o.type==="select"?n=await Gl(e,o.labelText,r):o.type==="checkbox"&&(n=await Wl(e,o.labelText,r))}catch(s){console.log(` \u26A0 setter failed for "${o.labelText}": ${s.message?.slice(0,80)}`)}o.answer=r,console.log(` ? [${n?"opt":"opt-noapply"} ${o.type}] "${o.labelText.slice(0,55)}" \u2192 "${r.slice(0,50)}"`)}}async function ni(e,t){let o=[],r=!0,n=0,i=null,s=0;for(;r;){if(n++,await eo(e))return console.log(" Daily limit reached during form navigation"),await ai(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let c=(await Hl(e)).filter(p=>!o.some(m=>m.labelText===p.labelText));o.push(...c);try{let p=o.find(h=>h.labelText==="City"||h.labelText==="Location (city)"),m=o.filter(h=>h.labelText!=null).find(h=>h.labelText!==null&&h.labelText.trim()!==null&&(h.labelText.trim().toLowerCase()==="cv"||h.labelText.trim().toLowerCase()==="curriculum vitae"||h.labelText.trim().toLowerCase()==="cover letter"||h.labelText.trim().toLowerCase()==="cover"));if(p&&!p.answer){let h=process.env.City;await Zo(e,p.labelText,h),p.answer=h}else if(m){let h=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!m.answer||m.answer!==h)&&(await w(1e4),await Zo(e,m.labelText,h),m.answer=h,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await Yl(e,c)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let u=null;try{u=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(u!==null){if(u.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:u};let p=u&&o.find(h=>h.errorMsgText&&h.labelText===u.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(u,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:u};let m=o.findIndex(h=>h.labelText===u.labelText&&!h.answer);m!==-1&&o.splice(m,1),o.push(u)}let f=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of p){let h=m.querySelectorAll("button");for(let g of h){let y=g.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return g.click(),y}}return null});f&&console.log(` Dismissed safety popup (${f})`);let d=await e.evaluate(async()=>{function p(b){let E=document.querySelector(b);if(E)return E;let R=document.querySelector("#interop-outlet")?.shadowRoot;return R?R.querySelector(b):null}function m(b){let E=document.querySelectorAll(b),R=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(b);return[...E||[],...R||[]]}let h=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(b=>b.innerText?.trim()==="Next"),g=m('footer[role="presentation"] button').some(b=>b.innerText.trim()==="Review")||m("button").some(b=>b.innerText.trim()==="Review"&&b.getAttribute("aria-label")?.includes("Review")),y=p('button[aria-label="Submit application"]'),S=async()=>{let b=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(E=>E.innerText?.trim()==="Next");b?b.click():console.log("Next button not found")},v=()=>{let b=m("button").find(E=>E.innerText?.trim()==="Review");b&&b.click()};return h?(await S(),{type:"next"}):g?(await v(),{type:"review"}):y?{type:"submit"}:{type:null}});if(d==null)return{filledFields:o,formPages:n,skip:!0};if(d.type&&console.log(` \u2192 ${d.type}`),d.type===null){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of m){let g=h.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of g){let S=y.innerText||"";if(S.includes("application was sent")||S.includes("resume into a profile")||S.includes("Application submitted")||S.includes("Next best action"))for(let v of y.querySelectorAll("button")){let b=v.innerText?.trim();if(b==="Not now"||b==="Done"||b==="Dismiss"||b==="Got it")return v.click(),b}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await w(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(s===0){let m=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],y=[];for(let S of h){for(let b of S.querySelectorAll("button")){let E=b.innerText?.trim();E&&E.length<60&&g.push(E)}let v=S.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');v&&y.push(v.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(m.buttons)}`),m.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(m.modalText)}`)}}if(d.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(u===null&&d.type===i?s++:s=0,i=d.type,s>=5){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),h=[],g=[];for(let y of m){for(let S of y.querySelectorAll(".artdeco-inline-feedback__message"))h.push(S.textContent?.trim()?.slice(0,60));for(let S of y.querySelectorAll(".fb-dash-form-element")){let v=S.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),b=S.querySelector("input, select, textarea"),E=!!S.querySelector(".artdeco-inline-feedback__message");v&&(E||b&&!b.value)&&g.push({label:v.slice(0,40),hasError:E,value:b?.value?.slice(0,20)||""})}}return{errors:h,emptyRequired:g.slice(0,5)}});return console.error(` \u26A0 Stuck on "${d.type}" for ${s} iterations \u2014 form not progressing.`),p.errors.length&&console.error(` Visible errors: ${JSON.stringify(p.errors)}`),p.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(p.emptyRequired)}`),console.error(" Skipping job."),{filledFields:o,formPages:n,skip:!0,duplicateField:{labelText:`stuck_on_${d.type}`}}}await w(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function ri(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 Kl(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 zl(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of o){for(let i of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(i.innerText?.trim()==="Done")return i.click(),"Done";let n=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let i of n){let s=i.innerText||"";if(s.includes("application was sent")||s.includes("Application sent")||s.includes("resume into a profile")||s.includes("Next best action"))for(let a of i.querySelectorAll("button")){let l=a.innerText?.trim();if(l==="Not now"||l==="Dismiss")return a.click(),l}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await w(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function Xt(e){try{await e.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let t=await e.$('button[aria-label="Dismiss"]');t?(await t.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await w(1e3)):console.log("Popup \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.")}catch{console.log("closeJobApplicationPopup failed to execute: \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D \u0438\u043B\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F.")}}async function Qo(e){try{await e.waitForSelector('button[data-control-name="discard_application_confirm_btn"]',{timeout:3e3});let t=await e.$('button[data-control-name="discard_application_confirm_btn"]');t&&(await t.click(),console.log("Discard confirmed"),await w(500))}catch{console.log("No discard confirmation needed")}}async function ci(e,t){let o=[],r=t._fromQueue;try{k.attempted++,console.log(`
297
297
  --- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&Ao(n)?.status==="applied")return k.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (our DB): ${t.jobTitle} \u2014 skipping`),{keepGoing:!0};let i=null;if(!r){let d=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name")?.innerText?.trim()?.replace(/\s+/g," ")?.toLowerCase()||""),p=(t.companyName||"").replace(/\s+/g," ").toLowerCase().trim(),m=d.split(" ")[0],h=p.split(" ")[0];if(m&&h&&!d.includes(h)&&!p.includes(m))return k.mismatch++,console.log(` \u2298 MISMATCH: expected company "${t.companyName}" but panel shows "${d}"`),console.log(` job title: "${t.jobTitle}"`),{keepGoing:!0};if(await e.evaluate(()=>{let y=document.querySelector(".jobs-details__main-content, .job-details-jobs-unified-top-card");if(!y)return!1;let S=y.innerText;return/Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago/i.test(S)||S.includes("Application submitted")}))return k.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${t.jobTitle} \u2014 skipping`),n&&Fe(n,"applied",{source:"detected"}),{keepGoing:!0};try{i=await pr(e)}catch{}}let s=await ti(e);if(s.dailyLimitReached){console.log(`
298
298
  ========================================`),console.log("LinkedIn daily application limit reached!"),console.log(`========================================
299
299
  `);let d=He("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${d.total}`),console.log(` - This session: ${to}`),console.log(` - Unprocessed: ${d.unprocessed}`),k.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:d}}if(!s.clicked)return k.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${t.jobTitle} @ ${t.companyName}`),{keepGoing:!0};await ri(e);let a=await _l();console.log(`Applying for job: ${t.id}`);let l=`### Job Information
@@ -302,20 +302,20 @@ ${r.join(`
302
302
  - **Company:** ${t.companyName}
303
303
  - **Location:** ${t.location}
304
304
  - **Salary:** ${t.salary}
305
- - **Job URL:** ${t.href}`,c=process.env.NODE_EASY_APPLY_MAIN;await Ie.addMessage(c,l,{lifebot:Qr.off});let u=await Je("Should I apply for this job? Answer only 'yes' or 'no'!!");if(Xr(),console.log(`Should I apply for ${t.jobTitle} ?? `+u),u.toLowerCase()==="no"){k.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await Xt(e),await Qo(e),await ei(e,t.id);let d=t.id?.match(/\d+/)?.[0];return ze({jobId:d,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),Fe(d,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let f=await ni(e,oi);if(f.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await ti(e)).clicked?f=await ni(e,oi):(console.log(" pressApplyButton failed on retry"),f={filledFields:[],formPages:0,skip:!0,duplicateField:{labelText:"stale_popup_retry_failed"}})),console.log(`processNavigation: pages=${f.formPages}, fields=${f.filledFields?.length||0}, skip=${f.skip}${f.dailyLimitReached?", DAILY LIMIT":""}`),f.dailyLimitReached)return console.log(" Daily limit reached \u2014 stopping"),await Xt(e),{keepGoing:!1,dailyLimitReached:!0};if(f.skip){if(await Xt(e),await Qo(e),f.duplicateField){await ei(e,t.id);let d=process.env.NODE_EASY_APPLY_ERRORS;await Ie.addMessage(d,`${t.href} failed at label ${f.duplicateField?.labelText}`,{lifebot:Qr.off})}k.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${f.duplicateField?.labelText||"form error"}`),ze({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"failed",formPages:f.formPages,failedField:f.duplicateField?.labelText||null,questions:f.filledFields||[]})}else{o=f.filledFields,o.length,await ri(e),await Kl(e),await w(2e3),await zl(e),k.submitted++,console.log(` \u2713 APPLIED: ${t.jobTitle} @ ${t.companyName} (${f.formPages} pages, ${o.length} fields)`);let d=t.id?.match(/\d+/)?.[0];if(d&&(jt(d,{title:t.jobTitle,company:t.companyName,location:t.location,salary:t.salary,url:t.href,applied:!0}),Co(d,{title:t.jobTitle,company:i?.companyName||t.companyName,companyUrl:i?.companyUrl,location:t.location,salary:t.salary,url:t.href,isEasyApply:!0,applyType:"easy-apply",applied:!0,appliedAt:new Date().toISOString().slice(0,10),description:i?.description,techStack:i?.techStack,jobTags:i?.jobTags,seniority:i?.seniority,employmentType:i?.employmentType,industries:i?.industries,jobFunction:i?.jobFunction,postedTime:i?.postedTime,applicantCount:i?.applicantCount,companySize:i?.companySize,workplaceType:i?.workplaceType,contractType:i?.contractType,aboutCompany:i?.aboutCompany}),Fe(d,"applied",{source:"easy-apply"}),i?.companyUrl&&Jt(i.companyUrl,{name:i.companyName||t.companyName,about:i.aboutCompany,size:i.companySize,industries:i.industries,jobId:d})),await Fl(e,t),ze({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:f.formPages,questions:o}),!Il())return{keepGoing:!1}}}catch(n){if(nt(n))throw console.log(`\u26A0 CDP dead during "${t.jobTitle}" \u2014 bubbling up for page recovery: ${(n.message||"").slice(0,100)}`),n;let i=li(n);if(!i)return console.log(`\u274C Unknown error \u2014 stopping: ${(n.message||"").slice(0,120)}`),console.log(n),{keepGoing:!1};if(i.severity==="fatal")return console.log(`\u274C [${i.label}] Fatal \u2014 stopping: ${(n.message||"").slice(0,120)}`),i.instructions&&console.log(` \u2192 ${i.instructions}`),i.label==="ilml-auth-expired"?k.fatalAuthExpired="ilml":i.label==="linkedin-session-expired"&&(k.fatalAuthExpired="linkedin"),{keepGoing:!1};let s=Rl(i.label);if(console.log(`\u26A0 [${i.label}] on "${t.jobTitle}" (${s}/${i.maxConsecutive} consecutive): ${(n.message||"").slice(0,120)}`),i.cleanup==="popup"){try{await Xt(e)}catch{}try{await Qo(e)}catch{}}return s>=i.maxConsecutive?(console.log(`\u274C [${i.label}] ${i.maxConsecutive} consecutive \u2014 stopping.`),i.instructions&&console.log(` \u2192 ${i.instructions}`),{keepGoing:!1}):(i.cooldownMs&&await w(i.cooldownMs),{keepGoing:!0})}return Xr(),{keepGoing:!0}}async function Ql(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL,n=[],i=0;for(;;){await Xo(e,r)&&(await oe(e),await w(2e3));try{await e.waitForSelector("li.scaffold-layout__list-item",{timeout:3e4})}catch{}await o(e);let a=await Dl(e);if(a.length===0){if(!e.url().includes("/jobs/")){if(i++,i>3){console.log(" Too many recovery attempts \u2014 LinkedIn keeps redirecting. Stopping.");break}console.log(` No jobs found but not on /jobs/ page \u2014 recovery attempt ${i}/3...`),await Xo(e,r);continue}let c=await e.evaluate(()=>({totalCards:document.querySelectorAll("li.scaffold-layout__list-item").length,hasListContainer:!!document.querySelector(".jobs-search-results-list, .scaffold-layout__list-container")}));c.totalCards===0?console.log(` \u26A0 No job cards on page (container present: ${c.hasListContainer}). Either the search returned nothing, the page never finished loading, or LinkedIn changed its markup.`):console.log(` ${c.totalCards} job card(s) on page but none are Easy Apply \u2014 nothing to apply to with this search filter.`);break}if(i=0,n.length===0){n=a;let{keepGoing:l}=await Zr(e,a,t);if(!l)return{keepGoing:!1,jobsDone:n}}else{let l=a.filter(u=>!n.some(f=>f.id===u.id));if(console.log(` New jobs on page: ${l.length} (page: ${a.length}, total seen: ${n.length})`),l.length===0)break;let{keepGoing:c}=await Zr(e,l,t);if(n=[...n,...l],!c)return{keepGoing:!1,jobsDone:n}}}return console.log(` All jobs processed. Total: ${n.length}`),{keepGoing:!0,jobsDone:n}}var k={attempted:0,submitted:0,skippedByLifebot:0,failed:0,mismatch:0,alreadyApplied:0,expired:0,noApplyButton:0,dailyLimitHit:!1,cdpRecoveries:0,browserRestarts:0,fatalAuthExpired:null};(async()=>{let e=process.argv.find(l=>l.startsWith("--job-urls=")),t=_r("apply",e?"queue":"search"),o=null,r=null,n=[],i=async()=>(await Wo(zr,{devtools:!1})).browser,s=async l=>{await l.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},a=()=>Kt();try{let l=await Wo(zr,{devtools:!1});o=l.browser;let c=await o.newPage();await s(c),await Hr(c,l);let u=process.argv.find($=>$.startsWith("--job-urls=")),f=u?u.split("=").slice(1).join("=").replace(/^@/,""):null,d=process.env.LINKEDIN_SEARCH_URL,p=f?"https://www.linkedin.com/feed/":d;try{await c.goto(p,{waitUntil:"domcontentloaded",timeout:6e4})}catch($){console.error("\u274C Navigation error:",$.message),console.log("Trying to continue anyway..."),await w(5e3)}let m=c.url();if(/\/login|\/checkpoint|\/authwall|\/uas\/login/.test(m))throw new Error("Not logged in (or session expired). Run: ilml linkedin login");console.log("\u2713 Logged in to LinkedIn.");let h=He("recruiters-from-jobs");h.total>0&&console.log(`
305
+ - **Job URL:** ${t.href}`,c=process.env.NODE_EASY_APPLY_MAIN;await Ie.addMessage(c,l,{lifebot:Qr.off});let u=await Je("Should I apply for this job? Answer only 'yes' or 'no'!!");if(Xr(),console.log(`Should I apply for ${t.jobTitle} ?? `+u),u.toLowerCase()==="no"){k.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await Xt(e),await Qo(e),await ei(e,t.id);let d=t.id?.match(/\d+/)?.[0];return ze({jobId:d,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),Fe(d,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let f=await ni(e,oi);if(f.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await ti(e)).clicked?f=await ni(e,oi):(console.log(" pressApplyButton failed on retry"),f={filledFields:[],formPages:0,skip:!0,duplicateField:{labelText:"stale_popup_retry_failed"}})),console.log(`processNavigation: pages=${f.formPages}, fields=${f.filledFields?.length||0}, skip=${f.skip}${f.dailyLimitReached?", DAILY LIMIT":""}`),f.dailyLimitReached)return console.log(" Daily limit reached \u2014 stopping"),await Xt(e),{keepGoing:!1,dailyLimitReached:!0};if(f.skip){if(await Xt(e),await Qo(e),f.duplicateField){await ei(e,t.id);let d=process.env.NODE_EASY_APPLY_ERRORS;await Ie.addMessage(d,`${t.href} failed at label ${f.duplicateField?.labelText}`,{lifebot:Qr.off})}k.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${f.duplicateField?.labelText||"form error"}`),ze({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"failed",formPages:f.formPages,failedField:f.duplicateField?.labelText||null,questions:f.filledFields||[]})}else{o=f.filledFields,o.length,await ri(e),await Kl(e),await w(2e3),await zl(e),k.submitted++,console.log(` \u2713 APPLIED: ${t.jobTitle} @ ${t.companyName} (${f.formPages} pages, ${o.length} fields)`);let d=t.id?.match(/\d+/)?.[0];if(d&&(Dt(d,{title:t.jobTitle,company:t.companyName,location:t.location,salary:t.salary,url:t.href,applied:!0}),Co(d,{title:t.jobTitle,company:i?.companyName||t.companyName,companyUrl:i?.companyUrl,location:t.location,salary:t.salary,url:t.href,isEasyApply:!0,applyType:"easy-apply",applied:!0,appliedAt:new Date().toISOString().slice(0,10),description:i?.description,techStack:i?.techStack,jobTags:i?.jobTags,seniority:i?.seniority,employmentType:i?.employmentType,industries:i?.industries,jobFunction:i?.jobFunction,postedTime:i?.postedTime,applicantCount:i?.applicantCount,companySize:i?.companySize,workplaceType:i?.workplaceType,contractType:i?.contractType,aboutCompany:i?.aboutCompany}),Fe(d,"applied",{source:"easy-apply"}),i?.companyUrl&&Jt(i.companyUrl,{name:i.companyName||t.companyName,about:i.aboutCompany,size:i.companySize,industries:i.industries,jobId:d})),await Fl(e,t),ze({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:f.formPages,questions:o}),!Il())return{keepGoing:!1}}}catch(n){if(nt(n))throw console.log(`\u26A0 CDP dead during "${t.jobTitle}" \u2014 bubbling up for page recovery: ${(n.message||"").slice(0,100)}`),n;let i=li(n);if(!i)return console.log(`\u274C Unknown error \u2014 stopping: ${(n.message||"").slice(0,120)}`),console.log(n),{keepGoing:!1};if(i.severity==="fatal")return console.log(`\u274C [${i.label}] Fatal \u2014 stopping: ${(n.message||"").slice(0,120)}`),i.instructions&&console.log(` \u2192 ${i.instructions}`),i.label==="ilml-auth-expired"?k.fatalAuthExpired="ilml":i.label==="linkedin-session-expired"&&(k.fatalAuthExpired="linkedin"),{keepGoing:!1};let s=Rl(i.label);if(console.log(`\u26A0 [${i.label}] on "${t.jobTitle}" (${s}/${i.maxConsecutive} consecutive): ${(n.message||"").slice(0,120)}`),i.cleanup==="popup"){try{await Xt(e)}catch{}try{await Qo(e)}catch{}}return s>=i.maxConsecutive?(console.log(`\u274C [${i.label}] ${i.maxConsecutive} consecutive \u2014 stopping.`),i.instructions&&console.log(` \u2192 ${i.instructions}`),{keepGoing:!1}):(i.cooldownMs&&await w(i.cooldownMs),{keepGoing:!0})}return Xr(),{keepGoing:!0}}async function Ql(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL,n=[],i=0;for(;;){await Xo(e,r)&&(await oe(e),await w(2e3));try{await e.waitForSelector("li.scaffold-layout__list-item",{timeout:3e4})}catch{}await o(e);let a=await jl(e);if(a.length===0){if(!e.url().includes("/jobs/")){if(i++,i>3){console.log(" Too many recovery attempts \u2014 LinkedIn keeps redirecting. Stopping.");break}console.log(` No jobs found but not on /jobs/ page \u2014 recovery attempt ${i}/3...`),await Xo(e,r);continue}let c=await e.evaluate(()=>({totalCards:document.querySelectorAll("li.scaffold-layout__list-item").length,hasListContainer:!!document.querySelector(".jobs-search-results-list, .scaffold-layout__list-container")}));c.totalCards===0?console.log(` \u26A0 No job cards on page (container present: ${c.hasListContainer}). Either the search returned nothing, the page never finished loading, or LinkedIn changed its markup.`):console.log(` ${c.totalCards} job card(s) on page but none are Easy Apply \u2014 nothing to apply to with this search filter.`);break}if(i=0,n.length===0){n=a;let{keepGoing:l}=await Zr(e,a,t);if(!l)return{keepGoing:!1,jobsDone:n}}else{let l=a.filter(u=>!n.some(f=>f.id===u.id));if(console.log(` New jobs on page: ${l.length} (page: ${a.length}, total seen: ${n.length})`),l.length===0)break;let{keepGoing:c}=await Zr(e,l,t);if(n=[...n,...l],!c)return{keepGoing:!1,jobsDone:n}}}return console.log(` All jobs processed. Total: ${n.length}`),{keepGoing:!0,jobsDone:n}}var k={attempted:0,submitted:0,skippedByLifebot:0,failed:0,mismatch:0,alreadyApplied:0,expired:0,noApplyButton:0,dailyLimitHit:!1,cdpRecoveries:0,browserRestarts:0,fatalAuthExpired:null};(async()=>{let e=process.argv.find(l=>l.startsWith("--job-urls=")),t=_r("apply",e?"queue":"search"),o=null,r=null,n=[],i=async()=>(await Wo(zr,{devtools:!1})).browser,s=async l=>{await l.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},a=()=>Kt();try{let l=await Wo(zr,{devtools:!1});o=l.browser;let c=await o.newPage();await s(c),await Hr(c,l);let u=process.argv.find($=>$.startsWith("--job-urls=")),f=u?u.split("=").slice(1).join("=").replace(/^@/,""):null,d=process.env.LINKEDIN_SEARCH_URL,p=f?"https://www.linkedin.com/feed/":d;try{await c.goto(p,{waitUntil:"domcontentloaded",timeout:6e4})}catch($){console.error("\u274C Navigation error:",$.message),console.log("Trying to continue anyway..."),await w(5e3)}let m=c.url();if(/\/login|\/checkpoint|\/authwall|\/uas\/login/.test(m))throw new Error("Not logged in (or session expired). Run: ilml linkedin login");console.log("\u2713 Logged in to LinkedIn.");let h=He("recruiters-from-jobs");h.total>0&&console.log(`
306
306
  \u{1F4C2} Existing recruiters for today: ${h.total} (${h.unprocessed} unprocessed)
307
307
  `),await w(2e3);let g={page:c,browser:o,recoveryCtx:{searchUrl:d,launchFn:i,setupPage:s,cookiesProvider:a}},y=!1;if(f)try{let $=JSON.parse(ii.readFileSync(f,"utf-8"));console.log(`
308
308
  \u{1F4CB} Queue mode: ${$.length} jobs from ${f}
309
309
  `);for(let W=0;W<$.length;W++){let N=typeof $[W]=="string"?{url:$[W]}:$[W],q=N.url,G=N.title||"Unknown",x=N.company||"";console.log(`
310
- [${W+1}/${$.length}] ${G} @ ${x}`),console.log(` ${q}`),c=g.page,o=g.browser;try{let D=q.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await c.goto(q,{waitUntil:"domcontentloaded",timeout:6e4}),await w(8e3);let P=await c.evaluate(()=>{let fe=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:fe.includes("Application submitted"),noLongerAccepting:fe.includes("No longer accepting applications")}});if(P.alreadyApplied){console.log(" Already applied \u2014 skipping"),k.alreadyApplied++,Fe(D,"applied",{applyMethod:"detected"});continue}if(P.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),k.expired++,Fe(D,"expired",{reason:"no_longer_accepting"});continue}if(!P.hasApply){console.log(" No Easy Apply button \u2014 skipping"),k.noApplyButton++;continue}let B={id:`/jobs/view/${D}/`,href:q,jobTitle:G,companyName:x,location:N.location||"",salary:N.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let J=await ci(c,B);if(console.log(` Result: keepGoing=${J.keepGoing}, reason=${J.dailyLimitReached?"daily_limit":"ok"}`),!J.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),y=!0;break}}catch(D){if(nt(D))try{await Zt(g,`queue job ${W+1}: ${D.message?.slice(0,80)}`),c=g.page,o=g.browser}catch(P){console.error(`\u274C Queue mode: CDP recovery failed: ${P.message}`),console.error(" Aborting queue, falling back to standard search if possible.");break}else{let P=li(D);if(P?.severity==="fatal"){console.error(`\u274C [${P.label}] Fatal \u2014 stopping queue: ${(D.message||"").slice(0,120)}`),P.instructions&&console.error(` \u2192 ${P.instructions}`),P.label==="ilml-auth-expired"?k.fatalAuthExpired="ilml":P.label==="linkedin-session-expired"&&(k.fatalAuthExpired="linkedin");break}console.error(` Error: ${D.message?.slice(0,80)}`)}}}console.log(`
310
+ [${W+1}/${$.length}] ${G} @ ${x}`),console.log(` ${q}`),c=g.page,o=g.browser;try{let j=q.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await c.goto(q,{waitUntil:"domcontentloaded",timeout:6e4}),await w(8e3);let P=await c.evaluate(()=>{let fe=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:fe.includes("Application submitted"),noLongerAccepting:fe.includes("No longer accepting applications")}});if(P.alreadyApplied){console.log(" Already applied \u2014 skipping"),k.alreadyApplied++,Fe(j,"applied",{applyMethod:"detected"});continue}if(P.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),k.expired++,Fe(j,"expired",{reason:"no_longer_accepting"});continue}if(!P.hasApply){console.log(" No Easy Apply button \u2014 skipping"),k.noApplyButton++;continue}let B={id:`/jobs/view/${j}/`,href:q,jobTitle:G,companyName:x,location:N.location||"",salary:N.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let J=await ci(c,B);if(console.log(` Result: keepGoing=${J.keepGoing}, reason=${J.dailyLimitReached?"daily_limit":"ok"}`),!J.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),y=!0;break}}catch(j){if(nt(j))try{await Zt(g,`queue job ${W+1}: ${j.message?.slice(0,80)}`),c=g.page,o=g.browser}catch(P){console.error(`\u274C Queue mode: CDP recovery failed: ${P.message}`),console.error(" Aborting queue, falling back to standard search if possible.");break}else{let P=li(j);if(P?.severity==="fatal"){console.error(`\u274C [${P.label}] Fatal \u2014 stopping queue: ${(j.message||"").slice(0,120)}`),P.instructions&&console.error(` \u2192 ${P.instructions}`),P.label==="ilml-auth-expired"?k.fatalAuthExpired="ilml":P.label==="linkedin-session-expired"&&(k.fatalAuthExpired="linkedin");break}console.error(` Error: ${j.message?.slice(0,80)}`)}}}console.log(`
311
311
  Queue complete. ${y?"Daily limit hit.":"Continuing to search..."}`)}catch($){console.error(`Failed to read job URLs file: ${$.message}`)}if(!y){if(f){console.log(`
312
312
  Queue done. Continuing with standard search...`);try{await c.goto(d,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3)}catch($){console.error(" Navigation to search failed:",$.message)}}g.page=c,g.browser=o;try{await Pl(g)}catch($){nt($)||/CDP unrecoverable/.test($.message||"")?(console.error(`
313
313
  \u274C Apply phase ended: CDP channel could not be recovered after ${k.cdpRecoveries} page recoveries and ${k.browserRestarts} browser restarts.`),console.error(` Last error: ${$.message}`)):/Session expired/i.test($.message||"")?(console.error(`
314
314
  \u274C Apply phase ended: ${$.message}`),r=$):console.error(`
315
315
  \u26A0 Apply phase crashed: ${$.message}`)}c=g.page,o=g.browser}let S=k.submitted+k.skippedByLifebot+k.failed+k.mismatch+k.alreadyApplied+k.expired+k.noApplyButton,v=k.attempted-S,b=He("recruiters-from-jobs");n.push(`Jobs attempted: ${k.attempted}`),n.push(`Successfully applied: ${k.submitted}`),n.push(`Skipped by Lifebot: ${k.skippedByLifebot}`),n.push(`Failed (form errors): ${k.failed}`),k.mismatch>0&&n.push(`Mismatch (wrong panel): ${k.mismatch}`),k.alreadyApplied>0&&n.push(`Already applied: ${k.alreadyApplied}`),k.expired>0&&n.push(`Expired (closed): ${k.expired}`),k.noApplyButton>0&&n.push(`No Apply button: ${k.noApplyButton}`),v>0&&n.push(`Unaccounted: ${v}`),n.push(`Daily limit reached: ${k.dailyLimitHit?"Yes":"No"}`),k.cdpRecoveries>0&&n.push(`Page recoveries (CDP): ${k.cdpRecoveries}`),k.browserRestarts>0&&n.push(`Browser restarts: ${k.browserRestarts}`),n.push(`Recruiters found: ${to}`),n.push(`Recruiters total: ${b.total} (${b.unprocessed} unprocessed)`),console.log(`
316
316
  \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 E=!!o&&o.isConnected?.()!==!1,R=Cl?E?k.fatalAuthExpired==="linkedin"?"LinkedIn session expired (run: ilml linkedin login)":k.fatalAuthExpired==="ilml"?"iLiveMyLife token expired (run: ilml login)":null:"browser is not in a usable state":"recruiter auto-connect is disabled (FUNNEL_CONNECT_RECRUITERS=false)",I=!R;I||(console.log(`
317
- \u26A0 Skipping recruiter funnel \u2014 ${R}.`),console.log(` ${b.unprocessed} recruiters saved for next run.`),n.push(`Funnel: skipped (${R})`));let{markProfileProcessed:O}=await Promise.resolve().then(()=>(so(),pn)),{canSendConnection:A,getQuotaStatus:T}=await Qe().then(()=>jn),Y=()=>({message:$l,useCustomMessage:El,maxConnections:Al,excludeLocations:Yo,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async($,W,N)=>{O("recruiters-from-jobs",$.profileUrl,{status:N.reason,connectionSent:N.connectionSent,withCustomMessage:N.withCustomMessage,message:N.messageSent,method:N.method,reason:N.reason,error:N.error,profileInfo:N.profileInfo},$._fromDate||null)}});if(I&&b.unprocessed>0){console.log(`
318
- --- Funnel: today's recruiters (${b.unprocessed}) ---`),Yo.length>0&&console.log(` Excluding locations: ${Yo.join(", ")}`);let $=$t("recruiters-from-jobs");await jo(c,$,Y())}let K=A();if(I&&K.allowed){let $=_t("recruiters-from-jobs"),W=new Date().toISOString().split("T")[0],N=$.filter(q=>q._fromDate!==W);if(N.length>0){let q=T();console.log(`
319
- --- Funnel: backfill from previous days (${N.length} unprocessed) ---`),console.log(` Quota remaining: ${q.daily.remaining} today, ${q.weekly.remaining} this week`),await jo(c,N,{...Y(),maxConnections:q.daily.remaining})}}let M=T();console.log(`
317
+ \u26A0 Skipping recruiter funnel \u2014 ${R}.`),console.log(` ${b.unprocessed} recruiters saved for next run.`),n.push(`Funnel: skipped (${R})`));let{markProfileProcessed:O}=await Promise.resolve().then(()=>(so(),pn)),{canSendConnection:A,getQuotaStatus:T}=await Qe().then(()=>Dn),Y=()=>({message:$l,useCustomMessage:El,maxConnections:Al,excludeLocations:Yo,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async($,W,N)=>{O("recruiters-from-jobs",$.profileUrl,{status:N.reason,connectionSent:N.connectionSent,withCustomMessage:N.withCustomMessage,message:N.messageSent,method:N.method,reason:N.reason,error:N.error,profileInfo:N.profileInfo},$._fromDate||null)}});if(I&&b.unprocessed>0){console.log(`
318
+ --- Funnel: today's recruiters (${b.unprocessed}) ---`),Yo.length>0&&console.log(` Excluding locations: ${Yo.join(", ")}`);let $=$t("recruiters-from-jobs");await Do(c,$,Y())}let K=A();if(I&&K.allowed){let $=_t("recruiters-from-jobs"),W=new Date().toISOString().split("T")[0],N=$.filter(q=>q._fromDate!==W);if(N.length>0){let q=T();console.log(`
319
+ --- Funnel: backfill from previous days (${N.length} unprocessed) ---`),console.log(` Quota remaining: ${q.daily.remaining} today, ${q.weekly.remaining} this week`),await Do(c,N,{...Y(),maxConnections:q.daily.remaining})}}let M=T();console.log(`
320
320
  \u2705 Funnel done. Connection quota left: ${M.daily.remaining} of ${M.daily.max} today, ${M.weekly.remaining} of ${M.weekly.max} this week`),n.push(`Connection quota left: ${M.daily.remaining} of ${M.daily.max} today, ${M.weekly.remaining} of ${M.weekly.max} week`)}catch(l){r=l,console.error(`
321
321
  \u274C Apply session ended with error: ${l.message}`),l.stack&&console.error(l.stack)}Tr(t,r?"error":"success",{summaryLines:n,dailyLimitHit:k.dailyLimitHit,attempted:k.attempted,submitted:k.submitted,failed:k.failed,skippedByLifebot:k.skippedByLifebot},r?r.message:null);try{await o?.close()}catch{}r&&process.exit(1)})();