ilml-plugin-linkedin 1.2.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/run.mjs CHANGED
@@ -1,50 +1,50 @@
1
- var Oo=Object.defineProperty;var it=(t,e)=>()=>(t&&(e=t(t=0)),e);var lt=(t,e)=>{for(var n in e)Oo(t,n,{get:e[n],enumerable:!0})};var Ht={};lt(Ht,{default:()=>Yo,getAllUnprocessedProfiles:()=>Pe,getSummary:()=>ue,getUnprocessedProfiles:()=>Ne,listFiles:()=>Gt,loadProfiles:()=>Me,markProfileProcessed:()=>Jt,saveProfile:()=>we,saveProfiles:()=>Bt});import"dotenv/config";import*as A from"fs";import*as B from"path";import{fileURLToPath as Go}from"url";function ge(){A.existsSync(V)||A.mkdirSync(V,{recursive:!0})}function Wo(t,e){try{let n=`${t}-${ct()}.json`,r=A.readdirSync(V).filter(s=>s.startsWith(t)&&s.endsWith(".json")&&s!==n),o=0;for(let s of r)JSON.parse(A.readFileSync(B.join(V,s),"utf-8")).profiles?.some(a=>a.profileUrl===e)&&o++;return o}catch{return 0}}function ct(){return new Date().toISOString().split("T")[0]}function ut(t,e=null){let n=e||ct();return B.join(V,`${t}-${n}.json`)}function Me(t,e=null){ge();let n=ut(t,e);try{if(A.existsSync(n)){let r=A.readFileSync(n,"utf-8"),o=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${o.profiles.length} profiles from ${n}`),o.profiles}}catch(r){console.error(`Error loading profiles from ${n}:`,r.message)}return[]}function we(t,e){ge();let n=ut(t),r={source:t,date:ct(),lastUpdated:new Date().toISOString(),profiles:[]};try{A.existsSync(n)&&(r=JSON.parse(A.readFileSync(n,"utf-8")))}catch(l){console.error(`Error reading ${n}:`,l.message)}if(r.profiles.some(l=>l.profileUrl===e.profileUrl))return!1;let s=Wo(t,e.profileUrl);r.profiles.push({...e,collectedAt:new Date().toISOString(),seenBefore:s}),r.lastUpdated=new Date().toISOString();try{A.writeFileSync(n,JSON.stringify(r,null,2));let l=s>0?` (seen ${s} day${s>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${e.name||e.profileUrl}${l} (total: ${r.profiles.length})`),!0}catch(l){return console.error(`Error saving to ${n}:`,l.message),!1}}function Bt(t,e){let n=0;for(let r of e)we(t,r)&&n++;return n}function Ne(t,e=null){return Me(t,e).filter(r=>!r.processed)}function Jt(t,e,n,r=null){ge();let o=ut(t,r);try{if(!A.existsSync(o))return;let s=JSON.parse(A.readFileSync(o,"utf-8")),l=s.profiles.find(a=>a.profileUrl===e);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof n=="string")l.status=n;else if(typeof n=="object"){if(l.status=n.status,n.profileInfo){let a=n.profileInfo;a.name&&(l.name=a.name),a.title&&(l.title=a.title),a.location&&(l.location=a.location),a.company&&(l.company=a.company),a.connectionDegree&&(l.connectionDegree=a.connectionDegree),a.connectionsCount&&(l.connectionsCount=a.connectionsCount),a.mutualConnections&&(l.mutualConnections=a.mutualConnections),a.photoUrl&&(l.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=a.hasVerifiedBadge)}l.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}s.lastUpdated=new Date().toISOString(),A.writeFileSync(o,JSON.stringify(s,null,2))}}catch(s){console.error("Error marking profile processed:",s.message)}}function ue(t){let e=Me(t),n=e.filter(o=>o.processed),r=e.filter(o=>!o.processed);return{total:e.length,processed:n.length,unprocessed:r.length,statuses:n.reduce((o,s)=>(o[s.status]=(o[s.status]||0)+1,o),{})}}function Gt(){ge();try{return A.readdirSync(V).filter(e=>e.endsWith(".json")).map(e=>{let[n,r]=e.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let o=JSON.parse(A.readFileSync(B.join(V,e),"utf-8"));return{file:e,source:n,date:r,count:o.profiles?.length||0,unprocessed:o.profiles?.filter(s=>!s.processed).length||0}}catch{return{file:e,source:n,date:r,count:0,unprocessed:0}}})}catch(t){return console.error("Error listing files:",t.message),[]}}function Pe(t){ge();let e=[];try{let o=A.readdirSync(V).filter(s=>s.startsWith(t+"-")&&s.endsWith(".json")).sort().reverse();for(let s of o)try{let l=JSON.parse(A.readFileSync(B.join(V,s),"utf-8"));l.profiles&&e.push({file:s,date:l.date,profiles:l.profiles})}catch{}}catch{return[]}let n=new Set,r=[];for(let{date:o,profiles:s}of e)for(let l of s)!l.processed&&l.profileUrl&&!n.has(l.profileUrl)&&(n.add(l.profileUrl),r.push({...l,_fromDate:o}));return r}var Ho,Vo,V,Yo,dt=it(()=>{Ho=Go(import.meta.url),Vo=B.dirname(B.dirname(Ho)),V=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Vo,"collected-profiles");Yo={loadProfiles:Me,saveProfile:we,saveProfiles:Bt,getUnprocessedProfiles:Ne,getAllUnprocessedProfiles:Pe,markProfileProcessed:Jt,getSummary:ue,listFiles:Gt}});var wt={};lt(wt,{addEncounter:()=>ye,canSendConnection:()=>ze,commitDataSnapshot:()=>oo,default:()=>on,getAllApplications:()=>eo,getPersonStatus:()=>He,getQuestionStats:()=>to,getQuotaStatus:()=>Ce,getRecentConnections:()=>Qe,linkPersonToJob:()=>Ge,loadApplicationQuestions:()=>gt,loadConversations:()=>Yt,loadJobs:()=>Ue,loadPeople:()=>Q,loadQuota:()=>We,loadSyncState:()=>Kt,logApplicationQuestions:()=>be,migrateFromDailyFiles:()=>zt,recordConnectionSent:()=>Ye,resetCaches:()=>Xo,saveConversations:()=>Qt,saveJobs:()=>Be,savePeople:()=>ne,saveQuota:()=>ht,saveSyncState:()=>Xt,updateConnectionStatus:()=>Ve,upsertJob:()=>Je,upsertPerson:()=>xe});import"dotenv/config";import*as E from"fs";import*as j from"path";import{fileURLToPath as Qo}from"url";import{execSync as pt}from"child_process";function Xo(){de=null,pe=null,W=null,te=null,fe=null,ee=null}function N(){E.existsSync(M)||E.mkdirSync(M,{recursive:!0})}function oe(t,e){let n=JSON.stringify(e,null,2),r=t+".tmp";E.writeFileSync(r,n);for(let o=0;o<3;o++)try{E.renameSync(r,t);return}catch(s){if(o<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function ve(t,e){if(!E.existsSync(t))return null;try{let n=JSON.parse(E.readFileSync(t,"utf-8"));try{E.copyFileSync(t,t+".backup")}catch{}return n}catch(n){console.error(`[!] ${e} is corrupted: ${n.message}`),console.error(` File: ${j.resolve(t)}`);let r=t+".backup";if(E.existsSync(r))try{let o=JSON.parse(E.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{E.copyFileSync(r,t)}catch{}return o}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${t}.corrupted`);try{E.copyFileSync(t,t+".corrupted")}catch{}return null}}function me(){return new Date().toISOString().split("T")[0]}function Q(){return de||(N(),de=ve(ft,"people.json")||{},de)}function ne(t){N(),de=t;try{oe(ft,t)}catch(e){console.error(`[!] Failed to save people.json: ${e.message}`),console.error(` Path: ${j.resolve(ft)}`)}}function Ue(){return pe||(N(),pe=ve(mt,"jobs.json")||{},pe)}function Be(t){N(),pe=t;try{oe(mt,t)}catch(e){console.error(`[!] Failed to save jobs.json: ${e.message}`),console.error(` Path: ${j.resolve(mt)}`)}}function Yt(){return te||(N(),te=ve(Oe,"conversations.json")||{},Zo(te),te)}function Zo(t){let e=0;for(let n of Object.values(t)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let o=(n.messages||[]).find(s=>s.status==="draft");o&&n.draftStatus&&n.draftStatus!=="pending"&&(o.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,e++}if(e>0){console.log(` [migration] Moved draft state from conv to msg.status for ${e} conversations`);try{oe(Oe,t)}catch{}}}function Qt(t){N(),te=t;try{oe(Oe,t)}catch(e){console.error(`[!] Failed to save conversations.json: ${e.message}`),console.error(` Path: ${j.resolve(Oe)}`)}}function xe(t,e={}){if(!t)return null;let n=Q(),r=me(),o=new Date().toISOString(),s=n[t];if(s){s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=o,e.source&&!s.sources?.includes(e.source)&&(s.sources=s.sources||[],s.sources.push(e.source));for(let l of bt)e[l]!=null&&(s[l]=e[l])}else n[t]={name:e.name||null,title:e.title||null,location:e.location||null,company:e.company||null,connectionDegree:e.connectionDegree||null,connectionsCount:e.connectionsCount||null,mutualConnections:e.mutualConnections||null,photoUrl:e.photoUrl||null,hasVerifiedBadge:e.hasVerifiedBadge||!1,firstSeen:r,lastSeen:r,seenCount:1,sources:e.source?[e.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:o};return ne(n),n[t]}function Je(t,e={}){if(!t)return null;let n=Ue(),r=me(),o=n[t];if(o){let s=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let l of s)e[l]!=null&&(o[l]=e[l])}else n[t]={title:e.title||null,company:e.company||null,location:e.location||null,salary:e.salary||null,url:e.url||null,applied:e.applied||!1,appliedDate:e.appliedDate||r,recruiterUrl:e.recruiterUrl||null,firstSeen:r};return Be(n),n[t]}function Ge(t,e){if(!t||!e)return;let n=Q(),r=n[t];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(e)||(r.jobIds.push(e),r.lastUpdated=new Date().toISOString(),ne(n)))}function ye(t,e){if(!t||!e)return;let n=Q(),r=n[t];if(!r)return;r.encounters||(r.encounters=[]);let s={date:me(),source:e.source||"unknown",action:e.action||"unknown"};e.jobId&&(s.jobId=String(e.jobId)),e.jobTitle&&(s.jobTitle=e.jobTitle),e.jobCompany&&(s.jobCompany=e.jobCompany),!r.encounters.some(a=>a.date===s.date&&a.source===s.source&&a.action===s.action&&(a.jobId||"")===(s.jobId||""))&&(r.encounters.push(s),r.lastUpdated=new Date().toISOString(),ne(n))}function He(t){return t&&Q()[t]?.connectionStatus||null}function Ve(t,e,n={}){if(!t)return;let r=Q(),o=r[t];if(o||(xe(t,n.profileInfo||{}),o=r[t]),!!o){if(o.connectionStatus=e,o.connectionDate=me(),o.connectionMethod=n.method||o.connectionMethod,o.messageSent=n.messageSent||o.messageSent,o.lastUpdated=new Date().toISOString(),n.profileInfo)for(let s of bt)n.profileInfo[s]!=null&&(o[s]=n.profileInfo[s]);ne(r)}}function We(){return W||(N(),W=ve(Vt,"quota.json"),(!W||!W.connections)&&(W={connections:[]}),W)}function ht(t){N(),W=t;try{oe(Vt,t)}catch(e){console.error(`[!] Failed to save quota.json: ${e.message}`)}}function Ye(t,e="unknown"){let n=We(),r=new Date;n.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:t,source:e}),ht(n)}function Qe(){let t=We(),e=new Date;e.setDate(e.getDate()-7);let n=e.toISOString().split("T")[0];return t.connections.filter(r=>r.date>=n)}function ze(){let t=Qe(),e=me(),n=t.filter(i=>i.date===e).length,r=t.length,o=n>=Se,s=r>=ke,l=!o&&!s,a={allowed:l,daily:{sent:n,max:Se},weekly:{sent:r,max:ke}};return l||(a.reason=o?`Daily limit reached (${n}/${Se})`:`Weekly limit reached (${r}/${ke})`),a}function Ce(){let t=Qe(),e=me(),n=t.filter(o=>o.date===e).length,r=t.length;return{daily:{sent:n,max:Se,remaining:Se-n},weekly:{sent:r,max:ke,remaining:ke-r}}}function en(t){if(!t)return null;let e=t.match(/jobs\/view\/(\d+)/);return e?e[1]:null}function zt(){N();let t=E.readdirSync(M).filter(s=>s.endsWith(".json")&&s!=="people.json"&&s!=="jobs.json"&&s!=="quota.json");if(t.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
2
- Migrating from ${t.length} daily files...
3
- `);let e=Q(),n=Ue(),r=0,o=0;t.sort();for(let s of t){let l=j.join(M,s),a;try{a=JSON.parse(E.readFileSync(l,"utf-8"))}catch(p){console.log(` Skipping ${s}: ${p.message}`);continue}let i=a.date||s.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,u=a.source||s.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!a.profiles||!Array.isArray(a.profiles)){console.log(` Skipping ${s}: no profiles array`);continue}console.log(` ${s}: ${a.profiles.length} profiles`);for(let p of a.profiles){let f=p.profileUrl;if(!f)continue;let c=e[f];if(c){c.seenCount=(c.seenCount||1)+1,i&&(!c.lastSeen||i>c.lastSeen)&&(c.lastSeen=i),i&&(!c.firstSeen||i<c.firstSeen)&&(c.firstSeen=i),u&&!c.sources?.includes(u)&&(c.sources=c.sources||[],c.sources.push(u));for(let d of bt)p[d]!=null&&(c[d]=p[d]);p.status&&p.processed&&(c.connectionStatus=p.status,c.connectionDate=i,p.funnelResult&&(c.connectionMethod=p.funnelResult.method||c.connectionMethod,c.messageSent=p.funnelResult.message||c.messageSent)),c.lastUpdated=new Date().toISOString()}else e[f]={name:p.name||null,title:p.title||null,location:p.location||null,company:p.company||null,connectionDegree:p.connectionDegree||null,connectionsCount:p.connectionsCount||null,mutualConnections:p.mutualConnections||null,photoUrl:p.photoUrl||null,hasVerifiedBadge:p.hasVerifiedBadge||!1,firstSeen:i,lastSeen:i,seenCount:1,sources:u?[u]:[],connectionStatus:p.processed&&p.status||null,connectionDate:p.processed?i:null,connectionMethod:p.funnelResult?.method||null,messageSent:p.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(p.fromJob?.url){let d=en(p.fromJob.url);d&&(e[f].jobIds||(e[f].jobIds=[]),e[f].jobIds.includes(d)||e[f].jobIds.push(d),n[d]?n[d].recruiterUrl||(n[d].recruiterUrl=f):(n[d]={title:p.fromJob.title||null,company:p.fromJob.company||null,location:null,salary:null,url:p.fromJob.url,applied:!0,appliedDate:i,recruiterUrl:f,firstSeen:i},o++))}}}return ne(e),Be(n),console.log(`
4
- Migration complete!`),console.log(` People: ${Object.keys(e).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(n).length} total (${o} new)`),{people:Object.keys(e).length,jobs:Object.keys(n).length}}function Kt(){return fe||(N(),fe=ve(Wt,"sync-state.json")||{},fe)}function Xt(t){N(),fe=t;try{oe(Wt,t)}catch(e){console.error(`[!] Failed to save sync-state.json: ${e.message}`)}}function gt(){if(ee)return ee;N();try{E.existsSync(yt)&&(ee=JSON.parse(E.readFileSync(yt,"utf-8")))}catch{}return ee||(ee={}),ee}function Zt(t){return Array.isArray(t.applications)}function eo(){let t=gt();if(Zt(t))return t.applications;let e=[];for(let n of Object.values(t))n.applications&&e.push(...n.applications);return e}function be(t){if(!t||!t.questions||t.questions.length===0)return;let e=gt(),n=t.jobId||"unknown",o={applicationId:`${n}_${Date.now()}`,date:new Date().toISOString(),result:t.result||"submitted",formPages:t.formPages||null,duration:t.duration||null,retries:t.retries||0,failedField:t.failedField||null,questionCount:t.questions.length,questions:t.questions.map(s=>{let l={type:s.type||"input",question:s.labelText||s.question||"",answer:s.answer||""};return s.options&&(s.options.length<=tn?l.options=s.options:l.optionsOmitted=!0),s.page&&(l.page=s.page),s.wasPreFilled&&(l.wasPreFilled=!0),s.wasRetry&&(l.wasRetry=!0),l})};Zt(e)?(o.jobId=n,o.jobTitle=t.jobTitle||null,o.jobCompany=t.jobCompany||null,o.jobUrl=t.jobUrl||null,e.applications.push(o)):(e[n]||(e[n]={applications:[]}),e[n].applications.push(o));try{oe(yt,e)}catch(s){console.error(`[!] Failed to save application-questions.json: ${s.message}`)}}function to(){let t=eo(),e=new Map;for(let s of t)for(let l of s.questions||[]){let a=l.question.toLowerCase().trim();if(!a)continue;e.has(a)||e.set(a,{question:l.question,count:0,answers:new Map});let i=e.get(a);i.count++;let u=(l.answer||"").trim();i.answers.set(u,(i.answers.get(u)||0)+1)}let n=[...e.values()].sort((s,l)=>l.count-s.count),r=n.slice(0,15).map(s=>({question:s.question,count:s.count,topAnswer:[...s.answers.entries()].sort((l,a)=>a[1]-l[1])[0]?.[0]||""})),o=n.filter(s=>s.answers.size>1&&s.count>=3).map(s=>({question:s.question,count:s.count,answers:[...s.answers.entries()].sort((l,a)=>a[1]-l[1]).map(([l,a])=>`${l} (${a}x)`)}));return{totalApplications:t.length,uniqueQuestions:e.size,topQuestions:r,inconsistent:o}}function oo(t){if(E.existsSync(j.join(M,".git")))try{let e={cwd:M,stdio:"pipe",timeout:1e4};pt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",e);try{pt("git diff --cached --quiet",e);return}catch{}let n=(t||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');pt(`git commit -m "${n}"`,e)}catch(e){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${e.message?.slice(0,80)}`)}}var zo,Ko,M,ft,mt,Vt,Oe,Wt,yt,Se,ke,de,pe,W,te,fe,ee,bt,tn,on,_e=it(()=>{zo=Qo(import.meta.url),Ko=j.dirname(j.dirname(zo)),M=process.env.DATA_DIR?j.resolve(process.env.DATA_DIR,"collected-profiles"):j.join(Ko,"collected-profiles"),ft=j.join(M,"people.json"),mt=j.join(M,"jobs.json"),Vt=j.join(M,"quota.json"),Oe=j.join(M,"conversations.json"),Wt=j.join(M,"sync-state.json"),yt=j.join(M,"application-questions.json"),Se=20,ke=100,de=null,pe=null,W=null,te=null,fe=null,ee=null;bt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge"];tn=50;on={loadPeople:Q,savePeople:ne,loadJobs:Ue,saveJobs:Be,loadConversations:Yt,saveConversations:Qt,upsertPerson:xe,upsertJob:Je,linkPersonToJob:Ge,addEncounter:ye,getPersonStatus:He,updateConnectionStatus:Ve,migrateFromDailyFiles:zt,loadQuota:We,saveQuota:ht,recordConnectionSent:Ye,canSendConnection:ze,getRecentConnections:Qe,getQuotaStatus:Ce,loadSyncState:Kt,saveSyncState:Xt,commitDataSnapshot:oo,logApplicationQuestions:be,getQuestionStats:to}});var ho={};lt(ho,{getJobDecision:()=>$t,getLastVisit:()=>yn,getScoutStats:()=>bn,loadCompanies:()=>bo,loadDiscoveredPeople:()=>Et,loadJobDecisions:()=>_t,loadScoutedJobs:()=>xt,loadVisitLog:()=>Xe,recordVisit:()=>mn,resetCaches:()=>pn,saveCompany:()=>Ke,saveDiscoveredPerson:()=>fn,saveScoutedJob:()=>Ct,setJobDecision:()=>ie});import"dotenv/config";import*as J from"fs";import*as P from"path";import{fileURLToPath as cn}from"url";function Ie(){J.existsSync(se)||J.mkdirSync(se,{recursive:!0})}function qe(t,e){let n=JSON.stringify(e,null,2),r=t+".tmp";J.writeFileSync(r,n);for(let o=0;o<3;o++)try{J.renameSync(r,t);return}catch(s){if(o<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function De(t){try{if(J.existsSync(t))return JSON.parse(J.readFileSync(t,"utf-8"))}catch{}return null}function pn(){Ee=null,Ae=null,Te=null,je=null,re=null}function xt(){return Ee||(Ee=De(uo)||{},Ee)}function Ct(t,e){if(!t)return;Ie();let n=xt(),r=new Date().toISOString().slice(0,10);if(n[t]){for(let[o,s]of Object.entries(e))s!=null&&(n[t][o]=s);n[t].lastSeen=r}else n[t]={...e,scoutedAt:r,lastSeen:r};try{qe(uo,n)}catch(o){console.error(`[!] Failed to save scouted-jobs.json: ${o.message}`)}}function _t(){return Ae||(Ae=De(yo)||{},Ae)}function ie(t,e,n={}){if(!t||!e)return;Ie();let r=_t(),o=new Date().toISOString().slice(0,10);r[t]?(r[t].status=e,r[t].updatedAt=o,n.reason&&(r[t].reason=n.reason),n.score!=null&&(r[t].score=n.score),n.source&&(r[t].source=n.source)):r[t]={status:e,decidedAt:o,updatedAt:o,reason:n.reason||null,score:n.score??null,source:n.source||null};try{qe(yo,r)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function $t(t){return _t()[t]||null}function Et(){return Te||(Te=De(po)||{},Te)}function fn(t,e){if(!t)return;Ie();let n=Et(),r=new Date().toISOString().slice(0,10);if(n[t]){let o=n[t];e.name&&(o.name=e.name),e.title&&(o.title=e.title),e.company&&(o.company=e.company),e.location&&(o.location=e.location),e.role&&(o.role=e.role),e.isConnected!=null&&(o.isConnected=e.isConnected),e.jobId&&(o.jobIds||(o.jobIds=[]),o.jobIds.includes(e.jobId)||o.jobIds.push(e.jobId)),o.lastSeen=r,o.seenCount=(o.seenCount||1)+1}else n[t]={name:e.name||null,title:e.title||null,company:e.company||null,location:e.location||null,role:e.role||null,source:e.source||"scout",isConnected:e.isConnected||!1,discoveredAt:r,lastSeen:r,seenCount:1,jobIds:e.jobId?[e.jobId]:[]};try{qe(po,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function bo(){return je||(je=De(mo)||{},je)}function Ke(t,e){if(!t)return;Ie();let n=bo(),r=new Date().toISOString().slice(0,10);if(n[t]){let o=n[t];e.name&&(o.name=e.name),e.about&&(o.about=e.about),e.size&&(o.size=e.size),e.industries&&(o.industries=e.industries),e.jobId&&(o.jobIds||(o.jobIds=[]),o.jobIds.includes(e.jobId)||o.jobIds.push(e.jobId)),e.recruiterUrl&&(o.recruiterUrls||(o.recruiterUrls=[]),o.recruiterUrls.includes(e.recruiterUrl)||o.recruiterUrls.push(e.recruiterUrl)),o.lastSeen=r,o.jobCount=o.jobIds?.length||0}else n[t]={name:e.name||null,about:e.about||null,size:e.size||null,industries:e.industries||null,discoveredAt:r,lastSeen:r,jobIds:e.jobId?[e.jobId]:[],recruiterUrls:e.recruiterUrl?[e.recruiterUrl]:[],jobCount:e.jobId?1:0};try{qe(mo,n)}catch(o){console.error(`[!] Failed to save companies.json: ${o.message}`)}}function Xe(){return re||(re=De(fo)||{visits:[]},Array.isArray(re.visits)||(re.visits=[]),re)}function mn(t,e={}){if(!t)return;Ie();let n=Xe();n.visits.push({date:new Date().toISOString(),profileUrl:t,name:e.name||null,source:e.source||"manual"});let r=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(o=>new Date(o.date).getTime()>r);try{qe(fo,n)}catch(o){console.error(`[!] Failed to save visit-log.json: ${o.message}`)}}function yn(t){let e=Xe();for(let n=e.visits.length-1;n>=0;n--)if(e.visits[n].profileUrl===t)return e.visits[n].date;return null}function bn(){let t=xt(),e=Et(),n=Object.values(t),r=Object.values(e),o={};for(let c of n)c.company&&(o[c.company]=(o[c.company]||0)+1);let s=Object.entries(o).sort((c,d)=>d[1]-c[1]).slice(0,5).map(([c,d])=>`${c} (${d})`),l={};for(let c of n)for(let d of c.techStack||[])l[d]=(l[d]||0)+1;let a=Object.entries(l).sort((c,d)=>d[1]-c[1]).slice(0,8).map(([c,d])=>`${c} (${d})`),i=Xe(),u=new Date().toISOString().slice(0,10),p=i.visits.filter(c=>c.date.startsWith(u)).length,f=new Set(i.visits.map(c=>c.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:r.length,topCompanies:s,topTech:a,totalVisited:f,todayVisited:p,lastScoutDate:n.length>0?n.sort((c,d)=>(d.scoutedAt||"").localeCompare(c.scoutedAt||""))[0]?.scoutedAt:null}}var un,dn,se,uo,po,fo,mo,yo,Ee,Ae,Te,je,re,At=it(()=>{un=cn(import.meta.url),dn=P.dirname(P.dirname(un)),se=process.env.DATA_DIR?P.resolve(process.env.DATA_DIR,"market-research"):P.join(dn,"market-research"),uo=P.join(se,"scouted-jobs.json"),po=P.join(se,"discovered-people.json"),fo=P.join(se,"visit-log.json"),mo=P.join(se,"companies.json"),yo=P.join(se,"job-decisions.json");Ee=null;Ae=null;Te=null;je=null;re=null});import An from"puppeteer";import*as Re from"fs";async function h(t){let e=Math.floor(Math.random()*2001),n=t+e;return new Promise(r=>setTimeout(r,n))}function Pt(t){return parseInt(t,10)||0}async function U(t){return await t.evaluate(()=>{let e=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of e){let o=r.innerText||"",s=o.includes("Premium")||o.includes("premium")||o.includes("Upgrade")||o.includes("upgrade"),l=o.includes("Try for")||o.includes("free trial")||o.includes("/month")||o.includes("per month")||o.includes("Start my")||o.includes("Subscribe"),a=o.includes("Get hired faster")||o.includes("Get hired 2x");if(s||l||a){let i=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(i)return i.click(),{dismissed:!0,matched:o.substring(0,80)};let u=r.querySelectorAll("button");for(let p of u){let f=p.innerText?.trim().toLowerCase()||"",c=p.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||c.includes("dismiss"))return p.click(),{dismissed:!0,matched:o.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let r=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}import{createGraphClient as Uo,resolveToken as Bo}from"@ilivemylife/graph-sdk";import{config as Jo}from"dotenv";Jo();var Ot=Bo()||process.env.TOKEN;Ot||(console.error(`
1
+ var Bo=Object.defineProperty;var st=(e,t)=>()=>(e&&(t=e(e=0)),t);var it=(e,t)=>{for(var n in t)Bo(e,n,{get:t[n],enumerable:!0})};var Gt={};it(Gt,{default:()=>zo,getAllUnprocessedProfiles:()=>Ne,getSummary:()=>ue,getUnprocessedProfiles:()=>Me,listFiles:()=>Jt,loadProfiles:()=>Fe,markProfileProcessed:()=>Bt,saveProfile:()=>we,saveProfiles:()=>Ut});import"dotenv/config";import*as A from"fs";import*as B from"path";import{fileURLToPath as Vo}from"url";function ge(){A.existsSync(V)||A.mkdirSync(V,{recursive:!0})}function Qo(e,t){try{let n=`${e}-${at()}.json`,r=A.readdirSync(V).filter(s=>s.startsWith(e)&&s.endsWith(".json")&&s!==n),o=0;for(let s of r)JSON.parse(A.readFileSync(B.join(V,s),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&o++;return o}catch{return 0}}function at(){return new Date().toISOString().split("T")[0]}function ct(e,t=null){let n=t||at();return B.join(V,`${e}-${n}.json`)}function Fe(e,t=null){ge();let n=ct(e,t);try{if(A.existsSync(n)){let r=A.readFileSync(n,"utf-8"),o=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${o.profiles.length} profiles from ${n}`),o.profiles}}catch(r){console.error(`Error loading profiles from ${n}:`,r.message)}return[]}function we(e,t){ge();let n=ct(e),r={source:e,date:at(),lastUpdated:new Date().toISOString(),profiles:[]};try{A.existsSync(n)&&(r=JSON.parse(A.readFileSync(n,"utf-8")))}catch(l){console.error(`Error reading ${n}:`,l.message)}if(r.profiles.some(l=>l.profileUrl===t.profileUrl))return!1;let s=Qo(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:s}),r.lastUpdated=new Date().toISOString();try{A.writeFileSync(n,JSON.stringify(r,null,2));let l=s>0?` (seen ${s} day${s>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${l} (total: ${r.profiles.length})`),!0}catch(l){return console.error(`Error saving to ${n}:`,l.message),!1}}function Ut(e,t){let n=0;for(let r of t)we(e,r)&&n++;return n}function Me(e,t=null){return Fe(e,t).filter(r=>!r.processed)}function Bt(e,t,n,r=null){ge();let o=ct(e,r);try{if(!A.existsSync(o))return;let s=JSON.parse(A.readFileSync(o,"utf-8")),l=s.profiles.find(a=>a.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof n=="string")l.status=n;else if(typeof n=="object"){if(l.status=n.status,n.profileInfo){let a=n.profileInfo;a.name&&(l.name=a.name),a.title&&(l.title=a.title),a.location&&(l.location=a.location),a.company&&(l.company=a.company),a.connectionDegree&&(l.connectionDegree=a.connectionDegree),a.connectionsCount&&(l.connectionsCount=a.connectionsCount),a.mutualConnections&&(l.mutualConnections=a.mutualConnections),a.photoUrl&&(l.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=a.hasVerifiedBadge)}l.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}s.lastUpdated=new Date().toISOString(),A.writeFileSync(o,JSON.stringify(s,null,2))}}catch(s){console.error("Error marking profile processed:",s.message)}}function ue(e){let t=Fe(e),n=t.filter(o=>o.processed),r=t.filter(o=>!o.processed);return{total:t.length,processed:n.length,unprocessed:r.length,statuses:n.reduce((o,s)=>(o[s.status]=(o[s.status]||0)+1,o),{})}}function Jt(){ge();try{return A.readdirSync(V).filter(t=>t.endsWith(".json")).map(t=>{let[n,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let o=JSON.parse(A.readFileSync(B.join(V,t),"utf-8"));return{file:t,source:n,date:r,count:o.profiles?.length||0,unprocessed:o.profiles?.filter(s=>!s.processed).length||0}}catch{return{file:t,source:n,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function Ne(e){ge();let t=[];try{let o=A.readdirSync(V).filter(s=>s.startsWith(e+"-")&&s.endsWith(".json")).sort().reverse();for(let s of o)try{let l=JSON.parse(A.readFileSync(B.join(V,s),"utf-8"));l.profiles&&t.push({file:s,date:l.date,profiles:l.profiles})}catch{}}catch{return[]}let n=new Set,r=[];for(let{date:o,profiles:s}of t)for(let l of s)!l.processed&&l.profileUrl&&!n.has(l.profileUrl)&&(n.add(l.profileUrl),r.push({...l,_fromDate:o}));return r}var Wo,Yo,V,zo,ut=st(()=>{Wo=Vo(import.meta.url),Yo=B.dirname(B.dirname(Wo)),V=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Yo,"collected-profiles");zo={loadProfiles:Fe,saveProfile:we,saveProfiles:Ut,getUnprocessedProfiles:Me,getAllUnprocessedProfiles:Ne,markProfileProcessed:Bt,getSummary:ue,listFiles:Jt}});var gt={};it(gt,{addEncounter:()=>ye,canSendConnection:()=>Qe,commitDataSnapshot:()=>to,default:()=>rn,getAllApplications:()=>Zt,getPersonStatus:()=>Ge,getQuestionStats:()=>eo,getQuotaStatus:()=>Ce,getRecentConnections:()=>Ye,linkPersonToJob:()=>Je,loadApplicationQuestions:()=>bt,loadConversations:()=>Wt,loadJobs:()=>Oe,loadPeople:()=>Q,loadQuota:()=>Ve,loadSyncState:()=>zt,logApplicationQuestions:()=>he,migrateFromDailyFiles:()=>Qt,recordConnectionSent:()=>We,resetCaches:()=>en,saveConversations:()=>Yt,saveJobs:()=>Ue,savePeople:()=>ne,saveQuota:()=>ht,saveSyncState:()=>Kt,updateConnectionStatus:()=>He,upsertJob:()=>Be,upsertPerson:()=>xe});import"dotenv/config";import*as E from"fs";import*as j from"path";import{fileURLToPath as Ko}from"url";import{execSync as dt}from"child_process";function en(){de=null,pe=null,W=null,te=null,fe=null,ee=null}function N(){E.existsSync(M)||E.mkdirSync(M,{recursive:!0})}function oe(e,t){let n=JSON.stringify(t,null,2),r=e+".tmp";E.writeFileSync(r,n);for(let o=0;o<3;o++)try{E.renameSync(r,e);return}catch(s){if(o<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function ve(e,t){if(!E.existsSync(e))return null;try{let n=JSON.parse(E.readFileSync(e,"utf-8"));try{E.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${j.resolve(e)}`);let r=e+".backup";if(E.existsSync(r))try{let o=JSON.parse(E.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{E.copyFileSync(r,e)}catch{}return o}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{E.copyFileSync(e,e+".corrupted")}catch{}return null}}function me(){return new Date().toISOString().split("T")[0]}function Q(){return de||(N(),de=ve(pt,"people.json")||{},de)}function ne(e){N(),de=e;try{oe(pt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${j.resolve(pt)}`)}}function Oe(){return pe||(N(),pe=ve(ft,"jobs.json")||{},pe)}function Ue(e){N(),pe=e;try{oe(ft,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${j.resolve(ft)}`)}}function Wt(){return te||(N(),te=ve(Pe,"conversations.json")||{},tn(te),te)}function tn(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let o=(n.messages||[]).find(s=>s.status==="draft");o&&n.draftStatus&&n.draftStatus!=="pending"&&(o.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{oe(Pe,e)}catch{}}}function Yt(e){N(),te=e;try{oe(Pe,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${j.resolve(Pe)}`)}}function xe(e,t={}){if(!e)return null;let n=Q(),r=me(),o=new Date().toISOString(),s=n[e];if(s){s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=o,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let l of yt)t[l]!=null&&(s[l]=t[l])}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:o};return ne(n),n[e]}function Be(e,t={}){if(!e)return null;let n=Oe(),r=me(),o=n[e];if(o){let s=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let l of s)t[l]!=null&&(o[l]=t[l])}else n[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 Ue(n),n[e]}function Je(e,t){if(!e||!t)return;let n=Q(),r=n[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),ne(n)))}function ye(e,t){if(!e||!t)return;let n=Q(),r=n[e];if(!r)return;r.encounters||(r.encounters=[]);let s={date:me(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(s.jobId=String(t.jobId)),t.jobTitle&&(s.jobTitle=t.jobTitle),t.jobCompany&&(s.jobCompany=t.jobCompany),!r.encounters.some(a=>a.date===s.date&&a.source===s.source&&a.action===s.action&&(a.jobId||"")===(s.jobId||""))&&(r.encounters.push(s),r.lastUpdated=new Date().toISOString(),ne(n))}function Ge(e){return e&&Q()[e]?.connectionStatus||null}function He(e,t,n={}){if(!e)return;let r=Q(),o=r[e];if(o||(xe(e,n.profileInfo||{}),o=r[e]),!!o){if(o.connectionStatus=t,o.connectionDate=me(),o.connectionMethod=n.method||o.connectionMethod,o.messageSent=n.messageSent||o.messageSent,o.lastUpdated=new Date().toISOString(),n.profileInfo)for(let s of yt)n.profileInfo[s]!=null&&(o[s]=n.profileInfo[s]);ne(r)}}function Ve(){return W||(N(),W=ve(Ht,"quota.json"),(!W||!W.connections)&&(W={connections:[]}),W)}function ht(e){N(),W=e;try{oe(Ht,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function We(e,t="unknown"){let n=Ve(),r=new Date;n.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),ht(n)}function Ye(){let e=Ve(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=n)}function Qe(){let e=Ye(),t=me(),n=e.filter(i=>i.date===t).length,r=e.length,o=n>=Se,s=r>=ke,l=!o&&!s,a={allowed:l,daily:{sent:n,max:Se},weekly:{sent:r,max:ke}};return l||(a.reason=o?`Daily limit reached (${n}/${Se})`:`Weekly limit reached (${r}/${ke})`),a}function Ce(){let e=Ye(),t=me(),n=e.filter(o=>o.date===t).length,r=e.length;return{daily:{sent:n,max:Se,remaining:Se-n},weekly:{sent:r,max:ke,remaining:ke-r}}}function on(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function Qt(){N();let e=E.readdirSync(M).filter(s=>s.endsWith(".json")&&s!=="people.json"&&s!=="jobs.json"&&s!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
2
+ Migrating from ${e.length} daily files...
3
+ `);let t=Q(),n=Oe(),r=0,o=0;e.sort();for(let s of e){let l=j.join(M,s),a;try{a=JSON.parse(E.readFileSync(l,"utf-8"))}catch(p){console.log(` Skipping ${s}: ${p.message}`);continue}let i=a.date||s.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,u=a.source||s.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!a.profiles||!Array.isArray(a.profiles)){console.log(` Skipping ${s}: no profiles array`);continue}console.log(` ${s}: ${a.profiles.length} profiles`);for(let p of a.profiles){let f=p.profileUrl;if(!f)continue;let c=t[f];if(c){c.seenCount=(c.seenCount||1)+1,i&&(!c.lastSeen||i>c.lastSeen)&&(c.lastSeen=i),i&&(!c.firstSeen||i<c.firstSeen)&&(c.firstSeen=i),u&&!c.sources?.includes(u)&&(c.sources=c.sources||[],c.sources.push(u));for(let d of yt)p[d]!=null&&(c[d]=p[d]);p.status&&p.processed&&(c.connectionStatus=p.status,c.connectionDate=i,p.funnelResult&&(c.connectionMethod=p.funnelResult.method||c.connectionMethod,c.messageSent=p.funnelResult.message||c.messageSent)),c.lastUpdated=new Date().toISOString()}else t[f]={name:p.name||null,title:p.title||null,location:p.location||null,company:p.company||null,connectionDegree:p.connectionDegree||null,connectionsCount:p.connectionsCount||null,mutualConnections:p.mutualConnections||null,photoUrl:p.photoUrl||null,hasVerifiedBadge:p.hasVerifiedBadge||!1,firstSeen:i,lastSeen:i,seenCount:1,sources:u?[u]:[],connectionStatus:p.processed&&p.status||null,connectionDate:p.processed?i:null,connectionMethod:p.funnelResult?.method||null,messageSent:p.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(p.fromJob?.url){let d=on(p.fromJob.url);d&&(t[f].jobIds||(t[f].jobIds=[]),t[f].jobIds.includes(d)||t[f].jobIds.push(d),n[d]?n[d].recruiterUrl||(n[d].recruiterUrl=f):(n[d]={title:p.fromJob.title||null,company:p.fromJob.company||null,location:null,salary:null,url:p.fromJob.url,applied:!0,appliedDate:i,recruiterUrl:f,firstSeen:i},o++))}}}return ne(t),Ue(n),console.log(`
4
+ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(n).length} total (${o} new)`),{people:Object.keys(t).length,jobs:Object.keys(n).length}}function zt(){return fe||(N(),fe=ve(Vt,"sync-state.json")||{},fe)}function Kt(e){N(),fe=e;try{oe(Vt,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function bt(){if(ee)return ee;N();try{E.existsSync(mt)&&(ee=JSON.parse(E.readFileSync(mt,"utf-8")))}catch{}return ee||(ee={}),ee}function Xt(e){return Array.isArray(e.applications)}function Zt(){let e=bt();if(Xt(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function he(e){if(!e||!e.questions||e.questions.length===0)return;let t=bt(),n=e.jobId||"unknown",o={applicationId:`${n}_${Date.now()}`,date:new Date().toISOString(),result:e.result||"submitted",formPages:e.formPages||null,duration:e.duration||null,retries:e.retries||0,failedField:e.failedField||null,questionCount:e.questions.length,questions:e.questions.map(s=>{let l={type:s.type||"input",question:s.labelText||s.question||"",answer:s.answer||""};return s.options&&(s.options.length<=nn?l.options=s.options:l.optionsOmitted=!0),s.page&&(l.page=s.page),s.wasPreFilled&&(l.wasPreFilled=!0),s.wasRetry&&(l.wasRetry=!0),l})};Xt(t)?(o.jobId=n,o.jobTitle=e.jobTitle||null,o.jobCompany=e.jobCompany||null,o.jobUrl=e.jobUrl||null,t.applications.push(o)):(t[n]||(t[n]={applications:[]}),t[n].applications.push(o));try{oe(mt,t)}catch(s){console.error(`[!] Failed to save application-questions.json: ${s.message}`)}}function eo(){let e=Zt(),t=new Map;for(let s of e)for(let l of s.questions||[]){let a=l.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:l.question,count:0,answers:new Map});let i=t.get(a);i.count++;let u=(l.answer||"").trim();i.answers.set(u,(i.answers.get(u)||0)+1)}let n=[...t.values()].sort((s,l)=>l.count-s.count),r=n.slice(0,15).map(s=>({question:s.question,count:s.count,topAnswer:[...s.answers.entries()].sort((l,a)=>a[1]-l[1])[0]?.[0]||""})),o=n.filter(s=>s.answers.size>1&&s.count>=3).map(s=>({question:s.question,count:s.count,answers:[...s.answers.entries()].sort((l,a)=>a[1]-l[1]).map(([l,a])=>`${l} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:o}}function to(e){if(E.existsSync(j.join(M,".git")))try{let t={cwd:M,stdio:"pipe",timeout:1e4};dt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",t);try{dt("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');dt(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Xo,Zo,M,pt,ft,Ht,Pe,Vt,mt,Se,ke,de,pe,W,te,fe,ee,yt,nn,rn,_e=st(()=>{Xo=Ko(import.meta.url),Zo=j.dirname(j.dirname(Xo)),M=process.env.DATA_DIR?j.resolve(process.env.DATA_DIR,"collected-profiles"):j.join(Zo,"collected-profiles"),pt=j.join(M,"people.json"),ft=j.join(M,"jobs.json"),Ht=j.join(M,"quota.json"),Pe=j.join(M,"conversations.json"),Vt=j.join(M,"sync-state.json"),mt=j.join(M,"application-questions.json"),Se=20,ke=100,de=null,pe=null,W=null,te=null,fe=null,ee=null;yt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge"];nn=50;rn={loadPeople:Q,savePeople:ne,loadJobs:Oe,saveJobs:Ue,loadConversations:Wt,saveConversations:Yt,upsertPerson:xe,upsertJob:Be,linkPersonToJob:Je,addEncounter:ye,getPersonStatus:Ge,updateConnectionStatus:He,migrateFromDailyFiles:Qt,loadQuota:Ve,saveQuota:ht,recordConnectionSent:We,canSendConnection:Qe,getRecentConnections:Ye,getQuotaStatus:Ce,loadSyncState:zt,saveSyncState:Kt,commitDataSnapshot:to,logApplicationQuestions:he,getQuestionStats:eo}});var ho={};it(ho,{getJobDecision:()=>_t,getLastVisit:()=>bn,getScoutStats:()=>gn,loadCompanies:()=>yo,loadDiscoveredPeople:()=>$t,loadJobDecisions:()=>Ct,loadScoutedJobs:()=>vt,loadVisitLog:()=>Ke,recordVisit:()=>hn,resetCaches:()=>mn,saveCompany:()=>ze,saveDiscoveredPerson:()=>yn,saveScoutedJob:()=>xt,setJobDecision:()=>ie});import"dotenv/config";import*as J from"fs";import*as P from"path";import{fileURLToPath as dn}from"url";function Ie(){J.existsSync(se)||J.mkdirSync(se,{recursive:!0})}function qe(e,t){let n=JSON.stringify(t,null,2),r=e+".tmp";J.writeFileSync(r,n);for(let o=0;o<3;o++)try{J.renameSync(r,e);return}catch(s){if(o<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function De(e){try{if(J.existsSync(e))return JSON.parse(J.readFileSync(e,"utf-8"))}catch{}return null}function mn(){Ee=null,Ae=null,Te=null,je=null,re=null}function vt(){return Ee||(Ee=De(co)||{},Ee)}function xt(e,t){if(!e)return;Ie();let n=vt(),r=new Date().toISOString().slice(0,10);if(n[e]){for(let[o,s]of Object.entries(t))s!=null&&(n[e][o]=s);n[e].lastSeen=r}else n[e]={...t,scoutedAt:r,lastSeen:r};try{qe(co,n)}catch(o){console.error(`[!] Failed to save scouted-jobs.json: ${o.message}`)}}function Ct(){return Ae||(Ae=De(mo)||{},Ae)}function ie(e,t,n={}){if(!e||!t)return;Ie();let r=Ct(),o=new Date().toISOString().slice(0,10);r[e]?(r[e].status=t,r[e].updatedAt=o,n.reason&&(r[e].reason=n.reason),n.score!=null&&(r[e].score=n.score),n.source&&(r[e].source=n.source)):r[e]={status:t,decidedAt:o,updatedAt:o,reason:n.reason||null,score:n.score??null,source:n.source||null};try{qe(mo,r)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function _t(e){return Ct()[e]||null}function $t(){return Te||(Te=De(uo)||{},Te)}function yn(e,t){if(!e)return;Ie();let n=$t(),r=new Date().toISOString().slice(0,10);if(n[e]){let o=n[e];t.name&&(o.name=t.name),t.title&&(o.title=t.title),t.company&&(o.company=t.company),t.location&&(o.location=t.location),t.role&&(o.role=t.role),t.isConnected!=null&&(o.isConnected=t.isConnected),t.jobId&&(o.jobIds||(o.jobIds=[]),o.jobIds.includes(t.jobId)||o.jobIds.push(t.jobId)),o.lastSeen=r,o.seenCount=(o.seenCount||1)+1}else n[e]={name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:r,lastSeen:r,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{qe(uo,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function yo(){return je||(je=De(fo)||{},je)}function ze(e,t){if(!e)return;Ie();let n=yo(),r=new Date().toISOString().slice(0,10);if(n[e]){let o=n[e];t.name&&(o.name=t.name),t.about&&(o.about=t.about),t.size&&(o.size=t.size),t.industries&&(o.industries=t.industries),t.jobId&&(o.jobIds||(o.jobIds=[]),o.jobIds.includes(t.jobId)||o.jobIds.push(t.jobId)),t.recruiterUrl&&(o.recruiterUrls||(o.recruiterUrls=[]),o.recruiterUrls.includes(t.recruiterUrl)||o.recruiterUrls.push(t.recruiterUrl)),o.lastSeen=r,o.jobCount=o.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:r,lastSeen:r,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{qe(fo,n)}catch(o){console.error(`[!] Failed to save companies.json: ${o.message}`)}}function Ke(){return re||(re=De(po)||{visits:[]},Array.isArray(re.visits)||(re.visits=[]),re)}function hn(e,t={}){if(!e)return;Ie();let n=Ke();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let r=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(o=>new Date(o.date).getTime()>r);try{qe(po,n)}catch(o){console.error(`[!] Failed to save visit-log.json: ${o.message}`)}}function bn(e){let t=Ke();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function gn(){let e=vt(),t=$t(),n=Object.values(e),r=Object.values(t),o={};for(let c of n)c.company&&(o[c.company]=(o[c.company]||0)+1);let s=Object.entries(o).sort((c,d)=>d[1]-c[1]).slice(0,5).map(([c,d])=>`${c} (${d})`),l={};for(let c of n)for(let d of c.techStack||[])l[d]=(l[d]||0)+1;let a=Object.entries(l).sort((c,d)=>d[1]-c[1]).slice(0,8).map(([c,d])=>`${c} (${d})`),i=Ke(),u=new Date().toISOString().slice(0,10),p=i.visits.filter(c=>c.date.startsWith(u)).length,f=new Set(i.visits.map(c=>c.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:r.length,topCompanies:s,topTech:a,totalVisited:f,todayVisited:p,lastScoutDate:n.length>0?n.sort((c,d)=>(d.scoutedAt||"").localeCompare(c.scoutedAt||""))[0]?.scoutedAt:null}}var pn,fn,se,co,uo,po,fo,mo,Ee,Ae,Te,je,re,Et=st(()=>{pn=dn(import.meta.url),fn=P.dirname(P.dirname(pn)),se=process.env.DATA_DIR?P.resolve(process.env.DATA_DIR,"market-research"):P.join(fn,"market-research"),co=P.join(se,"scouted-jobs.json"),uo=P.join(se,"discovered-people.json"),po=P.join(se,"visit-log.json"),fo=P.join(se,"companies.json"),mo=P.join(se,"job-decisions.json");Ee=null;Ae=null;Te=null;je=null;re=null});import Dn from"puppeteer";import*as No from"fs";async function b(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(r=>setTimeout(r,n))}function Nt(e){return parseInt(e,10)||0}async function U(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let o=r.innerText||"",s=o.includes("Premium")||o.includes("premium")||o.includes("Upgrade")||o.includes("upgrade"),l=o.includes("Try for")||o.includes("free trial")||o.includes("/month")||o.includes("per month")||o.includes("Start my")||o.includes("Subscribe"),a=o.includes("Get hired faster")||o.includes("Get hired 2x");if(s||l||a){let i=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(i)return i.click(),{dismissed:!0,matched:o.substring(0,80)};let u=r.querySelectorAll("button");for(let p of u){let f=p.innerText?.trim().toLowerCase()||"",c=p.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||c.includes("dismiss"))return p.click(),{dismissed:!0,matched:o.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let r=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}import{createGraphClient as Jo,resolveToken as Go}from"@ilivemylife/graph-sdk";import{config as Ho}from"dotenv";Ho();var Pt=Go()||process.env.TOKEN;Pt||(console.error(`
5
5
  [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.
6
6
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
7
7
  `),console.error(` Or add ILML_TOKEN=... to .env
8
- `),process.exit(1));var Z=Uo({token:Ot});var ae=12e4;async function ce(t,{retries:e=2}={}){let n=process.env.NODE_EASY_APPLY_MAIN;if(!n||n.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<=e;r++)try{let o=await Z.askLifebot(n,t,{timeout:ae});return ae=Math.max(12e4,ae*.9),o.content}catch(o){if(o.constructor.name==="LifebotTimeoutError"&&r<e){ae=Math.min(ae*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${e}), increasing timeout to ${Math.round(ae/1e3)}s...`);continue}throw o}}async function Ut(t,e){(t=="City"||t=="Location (city)")&&(t="Tell my home city (not the city where position is).");let n=`Job application form field "${t}" \u2014 reply with ONLY the value to fill in, nothing else. `;return e&&(e==="Enter a decimal number larger than 0.0"&&(e="Enter a decimal number larger than 0"),n+=`Additional info: ${e}`),await ce(n)}async function at(t,e){let n=`Choose the best answer: ${t} Available options: ${e.join(", ")} `;return await ce(n)}async function Fe(t,e){let n=`Choose the best answer: ${t} Available options: ${e.join(", ")} `;return await ce(n)}dt();import{LIFEBOT_MESSAGE_TYPES as Ao}from"@ilivemylife/graph-sdk";_e();async function no(t,e){let n=t.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await h(3e3);let r=t.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function nn(t,e=[]){if(!t||!e||e.length===0)return!1;let n=t.toLowerCase();return e.some(r=>n.includes(r.toLowerCase()))}async function rn(t,e){try{await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await h(2e3+Math.random()*2e3),await U(t)&&(console.log(" Dismissed Premium overlay"),await h(1500),await no(t,e));let r=await t.evaluate(()=>{let o=document.querySelector("h1")?.textContent?.trim()||null,s=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,l=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,a=document.querySelector("section#about div.display-flex")?.textContent?.trim()||null,u=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,f=document.querySelector(".dist-value")?.textContent?.trim()||null,d=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,g=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),b=g?parseInt(g[1],10):null,k=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,w=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:o,title:s,location:l,about:a,company:u,connectionDegree:f,connectionsCount:d,mutualConnections:b,photoUrl:k,hasVerifiedBadge:w}});return console.log(`Viewed: ${r.name} - ${r.title}`),{...r,profileUrl:e}}catch(n){console.error(`Error viewing profile ${e}:`,n.message);try{await t.goto("about:blank",{timeout:1e4}),await h(1e3)}catch{}return null}}async function $e(t){let e=await t.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(n).map(i=>i.getAttribute("aria-label")),o=document.querySelector('button[aria-label*="Message"]'),s=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:n.length,pendingLabels:r,hasMessageBtn:!!o,hasConnectBtn:!!s};return n.length>0?{status:"pending",debug:l}:o&&!s?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(e.debug)),e.status}async function St(t){let e=null,n=await t.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(i=u.textContent?.trim(),i&&!i.includes("notification")))return i;let p=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(p)return p.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let i=await t.evaluate(()=>{let p=document.querySelectorAll('a[href*="custom-invite"]');return{count:p.length,labels:Array.from(p).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),e=await t.evaluateHandle(p=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),c=p.toLowerCase().split(" ")[0],d=null,m=null;for(let y of f){let g=y.getBoundingClientRect();if(g.width===0||g.height===0)continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(c)){d=y;break}m||(m=y)}return d||m||null},n);let u=e?.asElement?.()||null;if(u||await e?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let i=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let u=await t.evaluate(f=>{let c=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),d=document.querySelectorAll("button[aria-label]");return Array.from(d).filter(y=>{let g=y.getAttribute("aria-label")||"";return(g.toLowerCase().includes("invite")||g.toLowerCase().includes("connect"))&&c.test(g)}).map(y=>y.getAttribute("aria-label")?.slice(0,50))},i);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),e=await t.evaluateHandle(f=>{let c=document.querySelectorAll("button[aria-label]"),d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let m of c){let y=m.getAttribute("aria-label")||"";if((y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&d.test(y))return m}return null},i);let p=e?.asElement?.()||null;if(p||await e?.dispose?.().catch(()=>{}),p)return console.log(" Found: button matching profile name"),{button:p,method:"name_matched_button"}}if(e=await t.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),e&&n){let i=await t.evaluate(p=>(p.getAttribute("aria-label")||"").toLowerCase(),e),u=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping primary button: wrong person (${i})`),e=null)}if(e||(e=await t.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),e)return console.log(" Found: primary button"),{button:e,method:"primary_button"};let r=await t.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await t.$$('button[aria-label="Connect"]'));let o=n?n.split(" ")[0].toLowerCase():"",s=null;for(let i of r){let u=await t.evaluate((p,f)=>{let c=p.className.includes("muted"),d=p.className.includes("sticky-header")||p.className.includes("sticky"),m=p.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,y=(p.getAttribute("aria-label")||"").toLowerCase(),g=y.includes("invite"),b=f?y.includes(f):!0;return{isMuted:c,isStickyHeader:d,inRecommendations:m,hasInvite:g,matchesName:b,ariaLabel:y}},i,o);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}s=i;break}}for(let i of r)i!==s&&await i.dispose().catch(()=>{});if(s)return console.log(" Found: secondary button"),{button:s,method:"secondary_button"};if(e=await t.$('section.pv-supplementary-action button[aria-label*="Invite"]'),e||(e=await t.$('section.pv-supplementary-action button[aria-label="Connect"]')),e)return console.log(" Found: supplementary section"),{button:e,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,a=await t.$$('button[id*="profile-overflow-action"]');for(let i of a){let u=await t.evaluate(p=>{let f=p.getBoundingClientRect(),c=f.width>0&&f.height>0,d=p.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:c,isInStickyHeader:d,top:f.top}},i);if(u.isVisible&&!u.isInStickyHeader){l=i,console.log(" Found More button by ID pattern (main)");break}}for(let i of a)i!==l&&await i.dispose().catch(()=>{});if(!l&&a.length>0&&(l=a[a.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await t.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let i=await t.evaluateHandle(()=>{let p=Array.from(document.querySelectorAll("button, a")).find(c=>{let d=c.innerText?.trim(),m=c.getAttribute("aria-label")||"",y=c.getBoundingClientRect();return y.top<100||y.top>600||y.width===0?!1:d==="Follow"||d==="Message"||d==="Connect"||m.includes("Follow")||m.includes("Message")||m.includes("Invite")});if(!p)return null;let f=p.parentElement;for(let c=0;c<8&&f;c++){for(let d of f.querySelectorAll("button"))if(d.innerText?.trim()==="More"&&d!==p)return d;f=f.parentElement}return null});l=i?.asElement?.()||null,l||await i?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await t.evaluate(p=>p.scrollIntoView({behavior:"smooth",block:"center"}),l),await h(500),await t.evaluate(p=>p.click(),l),await h(2e3),!t.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await t.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await t.$('.artdeco-dropdown__item[aria-label*="connect"]')),u||(u=await t.$('.artdeco-dropdown__item[aria-label="Connect"]')),u||(u=await t.$('div[role="button"][aria-label*="Invite"]')),u||(u=await t.$('div[role="button"][aria-label*="connect"]')),!u){let p=await t.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let c of f){let d=c.querySelector('a[href*="custom-invite"]');if(d)return d;for(let m of c.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(m.innerText?.trim()==="Connect")return m}return null});u=p?.asElement?.()||null,u||await p?.dispose?.().catch(()=>{})}if(!u){let p=await t.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),c=[];for(let d of f)for(let m of d.querySelectorAll('[role="menuitem"], a, div')){let y=m.innerText?.trim();y&&y.length<40&&c.push(y)}return[...new Set(c)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(p)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};await t.keyboard.press("Escape")}catch(i){console.log(" More dropdown click failed:",i.message),await t.keyboard.press("Escape")}if(e=await t.$('button[aria-label*="Invite"]'),e&&n){let i=await t.evaluate(p=>(p.getAttribute("aria-label")||"").toLowerCase(),e),u=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping generic button: wrong person (${i})`),e=null)}return e||(e=await t.$('button[aria-label="Connect"]')),e?(console.log(" Found: generic button"),{button:e,method:"generic_button"}):null}async function sn(t,e){await t.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),e),await h(500);let n=await t.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),e),o=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),s=n.tag==="DIV";if(o){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([t.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),t.evaluate(p=>p.click(),e)]),await h(2e3);let u=t.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await t.goBack(),await h(2e3),"premium_redirect"}else s?(await t.evaluate(u=>u.click(),e),await h(3e3)):(await t.evaluate(u=>u.click(),e),await h(3e3));let l=t.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let a=await t.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),i=t.url();return console.log(a?` \u2713 Connect sent \u2014 ${i}`:` \u26A0 No modal after connect click \u2014 ${i}`),"success"}async function ln(t){console.log(" Upsell: Premium required for notes");let e=await t.$('button[aria-label="Dismiss"]')||await t.$("button.artdeco-modal__dismiss");e?await e.click():await t.keyboard.press("Escape"),await h(1500);let n=await St(t);if(n){await t.evaluate(o=>o.click(),n),await h(2e3);let r=await t.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(o=>o.click())}catch{console.log(" Click timeout, likely still sent")}return await h(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function an(t,e,n={}){let{message:r=null,useCustomMessage:o=!0,skipIfPending:s=!0,skipIfConnected:l=!0,excludeLocations:a=[]}=n,i={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let u=e.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
9
- --- Connecting: ${u} ---`),await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await h(5e3),await U(t)&&(console.log(" Dismissed Premium overlay"),await h(2e3),await no(t,e),await h(2e3)),i.profileInfo=await t.evaluate(()=>{let b=document.querySelector("h1")?.textContent?.trim()||null,S=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,k=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,C=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,T=document.querySelector(".dist-value")?.textContent?.trim()||null,L=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,K=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),he=K?parseInt(K[1],10):null,le=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,Y=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:b,title:S,location:k,company:C,connectionDegree:T,connectionsCount:L,mutualConnections:he,photoUrl:le,hasVerifiedBadge:Y}}),a.length>0&&nn(i.profileInfo?.location,a))return console.log(` \u26A0 Excluded location: ${i.profileInfo.location}`),i.reason="excluded_location",i;let f=await $e(t);if(f==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(f==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await U(t);let c=await St(t);if(!c&&(await U(t)&&(console.log(" Dismissed overlay, retrying connect button search..."),await h(2e3),c=await St(t)),!c))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;if(i.method=c.method,await sn(t,c.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await h(4e3);let b=await $e(t);if(b==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${b} \u2014 trying More dropdown...`),await U(t),await h(1e3);let S=await t.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await t.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),S),await h(500),await S.click().catch(()=>t.evaluate(w=>w.click(),S)),await h(2e3);let k=await t.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await t.$('.artdeco-dropdown__item[aria-label*="connect"]')||await t.$('.artdeco-dropdown__item[aria-label="Connect"]')||await t.$('div[role="button"][aria-label*="Invite"]')||await t.$('div[role="button"][aria-label*="connect"]');if(k){console.log(" Found Connect in More dropdown, clicking..."),await t.evaluate(I=>I.click(),k),await h(3e3);let w=t.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await h(3e3),i.reason="premium_required",i;if(await $e(t)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.method="more_dropdown",i.withCustomMessage=!1,i;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await t.keyboard.press("Escape"),await h(500),i.reason="premium_required",i}catch(k){return console.log(" More dropdown failed:",k.message),await t.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}if(await t.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let b=await t.$('button[aria-label="Dismiss"]');return b&&await b.click(),await h(500),i.reason="email_required",i}let y=await t.$('button[aria-label="Add a note"]'),g=await t.$('button[aria-label="Send without a note"]');if(!y&&!g){let b=await t.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let k=S.querySelector('button[aria-label="Add a note"]'),w=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!k,sendWithout:!!w}});if(b.addNote){let S=await t.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));y=S?.asElement?.()||null,y||await S.dispose().catch(()=>{})}if(b.sendWithout){let S=await t.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=S?.asElement?.()||null,g||await S.dispose().catch(()=>{})}}if(o){if(y&&r){if(console.log(" Adding personalized note..."),await y.click(),await h(1500),await t.$("div.modal-upsell")){let k=await ln(t);return i.success=k,i.connectionSent=k,i.reason=k?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let S=await t.$('textarea[name="message"]')||await t.$("textarea#custom-message")||await t.$("textarea");if(S){let k=await t.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=r.replace("{name}",k);await S.type(w,{delay:20}),await h(500);let C=await t.$('button[aria-label="Send invitation"]')||await t.$('button[aria-label="Send now"]');if(C){try{await C.evaluate(I=>I.click())}catch{console.log(" Click timeout, likely still sent")}return await h(3e3),console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=w,i}}}else if(g){console.log(" Sending without note...");try{await g.evaluate(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await h(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}else if(y&&!r){console.log(" No message provided, sending without note...");let b=await t.$('button[aria-label="Send without a note"]');if(b){try{await b.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await h(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let b=g;if(b){try{await b.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await h(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}if(c.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),t.url().includes("/in/")||(await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await h(4e3)),await U(t),await h(500);let S=await t.$$('button[id*="profile-overflow-action"]'),k=null;for(let w of S){let C=await t.evaluate(I=>{let T=I.getBoundingClientRect();return{visible:T.width>0&&T.height>0,inSticky:!!I.closest('.sticky-header, [class*="sticky"]')}},w);if(C.visible&&!C.inSticky){k=w;break}}!k&&S.length>0&&(k=S[S.length-1]);for(let w of S)w!==k&&await w.dispose().catch(()=>{});if(k)try{await t.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),k),await h(500),await k.click().catch(()=>t.evaluate(C=>C.click(),k)),await h(2e3);let w=await t.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await t.$('.artdeco-dropdown__item[aria-label*="connect"]')||await t.$('.artdeco-dropdown__item[aria-label="Connect"]')||await t.$('div[role="button"][aria-label*="Invite"]')||await t.$('div[role="button"][aria-label*="connect"]');if(w){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await t.evaluate(x=>x.click(),w),await h(3e3);let C=t.url();if(C.includes("/premium/")||C.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await h(3e3),await $e(t)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(i.reason="premium_required",i);if(await $e(t)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;let T=await t.$('button[aria-label="Send without a note"]');if(T){console.log(" Modal appeared via More dropdown, sending without note...");try{await T.evaluate(x=>x.click())}catch{}return await h(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await t.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await t.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(u){console.error(` \u2717 Error: ${u.message}`),i.reason="error",i.error=u.message;let p=u.message.toLowerCase();if(p.includes("detached")||p.includes("session closed")||p.includes("target closed")||p.includes("browser has disconnected")||p.includes("protocol error"))return i.fatal=!0,i;try{await t.goto("about:blank",{timeout:1e4}),await h(1e3)}catch{i.fatal=!0}return i}}async function kt(t,e,n={}){let{message:r=null,useCustomMessage:o=!0,maxConnections:s=20,viewOnly:l=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:i=null,excludeLocations:u=[],source:p="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
10
- === Running Funnel: ${e.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${s})`}`),l||console.log(`Custom messages: ${o?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!l){let d=Ce();console.log(`Quota: today ${d.daily.sent}/${d.daily.max} | week ${d.weekly.sent}/${d.weekly.max}`)}console.log("");let c=0;for(let d=0;d<e.length;d++){let m=e[d];try{if(t.isClosed()){console.log(`
8
+ `),process.exit(1));var Z=Jo({token:Pt});var ae=12e4;async function ce(e,{retries:t=2}={}){let n=process.env.NODE_EASY_APPLY_MAIN;if(!n||n.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 o=await Z.askLifebot(n,e,{timeout:ae});return ae=Math.max(12e4,ae*.9),o.content}catch(o){if(o.constructor.name==="LifebotTimeoutError"&&r<t){ae=Math.min(ae*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(ae/1e3)}s...`);continue}throw o}}async function Ot(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let n=`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"),n+=`Additional info: ${t}`),await ce(n)}async function lt(e,t){let n=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await ce(n)}async function Re(e,t){let n=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await ce(n)}ut();import{LIFEBOT_MESSAGE_TYPES as To}from"@ilivemylife/graph-sdk";_e();async function oo(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function sn(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(r=>n.includes(r.toLowerCase()))}async function ln(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(2e3+Math.random()*2e3),await U(e)&&(console.log(" Dismissed Premium overlay"),await b(1500),await oo(e,t));let r=await e.evaluate(()=>{let o=document.querySelector("h1")?.textContent?.trim()||null,s=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,l=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,a=document.querySelector("section#about div.display-flex")?.textContent?.trim()||null,u=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,f=document.querySelector(".dist-value")?.textContent?.trim()||null,d=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,g=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),h=g?parseInt(g[1],10):null,k=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,w=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:o,title:s,location:l,about:a,company:u,connectionDegree:f,connectionsCount:d,mutualConnections:h,photoUrl:k,hasVerifiedBadge:w}});return console.log(`Viewed: ${r.name} - ${r.title}`),{...r,profileUrl:t}}catch(n){console.error(`Error viewing profile ${t}:`,n.message);try{await e.goto("about:blank",{timeout:1e4}),await b(1e3)}catch{}return null}}async function $e(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(n).map(i=>i.getAttribute("aria-label")),o=document.querySelector('button[aria-label*="Message"]'),s=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:n.length,pendingLabels:r,hasMessageBtn:!!o,hasConnectBtn:!!s};return n.length>0?{status:"pending",debug:l}:o&&!s?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function wt(e){let t=null,n=await e.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(i=u.textContent?.trim(),i&&!i.includes("notification")))return i;let p=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(p)return p.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let i=await e.evaluate(()=>{let p=document.querySelectorAll('a[href*="custom-invite"]');return{count:p.length,labels:Array.from(p).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),t=await e.evaluateHandle(p=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),c=p.toLowerCase().split(" ")[0],d=null,m=null;for(let y of f){let g=y.getBoundingClientRect();if(g.width===0||g.height===0)continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(c)){d=y;break}m||(m=y)}return d||m||null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let i=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let u=await e.evaluate(f=>{let c=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),d=document.querySelectorAll("button[aria-label]");return Array.from(d).filter(y=>{let g=y.getAttribute("aria-label")||"";return(g.toLowerCase().includes("invite")||g.toLowerCase().includes("connect"))&&c.test(g)}).map(y=>y.getAttribute("aria-label")?.slice(0,50))},i);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(f=>{let c=document.querySelectorAll("button[aria-label]"),d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let m of c){let y=m.getAttribute("aria-label")||"";if((y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&d.test(y))return m}return null},i);let p=t?.asElement?.()||null;if(p||await t?.dispose?.().catch(()=>{}),p)return console.log(" Found: button matching profile name"),{button:p,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let i=await e.evaluate(p=>(p.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping primary button: wrong person (${i})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let o=n?n.split(" ")[0].toLowerCase():"",s=null;for(let i of r){let u=await e.evaluate((p,f)=>{let c=p.className.includes("muted"),d=p.className.includes("sticky-header")||p.className.includes("sticky"),m=p.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,y=(p.getAttribute("aria-label")||"").toLowerCase(),g=y.includes("invite"),h=f?y.includes(f):!0;return{isMuted:c,isStickyHeader:d,inRecommendations:m,hasInvite:g,matchesName:h,ariaLabel:y}},i,o);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}s=i;break}}for(let i of r)i!==s&&await i.dispose().catch(()=>{});if(s)return console.log(" Found: secondary button"),{button:s,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let i of a){let u=await e.evaluate(p=>{let f=p.getBoundingClientRect(),c=f.width>0&&f.height>0,d=p.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:c,isInStickyHeader:d,top:f.top}},i);if(u.isVisible&&!u.isInStickyHeader){l=i,console.log(" Found More button by ID pattern (main)");break}}for(let i of a)i!==l&&await i.dispose().catch(()=>{});if(!l&&a.length>0&&(l=a[a.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let i=await e.evaluateHandle(()=>{let p=Array.from(document.querySelectorAll("button, a")).find(c=>{let d=c.innerText?.trim(),m=c.getAttribute("aria-label")||"",y=c.getBoundingClientRect();return y.top<100||y.top>600||y.width===0?!1:d==="Follow"||d==="Message"||d==="Connect"||m.includes("Follow")||m.includes("Message")||m.includes("Invite")});if(!p)return null;let f=p.parentElement;for(let c=0;c<8&&f;c++){for(let d of f.querySelectorAll("button"))if(d.innerText?.trim()==="More"&&d!==p)return d;f=f.parentElement}return null});l=i?.asElement?.()||null,l||await i?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(p=>p.scrollIntoView({behavior:"smooth",block:"center"}),l),await b(500),await e.evaluate(p=>p.click(),l),await b(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),u||(u=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect"]')),!u){let p=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let c of f){let d=c.querySelector('a[href*="custom-invite"]');if(d)return d;for(let m of c.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(m.innerText?.trim()==="Connect")return m}return null});u=p?.asElement?.()||null,u||await p?.dispose?.().catch(()=>{})}if(!u){let p=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),c=[];for(let d of f)for(let m of d.querySelectorAll('[role="menuitem"], a, div')){let y=m.innerText?.trim();y&&y.length<40&&c.push(y)}return[...new Set(c)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(p)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(i){console.log(" More dropdown click failed:",i.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let i=await e.evaluate(p=>(p.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping generic button: wrong person (${i})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function an(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await b(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),o=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),s=n.tag==="DIV";if(o){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(p=>p.click(),t)]),await b(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 b(2e3),"premium_redirect"}else s?(await e.evaluate(u=>u.click(),t),await b(3e3)):(await e.evaluate(u=>u.click(),t),await b(3e3));let l=e.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),i=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${i}`:` \u26A0 No modal after connect click \u2014 ${i}`),"success"}async function cn(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await b(1500);let n=await wt(e);if(n){await e.evaluate(o=>o.click(),n),await b(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(o=>o.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function un(e,t,n={}){let{message:r=null,useCustomMessage:o=!0,skipIfPending:s=!0,skipIfConnected:l=!0,excludeLocations:a=[]}=n,i={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
9
+ --- Connecting: ${u} ---`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(5e3),await U(e)&&(console.log(" Dismissed Premium overlay"),await b(2e3),await oo(e,t),await b(2e3)),i.profileInfo=await e.evaluate(()=>{let h=document.querySelector("h1")?.textContent?.trim()||null,S=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,k=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,x=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,T=document.querySelector(".dist-value")?.textContent?.trim()||null,L=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,K=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),be=K?parseInt(K[1],10):null,le=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,Y=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:h,title:S,location:k,company:x,connectionDegree:T,connectionsCount:L,mutualConnections:be,photoUrl:le,hasVerifiedBadge:Y}}),a.length>0&&sn(i.profileInfo?.location,a))return console.log(` \u26A0 Excluded location: ${i.profileInfo.location}`),i.reason="excluded_location",i;let f=await $e(e);if(f==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(f==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await U(e);let c=await wt(e);if(!c&&(await U(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await b(2e3),c=await wt(e)),!c))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;if(i.method=c.method,await an(e,c.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(4e3);let h=await $e(e);if(h==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${h} \u2014 trying More dropdown...`),await U(e),await b(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),S),await b(500),await S.click().catch(()=>e.evaluate(w=>w.click(),S)),await b(2e3);let k=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(k){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(I=>I.click(),k),await b(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),i.reason="premium_required",i;if(await $e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.method="more_dropdown",i.withCustomMessage=!1,i;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await b(500),i.reason="premium_required",i}catch(k){return console.log(" More dropdown failed:",k.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let h=await e.$('button[aria-label="Dismiss"]');return h&&await h.click(),await b(500),i.reason="email_required",i}let y=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!y&&!g){let h=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let k=S.querySelector('button[aria-label="Add a note"]'),w=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!k,sendWithout:!!w}});if(h.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));y=S?.asElement?.()||null,y||await S.dispose().catch(()=>{})}if(h.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(o){if(y&&r){if(console.log(" Adding personalized note..."),await y.click(),await b(1500),await e.$("div.modal-upsell")){let k=await cn(e);return i.success=k,i.connectionSent=k,i.reason=k?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let k=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=r.replace("{name}",k);await S.type(w,{delay:20}),await b(500);let x=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(x){try{await x.evaluate(I=>I.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=w,i}}}else if(g){console.log(" Sending without note...");try{await g.evaluate(h=>h.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}else if(y&&!r){console.log(" No message provided, sending without note...");let h=await e.$('button[aria-label="Send without a note"]');if(h){try{await h.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let h=g;if(h){try{await h.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}if(c.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(4e3)),await U(e),await b(500);let S=await e.$$('button[id*="profile-overflow-action"]'),k=null;for(let w of S){let x=await e.evaluate(I=>{let T=I.getBoundingClientRect();return{visible:T.width>0&&T.height>0,inSticky:!!I.closest('.sticky-header, [class*="sticky"]')}},w);if(x.visible&&!x.inSticky){k=w;break}}!k&&S.length>0&&(k=S[S.length-1]);for(let w of S)w!==k&&await w.dispose().catch(()=>{});if(k)try{await e.evaluate(x=>x.scrollIntoView({behavior:"smooth",block:"center"}),k),await b(500),await k.click().catch(()=>e.evaluate(x=>x.click(),k)),await b(2e3);let w=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(w){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(C=>C.click(),w),await b(3e3);let x=e.url();if(x.includes("/premium/")||x.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),await $e(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(i.reason="premium_required",i);if(await $e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;let T=await e.$('button[aria-label="Send without a note"]');if(T){console.log(" Modal appeared via More dropdown, sending without note...");try{await T.evaluate(C=>C.click())}catch{}return await b(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(u){console.error(` \u2717 Error: ${u.message}`),i.reason="error",i.error=u.message;let p=u.message.toLowerCase();if(p.includes("detached")||p.includes("session closed")||p.includes("target closed")||p.includes("browser has disconnected")||p.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await b(1e3)}catch{i.fatal=!0}return i}}async function St(e,t,n={}){let{message:r=null,useCustomMessage:o=!0,maxConnections:s=20,viewOnly:l=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:i=null,excludeLocations:u=[],source:p="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
10
+ === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${s})`}`),l||console.log(`Custom messages: ${o?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!l){let d=Ce();console.log(`Quota: today ${d.daily.sent}/${d.daily.max} | week ${d.weekly.sent}/${d.weekly.max}`)}console.log("");let c=0;for(let d=0;d<t.length;d++){let m=t[d];try{if(e.isClosed()){console.log(`
11
11
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
12
- \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${d+1}/${e.length}] Skipping - no URL`);continue}let y=He(m.profileUrl);if(y==="pending"||y==="connected"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"){console.log(`[${d+1}/${e.length}] ${m.name||m.profileUrl} \u2014 skipped (db: ${y})`),y==="pending"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,i&&await i(m,f,{success:!1,reason:y,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${d+1}/${e.length}] ${m.name||m.profileUrl}`);let g=null;if(l){let b=await rn(t,m.profileUrl);b?(f.viewed++,g={success:!0,reason:"viewed",connectionSent:!1,profileInfo:b}):(f.errors++,g={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=s){console.log(` Max connections per session (${s}) reached`);break}let b=ze();if(!b.allowed){console.log(` \u26A0 Global quota exhausted: ${b.reason}`);break}if(g=await an(t,m.profileUrl,{message:r,useCustomMessage:o,excludeLocations:u}),g.success)f.connectionsSent++,g.connectionSent&&Ye(m.profileUrl,p);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(`
12
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${d+1}/${t.length}] Skipping - no URL`);continue}let y=Ge(m.profileUrl);if(y==="pending"||y==="connected"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"){console.log(`[${d+1}/${t.length}] ${m.name||m.profileUrl} \u2014 skipped (db: ${y})`),y==="pending"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,i&&await i(m,f,{success:!1,reason:y,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${d+1}/${t.length}] ${m.name||m.profileUrl}`);let g=null;if(l){let h=await ln(e,m.profileUrl);h?(f.viewed++,g={success:!0,reason:"viewed",connectionSent:!1,profileInfo:h}):(f.errors++,g={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=s){console.log(` Max connections per session (${s}) reached`);break}let h=Qe();if(!h.allowed){console.log(` \u26A0 Global quota exhausted: ${h.reason}`);break}if(g=await un(e,m.profileUrl,{message:r,useCustomMessage:o,excludeLocations:u}),g.success)f.connectionsSent++,g.connectionSent&&We(m.profileUrl,p);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(`
13
13
  \u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(g?.reason==="error"){if(c++,c>=3){console.log(`
14
- \u26A0 ${c} consecutive errors \u2014 aborting funnel`);break}}else c=0;if(g&&g.reason&&(Ve(m.profileUrl,g.reason,{method:g.method,messageSent:g.messageSent,profileInfo:g.profileInfo}),ye(m.profileUrl,{source:p||"funnel",jobId:m.jobId||m.fromJob?.jobId||null,jobTitle:m.fromJob?.title||null,jobCompany:m.fromJob?.company||null,action:g.reason})),i&&await i(m,f,g),d<e.length-1){let b=a+Math.random()*2e3;await h(b)}}if(console.log(`
15
- === 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}`),!l){let d=Ce();console.log(` Quota remaining: today ${d.daily.remaining}/${d.daily.max} | week ${d.weekly.remaining}/${d.weekly.max}`)}return f}_e();async function ro(t){let e=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await t.evaluate(async r=>{let o=null,s=null;for(let f of r)if(o=document.querySelector(f),o){s=f;break}if(!o){let f=document.querySelector("li.scaffold-layout__list-item");if(f){let c=f.parentElement;for(;c&&c!==document.body;){if(c.scrollHeight>c.clientHeight){o=c,s="parent of li.scaffold-layout__list-item";break}c=c.parentElement}}}if(!o)return{found:!1,triedSelectors:r};let l=o.scrollTop,a=300,i=300,u=50,p=0;for(;p<u&&(o.scrollBy(0,a),await new Promise(f=>setTimeout(f,i)),!(o.scrollTop+o.clientHeight>=o.scrollHeight));)p++;return{found:!0,usedSelector:s,initialScroll:l,finalScroll:o.scrollTop,scrollHeight:o.scrollHeight,attempts:p}},e)}async function so(t,{easyApplyOnly:e=!0}={}){let n=await t.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(o=>{let l=(o.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=o.querySelector("a.job-card-container__link");if(a){let i=a.getAttribute("href").split("?")[0],u=o.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),p=o.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),f=o.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),c=o.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:i,isEasyApply:l,applyType:l?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${i}`,jobTitle:u,companyName:p,location:f,salary:c||null,jobLink:l?a.href:null}}return{isEasyApply:!1}})});return e?n.filter(r=>r.isEasyApply&&r.href):n.filter(r=>r.href)}async function io(t){let e=await t.evaluate(()=>{let n=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(n&&!n.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return n.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",e.success?e.pageState:e.reason),e.success&&await h(2e3),e.success}async function vt(t,e){let n=t.url();if(n.includes("/jobs/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to job search..."),await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await h(3e3);let o=t.url();if(!o.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${o.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function lo(t,e,n,r){for(let o of e){await vt(t,r)&&(await U(t),await h(2e3));let l=await t.$(`a[data-control-id="${o.dataId}"]`),a="dataId";if(!l){let i=o.id?.match(/\d+/)?.[0];i&&(l=await t.$(`a[href*="/jobs/view/${i}/"]`),l&&(a="href"))}if(l){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${o.jobTitle}`);let i=await t.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await t.evaluate(c=>c.scrollIntoView({block:"center"}),l),await h(300),await l.click(),await h(1500);let u=!1;for(let c=0;c<8;c++){let d=await t.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(d&&d!==i){u=!0;break}await h(500)}if(!u){await t.evaluate(c=>c.click(),l),await h(1500);for(let c=0;c<6;c++){let d=await t.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(d&&d!==i){u=!0;break}await h(500)}u||console.log(` \u26A0 Panel did not update after retry click for: ${o.jobTitle}`)}let p=await t.evaluate(()=>{let c=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let d of c)for(let m of d.querySelectorAll("button")){let y=m.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return m.click(),y}return null});p&&console.log(` Dismissed popup before processing (${p})`);let{keepGoing:f}=await n(t,o);if(!f)return{keepGoing:!1}}else{let i=o.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${o.jobTitle||o.id} (dataId=${o.dataId}, jobId=${i})`)}}return{keepGoing:!0}}async function ao(t){return t.evaluate(()=>{let e=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,n=e.querySelector(".hirer-card__hirer-information");if(n){let l=n.querySelector('a[href*="/in/"]'),a=n.querySelector(".jobs-poster__name")||n.querySelector("strong")||n.querySelector('[class*="name"]');if(l)return{name:a?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"hiring_team"}}let r=e.querySelector(".jobs-poster__name");if(r){let l=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(l)return{name:r.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"poster_name"}}let o=e.querySelector(".job-details-people-who-can-help__section--two-pane")||e.querySelector('[class*="people-who-can-help"]');if(o){let l=o.querySelector('a[href*="/in/"]');if(l)return{name:(o.querySelector(".jobs-poster__name")||o.querySelector("strong"))?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"people_section"}}let s=e.querySelectorAll('a[href*="/in/"]');for(let l of s){let a=l.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:l.href?.split("?")[0],source:"details_link"}}return null})}async function co(t){return t.evaluate(()=>{let e=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(e.querySelector(".jobs-description__content")||e.querySelector(".jobs-box__html-content")||e.querySelector(".jobs-description"))?.innerText?.trim()||"",o={},s=e.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let X of s){let st=X.querySelector(".job-criteria__subheader")?.textContent?.trim(),Nt=X.querySelector(".job-criteria__text")?.textContent?.trim();st&&Nt&&(o[st.toLowerCase()]=Nt)}let l=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],a=[];for(let X of l)new RegExp("\\b"+X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(X.replace(/\\\+/g,"+"));let u=e.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,f=e.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,c=e.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),d=c?.innerText?.trim()||null,y=(c?.querySelector('a[href*="/company/"]')||e.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,b=e.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",k=b.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,w=b.match(/(\d[\d,]*)\s+applicant/i),C=w?parseInt(w[1].replace(/,/g,"")):null,I=e.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),T=Array.from(I).map(X=>X.innerText?.trim()?.replace(/\s+/g," ")),L=T.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,$=T.join(" ")+" "+b,R=/\bremote\b/i.test($)?"remote":/\bhybrid\b/i.test($)?"hybrid":/\bon-?site\b/i.test($)?"onsite":null,K=/\bcontract\b/i.test($)?"contract":/\bfull-?time\b/i.test($)?"full-time":/\bpart-?time\b/i.test($)?"part-time":/\bfreelance\b/i.test($)?"freelance":/\btemporary\b/i.test($)?"temporary":null,H=e.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",Y=e.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",D=(H+" "+r+" "+Y).toLowerCase(),F=H.toLowerCase(),_=[];/\bremote\b/.test(D)&&_.push("remote"),/\bhybrid\b/.test(D)&&_.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(D)&&_.push("onsite"),(_.length===0||!_.includes("remote")&&!_.includes("hybrid")&&!_.includes("onsite"))&&/remote/i.test(Y)&&_.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(F)&&_.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(F)&&_.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(F)&&!_.includes("managerial")&&_.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(F)?_.push("junior"):/\b(senior|sr\.?)\b/i.test(F)?_.push("senior"):/\b(staff|principal|distinguished)\b/i.test(F)?_.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(F)?_.push("executive"):/\b(lead|team lead)\b/i.test(F)&&_.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(D)&&_.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(D)&&_.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(D)&&_.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(D)&&_.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(D)&&_.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(D)&&_.push("mobile"),/\b(architect)\b/i.test(F)&&_.push("architect"),/\b(consultant|consulting)\b/i.test(F)&&_.push("consultant");let Mt=(o["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(Mt)||/\bcontract\b/i.test(D))&&_.push("contract"),/full.?time|permanent/i.test(Mt)&&_.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(Y)&&_.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(Y)&&_.push("usa"),(e.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&_.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:f,companyName:d,companyUrl:y?y.startsWith("/")?"https://www.linkedin.com"+y:y:null,aboutCompany:u,seniority:o["seniority level"]||null,employmentType:o["employment type"]||null,industries:o.industries||null,jobFunction:o["job function"]||null,postedTime:k,applicantCount:C,companySize:L,workplaceType:R,contractType:K,techStack:[...new Set(a)],jobTags:[...new Set(_)]}})}At();import"dotenv/config";import*as O from"fs";import*as q from"path";import{fileURLToPath as hn}from"url";var gn=hn(import.meta.url),wn=q.dirname(gn),So=q.dirname(q.dirname(wn)),Ze=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"collected-profiles"):q.join(So,"collected-profiles"),et=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"market-research"):q.join(So,"market-research"),Tt=1,Sn=[{version:1,file:"./v001-normalize-jobs-and-questions.mjs"}];function ko(t){return q.join(t,".schema-version")}function jt(t){let e=ko(t);if(!O.existsSync(e))return{version:0,migrations:[]};try{return JSON.parse(O.readFileSync(e,"utf-8"))}catch{return{version:0,migrations:[]}}}function kn(t,e){O.writeFileSync(ko(t),JSON.stringify(e,null,2))}function go(t,e){if(!O.existsSync(t))return;let n=`.pre-v${String(e).padStart(3,"0")}.backup`,r=O.readdirSync(t).filter(o=>o.endsWith(".json")&&!o.includes(".backup"));for(let o of r){let s=q.join(t,o),l=q.join(t,o+n);try{O.copyFileSync(s,l)}catch(a){console.error(` [!] Failed to backup ${o}: ${a.message}`)}}r.length>0&&console.log(` Backed up ${r.length} files in ${q.basename(t)}/ (${n})`)}var wo=!1;async function vo(){if(wo)return;wo=!0;let t=jt(Ze),e=jt(et),n=Math.min(t.version,e.version);if(n>=Tt)return;console.log(`
16
- \u{1F4E6} Schema migration: v${n} \u2192 v${Tt}`);let r=Sn.filter(o=>o.version>n);for(let o of r){console.log(`
17
- Running migration v${String(o.version).padStart(3,"0")}...`),go(Ze,o.version),go(et,o.version);let s=await import(o.file);try{await s.up(Ze,et)}catch(i){console.error(`
14
+ \u26A0 ${c} consecutive errors \u2014 aborting funnel`);break}}else c=0;if(g&&g.reason&&(He(m.profileUrl,g.reason,{method:g.method,messageSent:g.messageSent,profileInfo:g.profileInfo}),ye(m.profileUrl,{source:p||"funnel",jobId:m.jobId||m.fromJob?.jobId||null,jobTitle:m.fromJob?.title||null,jobCompany:m.fromJob?.company||null,action:g.reason})),i&&await i(m,f,g),d<t.length-1){let h=a+Math.random()*2e3;await b(h)}}if(console.log(`
15
+ === 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}`),!l){let d=Ce();console.log(` Quota remaining: today ${d.daily.remaining}/${d.daily.max} | week ${d.weekly.remaining}/${d.weekly.max}`)}return f}_e();async function no(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 o=null,s=null;for(let f of r)if(o=document.querySelector(f),o){s=f;break}if(!o){let f=document.querySelector("li.scaffold-layout__list-item");if(f){let c=f.parentElement;for(;c&&c!==document.body;){if(c.scrollHeight>c.clientHeight){o=c,s="parent of li.scaffold-layout__list-item";break}c=c.parentElement}}}if(!o)return{found:!1,triedSelectors:r};let l=o.scrollTop,a=300,i=300,u=50,p=0;for(;p<u&&(o.scrollBy(0,a),await new Promise(f=>setTimeout(f,i)),!(o.scrollTop+o.clientHeight>=o.scrollHeight));)p++;return{found:!0,usedSelector:s,initialScroll:l,finalScroll:o.scrollTop,scrollHeight:o.scrollHeight,attempts:p}},t)}async function ro(e,{easyApplyOnly:t=!0}={}){let n=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(o=>{let l=(o.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=o.querySelector("a.job-card-container__link");if(a){let i=a.getAttribute("href").split("?")[0],u=o.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),p=o.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),f=o.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),c=o.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:i,isEasyApply:l,applyType:l?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${i}`,jobTitle:u,companyName:p,location:f,salary:c||null,jobLink:l?a.href:null}}return{isEasyApply:!1}})});return t?n.filter(r=>r.isEasyApply&&r.href):n.filter(r=>r.href)}async function so(e){let t=await e.evaluate(()=>{let n=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(n&&!n.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return n.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 b(2e3),t.success}async function kt(e,t){let n=e.url();if(n.includes("/jobs/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let o=e.url();if(!o.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${o.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function io(e,t,n,r){for(let o of t){await kt(e,r)&&(await U(e),await b(2e3));let l=await e.$(`a[data-control-id="${o.dataId}"]`),a="dataId";if(!l){let i=o.id?.match(/\d+/)?.[0];i&&(l=await e.$(`a[href*="/jobs/view/${i}/"]`),l&&(a="href"))}if(l){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${o.jobTitle}`);let i=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await e.evaluate(c=>c.scrollIntoView({block:"center"}),l),await b(300),await l.click(),await b(1500);let u=!1;for(let c=0;c<8;c++){let d=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(d&&d!==i){u=!0;break}await b(500)}if(!u){await e.evaluate(c=>c.click(),l),await b(1500);for(let c=0;c<6;c++){let d=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(d&&d!==i){u=!0;break}await b(500)}u||console.log(` \u26A0 Panel did not update after retry click for: ${o.jobTitle}`)}let p=await e.evaluate(()=>{let c=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let d of c)for(let m of d.querySelectorAll("button")){let y=m.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return m.click(),y}return null});p&&console.log(` Dismissed popup before processing (${p})`);let{keepGoing:f}=await n(e,o);if(!f)return{keepGoing:!1}}else{let i=o.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${o.jobTitle||o.id} (dataId=${o.dataId}, jobId=${i})`)}}return{keepGoing:!0}}async function lo(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,n=t.querySelector(".hirer-card__hirer-information");if(n){let l=n.querySelector('a[href*="/in/"]'),a=n.querySelector(".jobs-poster__name")||n.querySelector("strong")||n.querySelector('[class*="name"]');if(l)return{name:a?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let l=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(l)return{name:r.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"poster_name"}}let o=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(o){let l=o.querySelector('a[href*="/in/"]');if(l)return{name:(o.querySelector(".jobs-poster__name")||o.querySelector("strong"))?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"people_section"}}let s=t.querySelectorAll('a[href*="/in/"]');for(let l of s){let a=l.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:l.href?.split("?")[0],source:"details_link"}}return null})}async function ao(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()||"",o={},s=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let X of s){let rt=X.querySelector(".job-criteria__subheader")?.textContent?.trim(),Mt=X.querySelector(".job-criteria__text")?.textContent?.trim();rt&&Mt&&(o[rt.toLowerCase()]=Mt)}let l=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],a=[];for(let X of l)new RegExp("\\b"+X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(X.replace(/\\\+/g,"+"));let u=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,c=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),d=c?.innerText?.trim()||null,y=(c?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,h=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",k=h.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,w=h.match(/(\d[\d,]*)\s+applicant/i),x=w?parseInt(w[1].replace(/,/g,"")):null,I=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),T=Array.from(I).map(X=>X.innerText?.trim()?.replace(/\s+/g," ")),L=T.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,$=T.join(" ")+" "+h,R=/\bremote\b/i.test($)?"remote":/\bhybrid\b/i.test($)?"hybrid":/\bon-?site\b/i.test($)?"onsite":null,K=/\bcontract\b/i.test($)?"contract":/\bfull-?time\b/i.test($)?"full-time":/\bpart-?time\b/i.test($)?"part-time":/\bfreelance\b/i.test($)?"freelance":/\btemporary\b/i.test($)?"temporary":null,H=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",Y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",D=(H+" "+r+" "+Y).toLowerCase(),F=H.toLowerCase(),_=[];/\bremote\b/.test(D)&&_.push("remote"),/\bhybrid\b/.test(D)&&_.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(D)&&_.push("onsite"),(_.length===0||!_.includes("remote")&&!_.includes("hybrid")&&!_.includes("onsite"))&&/remote/i.test(Y)&&_.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(F)&&_.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(F)&&_.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(F)&&!_.includes("managerial")&&_.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(F)?_.push("junior"):/\b(senior|sr\.?)\b/i.test(F)?_.push("senior"):/\b(staff|principal|distinguished)\b/i.test(F)?_.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(F)?_.push("executive"):/\b(lead|team lead)\b/i.test(F)&&_.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(D)&&_.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(D)&&_.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(D)&&_.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(D)&&_.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(D)&&_.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(D)&&_.push("mobile"),/\b(architect)\b/i.test(F)&&_.push("architect"),/\b(consultant|consulting)\b/i.test(F)&&_.push("consultant");let Ft=(o["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(Ft)||/\bcontract\b/i.test(D))&&_.push("contract"),/full.?time|permanent/i.test(Ft)&&_.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(Y)&&_.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(Y)&&_.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&_.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:f,companyName:d,companyUrl:y?y.startsWith("/")?"https://www.linkedin.com"+y:y:null,aboutCompany:u,seniority:o["seniority level"]||null,employmentType:o["employment type"]||null,industries:o.industries||null,jobFunction:o["job function"]||null,postedTime:k,applicantCount:x,companySize:L,workplaceType:R,contractType:K,techStack:[...new Set(a)],jobTags:[...new Set(_)]}})}Et();import"dotenv/config";import*as O from"fs";import*as q from"path";import{fileURLToPath as wn}from"url";var Sn=wn(import.meta.url),kn=q.dirname(Sn),wo=q.dirname(q.dirname(kn)),Xe=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"collected-profiles"):q.join(wo,"collected-profiles"),Ze=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"market-research"):q.join(wo,"market-research"),At=1,vn=[{version:1,file:"./v001-normalize-jobs-and-questions.mjs"}];function So(e){return q.join(e,".schema-version")}function Tt(e){let t=So(e);if(!O.existsSync(t))return{version:0,migrations:[]};try{return JSON.parse(O.readFileSync(t,"utf-8"))}catch{return{version:0,migrations:[]}}}function xn(e,t){O.writeFileSync(So(e),JSON.stringify(t,null,2))}function bo(e,t){if(!O.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,r=O.readdirSync(e).filter(o=>o.endsWith(".json")&&!o.includes(".backup"));for(let o of r){let s=q.join(e,o),l=q.join(e,o+n);try{O.copyFileSync(s,l)}catch(a){console.error(` [!] Failed to backup ${o}: ${a.message}`)}}r.length>0&&console.log(` Backed up ${r.length} files in ${q.basename(e)}/ (${n})`)}var go=!1;async function ko(){if(go)return;go=!0;let e=Tt(Xe),t=Tt(Ze),n=Math.min(e.version,t.version);if(n>=At)return;console.log(`
16
+ \u{1F4E6} Schema migration: v${n} \u2192 v${At}`);let r=vn.filter(o=>o.version>n);for(let o of r){console.log(`
17
+ Running migration v${String(o.version).padStart(3,"0")}...`),bo(Xe,o.version),bo(Ze,o.version);let s=await import(o.file);try{await s.up(Xe,Ze)}catch(i){console.error(`
18
18
  [FATAL] Migration v${o.version} failed: ${i.message}`),console.error(` Backups are in collected-profiles/ and market-research/ (.pre-v${String(o.version).padStart(3,"0")}.backup)`),console.error(` Fix the issue and restart.
19
- `),process.exit(1)}let l=new Date().toISOString(),a={version:o.version,name:s.NAME||`v${String(o.version).padStart(3,"0")}`,appliedAt:l};for(let i of[Ze,et]){if(!O.existsSync(i))continue;let u=jt(i);u.version=o.version,u.migratedAt=l,u.migrations.push(a),kn(i,u)}console.log(` \u2713 Migration v${String(o.version).padStart(3,"0")} complete`)}try{let{resetCaches:o}=await Promise.resolve().then(()=>(_e(),wt));o()}catch{}try{let{resetCaches:o}=await Promise.resolve().then(()=>(At(),ho));o()}catch{}console.log(`
20
- \u2713 Schema is now at v${Tt}
21
- `)}import"dotenv/config";import*as G from"fs";import*as z from"path";import{fileURLToPath as Cn}from"url";import"dotenv/config";function vn(t){if(!t||t<1e3)return`${t||0}ms`;let e=Math.round(t/1e3);if(e<60)return`${e}s`;let n=Math.floor(e/60),r=e%60;return r?`${n}m ${r}s`:`${n}m`}function xn({scriptName:t,mode:e,status:n,error:r,duration:o}){let s=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),a=o?` ${vn(o)}`:"",i=n==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=e&&e!=="default"?` (${e})`:"";return`${s} ${t}${u} \u2014 ${i} \u2014 ${l}${a}`}async function xo({scriptName:t,mode:e,status:n,summaryLines:r,error:o,duration:s}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(r)||r.length===0)return;let i=`**${xn({scriptName:t,mode:e,status:n,error:o,duration:s})}**
19
+ `),process.exit(1)}let l=new Date().toISOString(),a={version:o.version,name:s.NAME||`v${String(o.version).padStart(3,"0")}`,appliedAt:l};for(let i of[Xe,Ze]){if(!O.existsSync(i))continue;let u=Tt(i);u.version=o.version,u.migratedAt=l,u.migrations.push(a),xn(i,u)}console.log(` \u2713 Migration v${String(o.version).padStart(3,"0")} complete`)}try{let{resetCaches:o}=await Promise.resolve().then(()=>(_e(),gt));o()}catch{}try{let{resetCaches:o}=await Promise.resolve().then(()=>(Et(),ho));o()}catch{}console.log(`
20
+ \u2713 Schema is now at v${At}
21
+ `)}import"dotenv/config";import*as G from"fs";import*as z from"path";import{fileURLToPath as $n}from"url";import"dotenv/config";function Cn(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r?`${n}m ${r}s`:`${n}m`}function _n({scriptName:e,mode:t,status:n,error:r,duration:o}){let s=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),a=o?` ${Cn(o)}`:"",i=n==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${u} \u2014 ${i} \u2014 ${l}${a}`}async function vo({scriptName:e,mode:t,status:n,summaryLines:r,error:o,duration:s}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(r)||r.length===0)return;let i=`**${_n({scriptName:e,mode:t,status:n,error:o,duration:s})}**
22
22
 
23
23
  ${r.join(`
24
- `)}`;try{await Z.addMessage(l,i)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var _n=Cn(import.meta.url),$n=z.dirname(z.dirname(_n)),It=process.env.DATA_DIR?z.resolve(process.env.DATA_DIR,"collected-profiles"):z.join($n,"collected-profiles"),qt=z.join(It,"run-log.json");function En(t,e){let n=JSON.stringify(e,null,2),r=t+".tmp";G.writeFileSync(r,n);for(let o=0;o<3;o++)try{G.renameSync(r,t);return}catch(s){if(o<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function Co(){try{if(!G.existsSync(qt))return{runs:[]};let t=JSON.parse(G.readFileSync(qt,"utf-8"));return!t.runs||!Array.isArray(t.runs)?{runs:[]}:t}catch{return{runs:[]}}}function _o(t){G.existsSync(It)||G.mkdirSync(It,{recursive:!0});try{En(qt,t)}catch(e){console.error(`[!] Failed to save run-log.json: ${e.message}`)}}function $o(t,e="default"){let n=Co();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let r=new Date,o={timestamp:r.toISOString(),script:t,mode:e,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(o);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>s),_o(n),{script:t,mode:e,startTime:r.getTime(),runIndex:n.runs.length-1}}function Eo(t,e,n=null,r=null){if(!t)return;let o=null;try{let l=Co(),a=l.runs[t.runIndex];if(a&&a.status==="running"&&a.script===t.script)a.status=e,a.result=e,a.duration=Date.now()-t.startTime,a.stats=n,a.error=r,o=a.duration;else{let i=l.runs.find(u=>u.script===t.script&&u.status==="running"&&u.timestamp===new Date(t.startTime).toISOString());i&&(i.status=e,i.result=e,i.duration=Date.now()-t.startTime,i.stats=n,i.error=r,o=i.duration)}_o(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let l=e==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";xo({scriptName:t.script,mode:t.mode,status:l,summaryLines:s,error:r,duration:o??Date.now()-t.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}await vo();var rt=0,Tn=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",jn=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),In=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",Dt=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(t=>t.trim()).filter(Boolean):[],tt=-1;async function qn(){if(tt===-1){let t=await ce("What is last counter? Answer only number!!");if(console.log(`Lifebot answered about lastIndex:${t}`),!/^\d+$/.test(t.trim()))throw new Error(`Last Counter is not a number, got: "${t}"`);tt=Pt(t)+1,console.log(`lastIndex initialized as: ${tt}`)}return tt++}var Mo=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${Mo}`);var Dn=[{label:"browser-dead",match:t=>/Target closed|Session closed/.test(t.message),severity:"fatal"},{label:"session-expired",match:t=>/Session expired|redirected to login/.test(t.message),severity:"fatal"},{label:"lifebot-timeout",match:t=>t.constructor.name==="LifebotTimeoutError",severity:"transient",maxConsecutive:3,cleanup:"popup"},{label:"protocol-timeout",match:t=>t.constructor.name==="ProtocolError"||t.constructor.name==="TimeoutError"||/Protocol error|timed out/.test(t.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3,cleanup:"popup"},{label:"stale-context",match:t=>/Execution context was destroyed|Cannot find context/.test(t.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3,cleanup:"popup"}],Le={};function Ln(t){return Dn.find(e=>e.match(t))||null}function Rn(t){return Le[t]=(Le[t]||0)+1,Le[t]}function To(){for(let t of Object.keys(Le))Le[t]=0}var Lt=0;function Fn(){return Lt++,Lt>=Mo?(console.log(`Max run counter reached with ${Lt}`),!1):!0}async function Mn(t){let e=await ro(t)}async function Nn(t){return so(t,{easyApplyOnly:!0})}async function Pn(t){return io(t)}async function Ft(t,e){return vt(t,e)}async function On(t){let e=process.env.LINKEDIN_SEARCH_URL,n=3;for(let r=1;r<=n;r++){r>1&&(console.log(`
25
- --- Pass ${r}/${n}: re-checking for new jobs ---`),await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await h(3e3));let o=v.submitted,s=!0,l=!0;for(;s&&l;){await Ft(t,e);let a=await Kn(t,Po,Mn);l=a.keepGoing;let i=a.jobsDone;if(console.log("keepGoing",l),console.log("pageDone"),console.log(i.length),!l)break;s=await Pn(t)}if(console.log(`Scraping pass ${r} complete.`),!l)break;if(v.submitted===o){console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${v.submitted-o} new jobs in pass ${r}.`)}}async function jo(t,e,n){let r=process.env.LINKEDIN_SEARCH_URL;return lo(t,e,n,r)}async function Io(t,e){let n=e?.match(/\d+/)?.[0]||e,r=await t.$(`div[data-job-id="${n}"] button[aria-label^="Dismiss"]`);r?(await r.click(),console.log(` Dismissed job ${n} from list`)):console.log(` Dismiss button not found for ${n}`)}async function Un(t,e){try{let n=await ao(t);if(n&&n.profileUrl){n.fromJob={title:e.jobTitle,company:e.companyName,url:e.href},we("recruiters-from-jobs",n)?(rt++,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: ${n.name?.substring(0,30).padEnd(30)} \u2502`),console.log(`\u2502 Source: ${n.source.padEnd(28)} \u2502`),console.log(`\u2502 Company: ${e.companyName?.substring(0,27).padEnd(27)} \u2502`),console.log(`\u2502 Total today: ${String(rt).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: ${n.name}`),xe(n.profileUrl,{name:n.name,source:"recruiters-from-jobs"});let o=e.href?.match(/jobs\/view\/(\d+)/)?.[1];if(o){Ge(n.profileUrl,o),ye(n.profileUrl,{source:"job-apply",jobId:o,jobTitle:e.title||null,jobCompany:e.companyName||null,action:"recruiter_found"});let s=n.fromJob?.companyUrl;s&&Ke(s,{recruiterUrl:n.profileUrl,jobId:o})}return n}else console.log(" \u26AA No recruiter found on this job page");return null}catch(n){return console.error("Error extracting recruiter:",n.message),null}}async function nt(t){return await t.evaluate(()=>{let e=document.body.innerText||"",n=document.querySelector("#interop-outlet")?.shadowRoot?.textContent||"",r=e+" "+n;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 No(t){try{let e=await t.evaluate(()=>{let n=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let o of n){let s=o.querySelectorAll("button");for(let l of s){let a=l.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return l.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return e&&console.log(" Daily limit popup closed"),e}catch{return!1}}async function qo(t){await t.evaluate(()=>{let l=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of l)for(let i of a.querySelectorAll("button")){let u=i.innerText?.trim();if(u==="Continue applying"||u==="Got it"||u==="Dismiss"){i.click();return}}});let e=Date.now(),n=3e3,r=null;for(;!r&&Date.now()-e<n;){if(r=await t.$(".jobs-apply-button"),r||(r=await t.$('button[aria-label*="Easy Apply"]')),r||(r=await t.$('a[aria-label*="Easy Apply"]')),r||(r=await t.$('a[href*="/apply/"]')),!r){let l=await t.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let i of a){let u=i.innerText?.trim();if(u==="Easy Apply"||u==="Apply")return i}return null});r=l?.asElement?.()||null,r||await l.dispose().catch(()=>{})}r||await new Promise(l=>setTimeout(l,300))}let o=Date.now()-e;if(console.log(` pressApplyButton: found=${!!r}${o>400?` (waited ${o}ms)`:""}`),r){if(await t.evaluate(u=>u.disabled,r))return await nt(t)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await t.evaluate(u=>u.tagName==="A",r)){await t.evaluate(u=>u.click(),r),await h(3e3);try{await t.waitForFunction(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[data-easy-apply-next-button], button[aria-label="Submit application"]'),{timeout:1e4})}catch{await h(2e3)}}else await r.click(),await h(1500);return await nt(t)?(await No(t),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await nt(t)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function Bn(t){return await t.evaluate(async()=>{function e(){let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length>0)return i;let u=document.querySelector("#interop-outlet")?.shadowRoot;return u&&(i=u.querySelectorAll(".artdeco-inline-feedback__message")),i}let n=3e3,r=e();if(r?.length===0&&(await new Promise(i=>setTimeout(i,n)),r=e()),r?.length===0)return null;let o=r[0];console.log("errorMsg"),console.log(o);let s=o?.textContent.trim(),l=o.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=o.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(l),a||l){console.log("parentElement"),console.log(a);let i=a.querySelector(".artdeco-text-input--label")||a.querySelector("legend .fb-dash-form-element__label-title--is-required")||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||a.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),u=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),p=a.querySelectorAll('input[type="radio"]'),f=a.querySelector("select[data-test-text-entity-list-form-select]"),c=o.parentElement.parentElement.querySelector('input[type="file"]'),d=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(c),i&&u)return{type:"input",labelText:i.textContent.trim(),errorMsgText:s};if(i&&p.length){let m=i?i.querySelector("span:nth-of-type(1)")?.textContent.trim():null,y=Array.from(p).map(b=>{let k=(document.querySelector(`label[for="${b.id}"]`)||b.nextElementSibling)?.textContent?.trim();return{value:b.value,label:k||b.value}}),g=y.map(b=>b.label);return{type:"radio",labelText:m,errorMsgText:s,options:g,optionsData:y}}else if(f){let m=a.querySelector('label[for="'+f.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),y=m?m.querySelector("span:nth-of-type(2)")?.textContent.trim():null,g=Array.from(f.options).map(b=>b.value).filter(b=>b!=="Select an option");return{type:"select",labelText:y,errorMsgText:s,options:g}}else if(c){let m=o.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:s,labelText:m}}else{if(d)return{type:"datePicker",errorMsgText:s};{let m=i?i.querySelector("span:nth-of-type(2)")?.textContent.trim():null,y=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(y.length>0){let g=Array.from(y).map(b=>b.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:m,errorMsgText:s,options:g}}else return null}}}return null})}async function Jn(t,e,n){return await t.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));i.value=o;let u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let p=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});d.dispatchEvent(m)},f=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});d.dispatchEvent(m)};await(async d=>{await new Promise(m=>setTimeout(m,500)),f(d),await new Promise(m=>setTimeout(m,100)),p(d)})(i)}}return null},e,n)}async function Gn(t,e,n){return await t.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('input[type="radio"]'),u=o;if(r.optionsData){let p=r.optionsData.find(f=>f.label.toLowerCase()===o.toLowerCase());p&&(u=p.value,console.log(`Radio: matched label "${o}" to value "${u}"`))}for(let p of i){let c=(document.querySelector(`label[for="${p.id}"]`)||p.nextElementSibling)?.textContent?.trim()||"";if(p.value.toLowerCase()===u.toLowerCase()||c.toLowerCase()===o.toLowerCase()){p.checked=!0;let d=new Event("change",{bubbles:!0});p.dispatchEvent(d),console.log(`Radio selected: value="${p.value}", label="${c}"`);break}}}return null},e,n)}async function Hn(t,e,n){return await t.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelector("select[data-test-text-entity-list-form-select]");if(!i)return null;let u=Array.from(i.options),p=u.find(c=>c.text.toLowerCase()===o.toLowerCase())||u.find(c=>c.text.toLowerCase().includes(o.toLowerCase()));p?i.value=p.value:i.value=o;let f=new Event("change",{bubbles:!0});i.dispatchEvent(f)}return null},e,n)}async function Vn(t,e,n){return await t.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');i.length>0&&i.forEach(u=>{if(u.nextElementSibling.textContent.trim()===o.trim()){u.checked=!0;let p=new Event("change",{bubbles:!0});u.dispatchEvent(p)}})}return null},e,n)}async function Wn(t,e,n){return await t.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s?.length===0)return null;let l=s[0],a=l.closest(".fb-dash-form-element"),i=l.parentElement.parentElement.querySelector('input[type="file"]');if(a&&i){async function u(p,f,c){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let m=new Blob([new Uint8Array(f)]),y=new File([m],c,{type:"application/pdf"}),g=new DataTransfer;g.items.add(y),p.files=g.files;let b=new Event("change",{bubbles:!0});p.dispatchEvent(b)}await u(i,o,process.env.RESUME_FILENAME||"Resume.pdf")}return null},e,n)}async function Do(t){let e=await Bn(t);if(e===null)return null;if(e?.type==="input"){let o=await Ut(e.labelText,e.errorMsgText);o=o?.trim()||o,e.answer=o,await Jn(t,e,o)}else if(e?.type==="radio"){let o=await at(e.labelText,e.options);o=o?.trim()||o;let s=e.options||[];!s.find(a=>a.toLowerCase()===o?.toLowerCase())&&s.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${o}" for "${e.labelText}". Options: ${s.join(", ")}. Retrying...`),o=await at(e.labelText,e.options),o=o?.trim()||o,s.find(i=>i.toLowerCase()===o?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${o}". Using first option: "${s[0]}"`),o=s[0])),e.answer=o,await Gn(t,e,o)}else if(e?.type==="select"){let o=await Fe(e.labelText,e.options);o=o?.trim()||o;let s=e.options||[],l=s.find(a=>a.toLowerCase()===o?.toLowerCase());if(l)o=l;else if(s.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${o}" for "${e.labelText}". Options: ${s.join(", ")}. Retrying...`),o=await Fe(e.labelText,e.options),o=o?.trim()||o;let a=s.find(i=>i.toLowerCase()===o?.toLowerCase());a?o=a:(console.log(` \u26A0 Retry also invalid: "${o}". Using first option: "${s[0]}"`),o=s[0])}e.answer=o,await Hn(t,e,o)}else if(e?.type==="checkbox"){let o=await Fe(e.labelText,e.options);e.answer=o,await Vn(t,e,o)}else if(e?.type==="file"){let o=process.env.RESUME_PDF_URL;e.answer=o;let s=await fetch(o);if(!s.ok)throw new Error("Network response was not ok");let l=await s.arrayBuffer();await Wn(t,e,l)}else e?.type==="datePicker"?e.answer="(not implemented)":e.answer="(unknown field type)";let n=e.labelText?.slice(0,55)||"?",r=e.answer!=null?`"${String(e.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${e.type}] "${n}" \u2192 ${r}`),e}async function Yn(t){return await t.evaluate(async()=>{let e=[],n=document.querySelectorAll(".fb-dash-form-element");if(!n||n.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(n=r.querySelectorAll(".fb-dash-form-element"))}if(!n||n.length===0)return[];for(let r of n){let o=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),s=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),l=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),i=r.querySelector("select[data-test-text-entity-list-form-select]"),u=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),p=r.querySelector('input[type="file"]');if(o&&l&&a.length===0){let f=o.textContent.trim();e.push({type:"input",labelText:f,answer:l.value,isRequired:s,wasPreFilled:!!l.value})}else if(o&&a.length){let f=o?o.querySelector("span:nth-of-type(1)")?.textContent.trim():null,c=Array.from(a).map(m=>m.value),d=(Array.from(a).find(m=>m.checked)||{}).value?.toLowerCase()??"";e.push({type:"radio",labelText:f,options:c,answer:d,isRequired:s,wasPreFilled:!!d})}else if(i){let f=r.querySelector('label[for="'+i.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),c=f?f.querySelector("span:nth-of-type(2)")?.textContent.trim():null,d=Array.from(i.options).map(y=>y.value).filter(y=>y!=="Select an option"),m=i.value!=="Select an option"?i.value:"";e.push({type:"select",labelText:c,options:d,answer:m,isRequired:s,wasPreFilled:!!m})}else if(u.length>0){let f=r.querySelector("legend span")?.textContent?.trim(),c=Array.from(u).map(d=>({label:d.nextElementSibling?.textContent?.trim()||d.value,checked:d.checked}));e.push({type:"checkbox",labelText:f,options:c.map(d=>d.label),answer:c.filter(d=>d.checked).map(d=>d.label).join(", "),isRequired:s})}else if(p){let f=r.querySelector("label")?.textContent?.trim();e.push({type:"file",labelText:f,answer:p.value?"uploaded":"",isRequired:s})}}return e})}async function Lo(t,e,n){return await t.evaluate(async(r,o)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelector(".artdeco-text-input--label")||l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||l.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=l.querySelector(".artdeco-text-input--input")||l.querySelector("input");if(a&&i&&r===a.textContent.trim()){i.value=o;let u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r==="City"||r==="Location (city)"){let p=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});d.dispatchEvent(m)},f=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});d.dispatchEvent(m)};await(async d=>{await new Promise(m=>setTimeout(m,500)),f(d),await new Promise(m=>setTimeout(m,100)),p(d)})(i)}return!0}}return!1},e,n)}async function Ro(t,e){let n=[],r=!0,o=0,s=null,l=0;for(;r;){if(o++,await nt(t))return console.log(" Daily limit reached during form navigation"),await No(t),{filledFields:n,formPages:o,skip:!0,dailyLimitReached:!0};let u=(await Yn(t)).filter(d=>!n.some(m=>m.labelText===d.labelText));n.push(...u);try{let d=n.find(y=>y.labelText==="City"||y.labelText==="Location (city)"),m=n.filter(y=>y.labelText!=null).find(y=>y.labelText!==null&&y.labelText.trim()!==null&&(y.labelText.trim().toLowerCase()==="cv"||y.labelText.trim().toLowerCase()==="curriculum vitae"||y.labelText.trim().toLowerCase()==="cover letter"||y.labelText.trim().toLowerCase()==="cover"));if(d&&!d.answer){let y=process.env.City;await Lo(t,d.labelText,y),d.answer=y}else if(m){let y=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!m.answer||m.answer!==y)&&(await h(1e4),await Lo(t,m.labelText,y),m.answer=y,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}let p=null;try{p=await e(t)}catch(d){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${d.message?.slice(0,100)}`),{filledFields:n,formPages:o,skip:!0}}if(p!==null){if(p.type==="datePicker")return{filledFields:n,formPages:o,skip:!0,duplicateField:p};let d=p&&n.find(y=>y.errorMsgText&&y.labelText===p.labelText);if(d)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(p,null,2)),console.log("Previous attempt:",JSON.stringify(d,null,2)),{filledFields:n,formPages:o,skip:!0,duplicateField:p};let m=n.findIndex(y=>y.labelText===p.labelText&&!y.answer);m!==-1&&n.splice(m,1),n.push(p)}let f=await t.evaluate(()=>{let d=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of d){let y=m.querySelectorAll("button");for(let g of y){let b=g.innerText?.trim();if(b==="Continue applying"||b==="Got it"||b==="Dismiss")return g.click(),b}}return null});f&&console.log(` Dismissed safety popup (${f})`);let c=await t.evaluate(async()=>{function d(w){let C=document.querySelector(w);if(C)return C;let I=document.querySelector("#interop-outlet")?.shadowRoot;return I?I.querySelector(w):null}function m(w){let C=document.querySelectorAll(w),I=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(w);return[...C||[],...I||[]]}let y=d("button[data-easy-apply-next-button]")||d('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(w=>w.innerText?.trim()==="Next"),g=m('footer[role="presentation"] button').some(w=>w.innerText.trim()==="Review")||m("button").some(w=>w.innerText.trim()==="Review"&&w.getAttribute("aria-label")?.includes("Review")),b=d('button[aria-label="Submit application"]'),S=async()=>{let w=d("button[data-easy-apply-next-button]")||d('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(C=>C.innerText?.trim()==="Next");w?w.click():console.log("Next button not found")},k=()=>{let w=m("button").find(C=>C.innerText?.trim()==="Review");w&&w.click()};return y?(await S(),{type:"next"}):g?(await k(),{type:"review"}):b?{type:"submit"}:{type:null}});if(c==null)return{filledFields:n,formPages:o,skip:!0};if(c.type&&console.log(` \u2192 ${c.type}`),c.type===null){let d=await t.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let y of m){let g=y.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let b of g){let S=b.innerText||"";if(S.includes("application was sent")||S.includes("resume into a profile")||S.includes("Application submitted")||S.includes("Next best action"))for(let k of b.querySelectorAll("button")){let w=k.innerText?.trim();if(w==="Not now"||w==="Done"||w==="Dismiss"||w==="Got it")return k.click(),w}}}return null});if(d)return console.log(` Dismissed stale popup (${d}) \u2014 need to re-open Easy Apply`),await h(1500),{filledFields:n,formPages:o,skip:!1,stalePopupDismissed:!0};if(l===0){let m=await t.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],b=[];for(let S of y){for(let w of S.querySelectorAll("button")){let C=w.innerText?.trim();C&&C.length<60&&g.push(C)}let k=S.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');k&&b.push(k.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:b.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(c.type==="submit")return{filledFields:n,formPages:o,skip:!1};if(p===null&&c.type===s?l++:l=0,s=c.type,l>=5){let d=await t.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),y=[],g=[];for(let b of m){for(let S of b.querySelectorAll(".artdeco-inline-feedback__message"))y.push(S.textContent?.trim()?.slice(0,60));for(let S of b.querySelectorAll(".fb-dash-form-element")){let k=S.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),w=S.querySelector("input, select, textarea"),C=!!S.querySelector(".artdeco-inline-feedback__message");k&&(C||w&&!w.value)&&g.push({label:k.slice(0,40),hasError:C,value:w?.value?.slice(0,20)||""})}}return{errors:y,emptyRequired:g.slice(0,5)}});return console.error(` \u26A0 Stuck on "${c.type}" for ${l} iterations \u2014 form not progressing.`),d.errors.length&&console.error(` Visible errors: ${JSON.stringify(d.errors)}`),d.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(d.emptyRequired)}`),console.error(" Skipping job."),{filledFields:n,formPages:o,skip:!0,duplicateField:{labelText:`stuck_on_${c.type}`}}}await h(1500),r=!0}return{filledFields:n,formPages:o,skip:!1}}async function Fo(t){try{await t.evaluate(()=>{let e=document.getElementById("follow-company-checkbox");e?(e.checked=!1,e.dispatchEvent(new Event("change",{bubbles:!0}))):console.warn("Unfollow checkbox not found.")})}catch(e){console.error("Error in unfollowJobCheckbox:",e)}}async function Qn(t){let e=await t.$('button[aria-label="Submit application"]');if(!e){let n=await t.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Submit application"]')||null);e=n?.asElement?.()||null,e||await n.dispose().catch(()=>{})}e&&await e.click()}async function zn(t){try{let e=await t.evaluate(()=>{let n=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of n){for(let s of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(s.innerText?.trim()==="Done")return s.click(),"Done";let o=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let s of o){let l=s.innerText||"";if(l.includes("application was sent")||l.includes("Application sent")||l.includes("resume into a profile")||l.includes("Next best action"))for(let a of s.querySelectorAll("button")){let i=a.innerText?.trim();if(i==="Not now"||i==="Dismiss")return a.click(),i}}}return null});e?(console.log(` Post-apply popup closed (${e})`),await h(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(e){console.log("closeApplicationSentPopup: "+e.message)}}async function ot(t){try{await t.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let e=await t.$('button[aria-label="Dismiss"]');e?(await e.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await h(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 Rt(t){try{await t.waitForSelector('button[data-control-name="discard_application_confirm_btn"]',{timeout:3e3});let e=await t.$('button[data-control-name="discard_application_confirm_btn"]');e&&(await e.click(),console.log("Discard confirmed"),await h(500))}catch{console.log("No discard confirmation needed")}}async function Po(t,e){let n=[],r=e._fromQueue;try{v.attempted++,console.log(`
26
- --- Processing: ${e.jobTitle} at ${e.companyName} ---`);let o=e.id?.match(/\d+/)?.[0];if(o&&$t(o)?.status==="applied")return v.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (our DB): ${e.jobTitle} \u2014 skipping`),{keepGoing:!0};let s=null;if(!r){let c=await t.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name")?.innerText?.trim()?.replace(/\s+/g," ")?.toLowerCase()||""),d=(e.companyName||"").replace(/\s+/g," ").toLowerCase().trim(),m=c.split(" ")[0],y=d.split(" ")[0];if(m&&y&&!c.includes(y)&&!d.includes(m))return v.mismatch++,console.log(` \u2298 MISMATCH: expected company "${e.companyName}" but panel shows "${c}"`),console.log(` job title: "${e.jobTitle}"`),{keepGoing:!0};if(await t.evaluate(()=>{let b=document.querySelector(".jobs-details__main-content, .job-details-jobs-unified-top-card");if(!b)return!1;let S=b.innerText;return/Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago/i.test(S)||S.includes("Application submitted")}))return v.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${e.jobTitle} \u2014 skipping`),o&&ie(o,"applied",{source:"detected"}),{keepGoing:!0};try{s=await co(t)}catch{}}let l=await qo(t);if(l.dailyLimitReached){console.log(`
24
+ `)}`;try{await Z.addMessage(l,i)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var En=$n(import.meta.url),An=z.dirname(z.dirname(En)),jt=process.env.DATA_DIR?z.resolve(process.env.DATA_DIR,"collected-profiles"):z.join(An,"collected-profiles"),It=z.join(jt,"run-log.json");function Tn(e,t){let n=JSON.stringify(t,null,2),r=e+".tmp";G.writeFileSync(r,n);for(let o=0;o<3;o++)try{G.renameSync(r,e);return}catch(s){if(o<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function xo(){try{if(!G.existsSync(It))return{runs:[]};let e=JSON.parse(G.readFileSync(It,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Co(e){G.existsSync(jt)||G.mkdirSync(jt,{recursive:!0});try{Tn(It,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function _o(e,t="default"){let n=xo();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let r=new Date,o={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(o);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>s),Co(n),{script:e,mode:t,startTime:r.getTime(),runIndex:n.runs.length-1}}function $o(e,t,n=null,r=null){if(!e)return;let o=null;try{let l=xo(),a=l.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=r,o=a.duration;else{let i=l.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());i&&(i.status=t,i.result=t,i.duration=Date.now()-e.startTime,i.stats=n,i.error=r,o=i.duration)}Co(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";vo({scriptName:e.script,mode:e.mode,status:l,summaryLines:s,error:r,duration:o??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import Eo from"fs";import jn from"path";var In="cookies.json";function qn(){let e=process.env.ILML_SCOPE_DIR;return e?jn.join(e,"plugins-state","linkedin","cookies.json"):In}function Ao(){let e=qn();if(!Eo.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Eo.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}await ko();var nt=0,Ln=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Rn=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),Fn=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",qt=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],et=-1;async function Mn(){if(et===-1){let e=await ce("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}"`);et=Nt(e)+1,console.log(`lastIndex initialized as: ${et}`)}return et++}var Po=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${Po}`);var Nn=[{label:"browser-dead",match:e=>/Target closed|Session closed/.test(e.message),severity:"fatal"},{label:"session-expired",match:e=>/Session expired|redirected to login/.test(e.message),severity:"fatal"},{label:"lifebot-timeout",match:e=>e.constructor.name==="LifebotTimeoutError",severity:"transient",maxConsecutive:3,cleanup:"popup"},{label:"protocol-timeout",match:e=>e.constructor.name==="ProtocolError"||e.constructor.name==="TimeoutError"||/Protocol error|timed out/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3,cleanup:"popup"},{label:"stale-context",match:e=>/Execution context was destroyed|Cannot find context/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3,cleanup:"popup"}],Le={};function Pn(e){return Nn.find(t=>t.match(e))||null}function On(e){return Le[e]=(Le[e]||0)+1,Le[e]}function jo(){for(let e of Object.keys(Le))Le[e]=0}var Dt=0;function Un(){return Dt++,Dt>=Po?(console.log(`Max run counter reached with ${Dt}`),!1):!0}async function Bn(e){let t=await no(e)}async function Jn(e){return ro(e,{easyApplyOnly:!0})}async function Gn(e){return so(e)}async function Rt(e,t){return kt(e,t)}async function Hn(e){let t=process.env.LINKEDIN_SEARCH_URL,n=3;for(let r=1;r<=n;r++){r>1&&(console.log(`
25
+ --- Pass ${r}/${n}: re-checking for new jobs ---`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3));let o=v.submitted,s=!0,l=!0;for(;s&&l;){await Rt(e,t);let a=await or(e,Uo,Bn);l=a.keepGoing;let i=a.jobsDone;if(console.log("keepGoing",l),console.log("pageDone"),console.log(i.length),!l)break;s=await Gn(e)}if(console.log(`Scraping pass ${r} complete.`),!l)break;if(v.submitted===o){console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${v.submitted-o} new jobs in pass ${r}.`)}}async function Io(e,t,n){let r=process.env.LINKEDIN_SEARCH_URL;return io(e,t,n,r)}async function qo(e,t){let n=t?.match(/\d+/)?.[0]||t,r=await e.$(`div[data-job-id="${n}"] button[aria-label^="Dismiss"]`);r?(await r.click(),console.log(` Dismissed job ${n} from list`)):console.log(` Dismiss button not found for ${n}`)}async function Vn(e,t){try{let n=await lo(e);if(n&&n.profileUrl){n.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},we("recruiters-from-jobs",n)?(nt++,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: ${n.name?.substring(0,30).padEnd(30)} \u2502`),console.log(`\u2502 Source: ${n.source.padEnd(28)} \u2502`),console.log(`\u2502 Company: ${t.companyName?.substring(0,27).padEnd(27)} \u2502`),console.log(`\u2502 Total today: ${String(nt).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: ${n.name}`),xe(n.profileUrl,{name:n.name,source:"recruiters-from-jobs"});let o=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(o){Je(n.profileUrl,o),ye(n.profileUrl,{source:"job-apply",jobId:o,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let s=n.fromJob?.companyUrl;s&&ze(s,{recruiterUrl:n.profileUrl,jobId:o})}return n}else console.log(" \u26AA No recruiter found on this job page");return null}catch(n){return console.error("Error extracting recruiter:",n.message),null}}async function ot(e){return await e.evaluate(()=>{let t=document.body.innerText||"",n=document.querySelector("#interop-outlet")?.shadowRoot?.textContent||"",r=t+" "+n;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 Oo(e){try{let t=await e.evaluate(()=>{let n=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let o of n){let s=o.querySelectorAll("button");for(let l of s){let a=l.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return l.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return t&&console.log(" Daily limit popup closed"),t}catch{return!1}}async function Do(e){await e.evaluate(()=>{let l=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of l)for(let i of a.querySelectorAll("button")){let u=i.innerText?.trim();if(u==="Continue applying"||u==="Got it"||u==="Dismiss"){i.click();return}}});let t=Date.now(),n=3e3,r=null;for(;!r&&Date.now()-t<n;){if(r=await e.$(".jobs-apply-button"),r||(r=await e.$('button[aria-label*="Easy Apply"]')),r||(r=await e.$('a[aria-label*="Easy Apply"]')),r||(r=await e.$('a[href*="/apply/"]')),!r){let l=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let i of a){let u=i.innerText?.trim();if(u==="Easy Apply"||u==="Apply")return i}return null});r=l?.asElement?.()||null,r||await l.dispose().catch(()=>{})}r||await new Promise(l=>setTimeout(l,300))}let o=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${o>400?` (waited ${o}ms)`:""}`),r){if(await e.evaluate(u=>u.disabled,r))return await ot(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(u=>u.tagName==="A",r)){await e.evaluate(u=>u.click(),r),await b(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 b(2e3)}}else await r.click(),await b(1500);return await ot(e)?(await Oo(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await ot(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function Wn(e){return await e.evaluate(async()=>{function t(){let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length>0)return i;let u=document.querySelector("#interop-outlet")?.shadowRoot;return u&&(i=u.querySelectorAll(".artdeco-inline-feedback__message")),i}let n=3e3,r=t();if(r?.length===0&&(await new Promise(i=>setTimeout(i,n)),r=t()),r?.length===0)return null;let o=r[0];console.log("errorMsg"),console.log(o);let s=o?.textContent.trim(),l=o.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=o.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(l),a||l){console.log("parentElement"),console.log(a);let i=a.querySelector(".artdeco-text-input--label")||a.querySelector("legend .fb-dash-form-element__label-title--is-required")||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||a.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),u=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),p=a.querySelectorAll('input[type="radio"]'),f=a.querySelector("select[data-test-text-entity-list-form-select]"),c=o.parentElement.parentElement.querySelector('input[type="file"]'),d=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(c),i&&u)return{type:"input",labelText:i.textContent.trim(),errorMsgText:s};if(i&&p.length){let m=i?i.querySelector("span:nth-of-type(1)")?.textContent.trim():null,y=Array.from(p).map(h=>{let k=(document.querySelector(`label[for="${h.id}"]`)||h.nextElementSibling)?.textContent?.trim();return{value:h.value,label:k||h.value}}),g=y.map(h=>h.label);return{type:"radio",labelText:m,errorMsgText:s,options:g,optionsData:y}}else if(f){let m=a.querySelector('label[for="'+f.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),y=m?m.querySelector("span:nth-of-type(2)")?.textContent.trim():null,g=Array.from(f.options).map(h=>h.value).filter(h=>h!=="Select an option");return{type:"select",labelText:y,errorMsgText:s,options:g}}else if(c){let m=o.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:s,labelText:m}}else{if(d)return{type:"datePicker",errorMsgText:s};{let m=i?i.querySelector("span:nth-of-type(2)")?.textContent.trim():null,y=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(y.length>0){let g=Array.from(y).map(h=>h.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:m,errorMsgText:s,options:g}}else return null}}}return null})}async function Yn(e,t,n){return await e.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));i.value=o;let u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let p=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});d.dispatchEvent(m)},f=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});d.dispatchEvent(m)};await(async d=>{await new Promise(m=>setTimeout(m,500)),f(d),await new Promise(m=>setTimeout(m,100)),p(d)})(i)}}return null},t,n)}async function Qn(e,t,n){return await e.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('input[type="radio"]'),u=o;if(r.optionsData){let p=r.optionsData.find(f=>f.label.toLowerCase()===o.toLowerCase());p&&(u=p.value,console.log(`Radio: matched label "${o}" to value "${u}"`))}for(let p of i){let c=(document.querySelector(`label[for="${p.id}"]`)||p.nextElementSibling)?.textContent?.trim()||"";if(p.value.toLowerCase()===u.toLowerCase()||c.toLowerCase()===o.toLowerCase()){p.checked=!0;let d=new Event("change",{bubbles:!0});p.dispatchEvent(d),console.log(`Radio selected: value="${p.value}", label="${c}"`);break}}}return null},t,n)}async function zn(e,t,n){return await e.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelector("select[data-test-text-entity-list-form-select]");if(!i)return null;let u=Array.from(i.options),p=u.find(c=>c.text.toLowerCase()===o.toLowerCase())||u.find(c=>c.text.toLowerCase().includes(o.toLowerCase()));p?i.value=p.value:i.value=o;let f=new Event("change",{bubbles:!0});i.dispatchEvent(f)}return null},t,n)}async function Kn(e,t,n){return await e.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');i.length>0&&i.forEach(u=>{if(u.nextElementSibling.textContent.trim()===o.trim()){u.checked=!0;let p=new Event("change",{bubbles:!0});u.dispatchEvent(p)}})}return null},t,n)}async function Xn(e,t,n){return await e.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s?.length===0)return null;let l=s[0],a=l.closest(".fb-dash-form-element"),i=l.parentElement.parentElement.querySelector('input[type="file"]');if(a&&i){async function u(p,f,c){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let m=new Blob([new Uint8Array(f)]),y=new File([m],c,{type:"application/pdf"}),g=new DataTransfer;g.items.add(y),p.files=g.files;let h=new Event("change",{bubbles:!0});p.dispatchEvent(h)}await u(i,o,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,n)}async function Lo(e){let t=await Wn(e);if(t===null)return null;if(t?.type==="input"){let o=await Ot(t.labelText,t.errorMsgText);o=o?.trim()||o,t.answer=o,await Yn(e,t,o)}else if(t?.type==="radio"){let o=await lt(t.labelText,t.options);o=o?.trim()||o;let s=t.options||[];!s.find(a=>a.toLowerCase()===o?.toLowerCase())&&s.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${o}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),o=await lt(t.labelText,t.options),o=o?.trim()||o,s.find(i=>i.toLowerCase()===o?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${o}". Using first option: "${s[0]}"`),o=s[0])),t.answer=o,await Qn(e,t,o)}else if(t?.type==="select"){let o=await Re(t.labelText,t.options);o=o?.trim()||o;let s=t.options||[],l=s.find(a=>a.toLowerCase()===o?.toLowerCase());if(l)o=l;else if(s.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${o}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),o=await Re(t.labelText,t.options),o=o?.trim()||o;let a=s.find(i=>i.toLowerCase()===o?.toLowerCase());a?o=a:(console.log(` \u26A0 Retry also invalid: "${o}". Using first option: "${s[0]}"`),o=s[0])}t.answer=o,await zn(e,t,o)}else if(t?.type==="checkbox"){let o=await Re(t.labelText,t.options);t.answer=o,await Kn(e,t,o)}else if(t?.type==="file"){let o=process.env.RESUME_PDF_URL;t.answer=o;let s=await fetch(o);if(!s.ok)throw new Error("Network response was not ok");let l=await s.arrayBuffer();await Xn(e,t,l)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let n=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${n}" \u2192 ${r}`),t}async function Zn(e){return await e.evaluate(async()=>{let t=[],n=document.querySelectorAll(".fb-dash-form-element");if(!n||n.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(n=r.querySelectorAll(".fb-dash-form-element"))}if(!n||n.length===0)return[];for(let r of n){let o=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),s=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),l=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),i=r.querySelector("select[data-test-text-entity-list-form-select]"),u=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),p=r.querySelector('input[type="file"]');if(o&&l&&a.length===0){let f=o.textContent.trim();t.push({type:"input",labelText:f,answer:l.value,isRequired:s,wasPreFilled:!!l.value})}else if(o&&a.length){let f=o?o.querySelector("span:nth-of-type(1)")?.textContent.trim():null,c=Array.from(a).map(m=>m.value),d=(Array.from(a).find(m=>m.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:f,options:c,answer:d,isRequired:s,wasPreFilled:!!d})}else if(i){let f=r.querySelector('label[for="'+i.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),c=f?f.querySelector("span:nth-of-type(2)")?.textContent.trim():null,d=Array.from(i.options).map(y=>y.value).filter(y=>y!=="Select an option"),m=i.value!=="Select an option"?i.value:"";t.push({type:"select",labelText:c,options:d,answer:m,isRequired:s,wasPreFilled:!!m})}else if(u.length>0){let f=r.querySelector("legend span")?.textContent?.trim(),c=Array.from(u).map(d=>({label:d.nextElementSibling?.textContent?.trim()||d.value,checked:d.checked}));t.push({type:"checkbox",labelText:f,options:c.map(d=>d.label),answer:c.filter(d=>d.checked).map(d=>d.label).join(", "),isRequired:s})}else if(p){let f=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:f,answer:p.value?"uploaded":"",isRequired:s})}}return t})}async function Ro(e,t,n){return await e.evaluate(async(r,o)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelector(".artdeco-text-input--label")||l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||l.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=l.querySelector(".artdeco-text-input--input")||l.querySelector("input");if(a&&i&&r===a.textContent.trim()){i.value=o;let u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r==="City"||r==="Location (city)"){let p=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});d.dispatchEvent(m)},f=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});d.dispatchEvent(m)};await(async d=>{await new Promise(m=>setTimeout(m,500)),f(d),await new Promise(m=>setTimeout(m,100)),p(d)})(i)}return!0}}return!1},t,n)}async function Fo(e,t){let n=[],r=!0,o=0,s=null,l=0;for(;r;){if(o++,await ot(e))return console.log(" Daily limit reached during form navigation"),await Oo(e),{filledFields:n,formPages:o,skip:!0,dailyLimitReached:!0};let u=(await Zn(e)).filter(d=>!n.some(m=>m.labelText===d.labelText));n.push(...u);try{let d=n.find(y=>y.labelText==="City"||y.labelText==="Location (city)"),m=n.filter(y=>y.labelText!=null).find(y=>y.labelText!==null&&y.labelText.trim()!==null&&(y.labelText.trim().toLowerCase()==="cv"||y.labelText.trim().toLowerCase()==="curriculum vitae"||y.labelText.trim().toLowerCase()==="cover letter"||y.labelText.trim().toLowerCase()==="cover"));if(d&&!d.answer){let y=process.env.City;await Ro(e,d.labelText,y),d.answer=y}else if(m){let y=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!m.answer||m.answer!==y)&&(await b(1e4),await Ro(e,m.labelText,y),m.answer=y,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}let p=null;try{p=await t(e)}catch(d){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${d.message?.slice(0,100)}`),{filledFields:n,formPages:o,skip:!0}}if(p!==null){if(p.type==="datePicker")return{filledFields:n,formPages:o,skip:!0,duplicateField:p};let d=p&&n.find(y=>y.errorMsgText&&y.labelText===p.labelText);if(d)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(p,null,2)),console.log("Previous attempt:",JSON.stringify(d,null,2)),{filledFields:n,formPages:o,skip:!0,duplicateField:p};let m=n.findIndex(y=>y.labelText===p.labelText&&!y.answer);m!==-1&&n.splice(m,1),n.push(p)}let f=await e.evaluate(()=>{let d=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of d){let y=m.querySelectorAll("button");for(let g of y){let h=g.innerText?.trim();if(h==="Continue applying"||h==="Got it"||h==="Dismiss")return g.click(),h}}return null});f&&console.log(` Dismissed safety popup (${f})`);let c=await e.evaluate(async()=>{function d(w){let x=document.querySelector(w);if(x)return x;let I=document.querySelector("#interop-outlet")?.shadowRoot;return I?I.querySelector(w):null}function m(w){let x=document.querySelectorAll(w),I=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(w);return[...x||[],...I||[]]}let y=d("button[data-easy-apply-next-button]")||d('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(w=>w.innerText?.trim()==="Next"),g=m('footer[role="presentation"] button').some(w=>w.innerText.trim()==="Review")||m("button").some(w=>w.innerText.trim()==="Review"&&w.getAttribute("aria-label")?.includes("Review")),h=d('button[aria-label="Submit application"]'),S=async()=>{let w=d("button[data-easy-apply-next-button]")||d('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(x=>x.innerText?.trim()==="Next");w?w.click():console.log("Next button not found")},k=()=>{let w=m("button").find(x=>x.innerText?.trim()==="Review");w&&w.click()};return y?(await S(),{type:"next"}):g?(await k(),{type:"review"}):h?{type:"submit"}:{type:null}});if(c==null)return{filledFields:n,formPages:o,skip:!0};if(c.type&&console.log(` \u2192 ${c.type}`),c.type===null){let d=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let y of m){let g=y.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let h of g){let S=h.innerText||"";if(S.includes("application was sent")||S.includes("resume into a profile")||S.includes("Application submitted")||S.includes("Next best action"))for(let k of h.querySelectorAll("button")){let w=k.innerText?.trim();if(w==="Not now"||w==="Done"||w==="Dismiss"||w==="Got it")return k.click(),w}}}return null});if(d)return console.log(` Dismissed stale popup (${d}) \u2014 need to re-open Easy Apply`),await b(1500),{filledFields:n,formPages:o,skip:!1,stalePopupDismissed:!0};if(l===0){let m=await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],h=[];for(let S of y){for(let w of S.querySelectorAll("button")){let x=w.innerText?.trim();x&&x.length<60&&g.push(x)}let k=S.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');k&&h.push(k.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:h.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(c.type==="submit")return{filledFields:n,formPages:o,skip:!1};if(p===null&&c.type===s?l++:l=0,s=c.type,l>=5){let d=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),y=[],g=[];for(let h of m){for(let S of h.querySelectorAll(".artdeco-inline-feedback__message"))y.push(S.textContent?.trim()?.slice(0,60));for(let S of h.querySelectorAll(".fb-dash-form-element")){let k=S.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),w=S.querySelector("input, select, textarea"),x=!!S.querySelector(".artdeco-inline-feedback__message");k&&(x||w&&!w.value)&&g.push({label:k.slice(0,40),hasError:x,value:w?.value?.slice(0,20)||""})}}return{errors:y,emptyRequired:g.slice(0,5)}});return console.error(` \u26A0 Stuck on "${c.type}" for ${l} iterations \u2014 form not progressing.`),d.errors.length&&console.error(` Visible errors: ${JSON.stringify(d.errors)}`),d.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(d.emptyRequired)}`),console.error(" Skipping job."),{filledFields:n,formPages:o,skip:!0,duplicateField:{labelText:`stuck_on_${c.type}`}}}await b(1500),r=!0}return{filledFields:n,formPages:o,skip:!1}}async function Mo(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 er(e){let t=await e.$('button[aria-label="Submit application"]');if(!t){let n=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Submit application"]')||null);t=n?.asElement?.()||null,t||await n.dispose().catch(()=>{})}t&&await t.click()}async function tr(e){try{let t=await e.evaluate(()=>{let n=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of n){for(let s of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(s.innerText?.trim()==="Done")return s.click(),"Done";let o=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let s of o){let l=s.innerText||"";if(l.includes("application was sent")||l.includes("Application sent")||l.includes("resume into a profile")||l.includes("Next best action"))for(let a of s.querySelectorAll("button")){let i=a.innerText?.trim();if(i==="Not now"||i==="Dismiss")return a.click(),i}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await b(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function tt(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 b(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 Lt(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 b(500))}catch{console.log("No discard confirmation needed")}}async function Uo(e,t){let n=[],r=t._fromQueue;try{v.attempted++,console.log(`
26
+ --- Processing: ${t.jobTitle} at ${t.companyName} ---`);let o=t.id?.match(/\d+/)?.[0];if(o&&_t(o)?.status==="applied")return v.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (our DB): ${t.jobTitle} \u2014 skipping`),{keepGoing:!0};let s=null;if(!r){let c=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()||""),d=(t.companyName||"").replace(/\s+/g," ").toLowerCase().trim(),m=c.split(" ")[0],y=d.split(" ")[0];if(m&&y&&!c.includes(y)&&!d.includes(m))return v.mismatch++,console.log(` \u2298 MISMATCH: expected company "${t.companyName}" but panel shows "${c}"`),console.log(` job title: "${t.jobTitle}"`),{keepGoing:!0};if(await e.evaluate(()=>{let h=document.querySelector(".jobs-details__main-content, .job-details-jobs-unified-top-card");if(!h)return!1;let S=h.innerText;return/Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago/i.test(S)||S.includes("Application submitted")}))return v.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${t.jobTitle} \u2014 skipping`),o&&ie(o,"applied",{source:"detected"}),{keepGoing:!0};try{s=await ao(e)}catch{}}let l=await Do(e);if(l.dailyLimitReached){console.log(`
27
27
  ========================================`),console.log("LinkedIn daily application limit reached!"),console.log(`========================================
28
- `);let c=ue("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${c.total}`),console.log(` - This session: ${rt}`),console.log(` - Unprocessed: ${c.unprocessed}`),v.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:c}}if(!l.clicked)return v.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${e.jobTitle} @ ${e.companyName}`),{keepGoing:!0};await Fo(t);let a=await qn();console.log(`Applying for job: ${e.id}`);let i=`### Job Information
28
+ `);let c=ue("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${c.total}`),console.log(` - This session: ${nt}`),console.log(` - Unprocessed: ${c.unprocessed}`),v.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:c}}if(!l.clicked)return v.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${t.jobTitle} @ ${t.companyName}`),{keepGoing:!0};await Mo(e);let a=await Mn();console.log(`Applying for job: ${t.id}`);let i=`### Job Information
29
29
  - **Counter:** ${a}
30
- - **Job Title:** ${e.jobTitle}
31
- - **Company:** ${e.companyName}
32
- - **Location:** ${e.location}
33
- - **Salary:** ${e.salary}
34
- - **Job URL:** ${e.href}`,u=process.env.NODE_EASY_APPLY_MAIN;await Z.addMessage(u,i,{lifebot:Ao.off});let p=await ce("Should I apply for this job? Answer only 'yes' or 'no'!!");if(To(),console.log(`Should I apply for ${e.jobTitle} ?? `+p),p.toLowerCase()==="no"){v.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${e.jobTitle} @ ${e.companyName}`),await ot(t),await Rt(t),await Io(t,e.id);let c=e.id?.match(/\d+/)?.[0];return be({jobId:c,jobTitle:e.jobTitle,jobCompany:e.companyName,jobUrl:e.href,result:"skipped_by_lifebot",questions:[]}),ie(c,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let f=await Ro(t,Do);if(f.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await qo(t)).clicked?f=await Ro(t,Do):(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 ot(t),{keepGoing:!1,dailyLimitReached:!0};if(f.skip){if(await ot(t),await Rt(t),f.duplicateField){await Io(t,e.id);let c=process.env.NODE_EASY_APPLY_ERRORS;await Z.addMessage(c,`${e.href} failed at label ${f.duplicateField?.labelText}`,{lifebot:Ao.off})}v.failed++,console.log(` \u2717 FAILED: ${e.jobTitle} @ ${e.companyName} \u2014 ${f.duplicateField?.labelText||"form error"}`),be({jobId:e.id?.match(/\d+/)?.[0],jobTitle:e.jobTitle,jobCompany:e.companyName,jobUrl:e.href,result:"failed",formPages:f.formPages,failedField:f.duplicateField?.labelText||null,questions:f.filledFields||[]})}else{n=f.filledFields,n.length,await Fo(t),await Qn(t),await h(2e3),await zn(t),v.submitted++,console.log(` \u2713 APPLIED: ${e.jobTitle} @ ${e.companyName} (${f.formPages} pages, ${n.length} fields)`);let c=e.id?.match(/\d+/)?.[0];if(c&&(Je(c,{title:e.jobTitle,company:e.companyName,location:e.location,salary:e.salary,url:e.href,applied:!0}),Ct(c,{title:e.jobTitle,company:s?.companyName||e.companyName,companyUrl:s?.companyUrl,location:e.location,salary:e.salary,url:e.href,isEasyApply:!0,applyType:"easy-apply",applied:!0,appliedAt:new Date().toISOString().slice(0,10),description:s?.description,techStack:s?.techStack,jobTags:s?.jobTags,seniority:s?.seniority,employmentType:s?.employmentType,industries:s?.industries,jobFunction:s?.jobFunction,postedTime:s?.postedTime,applicantCount:s?.applicantCount,companySize:s?.companySize,workplaceType:s?.workplaceType,contractType:s?.contractType,aboutCompany:s?.aboutCompany}),ie(c,"applied",{source:"easy-apply"}),s?.companyUrl&&Ke(s.companyUrl,{name:s.companyName||e.companyName,about:s.aboutCompany,size:s.companySize,industries:s.industries,jobId:c})),await Un(t,e),be({jobId:e.id?.match(/\d+/)?.[0],jobTitle:e.jobTitle,jobCompany:e.companyName,jobUrl:e.href,result:"submitted",formPages:f.formPages,questions:n}),!Fn())return{keepGoing:!1}}}catch(o){console.log(o);let s=Ln(o);if(!s)return console.log(`\u274C Unknown error \u2014 stopping: ${(o.message||"").slice(0,120)}`),{keepGoing:!1};if(s.severity==="fatal")return console.log(`\u274C [${s.label}] Fatal \u2014 stopping: ${(o.message||"").slice(0,120)}`),{keepGoing:!1};let l=Rn(s.label);if(console.log(`\u26A0 [${s.label}] on "${e.jobTitle}" (${l}/${s.maxConsecutive} consecutive): ${(o.message||"").slice(0,120)}`),s.cleanup==="popup"){try{await ot(t)}catch{}try{await Rt(t)}catch{}}return l>=s.maxConsecutive?(console.log(`\u274C [${s.label}] ${s.maxConsecutive} consecutive \u2014 stopping.`),{keepGoing:!1}):(s.cooldownMs&&await h(s.cooldownMs),{keepGoing:!0})}return To(),{keepGoing:!0}}async function Kn(t,e,n){let r=process.env.LINKEDIN_SEARCH_URL,o=[],s=0;for(;;){await Ft(t,r)&&(await U(t),await h(2e3)),await n(t);let a=await Nn(t);if(a.length===0){if(!t.url().includes("/jobs/")){if(s++,s>3){console.log(" Too many recovery attempts \u2014 LinkedIn keeps redirecting. Stopping.");break}console.log(` No jobs found but not on /jobs/ page \u2014 recovery attempt ${s}/3...`),await Ft(t,r);continue}break}if(s=0,o.length===0){o=a;let{keepGoing:i}=await jo(t,a,e);if(!i)return{keepGoing:!1,jobsDone:o}}else{let i=a.filter(p=>!o.some(f=>f.id===p.id));if(console.log(` New jobs on page: ${i.length} (page: ${a.length}, total seen: ${o.length})`),i.length===0)break;let{keepGoing:u}=await jo(t,i,e);if(o=[...o,...i],!u)return{keepGoing:!1,jobsDone:o}}}return console.log(` All jobs processed. Total: ${o.length}`),{keepGoing:!0,jobsDone:o}}var v={attempted:0,submitted:0,skippedByLifebot:0,failed:0,mismatch:0,alreadyApplied:0,expired:0,noApplyButton:0,dailyLimitHit:!1};(async()=>{let t=process.argv.find(s=>s.startsWith("--job-urls=")),e=$o("apply",t?"queue":"search"),n=null,r=null,o=[];try{n=await An.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5});let s=async()=>{console.log(`
35
- Closing browser...`);try{await n.close()}catch{}process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s);let l=await n.newPage();if(!Re.existsSync("cookies.json"))throw new Error("cookies.json not found \u2014 run: npm run login");let a;try{let x=Re.readFileSync("cookies.json","utf-8");a=JSON.parse(x)}catch{throw new Error("cookies.json is corrupted \u2014 delete it and run: npm run login")}await l.setCookie(...a);let i=process.argv.find(x=>x.startsWith("--job-urls=")),u=i?i.split("=").slice(1).join("=").replace(/^@/,""):null,p=process.env.LINKEDIN_SEARCH_URL,f=u?"https://www.linkedin.com/feed/":p;try{await l.goto(f,{waitUntil:"domcontentloaded",timeout:6e4})}catch(x){console.error("\u274C Navigation error:",x.message),console.log("Trying to continue anyway..."),await h(5e3)}let c=l.url();if(c.includes("/login")||c.includes("/checkpoint"))throw new Error("Not logged in \u2014 cookies expired, run: npm run login");console.log("\u2713 \u0417\u0430\u043B\u043E\u0433\u0438\u043D\u0435\u043D\u044B \u043D\u0430 LinkedIn!");let d=ue("recruiters-from-jobs");d.total>0&&console.log(`
30
+ - **Job Title:** ${t.jobTitle}
31
+ - **Company:** ${t.companyName}
32
+ - **Location:** ${t.location}
33
+ - **Salary:** ${t.salary}
34
+ - **Job URL:** ${t.href}`,u=process.env.NODE_EASY_APPLY_MAIN;await Z.addMessage(u,i,{lifebot:To.off});let p=await ce("Should I apply for this job? Answer only 'yes' or 'no'!!");if(jo(),console.log(`Should I apply for ${t.jobTitle} ?? `+p),p.toLowerCase()==="no"){v.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await tt(e),await Lt(e),await qo(e,t.id);let c=t.id?.match(/\d+/)?.[0];return he({jobId:c,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),ie(c,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let f=await Fo(e,Lo);if(f.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await Do(e)).clicked?f=await Fo(e,Lo):(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 tt(e),{keepGoing:!1,dailyLimitReached:!0};if(f.skip){if(await tt(e),await Lt(e),f.duplicateField){await qo(e,t.id);let c=process.env.NODE_EASY_APPLY_ERRORS;await Z.addMessage(c,`${t.href} failed at label ${f.duplicateField?.labelText}`,{lifebot:To.off})}v.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${f.duplicateField?.labelText||"form error"}`),he({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{n=f.filledFields,n.length,await Mo(e),await er(e),await b(2e3),await tr(e),v.submitted++,console.log(` \u2713 APPLIED: ${t.jobTitle} @ ${t.companyName} (${f.formPages} pages, ${n.length} fields)`);let c=t.id?.match(/\d+/)?.[0];if(c&&(Be(c,{title:t.jobTitle,company:t.companyName,location:t.location,salary:t.salary,url:t.href,applied:!0}),xt(c,{title:t.jobTitle,company:s?.companyName||t.companyName,companyUrl:s?.companyUrl,location:t.location,salary:t.salary,url:t.href,isEasyApply:!0,applyType:"easy-apply",applied:!0,appliedAt:new Date().toISOString().slice(0,10),description:s?.description,techStack:s?.techStack,jobTags:s?.jobTags,seniority:s?.seniority,employmentType:s?.employmentType,industries:s?.industries,jobFunction:s?.jobFunction,postedTime:s?.postedTime,applicantCount:s?.applicantCount,companySize:s?.companySize,workplaceType:s?.workplaceType,contractType:s?.contractType,aboutCompany:s?.aboutCompany}),ie(c,"applied",{source:"easy-apply"}),s?.companyUrl&&ze(s.companyUrl,{name:s.companyName||t.companyName,about:s.aboutCompany,size:s.companySize,industries:s.industries,jobId:c})),await Vn(e,t),he({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:f.formPages,questions:n}),!Un())return{keepGoing:!1}}}catch(o){console.log(o);let s=Pn(o);if(!s)return console.log(`\u274C Unknown error \u2014 stopping: ${(o.message||"").slice(0,120)}`),{keepGoing:!1};if(s.severity==="fatal")return console.log(`\u274C [${s.label}] Fatal \u2014 stopping: ${(o.message||"").slice(0,120)}`),{keepGoing:!1};let l=On(s.label);if(console.log(`\u26A0 [${s.label}] on "${t.jobTitle}" (${l}/${s.maxConsecutive} consecutive): ${(o.message||"").slice(0,120)}`),s.cleanup==="popup"){try{await tt(e)}catch{}try{await Lt(e)}catch{}}return l>=s.maxConsecutive?(console.log(`\u274C [${s.label}] ${s.maxConsecutive} consecutive \u2014 stopping.`),{keepGoing:!1}):(s.cooldownMs&&await b(s.cooldownMs),{keepGoing:!0})}return jo(),{keepGoing:!0}}async function or(e,t,n){let r=process.env.LINKEDIN_SEARCH_URL,o=[],s=0;for(;;){await Rt(e,r)&&(await U(e),await b(2e3)),await n(e);let a=await Jn(e);if(a.length===0){if(!e.url().includes("/jobs/")){if(s++,s>3){console.log(" Too many recovery attempts \u2014 LinkedIn keeps redirecting. Stopping.");break}console.log(` No jobs found but not on /jobs/ page \u2014 recovery attempt ${s}/3...`),await Rt(e,r);continue}break}if(s=0,o.length===0){o=a;let{keepGoing:i}=await Io(e,a,t);if(!i)return{keepGoing:!1,jobsDone:o}}else{let i=a.filter(p=>!o.some(f=>f.id===p.id));if(console.log(` New jobs on page: ${i.length} (page: ${a.length}, total seen: ${o.length})`),i.length===0)break;let{keepGoing:u}=await Io(e,i,t);if(o=[...o,...i],!u)return{keepGoing:!1,jobsDone:o}}}return console.log(` All jobs processed. Total: ${o.length}`),{keepGoing:!0,jobsDone:o}}var v={attempted:0,submitted:0,skippedByLifebot:0,failed:0,mismatch:0,alreadyApplied:0,expired:0,noApplyButton:0,dailyLimitHit:!1};(async()=>{let e=process.argv.find(s=>s.startsWith("--job-urls=")),t=_o("apply",e?"queue":"search"),n=null,r=null,o=[];try{n=await Dn.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5});let s=async()=>{console.log(`
35
+ Closing browser...`);try{await n.close()}catch{}process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s);let l=await n.newPage(),a=Ao();await l.setCookie(...a);let i=process.argv.find(C=>C.startsWith("--job-urls=")),u=i?i.split("=").slice(1).join("=").replace(/^@/,""):null,p=process.env.LINKEDIN_SEARCH_URL,f=u?"https://www.linkedin.com/feed/":p;try{await l.goto(f,{waitUntil:"domcontentloaded",timeout:6e4})}catch(C){console.error("\u274C Navigation error:",C.message),console.log("Trying to continue anyway..."),await b(5e3)}let c=l.url();if(c.includes("/login")||c.includes("/checkpoint"))throw new Error("Not logged in \u2014 cookies expired, run: npm run login");console.log("\u2713 \u0417\u0430\u043B\u043E\u0433\u0438\u043D\u0435\u043D\u044B \u043D\u0430 LinkedIn!");let d=ue("recruiters-from-jobs");d.total>0&&console.log(`
36
36
  \u{1F4C2} Existing recruiters for today: ${d.total} (${d.unprocessed} unprocessed)
37
- `),await h(2e3);let m=!1;if(u)try{let x=JSON.parse(Re.readFileSync(u,"utf-8"));console.log(`
38
- \u{1F4CB} Queue mode: ${x.length} jobs from ${u}
39
- `);for(let L=0;L<x.length;L++){let $=typeof x[L]=="string"?{url:x[L]}:x[L],R=$.url,K=$.title||"Unknown",he=$.company||"";console.log(`
40
- [${L+1}/${x.length}] ${K} @ ${he}`),console.log(` ${R}`);try{let H=R.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await l.goto(R,{waitUntil:"domcontentloaded",timeout:6e4}),await h(8e3);let le=await l.evaluate(()=>{let F=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:F.includes("Application submitted"),noLongerAccepting:F.includes("No longer accepting applications")}});if(le.alreadyApplied){console.log(" Already applied \u2014 skipping"),v.alreadyApplied++,ie(H,"applied",{applyMethod:"detected"});continue}if(le.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),v.expired++,ie(H,"expired",{reason:"no_longer_accepting"});continue}if(!le.hasApply){console.log(" No Easy Apply button \u2014 skipping"),v.noApplyButton++;continue}let Y={id:`/jobs/view/${H}/`,href:R,jobTitle:K,companyName:he,location:$.location||"",salary:$.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let D=await Po(l,Y);if(console.log(` Result: keepGoing=${D.keepGoing}, reason=${D.dailyLimitReached?"daily_limit":"ok"}`),!D.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),m=!0;break}}catch(H){console.error(` Error: ${H.message?.slice(0,80)}`)}}console.log(`
41
- Queue complete. ${m?"Daily limit hit.":"Continuing to search..."}`)}catch(x){console.error(`Failed to read job URLs file: ${x.message}`)}if(!m){if(u){console.log(`
42
- Queue done. Continuing with standard search...`);try{await l.goto(p,{waitUntil:"domcontentloaded",timeout:6e4}),await h(3e3)}catch(x){console.error(" Navigation to search failed:",x.message)}}try{await On(l)}catch(x){console.error(`
43
- \u26A0 Apply phase crashed: ${x.message}`),console.log(`Continuing to recruiter funnel...
44
- `)}}let y=v.submitted+v.skippedByLifebot+v.failed+v.mismatch+v.alreadyApplied+v.expired+v.noApplyButton,g=v.attempted-y,b=ue("recruiters-from-jobs");o.push(`Jobs attempted: ${v.attempted}`),o.push(`Successfully applied: ${v.submitted}`),o.push(`Skipped by Lifebot: ${v.skippedByLifebot}`),o.push(`Failed (form errors): ${v.failed}`),v.mismatch>0&&o.push(`Mismatch (wrong panel): ${v.mismatch}`),v.alreadyApplied>0&&o.push(`Already applied: ${v.alreadyApplied}`),v.expired>0&&o.push(`Expired (closed): ${v.expired}`),v.noApplyButton>0&&o.push(`No Apply button: ${v.noApplyButton}`),g>0&&o.push(`Unaccounted: ${g}`),o.push(`Daily limit reached: ${v.dailyLimitHit?"Yes":"No"}`),o.push(`Recruiters found: ${rt}`),o.push(`Recruiters total: ${b.total} (${b.unprocessed} unprocessed)`),console.log(`
45
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 x of o)console.log(` ${x}`);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{markProfileProcessed:S}=await Promise.resolve().then(()=>(dt(),Ht)),{canSendConnection:k,getQuotaStatus:w}=await Promise.resolve().then(()=>(_e(),wt)),C=()=>({message:In,useCustomMessage:Tn,maxConnections:jn,excludeLocations:Dt,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async(x,L,$)=>{S("recruiters-from-jobs",x.profileUrl,{status:$.reason,connectionSent:$.connectionSent,withCustomMessage:$.withCustomMessage,message:$.messageSent,method:$.method,reason:$.reason,error:$.error,profileInfo:$.profileInfo},x._fromDate||null)}});if(b.unprocessed>0){console.log(`
46
- --- Funnel: today's recruiters (${b.unprocessed}) ---`),Dt.length>0&&console.log(` Excluding locations: ${Dt.join(", ")}`);let x=Ne("recruiters-from-jobs");await kt(l,x,C())}if(k().allowed){let x=Pe("recruiters-from-jobs"),L=new Date().toISOString().split("T")[0],$=x.filter(R=>R._fromDate!==L);if($.length>0){let R=w();console.log(`
47
- --- Funnel: backfill from previous days (${$.length} unprocessed) ---`),console.log(` Quota remaining: ${R.daily.remaining} today, ${R.weekly.remaining} this week`),await kt(l,$,{...C(),maxConnections:R.daily.remaining})}}let T=w();console.log(`
37
+ `),await b(2e3);let m=!1;if(u)try{let C=JSON.parse(No.readFileSync(u,"utf-8"));console.log(`
38
+ \u{1F4CB} Queue mode: ${C.length} jobs from ${u}
39
+ `);for(let L=0;L<C.length;L++){let $=typeof C[L]=="string"?{url:C[L]}:C[L],R=$.url,K=$.title||"Unknown",be=$.company||"";console.log(`
40
+ [${L+1}/${C.length}] ${K} @ ${be}`),console.log(` ${R}`);try{let H=R.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await l.goto(R,{waitUntil:"domcontentloaded",timeout:6e4}),await b(8e3);let le=await l.evaluate(()=>{let F=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:F.includes("Application submitted"),noLongerAccepting:F.includes("No longer accepting applications")}});if(le.alreadyApplied){console.log(" Already applied \u2014 skipping"),v.alreadyApplied++,ie(H,"applied",{applyMethod:"detected"});continue}if(le.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),v.expired++,ie(H,"expired",{reason:"no_longer_accepting"});continue}if(!le.hasApply){console.log(" No Easy Apply button \u2014 skipping"),v.noApplyButton++;continue}let Y={id:`/jobs/view/${H}/`,href:R,jobTitle:K,companyName:be,location:$.location||"",salary:$.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let D=await Uo(l,Y);if(console.log(` Result: keepGoing=${D.keepGoing}, reason=${D.dailyLimitReached?"daily_limit":"ok"}`),!D.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),m=!0;break}}catch(H){console.error(` Error: ${H.message?.slice(0,80)}`)}}console.log(`
41
+ Queue complete. ${m?"Daily limit hit.":"Continuing to search..."}`)}catch(C){console.error(`Failed to read job URLs file: ${C.message}`)}if(!m){if(u){console.log(`
42
+ Queue done. Continuing with standard search...`);try{await l.goto(p,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3)}catch(C){console.error(" Navigation to search failed:",C.message)}}try{await Hn(l)}catch(C){console.error(`
43
+ \u26A0 Apply phase crashed: ${C.message}`),console.log(`Continuing to recruiter funnel...
44
+ `)}}let y=v.submitted+v.skippedByLifebot+v.failed+v.mismatch+v.alreadyApplied+v.expired+v.noApplyButton,g=v.attempted-y,h=ue("recruiters-from-jobs");o.push(`Jobs attempted: ${v.attempted}`),o.push(`Successfully applied: ${v.submitted}`),o.push(`Skipped by Lifebot: ${v.skippedByLifebot}`),o.push(`Failed (form errors): ${v.failed}`),v.mismatch>0&&o.push(`Mismatch (wrong panel): ${v.mismatch}`),v.alreadyApplied>0&&o.push(`Already applied: ${v.alreadyApplied}`),v.expired>0&&o.push(`Expired (closed): ${v.expired}`),v.noApplyButton>0&&o.push(`No Apply button: ${v.noApplyButton}`),g>0&&o.push(`Unaccounted: ${g}`),o.push(`Daily limit reached: ${v.dailyLimitHit?"Yes":"No"}`),o.push(`Recruiters found: ${nt}`),o.push(`Recruiters total: ${h.total} (${h.unprocessed} unprocessed)`),console.log(`
45
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SESSION SUMMARY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let C of o)console.log(` ${C}`);console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let{markProfileProcessed:S}=await Promise.resolve().then(()=>(ut(),Gt)),{canSendConnection:k,getQuotaStatus:w}=await Promise.resolve().then(()=>(_e(),gt)),x=()=>({message:Fn,useCustomMessage:Ln,maxConnections:Rn,excludeLocations:qt,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async(C,L,$)=>{S("recruiters-from-jobs",C.profileUrl,{status:$.reason,connectionSent:$.connectionSent,withCustomMessage:$.withCustomMessage,message:$.messageSent,method:$.method,reason:$.reason,error:$.error,profileInfo:$.profileInfo},C._fromDate||null)}});if(h.unprocessed>0){console.log(`
46
+ --- Funnel: today's recruiters (${h.unprocessed}) ---`),qt.length>0&&console.log(` Excluding locations: ${qt.join(", ")}`);let C=Me("recruiters-from-jobs");await St(l,C,x())}if(k().allowed){let C=Ne("recruiters-from-jobs"),L=new Date().toISOString().split("T")[0],$=C.filter(R=>R._fromDate!==L);if($.length>0){let R=w();console.log(`
47
+ --- Funnel: backfill from previous days (${$.length} unprocessed) ---`),console.log(` Quota remaining: ${R.daily.remaining} today, ${R.weekly.remaining} this week`),await St(l,$,{...x(),maxConnections:R.daily.remaining})}}let T=w();console.log(`
48
48
  \u2705 Funnel done. Quota: ${T.daily.remaining}/${T.daily.max} today, ${T.weekly.remaining}/${T.weekly.max} this week`),o.push(`Funnel quota: ${T.daily.remaining}/${T.daily.max} today, ${T.weekly.remaining}/${T.weekly.max} week`),!u&&!process.argv.includes("--no-wait")&&(console.log(`
49
- Press Enter to close browser...`),await new Promise(x=>{process.stdin.once("data",()=>x())}))}catch(s){r=s,console.error(`
50
- \u274C Apply session ended with error: ${s.message}`),s.stack&&console.error(s.stack)}Eo(e,r?"error":"success",{summaryLines:o,dailyLimitHit:v.dailyLimitHit,attempted:v.attempted,submitted:v.submitted,failed:v.failed,skippedByLifebot:v.skippedByLifebot},r?r.message:null);try{await n?.close()}catch{}r&&process.exit(1)})();
49
+ Press Enter to close browser...`),await new Promise(C=>{process.stdin.once("data",()=>C())}))}catch(s){r=s,console.error(`
50
+ \u274C Apply session ended with error: ${s.message}`),s.stack&&console.error(s.stack)}$o(t,r?"error":"success",{summaryLines:o,dailyLimitHit:v.dailyLimitHit,attempted:v.attempted,submitted:v.submitted,failed:v.failed,skippedByLifebot:v.skippedByLifebot},r?r.message:null);try{await n?.close()}catch{}r&&process.exit(1)})();