ilml-plugin-linkedin 1.8.0 → 1.9.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/CHANGELOG.md +4 -0
- package/dist/run.mjs +28 -28
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.9.0
|
|
4
|
+
- **Apply phase no longer quits early after a CDP recovery.** v1.4.0 made the runner survive a dead Puppeteer↔Chrome channel, but `iterateAllPages` still exited the moment any pass produced 0 new submits — and a freshly recovered page often returns an empty job list on the very next scrape (page state hasn't fully restored). So a single CDP death anywhere in the pass would end the apply phase well before the daily quota was filled, even though there were plenty more jobs to apply to. The pass-exit check now also tracks how many CDP recoveries happened during the pass: if there were any and submits = 0, the next pass runs regardless (still bounded by `MAX_PASSES = 3`). Net effect: a recovery costs at most one stalled scrape, not the entire remaining daily allowance. Re-applying to the same job after recovery is already safe — the existing "Applied N ago" badge check at the start of `processJob` skips it cleanly without re-clicking Apply.
|
|
5
|
+
- No schema migration. Pass-bookkeeping is in-process state; nothing on disk changed. `CURRENT_SCHEMA_VERSION` unchanged.
|
|
6
|
+
|
|
3
7
|
## 1.8.0
|
|
4
8
|
- **Profile scrape works again on the 2026 LinkedIn DOM.** LinkedIn rebuilt the profile page with obfuscated class hashes and dropped `<h1>` and `section[id]` anchors, which silently broke `viewProfile()` and `sendConnectionRequest()`'s profile-info extraction — every visit had been returning all-null since the redesign. The new extractor uses structural anchors only: the name lives in the first `<h2>` inside `<main>` that isn't a section header; the top card is the nearest ancestor whose direct children include a contentful `<p>` (excluding connection-degree badges and pronoun chips); the About section is found by `<h2>About</h2>` walking to its `<section>` ancestor. Tested across recruiter, founder, and engineer profiles. `<h1>` is still tried first as a fallback in case LinkedIn ever reverts.
|
|
5
9
|
- **India / Pakistan location filter no longer leaks.** Three connection requests went to India-based recruiters in the last two weeks despite `FUNNEL_EXCLUDE_LOCATIONS=India,Pakistan`. Root cause: the live page-evaluate occasionally returned `null` for the location element (DOM variation, A/B render, or Premium-overlay timing), so `shouldExcludeLocation(null, ['India',...])` returned `false` and the connect proceeded — even though `people.json` already had the location stored from a prior visit. Fix is defense-in-depth: (1) early-skip *before* navigating, using the stored people.json location when known; (2) inside `sendConnectionRequest`, fall back to the stored location when the live scrape returned null; logs distinguish `(live)` vs `(stored)` so the trail is debuggable.
|
package/dist/run.mjs
CHANGED
|
@@ -1,44 +1,44 @@
|
|
|
1
|
-
var kn=Object.defineProperty;var eo=(e,t)=>()=>(e&&(t=e(e=0)),t);var We=(e,t)=>{for(var o in t)kn(e,o,{get:t[o],enumerable:!0})};var io={};We(io,{default:()=>Tn,getAllUnprocessedProfiles:()=>Ke,getSummary:()=>Ce,getUnprocessedProfiles:()=>ze,listFiles:()=>so,loadProfiles:()=>Qe,markProfileProcessed:()=>ro,saveProfile:()=>Pe,saveProfiles:()=>no});import"dotenv/config";import*as F from"fs";import*as Z from"path";import{fileURLToPath as Cn}from"url";function qe(){F.existsSync(le)||F.mkdirSync(le,{recursive:!0})}function _n(e,t){try{let o=`${e}-${St()}.json`,r=F.readdirSync(le).filter(s=>s.startsWith(e)&&s.endsWith(".json")&&s!==o),n=0;for(let s of r)JSON.parse(F.readFileSync(Z.join(le,s),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function St(){return new Date().toISOString().split("T")[0]}function kt(e,t=null){let o=t||St();return Z.join(le,`${e}-${o}.json`)}function Qe(e,t=null){qe();let o=kt(e,t);try{if(F.existsSync(o)){let r=F.readFileSync(o,"utf-8"),n=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${n.profiles.length} profiles from ${o}`),n.profiles}}catch(r){console.error(`Error loading profiles from ${o}:`,r.message)}return[]}function Pe(e,t){qe();let o=kt(e),r={source:e,date:St(),lastUpdated:new Date().toISOString(),profiles:[]};try{F.existsSync(o)&&(r=JSON.parse(F.readFileSync(o,"utf-8")))}catch(l){console.error(`Error reading ${o}:`,l.message)}if(r.profiles.some(l=>l.profileUrl===t.profileUrl))return!1;let s=_n(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:s}),r.lastUpdated=new Date().toISOString();try{F.writeFileSync(o,JSON.stringify(r,null,2));let l=s>0?` (seen ${s} day${s>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${l} (total: ${r.profiles.length})`),!0}catch(l){return console.error(`Error saving to ${o}:`,l.message),!1}}function no(e,t){let o=0;for(let r of t)Pe(e,r)&&o++;return o}function ze(e,t=null){return Qe(e,t).filter(r=>!r.processed)}function ro(e,t,o,r=null){qe();let n=kt(e,r);try{if(!F.existsSync(n))return;let s=JSON.parse(F.readFileSync(n,"utf-8")),l=s.profiles.find(a=>a.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof o=="string")l.status=o;else if(typeof o=="object"){if(l.status=o.status,o.profileInfo){let a=o.profileInfo;a.name&&(l.name=a.name),a.title&&(l.title=a.title),a.location&&(l.location=a.location),a.company&&(l.company=a.company),a.connectionDegree&&(l.connectionDegree=a.connectionDegree),a.connectionsCount&&(l.connectionsCount=a.connectionsCount),a.mutualConnections&&(l.mutualConnections=a.mutualConnections),a.photoUrl&&(l.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=a.hasVerifiedBadge)}l.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}s.lastUpdated=new Date().toISOString(),F.writeFileSync(n,JSON.stringify(s,null,2))}}catch(s){console.error("Error marking profile processed:",s.message)}}function Ce(e){let t=Qe(e),o=t.filter(n=>n.processed),r=t.filter(n=>!n.processed);return{total:t.length,processed:o.length,unprocessed:r.length,statuses:o.reduce((n,s)=>(n[s.status]=(n[s.status]||0)+1,n),{})}}function so(){qe();try{return F.readdirSync(le).filter(t=>t.endsWith(".json")).map(t=>{let[o,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let n=JSON.parse(F.readFileSync(Z.join(le,t),"utf-8"));return{file:t,source:o,date:r,count:n.profiles?.length||0,unprocessed:n.profiles?.filter(s=>!s.processed).length||0}}catch{return{file:t,source:o,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function Ke(e){qe();let t=[];try{let n=F.readdirSync(le).filter(s=>s.startsWith(e+"-")&&s.endsWith(".json")).sort().reverse();for(let s of n)try{let l=JSON.parse(F.readFileSync(Z.join(le,s),"utf-8"));l.profiles&&t.push({file:s,date:l.date,profiles:l.profiles})}catch{}}catch{return[]}let o=new Set,r=[];for(let{date:n,profiles:s}of t)for(let l of s)!l.processed&&l.profileUrl&&!o.has(l.profileUrl)&&(o.add(l.profileUrl),r.push({...l,_fromDate:n}));return r}var An,En,le,Tn,vt=eo(()=>{An=Cn(import.meta.url),En=Z.dirname(Z.dirname(An)),le=process.env.DATA_DIR?Z.resolve(process.env.DATA_DIR,"collected-profiles"):Z.join(En,"collected-profiles");Tn={loadProfiles:Qe,saveProfile:Pe,saveProfiles:no,getUnprocessedProfiles:ze,getAllUnprocessedProfiles:Ke,markProfileProcessed:ro,getSummary:Ce,listFiles:so}});var $o={};We($o,{addEncounter:()=>je,canSendConnection:()=>ct,commitDataSnapshot:()=>xo,default:()=>Un,getAllApplications:()=>ko,getPersonStatus:()=>rt,getQuestionStats:()=>vo,getQuotaStatus:()=>Me,getRecentConnections:()=>at,linkPersonToJob:()=>nt,loadApplicationQuestions:()=>It,loadConversations:()=>ho,loadJobs:()=>et,loadPeople:()=>Y,loadProfileHistory:()=>mo,loadQuota:()=>it,loadSyncState:()=>bo,logApplicationQuestions:()=>Re,migrateFromDailyFiles:()=>go,profileSlug:()=>Ze,recordConnectionSent:()=>lt,resetCaches:()=>_t,saveConversations:()=>yo,saveJobs:()=>tt,savePeople:()=>be,saveQuota:()=>Tt,saveSyncState:()=>wo,updateConnectionStatus:()=>st,upsertJob:()=>ot,upsertPerson:()=>ue});import"dotenv/config";import*as q from"fs";import*as M from"path";import{fileURLToPath as In}from"url";import{execSync as xt}from"child_process";function _t(){Ae=null,Ee=null,ae=null,ge=null,_e=null,ye=null}function Q(){q.existsSync(V)||q.mkdirSync(V,{recursive:!0})}function de(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";q.writeFileSync(r,o);for(let n=0;n<3;n++)try{q.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function Te(e,t){if(!q.existsSync(e))return null;try{let o=JSON.parse(q.readFileSync(e,"utf-8"));try{q.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${M.resolve(e)}`);let r=e+".backup";if(q.existsSync(r))try{let n=JSON.parse(q.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{q.copyFileSync(r,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{q.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ie(){return new Date().toISOString().split("T")[0]}function Ze(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Dn(){q.existsSync(Et)||q.mkdirSync(Et,{recursive:!0})}function po(e){let t=Ze(e);return t?M.join(Et,`${t}.json`):null}function mo(e){let t=po(e);return t?Te(t,`profile-history/${Ze(e)}.json`)||[]:[]}function Nn(e,t){let o=po(e);if(!o)return;Dn();let r=mo(e);r.unshift(t);try{de(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${Ze(e)}: ${n.message}`)}}function lo(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function ao(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function qn(e,t){if(!e)return[];let o=[];for(let r of Ln){let n=e[r],s=t[r];lo(n)||lo(s)||ao(n)!==ao(s)&&o.push(r)}return o}function Pn(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[r,n]of Object.entries(e))t.has(r)||(o[r]=n);return o}function Y(){return Ae||(Q(),Ae=Te($t,"people.json")||{},Ae)}function be(e){Q(),Ae=e;try{de($t,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${M.resolve($t)}`)}}function et(){return Ee||(Q(),Ee=Te(Ct,"jobs.json")||{},Ee)}function tt(e){Q(),Ee=e;try{de(Ct,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${M.resolve(Ct)}`)}}function ho(){return ge||(Q(),ge=Te(Xe,"conversations.json")||{},On(ge),ge)}function On(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let n=(o.messages||[]).find(s=>s.status==="draft");n&&o.draftStatus&&o.draftStatus!=="pending"&&(n.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{de(Xe,e)}catch{}}}function yo(e){Q(),ge=e;try{de(Xe,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${M.resolve(Xe)}`)}}function ue(e,t={}){if(!e)return null;let o=Y(),r=Ie(),n=new Date().toISOString(),s=o[e];if(s){let l=qn(s,t);l.length>0&&(Nn(e,{capturedAt:n,previousLastUpdated:s.lastUpdated||null,changedFields:l,snapshot:Pn(s)}),s.lastSnapshotAt=n),s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=n,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let a of fo)t[a]!=null&&(s[a]=t[a]);Array.isArray(t.availableSections)&&(s.lastFullVisitAt=n)}else o[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return be(o),o[e]}function ot(e,t={}){if(!e)return null;let o=et(),r=Ie(),n=o[e];if(n){let s=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let l of s)t[l]!=null&&(n[l]=t[l])}else o[e]={title:t.title||null,company:t.company||null,location:t.location||null,salary:t.salary||null,url:t.url||null,applied:t.applied||!1,appliedDate:t.appliedDate||r,recruiterUrl:t.recruiterUrl||null,firstSeen:r};return tt(o),o[e]}function nt(e,t){if(!e||!t)return;let o=Y(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),be(o)))}function je(e,t){if(!e||!t)return;let o=Y(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let s={date:Ie(),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(),be(o))}function rt(e){return e&&Y()[e]?.connectionStatus||null}function st(e,t,o={}){if(!e)return;o.profileInfo?ue(e,o.profileInfo):Y()[e]||ue(e,{});let r=Y(),n=r[e];n&&(n.connectionStatus=t,n.connectionDate=Ie(),n.connectionMethod=o.method||n.connectionMethod,n.messageSent=o.messageSent||n.messageSent,n.lastUpdated=new Date().toISOString(),be(r))}function it(){return ae||(Q(),ae=Te(co,"quota.json"),(!ae||!ae.connections)&&(ae={connections:[]}),ae)}function Tt(e){Q(),ae=e;try{de(co,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function lt(e,t="unknown"){let o=it(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),Tt(o)}function at(){let e=it(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function ct(){let e=at(),t=Ie(),o=e.filter(i=>i.date===t).length,r=e.length,n=o>=Oe,s=r>=Fe,l=!n&&!s,a={allowed:l,daily:{sent:o,max:Oe},weekly:{sent:r,max:Fe}};return l||(a.reason=n?`Daily limit reached (${o}/${Oe})`:`Weekly limit reached (${r}/${Fe})`),a}function Me(){let e=at(),t=Ie(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:Oe,remaining:Oe-o},weekly:{sent:r,max:Fe,remaining:Fe-r}}}function Fn(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function go(){Q();let e=q.readdirSync(V).filter(s=>s.endsWith(".json")&&s!=="people.json"&&s!=="jobs.json"&&s!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
|
|
1
|
+
var kn=Object.defineProperty;var eo=(e,t)=>()=>(e&&(t=e(e=0)),t);var We=(e,t)=>{for(var o in t)kn(e,o,{get:t[o],enumerable:!0})};var io={};We(io,{default:()=>Tn,getAllUnprocessedProfiles:()=>Ke,getSummary:()=>Ce,getUnprocessedProfiles:()=>ze,listFiles:()=>so,loadProfiles:()=>Qe,markProfileProcessed:()=>ro,saveProfile:()=>Pe,saveProfiles:()=>no});import"dotenv/config";import*as F from"fs";import*as Z from"path";import{fileURLToPath as Cn}from"url";function qe(){F.existsSync(le)||F.mkdirSync(le,{recursive:!0})}function _n(e,t){try{let o=`${e}-${St()}.json`,r=F.readdirSync(le).filter(s=>s.startsWith(e)&&s.endsWith(".json")&&s!==o),n=0;for(let s of r)JSON.parse(F.readFileSync(Z.join(le,s),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function St(){return new Date().toISOString().split("T")[0]}function kt(e,t=null){let o=t||St();return Z.join(le,`${e}-${o}.json`)}function Qe(e,t=null){qe();let o=kt(e,t);try{if(F.existsSync(o)){let r=F.readFileSync(o,"utf-8"),n=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${n.profiles.length} profiles from ${o}`),n.profiles}}catch(r){console.error(`Error loading profiles from ${o}:`,r.message)}return[]}function Pe(e,t){qe();let o=kt(e),r={source:e,date:St(),lastUpdated:new Date().toISOString(),profiles:[]};try{F.existsSync(o)&&(r=JSON.parse(F.readFileSync(o,"utf-8")))}catch(l){console.error(`Error reading ${o}:`,l.message)}if(r.profiles.some(l=>l.profileUrl===t.profileUrl))return!1;let s=_n(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:s}),r.lastUpdated=new Date().toISOString();try{F.writeFileSync(o,JSON.stringify(r,null,2));let l=s>0?` (seen ${s} day${s>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${l} (total: ${r.profiles.length})`),!0}catch(l){return console.error(`Error saving to ${o}:`,l.message),!1}}function no(e,t){let o=0;for(let r of t)Pe(e,r)&&o++;return o}function ze(e,t=null){return Qe(e,t).filter(r=>!r.processed)}function ro(e,t,o,r=null){qe();let n=kt(e,r);try{if(!F.existsSync(n))return;let s=JSON.parse(F.readFileSync(n,"utf-8")),l=s.profiles.find(a=>a.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof o=="string")l.status=o;else if(typeof o=="object"){if(l.status=o.status,o.profileInfo){let a=o.profileInfo;a.name&&(l.name=a.name),a.title&&(l.title=a.title),a.location&&(l.location=a.location),a.company&&(l.company=a.company),a.connectionDegree&&(l.connectionDegree=a.connectionDegree),a.connectionsCount&&(l.connectionsCount=a.connectionsCount),a.mutualConnections&&(l.mutualConnections=a.mutualConnections),a.photoUrl&&(l.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=a.hasVerifiedBadge)}l.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}s.lastUpdated=new Date().toISOString(),F.writeFileSync(n,JSON.stringify(s,null,2))}}catch(s){console.error("Error marking profile processed:",s.message)}}function Ce(e){let t=Qe(e),o=t.filter(n=>n.processed),r=t.filter(n=>!n.processed);return{total:t.length,processed:o.length,unprocessed:r.length,statuses:o.reduce((n,s)=>(n[s.status]=(n[s.status]||0)+1,n),{})}}function so(){qe();try{return F.readdirSync(le).filter(t=>t.endsWith(".json")).map(t=>{let[o,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let n=JSON.parse(F.readFileSync(Z.join(le,t),"utf-8"));return{file:t,source:o,date:r,count:n.profiles?.length||0,unprocessed:n.profiles?.filter(s=>!s.processed).length||0}}catch{return{file:t,source:o,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function Ke(e){qe();let t=[];try{let n=F.readdirSync(le).filter(s=>s.startsWith(e+"-")&&s.endsWith(".json")).sort().reverse();for(let s of n)try{let l=JSON.parse(F.readFileSync(Z.join(le,s),"utf-8"));l.profiles&&t.push({file:s,date:l.date,profiles:l.profiles})}catch{}}catch{return[]}let o=new Set,r=[];for(let{date:n,profiles:s}of t)for(let l of s)!l.processed&&l.profileUrl&&!o.has(l.profileUrl)&&(o.add(l.profileUrl),r.push({...l,_fromDate:n}));return r}var An,En,le,Tn,vt=eo(()=>{An=Cn(import.meta.url),En=Z.dirname(Z.dirname(An)),le=process.env.DATA_DIR?Z.resolve(process.env.DATA_DIR,"collected-profiles"):Z.join(En,"collected-profiles");Tn={loadProfiles:Qe,saveProfile:Pe,saveProfiles:no,getUnprocessedProfiles:ze,getAllUnprocessedProfiles:Ke,markProfileProcessed:ro,getSummary:Ce,listFiles:so}});var xo={};We(xo,{addEncounter:()=>je,canSendConnection:()=>ct,commitDataSnapshot:()=>$o,default:()=>Un,getAllApplications:()=>ko,getPersonStatus:()=>rt,getQuestionStats:()=>vo,getQuotaStatus:()=>Me,getRecentConnections:()=>at,linkPersonToJob:()=>nt,loadApplicationQuestions:()=>It,loadConversations:()=>ho,loadJobs:()=>et,loadPeople:()=>Y,loadProfileHistory:()=>mo,loadQuota:()=>it,loadSyncState:()=>bo,logApplicationQuestions:()=>Re,migrateFromDailyFiles:()=>go,profileSlug:()=>Ze,recordConnectionSent:()=>lt,resetCaches:()=>_t,saveConversations:()=>yo,saveJobs:()=>tt,savePeople:()=>be,saveQuota:()=>Tt,saveSyncState:()=>wo,updateConnectionStatus:()=>st,upsertJob:()=>ot,upsertPerson:()=>ue});import"dotenv/config";import*as q from"fs";import*as M from"path";import{fileURLToPath as In}from"url";import{execSync as $t}from"child_process";function _t(){Ae=null,Ee=null,ae=null,ge=null,_e=null,ye=null}function Q(){q.existsSync(V)||q.mkdirSync(V,{recursive:!0})}function de(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";q.writeFileSync(r,o);for(let n=0;n<3;n++)try{q.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function Te(e,t){if(!q.existsSync(e))return null;try{let o=JSON.parse(q.readFileSync(e,"utf-8"));try{q.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${M.resolve(e)}`);let r=e+".backup";if(q.existsSync(r))try{let n=JSON.parse(q.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{q.copyFileSync(r,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{q.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ie(){return new Date().toISOString().split("T")[0]}function Ze(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Dn(){q.existsSync(Et)||q.mkdirSync(Et,{recursive:!0})}function po(e){let t=Ze(e);return t?M.join(Et,`${t}.json`):null}function mo(e){let t=po(e);return t?Te(t,`profile-history/${Ze(e)}.json`)||[]:[]}function Nn(e,t){let o=po(e);if(!o)return;Dn();let r=mo(e);r.unshift(t);try{de(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${Ze(e)}: ${n.message}`)}}function lo(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function ao(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function qn(e,t){if(!e)return[];let o=[];for(let r of Ln){let n=e[r],s=t[r];lo(n)||lo(s)||ao(n)!==ao(s)&&o.push(r)}return o}function Pn(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[r,n]of Object.entries(e))t.has(r)||(o[r]=n);return o}function Y(){return Ae||(Q(),Ae=Te(xt,"people.json")||{},Ae)}function be(e){Q(),Ae=e;try{de(xt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${M.resolve(xt)}`)}}function et(){return Ee||(Q(),Ee=Te(Ct,"jobs.json")||{},Ee)}function tt(e){Q(),Ee=e;try{de(Ct,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${M.resolve(Ct)}`)}}function ho(){return ge||(Q(),ge=Te(Xe,"conversations.json")||{},On(ge),ge)}function On(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let n=(o.messages||[]).find(s=>s.status==="draft");n&&o.draftStatus&&o.draftStatus!=="pending"&&(n.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{de(Xe,e)}catch{}}}function yo(e){Q(),ge=e;try{de(Xe,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${M.resolve(Xe)}`)}}function ue(e,t={}){if(!e)return null;let o=Y(),r=Ie(),n=new Date().toISOString(),s=o[e];if(s){let l=qn(s,t);l.length>0&&(Nn(e,{capturedAt:n,previousLastUpdated:s.lastUpdated||null,changedFields:l,snapshot:Pn(s)}),s.lastSnapshotAt=n),s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=n,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let a of fo)t[a]!=null&&(s[a]=t[a]);Array.isArray(t.availableSections)&&(s.lastFullVisitAt=n)}else o[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return be(o),o[e]}function ot(e,t={}){if(!e)return null;let o=et(),r=Ie(),n=o[e];if(n){let s=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let l of s)t[l]!=null&&(n[l]=t[l])}else o[e]={title:t.title||null,company:t.company||null,location:t.location||null,salary:t.salary||null,url:t.url||null,applied:t.applied||!1,appliedDate:t.appliedDate||r,recruiterUrl:t.recruiterUrl||null,firstSeen:r};return tt(o),o[e]}function nt(e,t){if(!e||!t)return;let o=Y(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),be(o)))}function je(e,t){if(!e||!t)return;let o=Y(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let s={date:Ie(),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(),be(o))}function rt(e){return e&&Y()[e]?.connectionStatus||null}function st(e,t,o={}){if(!e)return;o.profileInfo?ue(e,o.profileInfo):Y()[e]||ue(e,{});let r=Y(),n=r[e];n&&(n.connectionStatus=t,n.connectionDate=Ie(),n.connectionMethod=o.method||n.connectionMethod,n.messageSent=o.messageSent||n.messageSent,n.lastUpdated=new Date().toISOString(),be(r))}function it(){return ae||(Q(),ae=Te(co,"quota.json"),(!ae||!ae.connections)&&(ae={connections:[]}),ae)}function Tt(e){Q(),ae=e;try{de(co,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function lt(e,t="unknown"){let o=it(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),Tt(o)}function at(){let e=it(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function ct(){let e=at(),t=Ie(),o=e.filter(i=>i.date===t).length,r=e.length,n=o>=Oe,s=r>=Fe,l=!n&&!s,a={allowed:l,daily:{sent:o,max:Oe},weekly:{sent:r,max:Fe}};return l||(a.reason=n?`Daily limit reached (${o}/${Oe})`:`Weekly limit reached (${r}/${Fe})`),a}function Me(){let e=at(),t=Ie(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:Oe,remaining:Oe-o},weekly:{sent:r,max:Fe,remaining:Fe-r}}}function Fn(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function go(){Q();let e=q.readdirSync(V).filter(s=>s.endsWith(".json")&&s!=="people.json"&&s!=="jobs.json"&&s!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
|
|
2
2
|
Migrating from ${e.length} daily files...
|
|
3
3
|
`);let t=Y(),o=et(),r=0,n=0;e.sort();for(let s of e){let l=M.join(V,s),a;try{a=JSON.parse(q.readFileSync(l,"utf-8"))}catch(u){console.log(` Skipping ${s}: ${u.message}`);continue}let i=a.date||s.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,c=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 u of a.profiles){let d=u.profileUrl;if(!d)continue;let f=t[d];if(f){f.seenCount=(f.seenCount||1)+1,i&&(!f.lastSeen||i>f.lastSeen)&&(f.lastSeen=i),i&&(!f.firstSeen||i<f.firstSeen)&&(f.firstSeen=i),c&&!f.sources?.includes(c)&&(f.sources=f.sources||[],f.sources.push(c));for(let p of fo)u[p]!=null&&(f[p]=u[p]);u.status&&u.processed&&(f.connectionStatus=u.status,f.connectionDate=i,u.funnelResult&&(f.connectionMethod=u.funnelResult.method||f.connectionMethod,f.messageSent=u.funnelResult.message||f.messageSent)),f.lastUpdated=new Date().toISOString()}else t[d]={name:u.name||null,title:u.title||null,location:u.location||null,company:u.company||null,connectionDegree:u.connectionDegree||null,connectionsCount:u.connectionsCount||null,mutualConnections:u.mutualConnections||null,photoUrl:u.photoUrl||null,hasVerifiedBadge:u.hasVerifiedBadge||!1,firstSeen:i,lastSeen:i,seenCount:1,sources:c?[c]:[],connectionStatus:u.processed&&u.status||null,connectionDate:u.processed?i:null,connectionMethod:u.funnelResult?.method||null,messageSent:u.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(u.fromJob?.url){let p=Fn(u.fromJob.url);p&&(t[d].jobIds||(t[d].jobIds=[]),t[d].jobIds.includes(p)||t[d].jobIds.push(p),o[p]?o[p].recruiterUrl||(o[p].recruiterUrl=d):(o[p]={title:u.fromJob.title||null,company:u.fromJob.company||null,location:null,salary:null,url:u.fromJob.url,applied:!0,appliedDate:i,recruiterUrl:d,firstSeen:i},n++))}}}return be(t),tt(o),console.log(`
|
|
4
|
-
Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(o).length} total (${n} new)`),{people:Object.keys(t).length,jobs:Object.keys(o).length}}function bo(){return _e||(Q(),_e=Te(uo,"sync-state.json")||{},_e)}function wo(e){Q(),_e=e;try{de(uo,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function It(){if(ye)return ye;Q();try{q.existsSync(At)&&(ye=JSON.parse(q.readFileSync(At,"utf-8")))}catch{}return ye||(ye={}),ye}function So(e){return Array.isArray(e.applications)}function ko(){let e=It();if(So(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function Re(e){if(!e||!e.questions||e.questions.length===0)return;let t=It(),o=e.jobId||"unknown",n={applicationId:`${o}_${Date.now()}`,date:new Date().toISOString(),result:e.result||"submitted",formPages:e.formPages||null,duration:e.duration||null,retries:e.retries||0,failedField:e.failedField||null,questionCount:e.questions.length,questions:e.questions.map(s=>{let l={type:s.type||"input",question:s.labelText||s.question||"",answer:s.answer||""};return s.options&&(s.options.length<=Mn?l.options=s.options:l.optionsOmitted=!0),s.page&&(l.page=s.page),s.wasPreFilled&&(l.wasPreFilled=!0),s.wasRetry&&(l.wasRetry=!0),typeof s.isRequired=="boolean"&&(l.isRequired=s.isRequired),s.wasOptional&&(l.wasOptional=!0),l})};So(t)?(n.jobId=o,n.jobTitle=e.jobTitle||null,n.jobCompany=e.jobCompany||null,n.jobUrl=e.jobUrl||null,t.applications.push(n)):(t[o]||(t[o]={applications:[]}),t[o].applications.push(n));try{de(At,t)}catch(s){console.error(`[!] Failed to save application-questions.json: ${s.message}`)}}function vo(){let e=ko(),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 c=(l.answer||"").trim();i.answers.set(c,(i.answers.get(c)||0)+1)}let o=[...t.values()].sort((s,l)=>l.count-s.count),r=o.slice(0,15).map(s=>({question:s.question,count:s.count,topAnswer:[...s.answers.entries()].sort((l,a)=>a[1]-l[1])[0]?.[0]||""})),n=o.filter(s=>s.answers.size>1&&s.count>=3).map(s=>({question:s.question,count:s.count,answers:[...s.answers.entries()].sort((l,a)=>a[1]-l[1]).map(([l,a])=>`${l} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:n}}function
|
|
4
|
+
Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(o).length} total (${n} new)`),{people:Object.keys(t).length,jobs:Object.keys(o).length}}function bo(){return _e||(Q(),_e=Te(uo,"sync-state.json")||{},_e)}function wo(e){Q(),_e=e;try{de(uo,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function It(){if(ye)return ye;Q();try{q.existsSync(At)&&(ye=JSON.parse(q.readFileSync(At,"utf-8")))}catch{}return ye||(ye={}),ye}function So(e){return Array.isArray(e.applications)}function ko(){let e=It();if(So(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function Re(e){if(!e||!e.questions||e.questions.length===0)return;let t=It(),o=e.jobId||"unknown",n={applicationId:`${o}_${Date.now()}`,date:new Date().toISOString(),result:e.result||"submitted",formPages:e.formPages||null,duration:e.duration||null,retries:e.retries||0,failedField:e.failedField||null,questionCount:e.questions.length,questions:e.questions.map(s=>{let l={type:s.type||"input",question:s.labelText||s.question||"",answer:s.answer||""};return s.options&&(s.options.length<=Mn?l.options=s.options:l.optionsOmitted=!0),s.page&&(l.page=s.page),s.wasPreFilled&&(l.wasPreFilled=!0),s.wasRetry&&(l.wasRetry=!0),typeof s.isRequired=="boolean"&&(l.isRequired=s.isRequired),s.wasOptional&&(l.wasOptional=!0),l})};So(t)?(n.jobId=o,n.jobTitle=e.jobTitle||null,n.jobCompany=e.jobCompany||null,n.jobUrl=e.jobUrl||null,t.applications.push(n)):(t[o]||(t[o]={applications:[]}),t[o].applications.push(n));try{de(At,t)}catch(s){console.error(`[!] Failed to save application-questions.json: ${s.message}`)}}function vo(){let e=ko(),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 c=(l.answer||"").trim();i.answers.set(c,(i.answers.get(c)||0)+1)}let o=[...t.values()].sort((s,l)=>l.count-s.count),r=o.slice(0,15).map(s=>({question:s.question,count:s.count,topAnswer:[...s.answers.entries()].sort((l,a)=>a[1]-l[1])[0]?.[0]||""})),n=o.filter(s=>s.answers.size>1&&s.count>=3).map(s=>({question:s.question,count:s.count,answers:[...s.answers.entries()].sort((l,a)=>a[1]-l[1]).map(([l,a])=>`${l} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:n}}function $o(e){if(q.existsSync(M.join(V,".git")))try{let t={cwd:V,stdio:"pipe",timeout:1e4};$t("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",t);try{$t("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');$t(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var jn,Rn,V,xt,Ct,co,Xe,uo,At,Et,Oe,Fe,Ae,Ee,ae,ge,_e,ye,fo,Ln,Mn,Un,Ue=eo(()=>{jn=In(import.meta.url),Rn=M.dirname(M.dirname(jn)),V=process.env.DATA_DIR?M.resolve(process.env.DATA_DIR,"collected-profiles"):M.join(Rn,"collected-profiles"),xt=M.join(V,"people.json"),Ct=M.join(V,"jobs.json"),co=M.join(V,"quota.json"),Xe=M.join(V,"conversations.json"),uo=M.join(V,"sync-state.json"),At=M.join(V,"application-questions.json"),Et=M.join(V,"profile-history"),Oe=20,Fe=100,Ae=null,Ee=null,ae=null,ge=null,_e=null,ye=null;fo=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections"],Ln=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];Mn=50;Un={loadPeople:Y,savePeople:be,loadJobs:et,saveJobs:tt,loadConversations:ho,saveConversations:yo,upsertPerson:ue,upsertJob:ot,linkPersonToJob:nt,addEncounter:je,getPersonStatus:rt,updateConnectionStatus:st,migrateFromDailyFiles:go,loadQuota:it,saveQuota:Tt,recordConnectionSent:lt,canSendConnection:ct,getRecentConnections:at,getQuotaStatus:Me,loadSyncState:bo,saveSyncState:wo,commitDataSnapshot:$o,logApplicationQuestions:Re,getQuestionStats:vo}});import Nr from"puppeteer";import*as hn from"fs";async function g(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}function to(e){return parseInt(e,10)||0}async function X(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let n=r.innerText||"",s=n.includes("Premium")||n.includes("premium")||n.includes("Upgrade")||n.includes("upgrade"),l=n.includes("Try for")||n.includes("free trial")||n.includes("/month")||n.includes("per month")||n.includes("Start my")||n.includes("Subscribe"),a=n.includes("Get hired faster")||n.includes("Get hired 2x");if(s||l||a){let i=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(i)return i.click(),{dismissed:!0,matched:n.substring(0,80)};let c=r.querySelectorAll("button");for(let u of c){let d=u.innerText?.trim().toLowerCase()||"",f=u.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return u.click(),{dismissed:!0,matched:n.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}import{createGraphClient as vn,resolveToken as $n}from"@ilivemylife/graph-sdk";import{config as xn}from"dotenv";xn();var oo=$n()||process.env.TOKEN;oo||(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 he=vn({token:oo});var xe=12e4;async function $e(e,{retries:t=2}={}){let o=process.env.NODE_EASY_APPLY_MAIN;if(!o||o.startsWith("YOUR_"))throw new Error('NODE_EASY_APPLY_MAIN is not configured in .env. Create a node in iLiveMyLife, add "assist" tag, and set the node ID in .env. See README.md for setup instructions.');for(let r=1;r<=t;r++)try{let n=await he.askLifebot(o,e,{timeout:xe});return xe=Math.max(12e4,xe*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){xe=Math.min(xe*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(xe/1e3)}s...`);continue}throw n}}async function wt(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let o=`Job application form field "${e}" \u2014 reply with ONLY the value to fill in, nothing else. `;return t&&(t==="Enter a decimal number larger than 0.0"&&(t="Enter a decimal number larger than 0"),o+=`Additional info: ${t}`),await $e(o)}async function Ye(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await $e(o)}async function Ne(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await $e(o)}vt();import{LIFEBOT_MESSAGE_TYPES as ln}from"@ilivemylife/graph-sdk";Ue();async function Ao(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function Co(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function Bn(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await X(e)&&(console.log(" Dismissed Premium overlay"),await g(1500),await Ao(e,t));let r=0;for(let s=0;s<2;s++){let l=await e.evaluate(()=>document.body.scrollHeight);for(let i=1;i<=6;i++)await e.evaluate(c=>window.scrollTo(0,c),l*i/6),await g(900);let a=await e.evaluate(()=>document.body.scrollHeight);if(a===r)break;r=a}await g(800);let n=await e.evaluate(()=>{let s=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),l=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),a=v=>{let E=(v||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(E)},i={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},c=document.querySelector("main");if(!c)return i;let u=[...Array.from(c.querySelectorAll("h1")),...Array.from(c.querySelectorAll("h2"))],d=Array.from(c.querySelectorAll("h2")),f=u.find(v=>{let E=v.textContent&&v.textContent.trim(),T=(E||"").replace(/\s*\(\d+\)$/,"").trim();return E&&E.length>1&&E.length<100&&!s.has(T)&&!l.has(T)}),p=f?f.textContent.trim():null,h=f?f.parentElement:null;for(;h&&h!==c&&!Array.from(h.children).filter(E=>E.tagName==="P").some(E=>{let T=E.textContent&&E.textContent.trim();return T&&T.length>5&&!a(T)});)h=h.parentElement;let m=null,b=null,y=null,S=null;if(h&&h!==c){let v=Array.from(h.children).filter(T=>T.tagName==="P").filter(T=>{let ie=T.textContent&&T.textContent.trim();return ie&&ie.length>5&&!a(ie)});if(v[0]&&(m=v[0].textContent.trim()),v[1]){let T=v[1].textContent.trim().split(/\s*[·•]\s*/);b=T[0]||null,T.length>1&&(y=T.slice(1).join(" \xB7 "))}let E=Array.from(h.children).filter(T=>T.tagName==="DIV");for(let T=E.length-1;T>=0;T--){let ie=E[T].textContent&&E[T].textContent.trim();if(ie&&!(p&&ie.startsWith(p))&&(S=ie.split(/[·•]/)[0].trim(),S))break}}let C=null;if(h){let v=h.querySelectorAll("p, span, div");for(let E of v){let T=(E.textContent||"").trim().replace(/^[·•]\s*/,"");if(T==="1st"||T==="2nd"||T==="3rd"){C=T;break}}}let w=!!c.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),A=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),U=A&&A.src||null,P=c.textContent||"",G=null,H=P.match(/(\d+\+?)\s+connections\b/i);H&&(G=H[1]+" connections");let J=null,re=P.match(/(\d+)\s+mutual connection/i),K=P.match(/and\s+(\d+)\s+other mutual/i),me=P.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);re?J=parseInt(re[1],10):K?J=2+parseInt(K[1],10):me&&(J=2);let B=null,_=null,O=d.find(v=>v.textContent&&v.textContent.trim()==="About");if(O){let v=O.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let E=(v.textContent||"").trim();E=E.replace(/^About\s*/,"").trim();let T=E.match(/Top skills\s*(.+?)$/i);if(T){let bt=T[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Sn=>Sn.trim()).filter(Boolean);bt.length>0&&bt.length<10&&(_=bt)}E=E.split(/\n?…\s*more/i)[0].trim(),E=E.split(/\n?\.\.\.\s*more/i)[0].trim(),E=E.split(/\bTop skills\b/i)[0].trim(),E=E.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),B=E||null}}let I=null,D=d.find(v=>v.textContent&&v.textContent.trim()==="Activity");if(D){let v=D.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let E=(v.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);E&&(I=parseInt(E[1].replace(/,/g,""),10))}}let x=[...new Set(d.map(v=>(v.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(v=>v&&v.length>1&&v.length<60&&v!==p).filter(v=>s.has(v)))],R=document.body.textContent||"",N=/#OpenToWork\b/i.test(R)||/\bOpen to work\b/.test(R),j=/#Hiring\b/i.test(R)||/\bI'?m hiring\b/i.test(R)||/\bWe are hiring\b/i.test(R);return{name:p,title:m,location:S,currentCompany:b,currentSchool:y,connectionDegree:C,hasVerifiedBadge:w,photoUrl:U,connectionsLevel:G,mutualConnectionsCount:J,followers:I,openToWork:N,hiring:j,about:B,topSkills:_,availableSections:x}});return console.log(`Viewed: ${n.name} - ${n.title}`),{...n,profileUrl:t}}catch(o){console.error(`Error viewing profile ${t}:`,o.message);try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{}return null}}async function Be(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(o).map(i=>i.getAttribute("aria-label")),n=document.querySelector('button[aria-label*="Message"]'),s=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:o.length,pendingLabels:r,hasMessageBtn:!!n,hasConnectBtn:!!s};return o.length>0?{status:"pending",debug:l}:n&&!s?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function jt(e){let t=null,o=await e.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(i=c.textContent?.trim(),i&&!i.includes("notification")))return i;let u=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(u)return u.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let i=await e.evaluate(()=>{let u=document.querySelectorAll('a[href*="custom-invite"]');return{count:u.length,labels:Array.from(u).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),t=await e.evaluateHandle(u=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=u.toLowerCase().split(" ")[0],p=null,h=null;for(let m of d){let b=m.getBoundingClientRect();if(b.width===0||b.height===0)continue;if((m.getAttribute("aria-label")||"").toLowerCase().includes(f)){p=m;break}h||(h=m)}return p||h||null},o);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:c,method:"connect_link"}}if(o){let i=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let c=await e.evaluate(d=>{let f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let b=m.getAttribute("aria-label")||"";return(b.toLowerCase().includes("invite")||b.toLowerCase().includes("connect"))&&f.test(b)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},i);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of f){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},i);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: button matching profile name"),{button:u,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let i=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(c)&&(console.log(` Skipping primary button: wrong person (${i})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let n=o?o.split(" ")[0].toLowerCase():"",s=null;for(let i of r){let c=await e.evaluate((u,d)=>{let f=u.className.includes("muted"),p=u.className.includes("sticky-header")||u.className.includes("sticky"),h=u.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(u.getAttribute("aria-label")||"").toLowerCase(),b=m.includes("invite"),y=d?m.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:h,hasInvite:b,matchesName:y,ariaLabel:m}},i,n);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.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 c=await e.evaluate(u=>{let d=u.getBoundingClientRect(),f=d.width>0&&d.height>0,p=u.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},i);if(c.isVisible&&!c.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 u=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),h=f.getAttribute("aria-label")||"",m=f.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!u)return null;let d=u.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==u)return p;d=d.parentElement}return null});l=i?.asElement?.()||null,l||await i?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),l),await g(500),await e.evaluate(u=>u.click(),l),await g(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let c=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(c||(c=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),c||(c=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),c||(c=await e.$('div[role="button"][aria-label*="Invite"]')),c||(c=await e.$('div[role="button"][aria-label*="connect"]')),!c){let u=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});c=u?.asElement?.()||null,c||await u?.dispose?.().catch(()=>{})}if(!c){let u=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&f.push(m)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(u)}`)}if(c)return console.log(" Found: More dropdown"),{button:c,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(i){console.log(" More dropdown click failed:",i.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&o){let i=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(c)&&(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 Jn(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await g(500);let o=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),n=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),s=o.tag==="DIV";if(n){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(u=>u.click(),t)]),await g(2e3);let c=e.url();if(c.includes("premium")||c.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await g(2e3),"premium_redirect"}else s?(await e.evaluate(c=>c.click(),t),await g(3e3)):(await e.evaluate(c=>c.click(),t),await g(3e3));let l=e.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),i=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${i}`:` \u26A0 No modal after connect click \u2014 ${i}`),"success"}async function Hn(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await g(1500);let o=await jt(e);if(o){await e.evaluate(n=>n.click(),o),await g(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(n=>n.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Gn(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,skipIfPending:s=!0,skipIfConnected:l=!0,excludeLocations:a=[]}=o,i={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
9
|
-
--- Connecting: ${c} ---`),a.length>0){let y=Y()[t]?.location;if(Co(y,a))return console.log(` \u26A0 Excluded location (stored): ${y}`),i.reason="excluded_location",i.profileInfo={location:y},i}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(5e3),await X(e)&&(console.log(" Dismissed Premium overlay"),await g(2e3),await Ao(e,t),await g(2e3)),i.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),S=x=>{let R=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(R)},C={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},w=document.querySelector("main");if(!w)return C;let A=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],U=Array.from(w.querySelectorAll("h2")),P=A.find(x=>{let R=x.textContent&&x.textContent.trim();return R&&R.length>1&&R.length<100&&!y.has(R)&&R!=="0 notifications"}),G=P?P.textContent.trim():null,H=P?P.parentElement:null;for(;H&&H!==w&&!Array.from(H.children).filter(N=>N.tagName==="P").some(N=>{let j=N.textContent&&N.textContent.trim();return j&&j.length>5&&!S(j)});)H=H.parentElement;let J=null,re=null,K=null;if(H&&H!==w){let x=Array.from(H.children),R=x.filter(j=>j.tagName==="P").filter(j=>{let v=j.textContent&&j.textContent.trim();return v&&v.length>5&&!S(v)});R[0]&&(J=R[0].textContent.trim()),R[1]&&(re=R[1].textContent.trim());let N=x.filter(j=>j.tagName==="DIV");for(let j=N.length-1;j>=0;j--){let v=N[j].textContent&&N[j].textContent.trim();if(v&&!(G&&v.startsWith(G))&&(K=v.split(/[·•]/)[0].trim(),K))break}}let me=null;if(H){let x=H.querySelectorAll("p, span, div");for(let R of x){let N=(R.textContent||"").trim().replace(/^[·•]\s*/,"");if(N==="1st"||N==="2nd"||N==="3rd"){me=N;break}}}let B=null,_=U.find(x=>x.textContent&&x.textContent.trim()==="About");if(_){let x=_.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;x&&(B=(x.textContent||"").trim().replace(/^About\s*/,"").trim()||null,B&&(B=B.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let O=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),I=O&&O.src||null,D=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:G,title:J,location:K,about:B,company:re,connectionDegree:me,connectionsCount:null,mutualConnections:null,photoUrl:I,hasVerifiedBadge:D}}),a.length>0){let y=i.profileInfo?.location,S=Y()[t]?.location,C=y||S;if(Co(C,a))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${C}`),i.reason="excluded_location",i;!y&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await Be(e);if(d==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await X(e);let f=await jt(e);if(!f&&(await X(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await g(2e3),f=await jt(e)),!f))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;if(i.method=f.method,await Jn(e,f.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3);let y=await Be(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await X(e),await g(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 g(500),await S.click().catch(()=>e.evaluate(w=>w.click(),S)),await g(2e3);let C=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(C){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(U=>U.click(),C),await g(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),i.reason="premium_required",i;if(await Be(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.method="more_dropdown",i.withCustomMessage=!1,i;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await g(500),i.reason="premium_required",i}catch(C){return console.log(" More dropdown failed:",C.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let y=await e.$('button[aria-label="Dismiss"]');return y&&await y.click(),await g(500),i.reason="email_required",i}let m=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!m&&!b){let y=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let C=S.querySelector('button[aria-label="Add a note"]'),w=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!C,sendWithout:!!w}});if(y.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=S?.asElement?.()||null,m||await S.dispose().catch(()=>{})}if(y.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=S?.asElement?.()||null,b||await S.dispose().catch(()=>{})}}if(n){if(m&&r){if(console.log(" Adding personalized note..."),await m.click(),await g(1500),await e.$("div.modal-upsell")){let C=await Hn(e);return i.success=C,i.connectionSent=C,i.reason=C?"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 C=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=r.replace("{name}",C);await S.type(w,{delay:20}),await g(500);let A=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(A){try{await A.evaluate(U=>U.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=w,i}}}else if(b){console.log(" Sending without note...");try{await b.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}else if(m&&!r){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y){try{await y.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let y=b;if(y){try{await y.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}if(f.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3)),await X(e),await g(500);let S=await e.$$('button[id*="profile-overflow-action"]'),C=null;for(let w of S){let A=await e.evaluate(U=>{let P=U.getBoundingClientRect();return{visible:P.width>0&&P.height>0,inSticky:!!U.closest('.sticky-header, [class*="sticky"]')}},w);if(A.visible&&!A.inSticky){C=w;break}}!C&&S.length>0&&(C=S[S.length-1]);for(let w of S)w!==C&&await w.dispose().catch(()=>{});if(C)try{await e.evaluate(A=>A.scrollIntoView({behavior:"smooth",block:"center"}),C),await g(500),await C.click().catch(()=>e.evaluate(A=>A.click(),C)),await g(2e3);let w=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(w){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(G=>G.click(),w),await g(3e3);let A=e.url();if(A.includes("/premium/")||A.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await Be(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 Be(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 P=await e.$('button[aria-label="Send without a note"]');if(P){console.log(" Modal appeared via More dropdown, sending without note...");try{await P.evaluate(G=>G.click())}catch{}return await g(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(c){console.error(` \u2717 Error: ${c.message}`),i.reason="error",i.error=c.message;let u=c.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{i.fatal=!0}return i}}async function Rt(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:s=20,viewOnly:l=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:i=null,excludeLocations:c=[],source:u="unknown"}=o,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
8
|
+
`),process.exit(1));var he=vn({token:oo});var $e=12e4;async function xe(e,{retries:t=2}={}){let o=process.env.NODE_EASY_APPLY_MAIN;if(!o||o.startsWith("YOUR_"))throw new Error('NODE_EASY_APPLY_MAIN is not configured in .env. Create a node in iLiveMyLife, add "assist" tag, and set the node ID in .env. See README.md for setup instructions.');for(let r=1;r<=t;r++)try{let n=await he.askLifebot(o,e,{timeout:$e});return $e=Math.max(12e4,$e*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){$e=Math.min($e*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round($e/1e3)}s...`);continue}throw n}}async function wt(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let o=`Job application form field "${e}" \u2014 reply with ONLY the value to fill in, nothing else. `;return t&&(t==="Enter a decimal number larger than 0.0"&&(t="Enter a decimal number larger than 0"),o+=`Additional info: ${t}`),await xe(o)}async function Ye(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await xe(o)}async function Ne(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await xe(o)}vt();import{LIFEBOT_MESSAGE_TYPES as ln}from"@ilivemylife/graph-sdk";Ue();async function Ao(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function Co(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function Bn(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await X(e)&&(console.log(" Dismissed Premium overlay"),await g(1500),await Ao(e,t));let r=0;for(let s=0;s<2;s++){let l=await e.evaluate(()=>document.body.scrollHeight);for(let i=1;i<=6;i++)await e.evaluate(c=>window.scrollTo(0,c),l*i/6),await g(900);let a=await e.evaluate(()=>document.body.scrollHeight);if(a===r)break;r=a}await g(800);let n=await e.evaluate(()=>{let s=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),l=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),a=v=>{let E=(v||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(E)},i={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},c=document.querySelector("main");if(!c)return i;let u=[...Array.from(c.querySelectorAll("h1")),...Array.from(c.querySelectorAll("h2"))],d=Array.from(c.querySelectorAll("h2")),f=u.find(v=>{let E=v.textContent&&v.textContent.trim(),T=(E||"").replace(/\s*\(\d+\)$/,"").trim();return E&&E.length>1&&E.length<100&&!s.has(T)&&!l.has(T)}),p=f?f.textContent.trim():null,h=f?f.parentElement:null;for(;h&&h!==c&&!Array.from(h.children).filter(E=>E.tagName==="P").some(E=>{let T=E.textContent&&E.textContent.trim();return T&&T.length>5&&!a(T)});)h=h.parentElement;let m=null,b=null,y=null,k=null;if(h&&h!==c){let v=Array.from(h.children).filter(T=>T.tagName==="P").filter(T=>{let ie=T.textContent&&T.textContent.trim();return ie&&ie.length>5&&!a(ie)});if(v[0]&&(m=v[0].textContent.trim()),v[1]){let T=v[1].textContent.trim().split(/\s*[·•]\s*/);b=T[0]||null,T.length>1&&(y=T.slice(1).join(" \xB7 "))}let E=Array.from(h.children).filter(T=>T.tagName==="DIV");for(let T=E.length-1;T>=0;T--){let ie=E[T].textContent&&E[T].textContent.trim();if(ie&&!(p&&ie.startsWith(p))&&(k=ie.split(/[·•]/)[0].trim(),k))break}}let C=null;if(h){let v=h.querySelectorAll("p, span, div");for(let E of v){let T=(E.textContent||"").trim().replace(/^[·•]\s*/,"");if(T==="1st"||T==="2nd"||T==="3rd"){C=T;break}}}let w=!!c.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),A=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),U=A&&A.src||null,P=c.textContent||"",G=null,H=P.match(/(\d+\+?)\s+connections\b/i);H&&(G=H[1]+" connections");let J=null,re=P.match(/(\d+)\s+mutual connection/i),K=P.match(/and\s+(\d+)\s+other mutual/i),me=P.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);re?J=parseInt(re[1],10):K?J=2+parseInt(K[1],10):me&&(J=2);let B=null,_=null,O=d.find(v=>v.textContent&&v.textContent.trim()==="About");if(O){let v=O.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let E=(v.textContent||"").trim();E=E.replace(/^About\s*/,"").trim();let T=E.match(/Top skills\s*(.+?)$/i);if(T){let bt=T[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Sn=>Sn.trim()).filter(Boolean);bt.length>0&&bt.length<10&&(_=bt)}E=E.split(/\n?…\s*more/i)[0].trim(),E=E.split(/\n?\.\.\.\s*more/i)[0].trim(),E=E.split(/\bTop skills\b/i)[0].trim(),E=E.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),B=E||null}}let I=null,D=d.find(v=>v.textContent&&v.textContent.trim()==="Activity");if(D){let v=D.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let E=(v.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);E&&(I=parseInt(E[1].replace(/,/g,""),10))}}let $=[...new Set(d.map(v=>(v.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(v=>v&&v.length>1&&v.length<60&&v!==p).filter(v=>s.has(v)))],R=document.body.textContent||"",N=/#OpenToWork\b/i.test(R)||/\bOpen to work\b/.test(R),j=/#Hiring\b/i.test(R)||/\bI'?m hiring\b/i.test(R)||/\bWe are hiring\b/i.test(R);return{name:p,title:m,location:k,currentCompany:b,currentSchool:y,connectionDegree:C,hasVerifiedBadge:w,photoUrl:U,connectionsLevel:G,mutualConnectionsCount:J,followers:I,openToWork:N,hiring:j,about:B,topSkills:_,availableSections:$}});return console.log(`Viewed: ${n.name} - ${n.title}`),{...n,profileUrl:t}}catch(o){console.error(`Error viewing profile ${t}:`,o.message);try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{}return null}}async function Be(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(o).map(i=>i.getAttribute("aria-label")),n=document.querySelector('button[aria-label*="Message"]'),s=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:o.length,pendingLabels:r,hasMessageBtn:!!n,hasConnectBtn:!!s};return o.length>0?{status:"pending",debug:l}:n&&!s?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function jt(e){let t=null,o=await e.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(i=c.textContent?.trim(),i&&!i.includes("notification")))return i;let u=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(u)return u.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let i=await e.evaluate(()=>{let u=document.querySelectorAll('a[href*="custom-invite"]');return{count:u.length,labels:Array.from(u).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),t=await e.evaluateHandle(u=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=u.toLowerCase().split(" ")[0],p=null,h=null;for(let m of d){let b=m.getBoundingClientRect();if(b.width===0||b.height===0)continue;if((m.getAttribute("aria-label")||"").toLowerCase().includes(f)){p=m;break}h||(h=m)}return p||h||null},o);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:c,method:"connect_link"}}if(o){let i=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let c=await e.evaluate(d=>{let f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let b=m.getAttribute("aria-label")||"";return(b.toLowerCase().includes("invite")||b.toLowerCase().includes("connect"))&&f.test(b)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},i);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of f){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},i);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: button matching profile name"),{button:u,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let i=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(c)&&(console.log(` Skipping primary button: wrong person (${i})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let n=o?o.split(" ")[0].toLowerCase():"",s=null;for(let i of r){let c=await e.evaluate((u,d)=>{let f=u.className.includes("muted"),p=u.className.includes("sticky-header")||u.className.includes("sticky"),h=u.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(u.getAttribute("aria-label")||"").toLowerCase(),b=m.includes("invite"),y=d?m.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:h,hasInvite:b,matchesName:y,ariaLabel:m}},i,n);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.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 c=await e.evaluate(u=>{let d=u.getBoundingClientRect(),f=d.width>0&&d.height>0,p=u.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},i);if(c.isVisible&&!c.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 u=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),h=f.getAttribute("aria-label")||"",m=f.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!u)return null;let d=u.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==u)return p;d=d.parentElement}return null});l=i?.asElement?.()||null,l||await i?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),l),await g(500),await e.evaluate(u=>u.click(),l),await g(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let c=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(c||(c=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),c||(c=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),c||(c=await e.$('div[role="button"][aria-label*="Invite"]')),c||(c=await e.$('div[role="button"][aria-label*="connect"]')),!c){let u=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});c=u?.asElement?.()||null,c||await u?.dispose?.().catch(()=>{})}if(!c){let u=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&f.push(m)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(u)}`)}if(c)return console.log(" Found: More dropdown"),{button:c,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(i){console.log(" More dropdown click failed:",i.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&o){let i=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(c)&&(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 Jn(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await g(500);let o=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),n=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),s=o.tag==="DIV";if(n){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(u=>u.click(),t)]),await g(2e3);let c=e.url();if(c.includes("premium")||c.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await g(2e3),"premium_redirect"}else s?(await e.evaluate(c=>c.click(),t),await g(3e3)):(await e.evaluate(c=>c.click(),t),await g(3e3));let l=e.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),i=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${i}`:` \u26A0 No modal after connect click \u2014 ${i}`),"success"}async function Hn(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await g(1500);let o=await jt(e);if(o){await e.evaluate(n=>n.click(),o),await g(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(n=>n.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Gn(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,skipIfPending:s=!0,skipIfConnected:l=!0,excludeLocations:a=[]}=o,i={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
9
|
+
--- Connecting: ${c} ---`),a.length>0){let y=Y()[t]?.location;if(Co(y,a))return console.log(` \u26A0 Excluded location (stored): ${y}`),i.reason="excluded_location",i.profileInfo={location:y},i}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(5e3),await X(e)&&(console.log(" Dismissed Premium overlay"),await g(2e3),await Ao(e,t),await g(2e3)),i.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),k=$=>{let R=($||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(R)},C={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},w=document.querySelector("main");if(!w)return C;let A=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],U=Array.from(w.querySelectorAll("h2")),P=A.find($=>{let R=$.textContent&&$.textContent.trim();return R&&R.length>1&&R.length<100&&!y.has(R)&&R!=="0 notifications"}),G=P?P.textContent.trim():null,H=P?P.parentElement:null;for(;H&&H!==w&&!Array.from(H.children).filter(N=>N.tagName==="P").some(N=>{let j=N.textContent&&N.textContent.trim();return j&&j.length>5&&!k(j)});)H=H.parentElement;let J=null,re=null,K=null;if(H&&H!==w){let $=Array.from(H.children),R=$.filter(j=>j.tagName==="P").filter(j=>{let v=j.textContent&&j.textContent.trim();return v&&v.length>5&&!k(v)});R[0]&&(J=R[0].textContent.trim()),R[1]&&(re=R[1].textContent.trim());let N=$.filter(j=>j.tagName==="DIV");for(let j=N.length-1;j>=0;j--){let v=N[j].textContent&&N[j].textContent.trim();if(v&&!(G&&v.startsWith(G))&&(K=v.split(/[·•]/)[0].trim(),K))break}}let me=null;if(H){let $=H.querySelectorAll("p, span, div");for(let R of $){let N=(R.textContent||"").trim().replace(/^[·•]\s*/,"");if(N==="1st"||N==="2nd"||N==="3rd"){me=N;break}}}let B=null,_=U.find($=>$.textContent&&$.textContent.trim()==="About");if(_){let $=_.parentElement;for(;$&&$.tagName!=="SECTION";)$=$.parentElement;$&&(B=($.textContent||"").trim().replace(/^About\s*/,"").trim()||null,B&&(B=B.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let O=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),I=O&&O.src||null,D=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:G,title:J,location:K,about:B,company:re,connectionDegree:me,connectionsCount:null,mutualConnections:null,photoUrl:I,hasVerifiedBadge:D}}),a.length>0){let y=i.profileInfo?.location,k=Y()[t]?.location,C=y||k;if(Co(C,a))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${C}`),i.reason="excluded_location",i;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await Be(e);if(d==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await X(e);let f=await jt(e);if(!f&&(await X(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await g(2e3),f=await jt(e)),!f))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;if(i.method=f.method,await Jn(e,f.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3);let y=await Be(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await X(e),await g(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),k),await g(500),await k.click().catch(()=>e.evaluate(w=>w.click(),k)),await g(2e3);let C=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(C){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(U=>U.click(),C),await g(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),i.reason="premium_required",i;if(await Be(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.method="more_dropdown",i.withCustomMessage=!1,i;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await g(500),i.reason="premium_required",i}catch(C){return console.log(" More dropdown failed:",C.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let y=await e.$('button[aria-label="Dismiss"]');return y&&await y.click(),await g(500),i.reason="email_required",i}let m=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!m&&!b){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let C=k.querySelector('button[aria-label="Add a note"]'),w=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!C,sendWithout:!!w}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=k?.asElement?.()||null,m||await k.dispose().catch(()=>{})}if(y.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=k?.asElement?.()||null,b||await k.dispose().catch(()=>{})}}if(n){if(m&&r){if(console.log(" Adding personalized note..."),await m.click(),await g(1500),await e.$("div.modal-upsell")){let C=await Hn(e);return i.success=C,i.connectionSent=C,i.reason=C?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let C=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=r.replace("{name}",C);await k.type(w,{delay:20}),await g(500);let A=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(A){try{await A.evaluate(U=>U.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=w,i}}}else if(b){console.log(" Sending without note...");try{await b.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}else if(m&&!r){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let y=b;if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}if(f.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3)),await X(e),await g(500);let k=await e.$$('button[id*="profile-overflow-action"]'),C=null;for(let w of k){let A=await e.evaluate(U=>{let P=U.getBoundingClientRect();return{visible:P.width>0&&P.height>0,inSticky:!!U.closest('.sticky-header, [class*="sticky"]')}},w);if(A.visible&&!A.inSticky){C=w;break}}!C&&k.length>0&&(C=k[k.length-1]);for(let w of k)w!==C&&await w.dispose().catch(()=>{});if(C)try{await e.evaluate(A=>A.scrollIntoView({behavior:"smooth",block:"center"}),C),await g(500),await C.click().catch(()=>e.evaluate(A=>A.click(),C)),await g(2e3);let w=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(w){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(G=>G.click(),w),await g(3e3);let A=e.url();if(A.includes("/premium/")||A.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await Be(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 Be(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 P=await e.$('button[aria-label="Send without a note"]');if(P){console.log(" Modal appeared via More dropdown, sending without note...");try{await P.evaluate(G=>G.click())}catch{}return await g(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(c){console.error(` \u2717 Error: ${c.message}`),i.reason="error",i.error=c.message;let u=c.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{i.fatal=!0}return i}}async function Rt(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:s=20,viewOnly:l=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:i=null,excludeLocations:c=[],source:u="unknown"}=o,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
10
10
|
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${s})`}`),l||console.log(`Custom messages: ${n?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!l){let p=Me();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let f=0;for(let p=0;p<t.length;p++){let h=t[p];try{if(e.isClosed()){console.log(`
|
|
11
11
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
12
12
|
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=rt(h.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,i&&await i(h,d,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl}`);let b=null;if(l){let y=await Bn(e,h.profileUrl);y?(ue(h.profileUrl,{...y,source:u}),d.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y}):(d.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=s){console.log(` Max connections per session (${s}) reached`);break}let y=ct();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(b=await Gn(e,h.profileUrl,{message:r,useCustomMessage:n,excludeLocations:c}),b.success)d.connectionsSent++,b.connectionSent&<(h.profileUrl,u);else switch(b.reason){case"pending":d.skipped.pending++;break;case"connected":d.skipped.connected++;break;case"email_required":d.skipped.email++;break;case"button_not_found":d.skipped.notFound++;break;case"excluded_location":d.skipped.excludedLocation++;break;default:d.errors++}}if(b?.fatal){console.log(`
|
|
13
13
|
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(b?.reason==="error"){if(f++,f>=3){console.log(`
|
|
14
14
|
\u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(b&&b.reason&&(st(h.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),je(h.profileUrl,{source:u||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:b.reason})),i&&await i(h,d,b),p<t.length-1){let y=a+Math.random()*2e3;await g(y)}}if(console.log(`
|
|
15
|
-
=== Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!l){let p=Me();console.log(` Quota remaining: today ${p.daily.remaining}/${p.daily.max} | week ${p.weekly.remaining}/${p.weekly.max}`)}return d}Ue();async function Eo(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let n=null,s=null;for(let d of r)if(n=document.querySelector(d),n){s=d;break}if(!n){let d=document.querySelector("li.scaffold-layout__list-item");if(d){let f=d.parentElement;for(;f&&f!==document.body;){if(f.scrollHeight>f.clientHeight){n=f,s="parent of li.scaffold-layout__list-item";break}f=f.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let l=n.scrollTop,a=300,i=300,c=50,u=0;for(;u<c&&(n.scrollBy(0,a),await new Promise(d=>setTimeout(d,i)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)u++;return{found:!0,usedSelector:s,initialScroll:l,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:u}},t)}async function _o(e,{easyApplyOnly:t=!0}={}){let o=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(n=>{let l=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=n.querySelector("a.job-card-container__link");if(a){let i=a.getAttribute("href").split("?")[0],c=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),u=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),d=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),f=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:i,isEasyApply:l,applyType:l?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${i}`,jobTitle:c,companyName:u,location:d,salary:f||null,jobLink:l?a.href:null}}return{isEasyApply:!1}})});return t?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function To(e){let t=await e.evaluate(()=>{let o=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(o&&!o.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return o.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",t.success?t.pageState:t.reason),t.success&&await g(2e3),t.success}async function Lt(e,t){let o=e.url();if(o.includes("/jobs/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let n=e.url();if(!n.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${n.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function Io(e,t,o,r){for(let n of t){await Lt(e,r)&&(await X(e),await g(2e3));let l=await e.$(`a[data-control-id="${n.dataId}"]`),a="dataId";if(!l){let i=n.id?.match(/\d+/)?.[0];i&&(l=await e.$(`a[href*="/jobs/view/${i}/"]`),l&&(a="href"))}if(l){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${n.jobTitle}`);let i=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await e.evaluate(f=>f.scrollIntoView({block:"center"}),l),await g(300),await l.click(),await g(1500);let c=!1;for(let f=0;f<8;f++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==i){c=!0;break}await g(500)}if(!c){await e.evaluate(f=>f.click(),l),await g(1500);for(let f=0;f<6;f++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==i){c=!0;break}await g(500)}c||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let u=await e.evaluate(()=>{let f=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of f)for(let h of p.querySelectorAll("button")){let m=h.innerText?.trim();if(m==="Continue applying"||m==="Got it"||m==="Dismiss")return h.click(),m}return null});u&&console.log(` Dismissed popup before processing (${u})`);let{keepGoing:d}=await o(e,n);if(!d)return{keepGoing:!1}}else{let i=n.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${n.jobTitle||n.id} (dataId=${n.dataId}, jobId=${i})`)}}return{keepGoing:!0}}async function jo(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=t.querySelector(".hirer-card__hirer-information");if(o){let l=o.querySelector('a[href*="/in/"]'),a=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(l)return{name:a?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let l=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(l)return{name:r.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"poster_name"}}let n=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(n){let l=n.querySelector('a[href*="/in/"]');if(l)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"people_section"}}let s=t.querySelectorAll('a[href*="/in/"]');for(let l of s){let a=l.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:l.href?.split("?")[0],source:"details_link"}}return null})}async function Ro(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},s=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let v of s){let E=v.querySelector(".job-criteria__subheader")?.textContent?.trim(),T=v.querySelector(".job-criteria__text")?.textContent?.trim();E&&T&&(n[E.toLowerCase()]=T)}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 v of l)new RegExp("\\b"+v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(v.replace(/\\\+/g,"+"));let c=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,d=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,f=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=f?.innerText?.trim()||null,m=(f?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",C=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,w=y.match(/(\d[\d,]*)\s+applicant/i),A=w?parseInt(w[1].replace(/,/g,"")):null,U=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),P=Array.from(U).map(v=>v.innerText?.trim()?.replace(/\s+/g," ")),H=P.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,J=P.join(" ")+" "+y,re=/\bremote\b/i.test(J)?"remote":/\bhybrid\b/i.test(J)?"hybrid":/\bon-?site\b/i.test(J)?"onsite":null,K=/\bcontract\b/i.test(J)?"contract":/\bfull-?time\b/i.test(J)?"full-time":/\bpart-?time\b/i.test(J)?"part-time":/\bfreelance\b/i.test(J)?"freelance":/\btemporary\b/i.test(J)?"temporary":null,B=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",O=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",I=(B+" "+r+" "+O).toLowerCase(),D=B.toLowerCase(),x=[];/\bremote\b/.test(I)&&x.push("remote"),/\bhybrid\b/.test(I)&&x.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(I)&&x.push("onsite"),(x.length===0||!x.includes("remote")&&!x.includes("hybrid")&&!x.includes("onsite"))&&/remote/i.test(O)&&x.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(D)&&x.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(D)&&x.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(D)&&!x.includes("managerial")&&x.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(D)?x.push("junior"):/\b(senior|sr\.?)\b/i.test(D)?x.push("senior"):/\b(staff|principal|distinguished)\b/i.test(D)?x.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(D)?x.push("executive"):/\b(lead|team lead)\b/i.test(D)&&x.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(I)&&x.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(I)&&x.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(I)&&x.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(I)&&x.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(I)&&x.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(I)&&x.push("mobile"),/\b(architect)\b/i.test(D)&&x.push("architect"),/\b(consultant|consulting)\b/i.test(D)&&x.push("consultant");let R=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(R)||/\bcontract\b/i.test(I))&&x.push("contract"),/full.?time|permanent/i.test(R)&&x.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(O)&&x.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(O)&&x.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&x.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:d,companyName:p,companyUrl:m?m.startsWith("/")?"https://www.linkedin.com"+m:m:null,aboutCompany:c,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:C,applicantCount:A,companySize:H,workplaceType:re,contractType:K,techStack:[...new Set(a)],jobTags:[...new Set(x)]}})}import"dotenv/config";import*as ee from"fs";import*as z from"path";import{fileURLToPath as Vn}from"url";var Wn=Vn(import.meta.url),Yn=z.dirname(z.dirname(Wn)),we=process.env.DATA_DIR?z.resolve(process.env.DATA_DIR,"market-research"):z.join(Yn,"market-research"),Lo=z.join(we,"scouted-jobs.json"),Ts=z.join(we,"discovered-people.json"),Is=z.join(we,"visit-log.json"),Do=z.join(we,"companies.json"),No=z.join(we,"job-decisions.json");function Dt(){ee.existsSync(we)||ee.mkdirSync(we,{recursive:!0})}function Nt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ee.writeFileSync(r,o);for(let n=0;n<3;n++)try{ee.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function qt(e){try{if(ee.existsSync(e))return JSON.parse(ee.readFileSync(e,"utf-8"))}catch{}return null}function qo(){Je=null,He=null,zn=null,Ge=null,Xn=null}var Je=null;function Qn(){return Je||(Je=qt(Lo)||{},Je)}function Po(e,t){if(!e)return;Dt();let o=Qn(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[n,s]of Object.entries(t))s!=null&&(o[e][n]=s);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{Nt(Lo,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}var He=null;function Oo(){return He||(He=qt(No)||{},He)}function Le(e,t,o={}){if(!e||!t)return;Dt();let r=Oo(),n=new Date().toISOString().slice(0,10);r[e]?(r[e].status=t,r[e].updatedAt=n,o.reason&&(r[e].reason=o.reason),o.score!=null&&(r[e].score=o.score),o.source&&(r[e].source=o.source)):r[e]={status:t,decidedAt:n,updatedAt:n,reason:o.reason||null,score:o.score??null,source:o.source||null};try{Nt(No,r)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function Fo(e){return Oo()[e]||null}var zn=null;var Ge=null;function Kn(){return Ge||(Ge=qt(Do)||{},Ge)}function Pt(e,t){if(!e)return;Dt();let o=Kn(),r=new Date().toISOString().slice(0,10);if(o[e]){let n=o[e];t.name&&(n.name=t.name),t.about&&(n.about=t.about),t.size&&(n.size=t.size),t.industries&&(n.industries=t.industries),t.jobId&&(n.jobIds||(n.jobIds=[]),n.jobIds.includes(t.jobId)||n.jobIds.push(t.jobId)),t.recruiterUrl&&(n.recruiterUrls||(n.recruiterUrls=[]),n.recruiterUrls.includes(t.recruiterUrl)||n.recruiterUrls.push(t.recruiterUrl)),n.lastSeen=r,n.jobCount=n.jobIds?.length||0}else o[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:r,lastSeen:r,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{Nt(Do,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}var Xn=null;import"dotenv/config";import*as $ from"fs";import*as Jt from"os";import*as L from"path";import{fileURLToPath as cr}from"url";var Mt={};We(Mt,{NAME:()=>er,VERSION:()=>Zn,up:()=>nr});import*as te from"fs";import*as ut from"path";var Zn=1,er="normalize-jobs-and-questions",tr=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],or=50;function Ot(e){return te.existsSync(e)?JSON.parse(te.readFileSync(e,"utf-8")):null}function Ft(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{te.writeFileSync(r,o)}catch(n){try{te.unlinkSync(r)}catch{}throw n}try{te.renameSync(r,e)}catch(n){try{te.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function nr(e,t){let o=ut.join(e,"jobs.json"),r=ut.join(t,"scouted-jobs.json"),n=ut.join(e,"application-questions.json"),s=Ot(o)||{},l=Ot(r)||{},a=0,i=[];for(let u of Object.keys(s)){if(!l[u])continue;let d=l[u],f=s[u];for(let p of tr)d[p]!=null&&f[p]==null&&(f[p]=d[p]);i.push(u),a++}a>0?(Ft(o,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let c=Ot(n);if(c&&Array.isArray(c.applications)){let u={},d=0;for(let f of c.applications){let p=f.jobId||"unknown";u[p]||(u[p]={applications:[]});let h=(f.questions||[]).map(m=>{let b={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=or?b.options=m.options:(b.optionsOmitted=!0,d++)),m.page&&(b.page=m.page),m.wasPreFilled&&(b.wasPreFilled=!0),m.wasRetry&&(b.wasRetry=!0),b});u[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||h.length,questions:h})}Ft(n,u),console.log(` Phase 2: Rekeyed ${c.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else c&&!c.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(i.length>0){for(let u of i)delete l[u];Ft(r,l),console.log(` Phase 3: Removed ${i.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Ut={};We(Ut,{NAME:()=>sr,VERSION:()=>rr,up:()=>ar});import*as oe from"fs";import*as Mo from"path";var rr=2,sr="reset-unread-flags";function ir(e){return oe.existsSync(e)?JSON.parse(oe.readFileSync(e,"utf-8")):null}function lr(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{oe.writeFileSync(r,o)}catch(n){try{oe.unlinkSync(r)}catch{}throw n}try{oe.renameSync(r,e)}catch(n){try{oe.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function ar(e){let t=Mo.join(e,"conversations.json"),o=ir(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let r=0;for(let n of Object.keys(o))o[n].unread===!0&&(o[n].unread=!1,r++);if(r===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}lr(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}Ue();var ur=cr(import.meta.url),dr=L.dirname(ur),fr=L.dirname(L.dirname(dr));function pr(e){return e&&(e==="~"?Jt.homedir():e.startsWith("~/")||e.startsWith("~\\")?L.join(Jt.homedir(),e.slice(2)):e)}var se=process.env.DATA_DIR?L.resolve(pr(process.env.DATA_DIR)):fr,ke=L.join(se,"collected-profiles"),ve=L.join(se,"market-research"),W=L.join(se,".schema-version"),Uo=[L.join(ke,".schema-version"),L.join(ve,".schema-version")],fe=2,ce=[{version:1,module:Mt},{version:2,module:Ut}];(function(){ce.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of ce){if(!Number.isInteger(r.version)||r.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(r.version)} (must be positive integer)`);if(t.has(r.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${r.version}`);t.add(r.version);let n=r.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${r.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==r.version)throw new Error(`MIGRATION_REGISTRY: v${r.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=ce.length?ce[ce.length-1].version:0;if(o!==fe)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${fe}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<ce.length;r++){let n=r+1;if(ce[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${ce[r].version}`)}})();function Go(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
15
|
+
=== Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!l){let p=Me();console.log(` Quota remaining: today ${p.daily.remaining}/${p.daily.max} | week ${p.weekly.remaining}/${p.weekly.max}`)}return d}Ue();async function Eo(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let n=null,s=null;for(let d of r)if(n=document.querySelector(d),n){s=d;break}if(!n){let d=document.querySelector("li.scaffold-layout__list-item");if(d){let f=d.parentElement;for(;f&&f!==document.body;){if(f.scrollHeight>f.clientHeight){n=f,s="parent of li.scaffold-layout__list-item";break}f=f.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let l=n.scrollTop,a=300,i=300,c=50,u=0;for(;u<c&&(n.scrollBy(0,a),await new Promise(d=>setTimeout(d,i)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)u++;return{found:!0,usedSelector:s,initialScroll:l,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:u}},t)}async function _o(e,{easyApplyOnly:t=!0}={}){let o=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(n=>{let l=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=n.querySelector("a.job-card-container__link");if(a){let i=a.getAttribute("href").split("?")[0],c=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),u=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),d=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),f=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:i,isEasyApply:l,applyType:l?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${i}`,jobTitle:c,companyName:u,location:d,salary:f||null,jobLink:l?a.href:null}}return{isEasyApply:!1}})});return t?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function To(e){let t=await e.evaluate(()=>{let o=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(o&&!o.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return o.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",t.success?t.pageState:t.reason),t.success&&await g(2e3),t.success}async function Lt(e,t){let o=e.url();if(o.includes("/jobs/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let n=e.url();if(!n.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${n.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function Io(e,t,o,r){for(let n of t){await Lt(e,r)&&(await X(e),await g(2e3));let l=await e.$(`a[data-control-id="${n.dataId}"]`),a="dataId";if(!l){let i=n.id?.match(/\d+/)?.[0];i&&(l=await e.$(`a[href*="/jobs/view/${i}/"]`),l&&(a="href"))}if(l){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${n.jobTitle}`);let i=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await e.evaluate(f=>f.scrollIntoView({block:"center"}),l),await g(300),await l.click(),await g(1500);let c=!1;for(let f=0;f<8;f++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==i){c=!0;break}await g(500)}if(!c){await e.evaluate(f=>f.click(),l),await g(1500);for(let f=0;f<6;f++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==i){c=!0;break}await g(500)}c||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let u=await e.evaluate(()=>{let f=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of f)for(let h of p.querySelectorAll("button")){let m=h.innerText?.trim();if(m==="Continue applying"||m==="Got it"||m==="Dismiss")return h.click(),m}return null});u&&console.log(` Dismissed popup before processing (${u})`);let{keepGoing:d}=await o(e,n);if(!d)return{keepGoing:!1}}else{let i=n.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${n.jobTitle||n.id} (dataId=${n.dataId}, jobId=${i})`)}}return{keepGoing:!0}}async function jo(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=t.querySelector(".hirer-card__hirer-information");if(o){let l=o.querySelector('a[href*="/in/"]'),a=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(l)return{name:a?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let l=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(l)return{name:r.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"poster_name"}}let n=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(n){let l=n.querySelector('a[href*="/in/"]');if(l)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"people_section"}}let s=t.querySelectorAll('a[href*="/in/"]');for(let l of s){let a=l.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:l.href?.split("?")[0],source:"details_link"}}return null})}async function Ro(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},s=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let v of s){let E=v.querySelector(".job-criteria__subheader")?.textContent?.trim(),T=v.querySelector(".job-criteria__text")?.textContent?.trim();E&&T&&(n[E.toLowerCase()]=T)}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 v of l)new RegExp("\\b"+v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(v.replace(/\\\+/g,"+"));let c=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,d=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,f=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=f?.innerText?.trim()||null,m=(f?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",C=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,w=y.match(/(\d[\d,]*)\s+applicant/i),A=w?parseInt(w[1].replace(/,/g,"")):null,U=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),P=Array.from(U).map(v=>v.innerText?.trim()?.replace(/\s+/g," ")),H=P.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,J=P.join(" ")+" "+y,re=/\bremote\b/i.test(J)?"remote":/\bhybrid\b/i.test(J)?"hybrid":/\bon-?site\b/i.test(J)?"onsite":null,K=/\bcontract\b/i.test(J)?"contract":/\bfull-?time\b/i.test(J)?"full-time":/\bpart-?time\b/i.test(J)?"part-time":/\bfreelance\b/i.test(J)?"freelance":/\btemporary\b/i.test(J)?"temporary":null,B=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",O=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",I=(B+" "+r+" "+O).toLowerCase(),D=B.toLowerCase(),$=[];/\bremote\b/.test(I)&&$.push("remote"),/\bhybrid\b/.test(I)&&$.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(I)&&$.push("onsite"),($.length===0||!$.includes("remote")&&!$.includes("hybrid")&&!$.includes("onsite"))&&/remote/i.test(O)&&$.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(D)&&$.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(D)&&$.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(D)&&!$.includes("managerial")&&$.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(D)?$.push("junior"):/\b(senior|sr\.?)\b/i.test(D)?$.push("senior"):/\b(staff|principal|distinguished)\b/i.test(D)?$.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(D)?$.push("executive"):/\b(lead|team lead)\b/i.test(D)&&$.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(I)&&$.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(I)&&$.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(I)&&$.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(I)&&$.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(I)&&$.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(I)&&$.push("mobile"),/\b(architect)\b/i.test(D)&&$.push("architect"),/\b(consultant|consulting)\b/i.test(D)&&$.push("consultant");let R=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(R)||/\bcontract\b/i.test(I))&&$.push("contract"),/full.?time|permanent/i.test(R)&&$.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(O)&&$.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(O)&&$.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:d,companyName:p,companyUrl:m?m.startsWith("/")?"https://www.linkedin.com"+m:m:null,aboutCompany:c,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:C,applicantCount:A,companySize:H,workplaceType:re,contractType:K,techStack:[...new Set(a)],jobTags:[...new Set($)]}})}import"dotenv/config";import*as ee from"fs";import*as z from"path";import{fileURLToPath as Vn}from"url";var Wn=Vn(import.meta.url),Yn=z.dirname(z.dirname(Wn)),we=process.env.DATA_DIR?z.resolve(process.env.DATA_DIR,"market-research"):z.join(Yn,"market-research"),Lo=z.join(we,"scouted-jobs.json"),Ts=z.join(we,"discovered-people.json"),Is=z.join(we,"visit-log.json"),Do=z.join(we,"companies.json"),No=z.join(we,"job-decisions.json");function Dt(){ee.existsSync(we)||ee.mkdirSync(we,{recursive:!0})}function Nt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ee.writeFileSync(r,o);for(let n=0;n<3;n++)try{ee.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function qt(e){try{if(ee.existsSync(e))return JSON.parse(ee.readFileSync(e,"utf-8"))}catch{}return null}function qo(){Je=null,He=null,zn=null,Ge=null,Xn=null}var Je=null;function Qn(){return Je||(Je=qt(Lo)||{},Je)}function Po(e,t){if(!e)return;Dt();let o=Qn(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[n,s]of Object.entries(t))s!=null&&(o[e][n]=s);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{Nt(Lo,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}var He=null;function Oo(){return He||(He=qt(No)||{},He)}function Le(e,t,o={}){if(!e||!t)return;Dt();let r=Oo(),n=new Date().toISOString().slice(0,10);r[e]?(r[e].status=t,r[e].updatedAt=n,o.reason&&(r[e].reason=o.reason),o.score!=null&&(r[e].score=o.score),o.source&&(r[e].source=o.source)):r[e]={status:t,decidedAt:n,updatedAt:n,reason:o.reason||null,score:o.score??null,source:o.source||null};try{Nt(No,r)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function Fo(e){return Oo()[e]||null}var zn=null;var Ge=null;function Kn(){return Ge||(Ge=qt(Do)||{},Ge)}function Pt(e,t){if(!e)return;Dt();let o=Kn(),r=new Date().toISOString().slice(0,10);if(o[e]){let n=o[e];t.name&&(n.name=t.name),t.about&&(n.about=t.about),t.size&&(n.size=t.size),t.industries&&(n.industries=t.industries),t.jobId&&(n.jobIds||(n.jobIds=[]),n.jobIds.includes(t.jobId)||n.jobIds.push(t.jobId)),t.recruiterUrl&&(n.recruiterUrls||(n.recruiterUrls=[]),n.recruiterUrls.includes(t.recruiterUrl)||n.recruiterUrls.push(t.recruiterUrl)),n.lastSeen=r,n.jobCount=n.jobIds?.length||0}else o[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:r,lastSeen:r,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{Nt(Do,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}var Xn=null;import"dotenv/config";import*as x from"fs";import*as Jt from"os";import*as L from"path";import{fileURLToPath as cr}from"url";var Mt={};We(Mt,{NAME:()=>er,VERSION:()=>Zn,up:()=>nr});import*as te from"fs";import*as ut from"path";var Zn=1,er="normalize-jobs-and-questions",tr=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],or=50;function Ot(e){return te.existsSync(e)?JSON.parse(te.readFileSync(e,"utf-8")):null}function Ft(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{te.writeFileSync(r,o)}catch(n){try{te.unlinkSync(r)}catch{}throw n}try{te.renameSync(r,e)}catch(n){try{te.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function nr(e,t){let o=ut.join(e,"jobs.json"),r=ut.join(t,"scouted-jobs.json"),n=ut.join(e,"application-questions.json"),s=Ot(o)||{},l=Ot(r)||{},a=0,i=[];for(let u of Object.keys(s)){if(!l[u])continue;let d=l[u],f=s[u];for(let p of tr)d[p]!=null&&f[p]==null&&(f[p]=d[p]);i.push(u),a++}a>0?(Ft(o,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let c=Ot(n);if(c&&Array.isArray(c.applications)){let u={},d=0;for(let f of c.applications){let p=f.jobId||"unknown";u[p]||(u[p]={applications:[]});let h=(f.questions||[]).map(m=>{let b={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=or?b.options=m.options:(b.optionsOmitted=!0,d++)),m.page&&(b.page=m.page),m.wasPreFilled&&(b.wasPreFilled=!0),m.wasRetry&&(b.wasRetry=!0),b});u[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||h.length,questions:h})}Ft(n,u),console.log(` Phase 2: Rekeyed ${c.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else c&&!c.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(i.length>0){for(let u of i)delete l[u];Ft(r,l),console.log(` Phase 3: Removed ${i.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Ut={};We(Ut,{NAME:()=>sr,VERSION:()=>rr,up:()=>ar});import*as oe from"fs";import*as Mo from"path";var rr=2,sr="reset-unread-flags";function ir(e){return oe.existsSync(e)?JSON.parse(oe.readFileSync(e,"utf-8")):null}function lr(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{oe.writeFileSync(r,o)}catch(n){try{oe.unlinkSync(r)}catch{}throw n}try{oe.renameSync(r,e)}catch(n){try{oe.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function ar(e){let t=Mo.join(e,"conversations.json"),o=ir(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let r=0;for(let n of Object.keys(o))o[n].unread===!0&&(o[n].unread=!1,r++);if(r===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}lr(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}Ue();var ur=cr(import.meta.url),dr=L.dirname(ur),fr=L.dirname(L.dirname(dr));function pr(e){return e&&(e==="~"?Jt.homedir():e.startsWith("~/")||e.startsWith("~\\")?L.join(Jt.homedir(),e.slice(2)):e)}var se=process.env.DATA_DIR?L.resolve(pr(process.env.DATA_DIR)):fr,ke=L.join(se,"collected-profiles"),ve=L.join(se,"market-research"),W=L.join(se,".schema-version"),Uo=[L.join(ke,".schema-version"),L.join(ve,".schema-version")],fe=2,ce=[{version:1,module:Mt},{version:2,module:Ut}];(function(){ce.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of ce){if(!Number.isInteger(r.version)||r.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(r.version)} (must be positive integer)`);if(t.has(r.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${r.version}`);t.add(r.version);let n=r.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${r.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==r.version)throw new Error(`MIGRATION_REGISTRY: v${r.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=ce.length?ce[ce.length-1].version:0;if(o!==fe)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${fe}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<ce.length;r++){let n=r+1;if(ce[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${ce[r].version}`)}})();function Go(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
16
16
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
17
|
-
`),process.exit(1));try{
|
|
17
|
+
`),process.exit(1));try{x.mkdirSync(se,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
18
18
|
[FATAL] Cannot create DATA_DIR (${se}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
19
|
-
`),process.exit(1))}let e;try{e
|
|
19
|
+
`),process.exit(1))}let e;try{e=x.statSync(se)}catch(t){console.error(`
|
|
20
20
|
[FATAL] DATA_DIR (${se}) is not accessible: ${t.message}
|
|
21
21
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
22
22
|
[FATAL] DATA_DIR (${se}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
23
|
-
`),process.exit(1));for(let t of[ke,ve]){let o;try{o
|
|
23
|
+
`),process.exit(1));for(let t of[ke,ve]){let o;try{o=x.lstatSync(t)}catch(r){if(r.code==="ENOENT")continue;throw r}o.isSymbolicLink()&&(console.error(`
|
|
24
24
|
[FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
|
|
25
|
-
`),process.exit(1))}}var Se=L.join(se,".migration-lock");function mr(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return
|
|
25
|
+
`),process.exit(1))}}var Se=L.join(se,".migration-lock");function mr(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return x.writeFileSync(Se,e,{flag:"wx"}),!0}catch(r){if(r.code!=="EEXIST")throw r}let t;try{t=JSON.parse(x.readFileSync(Se,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let r=!1;try{process.kill(t.pid,0),r=!0}catch(l){l.code==="EPERM"&&(r=!0)}let n=24*60*60*1e3,s=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(s=Date.now()-l)}r&&s<n&&(console.error(`
|
|
26
26
|
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Se}
|
|
27
27
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
28
|
-
`),process.exit(1)),r&&s>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=Se+".tmp";try{return
|
|
28
|
+
`),process.exit(1)),r&&s>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=Se+".tmp";try{return x.writeFileSync(o,e),x.renameSync(o,Se),!0}catch(r){try{x.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${r.message}`)}}function Ht(){try{if(JSON.parse(x.readFileSync(Se,"utf-8")).pid!==process.pid)return;x.unlinkSync(Se)}catch{}}var Bo=!1;function hr(){if(Bo)return;Bo=!0;let e=()=>{try{Ht()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function yr(){if(x.existsSync(W))return;let e=[],t=[];for(let s of Uo)if(x.existsSync(s))try{e.push({file:s,schema:dt(s)})}catch(l){t.push({file:s,err:l.message})}if(t.length>0){console.error(`
|
|
29
29
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of t)console.error(` ${s.file}: ${s.err}`);console.error(`
|
|
30
30
|
Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
|
|
31
31
|
`),process.exit(1)}if(e.length===0)return;let o=e.map(s=>s.schema.version);if(new Set(o).size>1){console.error(`
|
|
32
32
|
[FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
33
|
-
`),process.exit(1)}let r=e[0].schema,n=W+".tmp";try{
|
|
33
|
+
`),process.exit(1)}let r=e[0].schema,n=W+".tmp";try{x.writeFileSync(n,JSON.stringify(r,null,2)),x.renameSync(n,W)}catch(s){try{x.unlinkSync(n)}catch{}throw s}for(let s of Uo)if(x.existsSync(s))try{x.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${W}`)}function gr(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function dt(e){let t=x.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Jo(){if(yr(),!x.existsSync(W))return{version:0,migrations:[]};let e;try{e=dt(W)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
34
34
|
[FATAL] ${W} is not valid JSON: ${o.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
35
35
|
`),process.exit(1)}let t=gr(e);return t===null&&(console.error(`
|
|
36
36
|
[FATAL] ${W} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
37
|
-
`),process.exit(1)),t}function Vo(e){try{
|
|
37
|
+
`),process.exit(1)),t}function Vo(e){try{x.chmodSync(e,384)}catch{}}function br(e){if(Go(),x.existsSync(W))try{if(x.lstatSync(W).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${W}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=W+".tmp";try{x.writeFileSync(t,JSON.stringify(e,null,2)),Vo(t),x.renameSync(t,W)}catch(o){try{x.unlinkSync(t)}catch{}throw o}}function Ho(e,t){if(!x.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,r=x.readdirSync(e).filter(a=>{let i=a.toLowerCase();if(i.includes(".backup")||i===".schema-version"||i.endsWith(".tmp"))return!1;try{return x.statSync(L.join(e,a)).isFile()}catch{return!1}}),n=0,s=0,l=[];for(let a of r){let i=L.join(e,a),c=L.join(e,a+o);if(x.existsSync(c)){s++;continue}try{Yo(i,c),n++}catch(u){l.push({file:a,err:u.message})}}if(l.length>0){let a=new Error(`Failed to back up ${l.length} file(s) in ${L.basename(e)}/: `+l.map(i=>`${i.file} (${i.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(n>0||s>0){let a=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${n} files in ${L.basename(e)}/ (${o})${a}`)}}var Bt=!1;async function Wo(){if(Bt)return;Go(),$r();let t=Jo().version;if(t===fe){Bt=!0;return}hr(),mr(),process.on("exit",Ht),t>fe&&(console.error(`
|
|
38
38
|
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${fe}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
|
|
39
39
|
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${fe}.
|
|
40
40
|
`),process.exit(1)),console.log(`
|
|
41
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${fe}`);let o
|
|
41
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${fe}`);let o=xr();if(!o.ok){console.error(`
|
|
42
42
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let n of o.broken)console.error(` ${n.dir}/${n.file}: ${n.err}`);console.error(`
|
|
43
43
|
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
44
44
|
`),process.exit(1)}let r=ce.filter(n=>n.version>t);for(let n of r){console.log(`
|
|
@@ -52,34 +52,34 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
|
|
|
52
52
|
[FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${i.message}`),console.error(` Your data is in the v${n.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
53
53
|
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{_t()}catch{}try{qo()}catch{}Bt=!0,Ht(),console.log(`
|
|
54
54
|
\u2713 Schema is now at v${fe}
|
|
55
|
-
`)}var wr=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Sr(e){let t=e.toLowerCase();return wr.some(o=>o.test(t))}var kr=6e4;function vr(){let e=Date.now(),t=[];for(let o of[se,ke,ve]){if(
|
|
55
|
+
`)}var wr=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Sr(e){let t=e.toLowerCase();return wr.some(o=>o.test(t))}var kr=6e4;function vr(){let e=Date.now(),t=[];for(let o of[se,ke,ve]){if(!x.existsSync(o))continue;let r;try{r=x.readdirSync(o)}catch{continue}for(let n of r){if(!Sr(n))continue;let s=L.join(o,n);try{let l=x.statSync(s);if(!l.isFile()||e-l.mtimeMs<kr)continue;t.push({dir:o,file:n,fullPath:s})}catch{}}}return t}function $r({verbose:e=!1}={}){let t=vr();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let r of t)try{x.unlinkSync(r.fullPath),o++,e&&console.log(` Removed orphan: ${L.basename(r.dir)}/${r.file}`)}catch(n){console.warn(` [!] Could not remove orphan ${r.fullPath}: ${n.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function xr(){let e=[];for(let t of[ke,ve]){if(!x.existsSync(t))continue;let o=x.readdirSync(t).filter(r=>{let n=r.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let r of o){let n=L.join(t,r);try{dt(n)}catch(s){e.push({dir:L.basename(t),file:r,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Cr(e){let t=[],o=[];for(let s of[ke,ve]){if(!x.existsSync(s))continue;let l=x.readdirSync(s).filter(a=>a.endsWith(e));for(let a of l){let i=L.join(s,a),c=a.slice(0,-e.length),u=L.join(s,c);try{c.toLowerCase().endsWith(".json")?dt(i):x.accessSync(i,x.constants.R_OK),t.push({backupPath:i,originalPath:u,fileName:a,dir:s})}catch(d){o.push(`${L.basename(s)}/${a}: ${d.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let r=0,n=[];for(let{backupPath:s,originalPath:l,fileName:a,dir:i}of t)try{Yo(s,l),r++}catch(c){n.push(`${L.basename(i)}/${a}: ${c.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:r}:{ok:!0,restored:r}}function Yo(e,t){let o=t+".tmp";try{x.copyFileSync(e,o),Vo(o)}catch(r){try{x.unlinkSync(o)}catch{}throw r}try{x.renameSync(o,t)}catch(r){try{x.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let n=new Error(`File locked: ${t} (${r.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw n.code=r.code,n}throw r}}import"dotenv/config";import*as ne from"fs";import*as pe from"path";import{fileURLToPath as _r}from"url";import"dotenv/config";function Ar(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),r=t%60;return r?`${o}m ${r}s`:`${o}m`}function Er({scriptName:e,mode:t,status:o,error:r,duration:n}){let s=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),a=n?` ${Ar(n)}`:"",i=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",c=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${c} \u2014 ${i} \u2014 ${l}${a}`}async function Qo({scriptName:e,mode:t,status:o,summaryLines:r,error:n,duration:s}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(r)||r.length===0)return;let i=`**${Er({scriptName:e,mode:t,status:o,error:n,duration:s})}**
|
|
56
56
|
|
|
57
57
|
${r.join(`
|
|
58
|
-
`)}`;try{await he.addMessage(l,i)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var Tr=_r(import.meta.url),Ir=pe.dirname(pe.dirname(Tr)),Gt=process.env.DATA_DIR?pe.resolve(process.env.DATA_DIR,"collected-profiles"):pe.join(Ir,"collected-profiles"),Vt=pe.join(Gt,"run-log.json");function jr(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ne.writeFileSync(r,o);for(let n=0;n<3;n++)try{ne.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function zo(){try{if(!ne.existsSync(Vt))return{runs:[]};let e=JSON.parse(ne.readFileSync(Vt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ko(e){ne.existsSync(Gt)||ne.mkdirSync(Gt,{recursive:!0});try{jr(Vt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Xo(e,t="default"){let o=zo();for(let l of o.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let r=new Date,n={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let s=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(l=>new Date(l.timestamp).getTime()>s),Ko(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Zo(e,t,o=null,r=null){if(!e)return;let n=null;try{let l=zo(),a=l.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=o,a.error=r,n=a.duration;else{let i=l.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());i&&(i.status=t,i.result=t,i.duration=Date.now()-e.startTime,i.stats=o,i.error=r,n=i.duration)}Ko(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let s=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Qo({scriptName:e.script,mode:e.mode,status:l,summaryLines:s,error:r,duration:n??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import en from"fs";import Rr from"path";var Lr="cookies.json";function Dr(){let e=process.env.ILML_SCOPE_DIR;return e?Rr.join(e,"plugins-state","linkedin","cookies.json"):Lr}function Wt(){let e=Dr();if(!en.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=en.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}async function ft(e,t,o="op"){let r,n=new Promise((s,l)=>{r=setTimeout(()=>l(new Error(`${o} timeout after ${t}ms`)),t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}function De(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let o=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(o)||/Target closed/i.test(o)||/Session closed/i.test(o)||/Connection closed/i.test(o)||/Most likely the page has been closed/i.test(o)||/Navigating frame was detached/i.test(o)||/Protocol error.*timed out/i.test(o)}async function tn(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await ft(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function on(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await tn(e,t)?!0:(await g(o),await tn(e,t))}async function nn(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await ft(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function rn(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:s=null}={}){try{await ft(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let l=await e.newPage();if(s)try{await s(l)}catch{}if(n)try{let a=n();Array.isArray(a)&&a.length>0&&await l.setCookie(...a)}catch{}if(o){await l.goto(o,{waitUntil:"domcontentloaded",timeout:r});let a=l.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(a))throw new Error(`Session expired after recovery \u2014 landed on ${a}. Run: ilml linkedin login`)}return l}async function sn(e,{launchFn:t,returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:s=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");try{await ft(e.close(),5e3,"oldBrowser.close")}catch{}let l=await t(),a=await l.newPage();if(s)try{await s(a)}catch{}if(n)try{let i=n();Array.isArray(i)&&i.length>0&&await a.setCookie(...i)}catch{}if(o){await a.goto(o,{waitUntil:"domcontentloaded",timeout:r});let i=a.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(i))throw new Error(`Session expired after browser restart \u2014 landed on ${i}. Run: ilml linkedin login`)}return{browser:l,page:a}}await Wo();var gt=0,qr=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Pr=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),Or=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",Yt=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],pt=-1;async function Fr(){if(pt===-1){let e=await
|
|
59
|
-
--- Pass ${r}/${o}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(a){if(De(a))await ht(e,`pass-${r} navigation: ${a.message?.slice(0,80)}`);else throw a}await g(3e3)}let n=k.submitted,s=!0,l=!0;for(;s&&l;){if(!await on(e.page)){await ht(e,"liveness probe failed twice");continue}try{await Xt(e.page,t);let i=await as(e.page,wn,Jr);l=i.keepGoing;let c=i.jobsDone;if(console.log("keepGoing",l),console.log("pageDone"),console.log(c.length),!l)break;s=await Gr(e.page),e._pageRecoveryStreak=0}catch(i){if(!De(i))throw i;await ht(e,`mid-iteration: ${i.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!l)break;if(k.submitted===n){console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${k.submitted-n} new jobs in pass ${r}.`)}}async function cn(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return Io(e,t,o,r)}async function un(e,t){let o=t?.match(/\d+/)?.[0]||t,r=await e.$(`div[data-job-id="${o}"] button[aria-label^="Dismiss"]`);r?(await r.click(),console.log(` Dismissed job ${o} from list`)):console.log(` Dismiss button not found for ${o}`)}async function Yr(e,t){try{let o=await jo(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},Pe("recruiters-from-jobs",o)?(gt++,console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F3AF} RECRUITER FOUND \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Name: ${o.name?.substring(0,30).padEnd(30)} \u2502`),console.log(`\u2502 Source: ${o.source.padEnd(28)} \u2502`),console.log(`\u2502 Company: ${t.companyName?.substring(0,27).padEnd(27)} \u2502`),console.log(`\u2502 Total today: ${String(gt).padEnd(23)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")):console.log(` \u2139 Recruiter already saved: ${o.name}`),ue(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){nt(o.profileUrl,n),je(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let s=o.fromJob?.companyUrl;s&&Pt(s,{recruiterUrl:o.profileUrl,jobId:n})}return o}else console.log(" \u26AA No recruiter found on this job page");return null}catch(o){return console.error("Error extracting recruiter:",o.message),null}}async function yt(e){return await e.evaluate(()=>{let t=document.body.innerText||"",o=document.querySelector("#interop-outlet")?.shadowRoot?.textContent||"",r=t+" "+o;return r.includes("We limit daily submissions")||r.includes("We limit Easy Apply submissions")||r.includes("Easy Apply limit")||r.includes("reached today")||r.includes("apply tomorrow")})}async function bn(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let n of o){let s=n.querySelectorAll("button");for(let l of s){let a=l.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return l.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return t&&console.log(" Daily limit popup closed"),t}catch{return!1}}async function dn(e){await e.evaluate(()=>{let l=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of l)for(let i of a.querySelectorAll("button")){let c=i.innerText?.trim();if(c==="Continue applying"||c==="Got it"||c==="Dismiss"){i.click();return}}});let t=Date.now(),o=3e3,r=null;for(;!r&&Date.now()-t<o;){if(r=await e.$(".jobs-apply-button"),r||(r=await e.$('button[aria-label*="Easy Apply"]')),r||(r=await e.$('a[aria-label*="Easy Apply"]')),r||(r=await e.$('a[href*="/apply/"]')),!r){let l=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let i of a){let c=i.innerText?.trim();if(c==="Easy Apply"||c==="Apply")return i}return null});r=l?.asElement?.()||null,r||await l.dispose().catch(()=>{})}r||await new Promise(l=>setTimeout(l,300))}let n=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${n>400?` (waited ${n}ms)`:""}`),r){if(await e.evaluate(c=>c.disabled,r))return await yt(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(c=>c.tagName==="A",r)){await e.evaluate(c=>c.click(),r),await g(3e3);try{await e.waitForFunction(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[data-easy-apply-next-button], button[aria-label="Submit application"]'),{timeout:1e4})}catch{await g(2e3)}}else await r.click(),await g(1500);return await yt(e)?(await bn(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await yt(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function Qr(e){return await e.evaluate(async()=>{function t(){let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length>0)return i;let c=document.querySelector("#interop-outlet")?.shadowRoot;return c&&(i=c.querySelectorAll(".artdeco-inline-feedback__message")),i}let o=3e3,r=t();if(r?.length===0&&(await new Promise(i=>setTimeout(i,o)),r=t()),r?.length===0)return null;let n=r[0];console.log("errorMsg"),console.log(n);let s=n?.textContent.trim(),l=n.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=n.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(l),a||l){console.log("parentElement"),console.log(a);let i=a.querySelector(".artdeco-text-input--label")||a.querySelector("legend .fb-dash-form-element__label-title--is-required")||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||a.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),c=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),u=a.querySelectorAll('input[type="radio"]'),d=a.querySelector("select[data-test-text-entity-list-form-select]"),f=n.parentElement.parentElement.querySelector('input[type="file"]'),p=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(f),i&&c)return{type:"input",labelText:i.textContent.trim(),errorMsgText:s};if(i&&u.length){let h=i?i.querySelector("span:nth-of-type(1)")?.textContent.trim():null,m=Array.from(u).map(y=>{let C=(document.querySelector(`label[for="${y.id}"]`)||y.nextElementSibling)?.textContent?.trim();return{value:y.value,label:C||y.value}}),b=m.map(y=>y.label);return{type:"radio",labelText:h,errorMsgText:s,options:b,optionsData:m}}else if(d){let h=a.querySelector('label[for="'+d.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),m=h?h.querySelector("span:nth-of-type(2)")?.textContent.trim():null,b=Array.from(d.options).map(y=>y.value).filter(y=>y!=="Select an option");return{type:"select",labelText:m,errorMsgText:s,options:b}}else if(f){let h=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:s,labelText:h}}else{if(p)return{type:"datePicker",errorMsgText:s};{let h=i?i.querySelector("span:nth-of-type(2)")?.textContent.trim():null,m=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(m.length>0){let b=Array.from(m).map(y=>y.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:h,errorMsgText:s,options:b}}else return null}}}return null})}async function zr(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));i.value=n;let c=new Event("input",{bubbles:!0});if(i.dispatchEvent(c),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let u=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(h)},d=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(h)};await(async p=>{await new Promise(h=>setTimeout(h,500)),d(p),await new Promise(h=>setTimeout(h,100)),u(p)})(i)}}return null},t,o)}async function Kr(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('input[type="radio"]'),c=n;if(r.optionsData){let u=r.optionsData.find(d=>d.label.toLowerCase()===n.toLowerCase());u&&(c=u.value,console.log(`Radio: matched label "${n}" to value "${c}"`))}for(let u of i){let f=(document.querySelector(`label[for="${u.id}"]`)||u.nextElementSibling)?.textContent?.trim()||"";if(u.value.toLowerCase()===c.toLowerCase()||f.toLowerCase()===n.toLowerCase()){u.checked=!0;let p=new Event("change",{bubbles:!0});u.dispatchEvent(p),console.log(`Radio selected: value="${u.value}", label="${f}"`);break}}}return null},t,o)}async function Xr(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelector("select[data-test-text-entity-list-form-select]");if(!i)return null;let c=Array.from(i.options),u=c.find(f=>f.text.toLowerCase()===n.toLowerCase())||c.find(f=>f.text.toLowerCase().includes(n.toLowerCase()));u?i.value=u.value:i.value=n;let d=new Event("change",{bubbles:!0});i.dispatchEvent(d)}return null},t,o)}async function Zr(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');i.length>0&&i.forEach(c=>{if(c.nextElementSibling.textContent.trim()===n.trim()){c.checked=!0;let u=new Event("change",{bubbles:!0});c.dispatchEvent(u)}})}return null},t,o)}async function es(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s?.length===0)return null;let l=s[0],a=l.closest(".fb-dash-form-element"),i=l.parentElement.parentElement.querySelector('input[type="file"]');if(a&&i){async function c(u,d,f){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let h=new Blob([new Uint8Array(d)]),m=new File([h],f,{type:"application/pdf"}),b=new DataTransfer;b.items.add(m),u.files=b.files;let y=new Event("change",{bubbles:!0});u.dispatchEvent(y)}await c(i,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function fn(e){let t=await Qr(e);if(t===null)return null;if(t?.type==="input"){let n=await wt(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await zr(e,t,n)}else if(t?.type==="radio"){let n=await Ye(t.labelText,t.options);n=n?.trim()||n;let s=t.options||[];!s.find(a=>a.toLowerCase()===n?.toLowerCase())&&s.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${n}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),n=await Ye(t.labelText,t.options),n=n?.trim()||n,s.find(i=>i.toLowerCase()===n?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${s[0]}"`),n=s[0])),t.answer=n,await Kr(e,t,n)}else if(t?.type==="select"){let n=await Ne(t.labelText,t.options);n=n?.trim()||n;let s=t.options||[],l=s.find(a=>a.toLowerCase()===n?.toLowerCase());if(l)n=l;else if(s.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${n}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),n=await Ne(t.labelText,t.options),n=n?.trim()||n;let a=s.find(i=>i.toLowerCase()===n?.toLowerCase());a?n=a:(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${s[0]}"`),n=s[0])}t.answer=n,await Xr(e,t,n)}else if(t?.type==="checkbox"){let n=await Ne(t.labelText,t.options);t.answer=n,await Zr(e,t,n)}else if(t?.type==="file"){let n=process.env.RESUME_PDF_URL;t.answer=n;let s=await fetch(n);if(!s.ok)throw new Error("Network response was not ok");let l=await s.arrayBuffer();await es(e,t,l)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let o=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${o}" \u2192 ${r}`),t}async function ts(e){return await e.evaluate(async()=>{let t=[],o=document.querySelectorAll(".fb-dash-form-element");if(!o||o.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(o=r.querySelectorAll(".fb-dash-form-element"))}if(!o||o.length===0)return[];for(let r of o){let n=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),s=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),l=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),i=r.querySelector("select[data-test-text-entity-list-form-select]"),c=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),u=r.querySelector('input[type="file"]');if(n&&l&&a.length===0){let d=n.textContent.trim();t.push({type:"input",labelText:d,answer:l.value,isRequired:s,wasPreFilled:!!l.value})}else if(n&&a.length){let d=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,f=Array.from(a).map(h=>h.value),p=(Array.from(a).find(h=>h.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:d,options:f,answer:p,isRequired:s,wasPreFilled:!!p})}else if(i){let d=r.querySelector('label[for="'+i.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),f=d?.querySelector("span:nth-of-type(2)")?.textContent.trim()||d?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||d?.querySelector("span")?.textContent.trim()||d?.textContent?.trim()||null,p=Array.from(i.options).map(m=>m.value).filter(m=>m!=="Select an option"),h=i.value!=="Select an option"?i.value:"";t.push({type:"select",labelText:f,options:p,answer:h,isRequired:s,wasPreFilled:!!h})}else if(c.length>0){let d=r.querySelector("legend span")?.textContent?.trim(),f=Array.from(c).map(m=>({label:m.nextElementSibling?.textContent?.trim()||m.value,checked:m.checked})),p=f.some(m=>m.checked),h=f.filter(m=>m.checked).map(m=>m.label).join(", ");t.push({type:"checkbox",labelText:d,options:f.map(m=>m.label),answer:h,isRequired:s,wasPreFilled:p})}else if(u){let d=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:d,answer:u.value?"uploaded":"",isRequired:s,wasPreFilled:!!u.value})}}return t})}async function Zt(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelector(".artdeco-text-input--label")||l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||l.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=l.querySelector(".artdeco-text-input--input")||l.querySelector("input");if(a&&i&&r===a.textContent.trim()){i.value=n;let c=new Event("input",{bubbles:!0});if(i.dispatchEvent(c),r==="City"||r==="Location (city)"){let u=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(h)},d=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(h)};await(async p=>{await new Promise(h=>setTimeout(h,500)),d(p),await new Promise(h=>setTimeout(h,100)),u(p)})(i)}return!0}}return!1},t,o)}async function os(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelectorAll('input[type="radio"]');if(a.length===0)continue;let i=l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('legend [class*="fb-dash-form-element__label"]')||l.querySelector("legend span");if((i?.querySelector("span:nth-of-type(1)")?.textContent.trim()||i?.textContent?.trim())!==r)continue;let u=(n||"").toLowerCase();for(let d of a){let f=d.getRootNode(),h=(d.id&&f.querySelector(`label[for="${d.id}"]`)||d.nextElementSibling)?.textContent?.trim()||"";if(d.value.toLowerCase()===u||h.toLowerCase()===u)return d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function ns(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelector("select[data-test-text-entity-list-form-select]");if(!a)continue;let i=l.querySelector(`label[for="${a.id}"]`)||l.querySelector(".fb-dash-form-element__label-title--is-required");if((i?.querySelector("span:nth-of-type(2)")?.textContent.trim()||i?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||i?.querySelector("span")?.textContent.trim()||i?.textContent?.trim())!==r)continue;let u=Array.from(a.options),d=(n||"").toLowerCase(),f=u.find(p=>p.text.toLowerCase()===d)||u.find(p=>p.value.toLowerCase()===d)||u.find(p=>p.text.toLowerCase().includes(d));return f?(a.value=f.value,a.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function rs(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let a=document.querySelector("#interop-outlet")?.shadowRoot;a&&(s=a.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;let l=(n||"").split(",").map(a=>a.trim().toLowerCase()).filter(Boolean);if(l.length===0)return!1;for(let a of s){let i=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(i.length===0||a.querySelector("legend span")?.textContent?.trim()!==r)continue;let u=!1;for(let d of i){let f=(d.nextElementSibling?.textContent||d.value||"").trim().toLowerCase();l.includes(f)&&!d.checked&&(d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),u=!0)}return u}return!1},t,o)}async function ss(e,t){for(let o of t){if(!o.labelText||o.isRequired||o.wasPreFilled||o.answer||o.type==="datePicker"||o.type==="file")continue;let r="";try{if(o.type==="input")r=await wt(o.labelText,"");else if(o.type==="radio")r=await Ye(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await Ne(o.labelText,o.options||[]);else continue}catch(l){console.log(` \u26A0 Lifebot failed for optional "${o.labelText}": ${l.message?.slice(0,80)}`);continue}if(r=(r||"").trim(),o.wasOptional=!0,!r){o.answer="",console.log(` ? [opt ${o.type}] "${o.labelText.slice(0,55)}" \u2192 (empty)`);continue}let n=!1;try{o.type==="input"?n=await Zt(e,o.labelText,r):o.type==="radio"?n=await os(e,o.labelText,r):o.type==="select"?n=await ns(e,o.labelText,r):o.type==="checkbox"&&(n=await rs(e,o.labelText,r))}catch(l){console.log(` \u26A0 setter failed for "${o.labelText}": ${l.message?.slice(0,80)}`)}o.answer=r,console.log(` ? [${n?"opt":"opt-noapply"} ${o.type}] "${o.labelText.slice(0,55)}" \u2192 "${r.slice(0,50)}"`)}}async function pn(e,t){let o=[],r=!0,n=0,s=null,l=0;for(;r;){if(n++,await yt(e))return console.log(" Daily limit reached during form navigation"),await bn(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let c=(await ts(e)).filter(p=>!o.some(h=>h.labelText===p.labelText));o.push(...c);try{let p=o.find(m=>m.labelText==="City"||m.labelText==="Location (city)"),h=o.filter(m=>m.labelText!=null).find(m=>m.labelText!==null&&m.labelText.trim()!==null&&(m.labelText.trim().toLowerCase()==="cv"||m.labelText.trim().toLowerCase()==="curriculum vitae"||m.labelText.trim().toLowerCase()==="cover letter"||m.labelText.trim().toLowerCase()==="cover"));if(p&&!p.answer){let m=process.env.City;await Zt(e,p.labelText,m),p.answer=m}else if(h){let m=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!h.answer||h.answer!==m)&&(await g(1e4),await Zt(e,h.labelText,m),h.answer=m,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await ss(e,c)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let u=null;try{u=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(u!==null){if(u.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:u};let p=u&&o.find(m=>m.errorMsgText&&m.labelText===u.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(u,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:u};let h=o.findIndex(m=>m.labelText===u.labelText&&!m.answer);h!==-1&&o.splice(h,1),o.push(u)}let d=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of p){let m=h.querySelectorAll("button");for(let b of m){let y=b.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return b.click(),y}}return null});d&&console.log(` Dismissed safety popup (${d})`);let f=await e.evaluate(async()=>{function p(w){let A=document.querySelector(w);if(A)return A;let U=document.querySelector("#interop-outlet")?.shadowRoot;return U?U.querySelector(w):null}function h(w){let A=document.querySelectorAll(w),U=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(w);return[...A||[],...U||[]]}let m=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||h("footer button, button.artdeco-button--primary").find(w=>w.innerText?.trim()==="Next"),b=h('footer[role="presentation"] button').some(w=>w.innerText.trim()==="Review")||h("button").some(w=>w.innerText.trim()==="Review"&&w.getAttribute("aria-label")?.includes("Review")),y=p('button[aria-label="Submit application"]'),S=async()=>{let w=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||h("footer button, button.artdeco-button--primary").find(A=>A.innerText?.trim()==="Next");w?w.click():console.log("Next button not found")},C=()=>{let w=h("button").find(A=>A.innerText?.trim()==="Review");w&&w.click()};return m?(await S(),{type:"next"}):b?(await C(),{type:"review"}):y?{type:"submit"}:{type:null}});if(f==null)return{filledFields:o,formPages:n,skip:!0};if(f.type&&console.log(` \u2192 ${f.type}`),f.type===null){let p=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of h){let b=m.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of b){let S=y.innerText||"";if(S.includes("application was sent")||S.includes("resume into a profile")||S.includes("Application submitted")||S.includes("Next best action"))for(let C of y.querySelectorAll("button")){let w=C.innerText?.trim();if(w==="Not now"||w==="Done"||w==="Dismiss"||w==="Got it")return C.click(),w}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await g(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(l===0){let h=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),b=[],y=[];for(let S of m){for(let w of S.querySelectorAll("button")){let A=w.innerText?.trim();A&&A.length<60&&b.push(A)}let C=S.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');C&&y.push(C.innerText?.slice(0,200))}return{buttons:b.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(h.buttons)}`),h.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(h.modalText)}`)}}if(f.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(u===null&&f.type===s?l++:l=0,s=f.type,l>=5){let p=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),m=[],b=[];for(let y of h){for(let S of y.querySelectorAll(".artdeco-inline-feedback__message"))m.push(S.textContent?.trim()?.slice(0,60));for(let S of y.querySelectorAll(".fb-dash-form-element")){let C=S.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),w=S.querySelector("input, select, textarea"),A=!!S.querySelector(".artdeco-inline-feedback__message");C&&(A||w&&!w.value)&&b.push({label:C.slice(0,40),hasError:A,value:w?.value?.slice(0,20)||""})}}return{errors:m,emptyRequired:b.slice(0,5)}});return console.error(` \u26A0 Stuck on "${f.type}" for ${l} iterations \u2014 form not progressing.`),p.errors.length&&console.error(` Visible errors: ${JSON.stringify(p.errors)}`),p.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(p.emptyRequired)}`),console.error(" Skipping job."),{filledFields:o,formPages:n,skip:!0,duplicateField:{labelText:`stuck_on_${f.type}`}}}await g(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function mn(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 is(e){let t=await e.$('button[aria-label="Submit application"]');if(!t){let o=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Submit application"]')||null);t=o?.asElement?.()||null,t||await o.dispose().catch(()=>{})}t&&await t.click()}async function ls(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of o){for(let s of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(s.innerText?.trim()==="Done")return s.click(),"Done";let n=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let s of n){let l=s.innerText||"";if(l.includes("application was sent")||l.includes("Application sent")||l.includes("resume into a profile")||l.includes("Next best action"))for(let a of s.querySelectorAll("button")){let i=a.innerText?.trim();if(i==="Not now"||i==="Dismiss")return a.click(),i}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await g(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function mt(e){try{await e.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let t=await e.$('button[aria-label="Dismiss"]');t?(await t.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await g(1e3)):console.log("Popup \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.")}catch{console.log("closeJobApplicationPopup failed to execute: \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D \u0438\u043B\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F.")}}async function Kt(e){try{await e.waitForSelector('button[data-control-name="discard_application_confirm_btn"]',{timeout:3e3});let t=await e.$('button[data-control-name="discard_application_confirm_btn"]');t&&(await t.click(),console.log("Discard confirmed"),await g(500))}catch{console.log("No discard confirmation needed")}}async function wn(e,t){let o=[],r=t._fromQueue;try{k.attempted++,console.log(`
|
|
60
|
-
--- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&Fo(n)?.status==="applied")return
|
|
58
|
+
`)}`;try{await he.addMessage(l,i)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var Tr=_r(import.meta.url),Ir=pe.dirname(pe.dirname(Tr)),Gt=process.env.DATA_DIR?pe.resolve(process.env.DATA_DIR,"collected-profiles"):pe.join(Ir,"collected-profiles"),Vt=pe.join(Gt,"run-log.json");function jr(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ne.writeFileSync(r,o);for(let n=0;n<3;n++)try{ne.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function zo(){try{if(!ne.existsSync(Vt))return{runs:[]};let e=JSON.parse(ne.readFileSync(Vt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ko(e){ne.existsSync(Gt)||ne.mkdirSync(Gt,{recursive:!0});try{jr(Vt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Xo(e,t="default"){let o=zo();for(let l of o.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let r=new Date,n={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let s=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(l=>new Date(l.timestamp).getTime()>s),Ko(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Zo(e,t,o=null,r=null){if(!e)return;let n=null;try{let l=zo(),a=l.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=o,a.error=r,n=a.duration;else{let i=l.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());i&&(i.status=t,i.result=t,i.duration=Date.now()-e.startTime,i.stats=o,i.error=r,n=i.duration)}Ko(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let s=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Qo({scriptName:e.script,mode:e.mode,status:l,summaryLines:s,error:r,duration:n??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import en from"fs";import Rr from"path";var Lr="cookies.json";function Dr(){let e=process.env.ILML_SCOPE_DIR;return e?Rr.join(e,"plugins-state","linkedin","cookies.json"):Lr}function Wt(){let e=Dr();if(!en.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=en.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}async function ft(e,t,o="op"){let r,n=new Promise((s,l)=>{r=setTimeout(()=>l(new Error(`${o} timeout after ${t}ms`)),t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}function De(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let o=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(o)||/Target closed/i.test(o)||/Session closed/i.test(o)||/Connection closed/i.test(o)||/Most likely the page has been closed/i.test(o)||/Navigating frame was detached/i.test(o)||/Protocol error.*timed out/i.test(o)}async function tn(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await ft(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function on(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await tn(e,t)?!0:(await g(o),await tn(e,t))}async function nn(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await ft(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function rn(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:s=null}={}){try{await ft(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let l=await e.newPage();if(s)try{await s(l)}catch{}if(n)try{let a=n();Array.isArray(a)&&a.length>0&&await l.setCookie(...a)}catch{}if(o){await l.goto(o,{waitUntil:"domcontentloaded",timeout:r});let a=l.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(a))throw new Error(`Session expired after recovery \u2014 landed on ${a}. Run: ilml linkedin login`)}return l}async function sn(e,{launchFn:t,returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:s=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");try{await ft(e.close(),5e3,"oldBrowser.close")}catch{}let l=await t(),a=await l.newPage();if(s)try{await s(a)}catch{}if(n)try{let i=n();Array.isArray(i)&&i.length>0&&await a.setCookie(...i)}catch{}if(o){await a.goto(o,{waitUntil:"domcontentloaded",timeout:r});let i=a.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(i))throw new Error(`Session expired after browser restart \u2014 landed on ${i}. Run: ilml linkedin login`)}return{browser:l,page:a}}await Wo();var gt=0,qr=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Pr=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),Or=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",Yt=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],pt=-1;async function Fr(){if(pt===-1){let e=await xe("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}"`);pt=to(e)+1,console.log(`lastIndex initialized as: ${pt}`)}return pt++}var yn=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${yn}`);var Mr=[{label:"linkedin-session-expired",match:e=>/redirected to login|cookies expired|Session expired after recovery/i.test(e.message),severity:"fatal",instructions:"Run: ilml linkedin login"},{label:"ilml-auth-expired",match:e=>{let t=e.message||"";return/Token is invalid or expired/i.test(t)||/\b401\b/.test(t)||/Unauthorized/i.test(t)||/authentication.*(failed|required)/i.test(t)},severity:"fatal",instructions:"Run: ilml login (this is the iLiveMyLife platform login, not the LinkedIn one)"},{label:"lifebot-timeout",match:e=>e.constructor.name==="LifebotTimeoutError",severity:"transient",maxConsecutive:3,cleanup:"popup"},{label:"stale-context",match:e=>/Execution context was destroyed|Cannot find context/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3}],Ve={};function gn(e){return Mr.find(t=>t.match(e))||null}function Ur(e){return Ve[e]=(Ve[e]||0)+1,Ve[e]}function an(){for(let e of Object.keys(Ve))Ve[e]=0}var Qt=0;function Br(){return Qt++,Qt>=yn?(console.log(`Max run counter reached with ${Qt}`),!1):!0}async function Jr(e){let t=await Eo(e)}async function Hr(e){return _o(e,{easyApplyOnly:!0})}async function Gr(e){return To(e)}async function Xt(e,t){return Lt(e,t)}var zt=3,Vr=2;async function ht(e,t){let{searchUrl:o,launchFn:r,setupPage:n,cookiesProvider:s}=e.recoveryCtx,l=await nn(e.browser);if(!l||e._pageRecoveryStreak>=zt){if(S.browserRestarts>=Vr)throw new Error(`CDP unrecoverable: ${S.browserRestarts} browser restart${S.browserRestarts===1?"":"s"} and ${S.cdpRecoveries} page recover${S.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let i=l?`${zt} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${i}). Reason: ${t}`);let c=await sn(e.browser,{launchFn:r,setupPage:n,cookiesProvider:s,returnUrl:o});e.browser=c.browser,e.page=c.page,e._pageRecoveryStreak=0,S.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${S.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${zt}). Reason: ${t}`),e.page=await rn(e.browser,e.page,{returnUrl:o,cookiesProvider:s,setupPage:n}),e._pageRecoveryStreak+=1,S.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${S.cdpRecoveries}).`)}async function Wr(e){let{searchUrl:t}=e.recoveryCtx,o=3;e._pageRecoveryStreak=e._pageRecoveryStreak||0;for(let r=1;r<=o;r++){if(r>1){console.log(`
|
|
59
|
+
--- Pass ${r}/${o}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(u){if(De(u))await ht(e,`pass-${r} navigation: ${u.message?.slice(0,80)}`);else throw u}await g(3e3)}let n=S.submitted,s=S.cdpRecoveries+S.browserRestarts,l=!0,a=!0;for(;l&&a;){if(!await on(e.page)){await ht(e,"liveness probe failed twice");continue}try{await Xt(e.page,t);let d=await as(e.page,wn,Jr);a=d.keepGoing;let f=d.jobsDone;if(console.log("keepGoing",a),console.log("pageDone"),console.log(f.length),!a)break;l=await Gr(e.page),e._pageRecoveryStreak=0}catch(d){if(!De(d))throw d;await ht(e,`mid-iteration: ${d.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!a)break;let i=S.submitted-n,c=S.cdpRecoveries+S.browserRestarts-s;if(i===0){if(c>0&&r<o){console.log(`No new jobs applied in pass ${r}, but ${c} CDP recover${c===1?"y":"ies"} \u2014 pass ${r+1} will retry.`);continue}console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${i} new jobs in pass ${r}.`)}}async function cn(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return Io(e,t,o,r)}async function un(e,t){let o=t?.match(/\d+/)?.[0]||t,r=await e.$(`div[data-job-id="${o}"] button[aria-label^="Dismiss"]`);r?(await r.click(),console.log(` Dismissed job ${o} from list`)):console.log(` Dismiss button not found for ${o}`)}async function Yr(e,t){try{let o=await jo(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},Pe("recruiters-from-jobs",o)?(gt++,console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F3AF} RECRUITER FOUND \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Name: ${o.name?.substring(0,30).padEnd(30)} \u2502`),console.log(`\u2502 Source: ${o.source.padEnd(28)} \u2502`),console.log(`\u2502 Company: ${t.companyName?.substring(0,27).padEnd(27)} \u2502`),console.log(`\u2502 Total today: ${String(gt).padEnd(23)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")):console.log(` \u2139 Recruiter already saved: ${o.name}`),ue(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){nt(o.profileUrl,n),je(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let s=o.fromJob?.companyUrl;s&&Pt(s,{recruiterUrl:o.profileUrl,jobId:n})}return o}else console.log(" \u26AA No recruiter found on this job page");return null}catch(o){return console.error("Error extracting recruiter:",o.message),null}}async function yt(e){return await e.evaluate(()=>{let t=document.body.innerText||"",o=document.querySelector("#interop-outlet")?.shadowRoot?.textContent||"",r=t+" "+o;return r.includes("We limit daily submissions")||r.includes("We limit Easy Apply submissions")||r.includes("Easy Apply limit")||r.includes("reached today")||r.includes("apply tomorrow")})}async function bn(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let n of o){let s=n.querySelectorAll("button");for(let l of s){let a=l.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return l.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return t&&console.log(" Daily limit popup closed"),t}catch{return!1}}async function dn(e){await e.evaluate(()=>{let l=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of l)for(let i of a.querySelectorAll("button")){let c=i.innerText?.trim();if(c==="Continue applying"||c==="Got it"||c==="Dismiss"){i.click();return}}});let t=Date.now(),o=3e3,r=null;for(;!r&&Date.now()-t<o;){if(r=await e.$(".jobs-apply-button"),r||(r=await e.$('button[aria-label*="Easy Apply"]')),r||(r=await e.$('a[aria-label*="Easy Apply"]')),r||(r=await e.$('a[href*="/apply/"]')),!r){let l=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let i of a){let c=i.innerText?.trim();if(c==="Easy Apply"||c==="Apply")return i}return null});r=l?.asElement?.()||null,r||await l.dispose().catch(()=>{})}r||await new Promise(l=>setTimeout(l,300))}let n=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${n>400?` (waited ${n}ms)`:""}`),r){if(await e.evaluate(c=>c.disabled,r))return await yt(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(c=>c.tagName==="A",r)){await e.evaluate(c=>c.click(),r),await g(3e3);try{await e.waitForFunction(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[data-easy-apply-next-button], button[aria-label="Submit application"]'),{timeout:1e4})}catch{await g(2e3)}}else await r.click(),await g(1500);return await yt(e)?(await bn(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await yt(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function Qr(e){return await e.evaluate(async()=>{function t(){let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length>0)return i;let c=document.querySelector("#interop-outlet")?.shadowRoot;return c&&(i=c.querySelectorAll(".artdeco-inline-feedback__message")),i}let o=3e3,r=t();if(r?.length===0&&(await new Promise(i=>setTimeout(i,o)),r=t()),r?.length===0)return null;let n=r[0];console.log("errorMsg"),console.log(n);let s=n?.textContent.trim(),l=n.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=n.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(l),a||l){console.log("parentElement"),console.log(a);let i=a.querySelector(".artdeco-text-input--label")||a.querySelector("legend .fb-dash-form-element__label-title--is-required")||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||a.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),c=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),u=a.querySelectorAll('input[type="radio"]'),d=a.querySelector("select[data-test-text-entity-list-form-select]"),f=n.parentElement.parentElement.querySelector('input[type="file"]'),p=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(f),i&&c)return{type:"input",labelText:i.textContent.trim(),errorMsgText:s};if(i&&u.length){let h=i?i.querySelector("span:nth-of-type(1)")?.textContent.trim():null,m=Array.from(u).map(y=>{let C=(document.querySelector(`label[for="${y.id}"]`)||y.nextElementSibling)?.textContent?.trim();return{value:y.value,label:C||y.value}}),b=m.map(y=>y.label);return{type:"radio",labelText:h,errorMsgText:s,options:b,optionsData:m}}else if(d){let h=a.querySelector('label[for="'+d.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),m=h?h.querySelector("span:nth-of-type(2)")?.textContent.trim():null,b=Array.from(d.options).map(y=>y.value).filter(y=>y!=="Select an option");return{type:"select",labelText:m,errorMsgText:s,options:b}}else if(f){let h=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:s,labelText:h}}else{if(p)return{type:"datePicker",errorMsgText:s};{let h=i?i.querySelector("span:nth-of-type(2)")?.textContent.trim():null,m=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(m.length>0){let b=Array.from(m).map(y=>y.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:h,errorMsgText:s,options:b}}else return null}}}return null})}async function zr(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));i.value=n;let c=new Event("input",{bubbles:!0});if(i.dispatchEvent(c),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let u=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(h)},d=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(h)};await(async p=>{await new Promise(h=>setTimeout(h,500)),d(p),await new Promise(h=>setTimeout(h,100)),u(p)})(i)}}return null},t,o)}async function Kr(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('input[type="radio"]'),c=n;if(r.optionsData){let u=r.optionsData.find(d=>d.label.toLowerCase()===n.toLowerCase());u&&(c=u.value,console.log(`Radio: matched label "${n}" to value "${c}"`))}for(let u of i){let f=(document.querySelector(`label[for="${u.id}"]`)||u.nextElementSibling)?.textContent?.trim()||"";if(u.value.toLowerCase()===c.toLowerCase()||f.toLowerCase()===n.toLowerCase()){u.checked=!0;let p=new Event("change",{bubbles:!0});u.dispatchEvent(p),console.log(`Radio selected: value="${u.value}", label="${f}"`);break}}}return null},t,o)}async function Xr(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelector("select[data-test-text-entity-list-form-select]");if(!i)return null;let c=Array.from(i.options),u=c.find(f=>f.text.toLowerCase()===n.toLowerCase())||c.find(f=>f.text.toLowerCase().includes(n.toLowerCase()));u?i.value=u.value:i.value=n;let d=new Event("change",{bubbles:!0});i.dispatchEvent(d)}return null},t,o)}async function Zr(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');i.length>0&&i.forEach(c=>{if(c.nextElementSibling.textContent.trim()===n.trim()){c.checked=!0;let u=new Event("change",{bubbles:!0});c.dispatchEvent(u)}})}return null},t,o)}async function es(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s?.length===0)return null;let l=s[0],a=l.closest(".fb-dash-form-element"),i=l.parentElement.parentElement.querySelector('input[type="file"]');if(a&&i){async function c(u,d,f){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let h=new Blob([new Uint8Array(d)]),m=new File([h],f,{type:"application/pdf"}),b=new DataTransfer;b.items.add(m),u.files=b.files;let y=new Event("change",{bubbles:!0});u.dispatchEvent(y)}await c(i,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function fn(e){let t=await Qr(e);if(t===null)return null;if(t?.type==="input"){let n=await wt(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await zr(e,t,n)}else if(t?.type==="radio"){let n=await Ye(t.labelText,t.options);n=n?.trim()||n;let s=t.options||[];!s.find(a=>a.toLowerCase()===n?.toLowerCase())&&s.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${n}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),n=await Ye(t.labelText,t.options),n=n?.trim()||n,s.find(i=>i.toLowerCase()===n?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${s[0]}"`),n=s[0])),t.answer=n,await Kr(e,t,n)}else if(t?.type==="select"){let n=await Ne(t.labelText,t.options);n=n?.trim()||n;let s=t.options||[],l=s.find(a=>a.toLowerCase()===n?.toLowerCase());if(l)n=l;else if(s.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${n}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),n=await Ne(t.labelText,t.options),n=n?.trim()||n;let a=s.find(i=>i.toLowerCase()===n?.toLowerCase());a?n=a:(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${s[0]}"`),n=s[0])}t.answer=n,await Xr(e,t,n)}else if(t?.type==="checkbox"){let n=await Ne(t.labelText,t.options);t.answer=n,await Zr(e,t,n)}else if(t?.type==="file"){let n=process.env.RESUME_PDF_URL;t.answer=n;let s=await fetch(n);if(!s.ok)throw new Error("Network response was not ok");let l=await s.arrayBuffer();await es(e,t,l)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let o=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${o}" \u2192 ${r}`),t}async function ts(e){return await e.evaluate(async()=>{let t=[],o=document.querySelectorAll(".fb-dash-form-element");if(!o||o.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(o=r.querySelectorAll(".fb-dash-form-element"))}if(!o||o.length===0)return[];for(let r of o){let n=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),s=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),l=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),i=r.querySelector("select[data-test-text-entity-list-form-select]"),c=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),u=r.querySelector('input[type="file"]');if(n&&l&&a.length===0){let d=n.textContent.trim();t.push({type:"input",labelText:d,answer:l.value,isRequired:s,wasPreFilled:!!l.value})}else if(n&&a.length){let d=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,f=Array.from(a).map(h=>h.value),p=(Array.from(a).find(h=>h.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:d,options:f,answer:p,isRequired:s,wasPreFilled:!!p})}else if(i){let d=r.querySelector('label[for="'+i.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),f=d?.querySelector("span:nth-of-type(2)")?.textContent.trim()||d?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||d?.querySelector("span")?.textContent.trim()||d?.textContent?.trim()||null,p=Array.from(i.options).map(m=>m.value).filter(m=>m!=="Select an option"),h=i.value!=="Select an option"?i.value:"";t.push({type:"select",labelText:f,options:p,answer:h,isRequired:s,wasPreFilled:!!h})}else if(c.length>0){let d=r.querySelector("legend span")?.textContent?.trim(),f=Array.from(c).map(m=>({label:m.nextElementSibling?.textContent?.trim()||m.value,checked:m.checked})),p=f.some(m=>m.checked),h=f.filter(m=>m.checked).map(m=>m.label).join(", ");t.push({type:"checkbox",labelText:d,options:f.map(m=>m.label),answer:h,isRequired:s,wasPreFilled:p})}else if(u){let d=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:d,answer:u.value?"uploaded":"",isRequired:s,wasPreFilled:!!u.value})}}return t})}async function Zt(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelector(".artdeco-text-input--label")||l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||l.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=l.querySelector(".artdeco-text-input--input")||l.querySelector("input");if(a&&i&&r===a.textContent.trim()){i.value=n;let c=new Event("input",{bubbles:!0});if(i.dispatchEvent(c),r==="City"||r==="Location (city)"){let u=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(h)},d=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(h)};await(async p=>{await new Promise(h=>setTimeout(h,500)),d(p),await new Promise(h=>setTimeout(h,100)),u(p)})(i)}return!0}}return!1},t,o)}async function os(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelectorAll('input[type="radio"]');if(a.length===0)continue;let i=l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('legend [class*="fb-dash-form-element__label"]')||l.querySelector("legend span");if((i?.querySelector("span:nth-of-type(1)")?.textContent.trim()||i?.textContent?.trim())!==r)continue;let u=(n||"").toLowerCase();for(let d of a){let f=d.getRootNode(),h=(d.id&&f.querySelector(`label[for="${d.id}"]`)||d.nextElementSibling)?.textContent?.trim()||"";if(d.value.toLowerCase()===u||h.toLowerCase()===u)return d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function ns(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelector("select[data-test-text-entity-list-form-select]");if(!a)continue;let i=l.querySelector(`label[for="${a.id}"]`)||l.querySelector(".fb-dash-form-element__label-title--is-required");if((i?.querySelector("span:nth-of-type(2)")?.textContent.trim()||i?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||i?.querySelector("span")?.textContent.trim()||i?.textContent?.trim())!==r)continue;let u=Array.from(a.options),d=(n||"").toLowerCase(),f=u.find(p=>p.text.toLowerCase()===d)||u.find(p=>p.value.toLowerCase()===d)||u.find(p=>p.text.toLowerCase().includes(d));return f?(a.value=f.value,a.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function rs(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let a=document.querySelector("#interop-outlet")?.shadowRoot;a&&(s=a.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;let l=(n||"").split(",").map(a=>a.trim().toLowerCase()).filter(Boolean);if(l.length===0)return!1;for(let a of s){let i=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(i.length===0||a.querySelector("legend span")?.textContent?.trim()!==r)continue;let u=!1;for(let d of i){let f=(d.nextElementSibling?.textContent||d.value||"").trim().toLowerCase();l.includes(f)&&!d.checked&&(d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),u=!0)}return u}return!1},t,o)}async function ss(e,t){for(let o of t){if(!o.labelText||o.isRequired||o.wasPreFilled||o.answer||o.type==="datePicker"||o.type==="file")continue;let r="";try{if(o.type==="input")r=await wt(o.labelText,"");else if(o.type==="radio")r=await Ye(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await Ne(o.labelText,o.options||[]);else continue}catch(l){console.log(` \u26A0 Lifebot failed for optional "${o.labelText}": ${l.message?.slice(0,80)}`);continue}if(r=(r||"").trim(),o.wasOptional=!0,!r){o.answer="",console.log(` ? [opt ${o.type}] "${o.labelText.slice(0,55)}" \u2192 (empty)`);continue}let n=!1;try{o.type==="input"?n=await Zt(e,o.labelText,r):o.type==="radio"?n=await os(e,o.labelText,r):o.type==="select"?n=await ns(e,o.labelText,r):o.type==="checkbox"&&(n=await rs(e,o.labelText,r))}catch(l){console.log(` \u26A0 setter failed for "${o.labelText}": ${l.message?.slice(0,80)}`)}o.answer=r,console.log(` ? [${n?"opt":"opt-noapply"} ${o.type}] "${o.labelText.slice(0,55)}" \u2192 "${r.slice(0,50)}"`)}}async function pn(e,t){let o=[],r=!0,n=0,s=null,l=0;for(;r;){if(n++,await yt(e))return console.log(" Daily limit reached during form navigation"),await bn(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let c=(await ts(e)).filter(p=>!o.some(h=>h.labelText===p.labelText));o.push(...c);try{let p=o.find(m=>m.labelText==="City"||m.labelText==="Location (city)"),h=o.filter(m=>m.labelText!=null).find(m=>m.labelText!==null&&m.labelText.trim()!==null&&(m.labelText.trim().toLowerCase()==="cv"||m.labelText.trim().toLowerCase()==="curriculum vitae"||m.labelText.trim().toLowerCase()==="cover letter"||m.labelText.trim().toLowerCase()==="cover"));if(p&&!p.answer){let m=process.env.City;await Zt(e,p.labelText,m),p.answer=m}else if(h){let m=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!h.answer||h.answer!==m)&&(await g(1e4),await Zt(e,h.labelText,m),h.answer=m,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await ss(e,c)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let u=null;try{u=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(u!==null){if(u.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:u};let p=u&&o.find(m=>m.errorMsgText&&m.labelText===u.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(u,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:u};let h=o.findIndex(m=>m.labelText===u.labelText&&!m.answer);h!==-1&&o.splice(h,1),o.push(u)}let d=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of p){let m=h.querySelectorAll("button");for(let b of m){let y=b.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return b.click(),y}}return null});d&&console.log(` Dismissed safety popup (${d})`);let f=await e.evaluate(async()=>{function p(w){let A=document.querySelector(w);if(A)return A;let U=document.querySelector("#interop-outlet")?.shadowRoot;return U?U.querySelector(w):null}function h(w){let A=document.querySelectorAll(w),U=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(w);return[...A||[],...U||[]]}let m=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||h("footer button, button.artdeco-button--primary").find(w=>w.innerText?.trim()==="Next"),b=h('footer[role="presentation"] button').some(w=>w.innerText.trim()==="Review")||h("button").some(w=>w.innerText.trim()==="Review"&&w.getAttribute("aria-label")?.includes("Review")),y=p('button[aria-label="Submit application"]'),k=async()=>{let w=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||h("footer button, button.artdeco-button--primary").find(A=>A.innerText?.trim()==="Next");w?w.click():console.log("Next button not found")},C=()=>{let w=h("button").find(A=>A.innerText?.trim()==="Review");w&&w.click()};return m?(await k(),{type:"next"}):b?(await C(),{type:"review"}):y?{type:"submit"}:{type:null}});if(f==null)return{filledFields:o,formPages:n,skip:!0};if(f.type&&console.log(` \u2192 ${f.type}`),f.type===null){let p=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of h){let b=m.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of b){let k=y.innerText||"";if(k.includes("application was sent")||k.includes("resume into a profile")||k.includes("Application submitted")||k.includes("Next best action"))for(let C of y.querySelectorAll("button")){let w=C.innerText?.trim();if(w==="Not now"||w==="Done"||w==="Dismiss"||w==="Got it")return C.click(),w}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await g(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(l===0){let h=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),b=[],y=[];for(let k of m){for(let w of k.querySelectorAll("button")){let A=w.innerText?.trim();A&&A.length<60&&b.push(A)}let C=k.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');C&&y.push(C.innerText?.slice(0,200))}return{buttons:b.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(h.buttons)}`),h.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(h.modalText)}`)}}if(f.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(u===null&&f.type===s?l++:l=0,s=f.type,l>=5){let p=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),m=[],b=[];for(let y of h){for(let k of y.querySelectorAll(".artdeco-inline-feedback__message"))m.push(k.textContent?.trim()?.slice(0,60));for(let k of y.querySelectorAll(".fb-dash-form-element")){let C=k.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),w=k.querySelector("input, select, textarea"),A=!!k.querySelector(".artdeco-inline-feedback__message");C&&(A||w&&!w.value)&&b.push({label:C.slice(0,40),hasError:A,value:w?.value?.slice(0,20)||""})}}return{errors:m,emptyRequired:b.slice(0,5)}});return console.error(` \u26A0 Stuck on "${f.type}" for ${l} iterations \u2014 form not progressing.`),p.errors.length&&console.error(` Visible errors: ${JSON.stringify(p.errors)}`),p.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(p.emptyRequired)}`),console.error(" Skipping job."),{filledFields:o,formPages:n,skip:!0,duplicateField:{labelText:`stuck_on_${f.type}`}}}await g(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function mn(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 is(e){let t=await e.$('button[aria-label="Submit application"]');if(!t){let o=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Submit application"]')||null);t=o?.asElement?.()||null,t||await o.dispose().catch(()=>{})}t&&await t.click()}async function ls(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of o){for(let s of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(s.innerText?.trim()==="Done")return s.click(),"Done";let n=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let s of n){let l=s.innerText||"";if(l.includes("application was sent")||l.includes("Application sent")||l.includes("resume into a profile")||l.includes("Next best action"))for(let a of s.querySelectorAll("button")){let i=a.innerText?.trim();if(i==="Not now"||i==="Dismiss")return a.click(),i}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await g(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function mt(e){try{await e.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let t=await e.$('button[aria-label="Dismiss"]');t?(await t.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await g(1e3)):console.log("Popup \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.")}catch{console.log("closeJobApplicationPopup failed to execute: \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D \u0438\u043B\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F.")}}async function Kt(e){try{await e.waitForSelector('button[data-control-name="discard_application_confirm_btn"]',{timeout:3e3});let t=await e.$('button[data-control-name="discard_application_confirm_btn"]');t&&(await t.click(),console.log("Discard confirmed"),await g(500))}catch{console.log("No discard confirmation needed")}}async function wn(e,t){let o=[],r=t._fromQueue;try{S.attempted++,console.log(`
|
|
60
|
+
--- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&Fo(n)?.status==="applied")return S.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (our DB): ${t.jobTitle} \u2014 skipping`),{keepGoing:!0};let s=null;if(!r){let f=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name")?.innerText?.trim()?.replace(/\s+/g," ")?.toLowerCase()||""),p=(t.companyName||"").replace(/\s+/g," ").toLowerCase().trim(),h=f.split(" ")[0],m=p.split(" ")[0];if(h&&m&&!f.includes(m)&&!p.includes(h))return S.mismatch++,console.log(` \u2298 MISMATCH: expected company "${t.companyName}" but panel shows "${f}"`),console.log(` job title: "${t.jobTitle}"`),{keepGoing:!0};if(await e.evaluate(()=>{let y=document.querySelector(".jobs-details__main-content, .job-details-jobs-unified-top-card");if(!y)return!1;let k=y.innerText;return/Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago/i.test(k)||k.includes("Application submitted")}))return S.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${t.jobTitle} \u2014 skipping`),n&&Le(n,"applied",{source:"detected"}),{keepGoing:!0};try{s=await Ro(e)}catch{}}let l=await dn(e);if(l.dailyLimitReached){console.log(`
|
|
61
61
|
========================================`),console.log("LinkedIn daily application limit reached!"),console.log(`========================================
|
|
62
|
-
`);let f=Ce("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${f.total}`),console.log(` - This session: ${gt}`),console.log(` - Unprocessed: ${f.unprocessed}`),
|
|
62
|
+
`);let f=Ce("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${f.total}`),console.log(` - This session: ${gt}`),console.log(` - Unprocessed: ${f.unprocessed}`),S.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:f}}if(!l.clicked)return S.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${t.jobTitle} @ ${t.companyName}`),{keepGoing:!0};await mn(e);let a=await Fr();console.log(`Applying for job: ${t.id}`);let i=`### Job Information
|
|
63
63
|
- **Counter:** ${a}
|
|
64
64
|
- **Job Title:** ${t.jobTitle}
|
|
65
65
|
- **Company:** ${t.companyName}
|
|
66
66
|
- **Location:** ${t.location}
|
|
67
67
|
- **Salary:** ${t.salary}
|
|
68
|
-
- **Job URL:** ${t.href}`,c=process.env.NODE_EASY_APPLY_MAIN;await he.addMessage(c,i,{lifebot:ln.off});let u=await
|
|
68
|
+
- **Job URL:** ${t.href}`,c=process.env.NODE_EASY_APPLY_MAIN;await he.addMessage(c,i,{lifebot:ln.off});let u=await xe("Should I apply for this job? Answer only 'yes' or 'no'!!");if(an(),console.log(`Should I apply for ${t.jobTitle} ?? `+u),u.toLowerCase()==="no"){S.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await mt(e),await Kt(e),await un(e,t.id);let f=t.id?.match(/\d+/)?.[0];return Re({jobId:f,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),Le(f,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let d=await pn(e,fn);if(d.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await dn(e)).clicked?d=await pn(e,fn):(console.log(" pressApplyButton failed on retry"),d={filledFields:[],formPages:0,skip:!0,duplicateField:{labelText:"stale_popup_retry_failed"}})),console.log(`processNavigation: pages=${d.formPages}, fields=${d.filledFields?.length||0}, skip=${d.skip}${d.dailyLimitReached?", DAILY LIMIT":""}`),d.dailyLimitReached)return console.log(" Daily limit reached \u2014 stopping"),await mt(e),{keepGoing:!1,dailyLimitReached:!0};if(d.skip){if(await mt(e),await Kt(e),d.duplicateField){await un(e,t.id);let f=process.env.NODE_EASY_APPLY_ERRORS;await he.addMessage(f,`${t.href} failed at label ${d.duplicateField?.labelText}`,{lifebot:ln.off})}S.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${d.duplicateField?.labelText||"form error"}`),Re({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"failed",formPages:d.formPages,failedField:d.duplicateField?.labelText||null,questions:d.filledFields||[]})}else{o=d.filledFields,o.length,await mn(e),await is(e),await g(2e3),await ls(e),S.submitted++,console.log(` \u2713 APPLIED: ${t.jobTitle} @ ${t.companyName} (${d.formPages} pages, ${o.length} fields)`);let f=t.id?.match(/\d+/)?.[0];if(f&&(ot(f,{title:t.jobTitle,company:t.companyName,location:t.location,salary:t.salary,url:t.href,applied:!0}),Po(f,{title:t.jobTitle,company:s?.companyName||t.companyName,companyUrl:s?.companyUrl,location:t.location,salary:t.salary,url:t.href,isEasyApply:!0,applyType:"easy-apply",applied:!0,appliedAt:new Date().toISOString().slice(0,10),description:s?.description,techStack:s?.techStack,jobTags:s?.jobTags,seniority:s?.seniority,employmentType:s?.employmentType,industries:s?.industries,jobFunction:s?.jobFunction,postedTime:s?.postedTime,applicantCount:s?.applicantCount,companySize:s?.companySize,workplaceType:s?.workplaceType,contractType:s?.contractType,aboutCompany:s?.aboutCompany}),Le(f,"applied",{source:"easy-apply"}),s?.companyUrl&&Pt(s.companyUrl,{name:s.companyName||t.companyName,about:s.aboutCompany,size:s.companySize,industries:s.industries,jobId:f})),await Yr(e,t),Re({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:d.formPages,questions:o}),!Br())return{keepGoing:!1}}}catch(n){if(De(n))throw console.log(`\u26A0 CDP dead during "${t.jobTitle}" \u2014 bubbling up for page recovery: ${(n.message||"").slice(0,100)}`),n;console.log(n);let s=gn(n);if(!s)return console.log(`\u274C Unknown error \u2014 stopping: ${(n.message||"").slice(0,120)}`),{keepGoing:!1};if(s.severity==="fatal")return console.log(`\u274C [${s.label}] Fatal \u2014 stopping: ${(n.message||"").slice(0,120)}`),s.instructions&&console.log(` \u2192 ${s.instructions}`),s.label==="ilml-auth-expired"?S.fatalAuthExpired="ilml":s.label==="linkedin-session-expired"&&(S.fatalAuthExpired="linkedin"),{keepGoing:!1};let l=Ur(s.label);if(console.log(`\u26A0 [${s.label}] on "${t.jobTitle}" (${l}/${s.maxConsecutive} consecutive): ${(n.message||"").slice(0,120)}`),s.cleanup==="popup"){try{await mt(e)}catch{}try{await Kt(e)}catch{}}return l>=s.maxConsecutive?(console.log(`\u274C [${s.label}] ${s.maxConsecutive} consecutive \u2014 stopping.`),{keepGoing:!1}):(s.cooldownMs&&await g(s.cooldownMs),{keepGoing:!0})}return an(),{keepGoing:!0}}async function as(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL,n=[],s=0;for(;;){await Xt(e,r)&&(await X(e),await g(2e3)),await o(e);let a=await Hr(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 Xt(e,r);continue}break}if(s=0,n.length===0){n=a;let{keepGoing:i}=await cn(e,a,t);if(!i)return{keepGoing:!1,jobsDone:n}}else{let i=a.filter(u=>!n.some(d=>d.id===u.id));if(console.log(` New jobs on page: ${i.length} (page: ${a.length}, total seen: ${n.length})`),i.length===0)break;let{keepGoing:c}=await cn(e,i,t);if(n=[...n,...i],!c)return{keepGoing:!1,jobsDone:n}}}return console.log(` All jobs processed. Total: ${n.length}`),{keepGoing:!0,jobsDone:n}}var S={attempted:0,submitted:0,skippedByLifebot:0,failed:0,mismatch:0,alreadyApplied:0,expired:0,noApplyButton:0,dailyLimitHit:!1,cdpRecoveries:0,browserRestarts:0,fatalAuthExpired:null};(async()=>{let e=process.argv.find(i=>i.startsWith("--job-urls=")),t=Xo("apply",e?"queue":"search"),o=null,r=null,n=[],s=async()=>Nr.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),l=async i=>{await i.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},a=()=>Wt();try{o=await s();let i=async()=>{console.log(`
|
|
69
69
|
Closing browser...`);try{await o.close()}catch{}process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i);let c=await o.newPage();await l(c);let u=Wt();await c.setCookie(...u);let d=process.argv.find(_=>_.startsWith("--job-urls=")),f=d?d.split("=").slice(1).join("=").replace(/^@/,""):null,p=process.env.LINKEDIN_SEARCH_URL,h=f?"https://www.linkedin.com/feed/":p;try{await c.goto(h,{waitUntil:"domcontentloaded",timeout:6e4})}catch(_){console.error("\u274C Navigation error:",_.message),console.log("Trying to continue anyway..."),await g(5e3)}let m=c.url();if(m.includes("/login")||m.includes("/checkpoint"))throw new Error("Not logged in \u2014 cookies expired, run: npm run login");console.log("\u2713 \u0417\u0430\u043B\u043E\u0433\u0438\u043D\u0435\u043D\u044B \u043D\u0430 LinkedIn!");let b=Ce("recruiters-from-jobs");b.total>0&&console.log(`
|
|
70
70
|
\u{1F4C2} Existing recruiters for today: ${b.total} (${b.unprocessed} unprocessed)
|
|
71
|
-
`),await g(2e3);let y={page:c,browser:o,recoveryCtx:{searchUrl:p,launchFn:s,setupPage:l,cookiesProvider:a}},
|
|
71
|
+
`),await g(2e3);let y={page:c,browser:o,recoveryCtx:{searchUrl:p,launchFn:s,setupPage:l,cookiesProvider:a}},k=!1;if(f)try{let _=JSON.parse(hn.readFileSync(f,"utf-8"));console.log(`
|
|
72
72
|
\u{1F4CB} Queue mode: ${_.length} jobs from ${f}
|
|
73
|
-
`);for(let O=0;O<_.length;O++){let I=typeof _[O]=="string"?{url:_[O]}:_[O],D=I.url
|
|
74
|
-
[${O+1}/${_.length}] ${
|
|
75
|
-
Queue complete. ${
|
|
73
|
+
`);for(let O=0;O<_.length;O++){let I=typeof _[O]=="string"?{url:_[O]}:_[O],D=I.url,$=I.title||"Unknown",R=I.company||"";console.log(`
|
|
74
|
+
[${O+1}/${_.length}] ${$} @ ${R}`),console.log(` ${D}`),c=y.page,o=y.browser;try{let N=D.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await c.goto(D,{waitUntil:"domcontentloaded",timeout:6e4}),await g(8e3);let j=await c.evaluate(()=>{let T=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:T.includes("Application submitted"),noLongerAccepting:T.includes("No longer accepting applications")}});if(j.alreadyApplied){console.log(" Already applied \u2014 skipping"),S.alreadyApplied++,Le(N,"applied",{applyMethod:"detected"});continue}if(j.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),S.expired++,Le(N,"expired",{reason:"no_longer_accepting"});continue}if(!j.hasApply){console.log(" No Easy Apply button \u2014 skipping"),S.noApplyButton++;continue}let v={id:`/jobs/view/${N}/`,href:D,jobTitle:$,companyName:R,location:I.location||"",salary:I.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let E=await wn(c,v);if(console.log(` Result: keepGoing=${E.keepGoing}, reason=${E.dailyLimitReached?"daily_limit":"ok"}`),!E.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),k=!0;break}}catch(N){if(De(N))try{await ht(y,`queue job ${O+1}: ${N.message?.slice(0,80)}`),c=y.page,o=y.browser}catch(j){console.error(`\u274C Queue mode: CDP recovery failed: ${j.message}`),console.error(" Aborting queue, falling back to standard search if possible.");break}else{let j=gn(N);if(j?.severity==="fatal"){console.error(`\u274C [${j.label}] Fatal \u2014 stopping queue: ${(N.message||"").slice(0,120)}`),j.instructions&&console.error(` \u2192 ${j.instructions}`),j.label==="ilml-auth-expired"?S.fatalAuthExpired="ilml":j.label==="linkedin-session-expired"&&(S.fatalAuthExpired="linkedin");break}console.error(` Error: ${N.message?.slice(0,80)}`)}}}console.log(`
|
|
75
|
+
Queue complete. ${k?"Daily limit hit.":"Continuing to search..."}`)}catch(_){console.error(`Failed to read job URLs file: ${_.message}`)}if(!k){if(f){console.log(`
|
|
76
76
|
Queue done. Continuing with standard search...`);try{await c.goto(p,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3)}catch(_){console.error(" Navigation to search failed:",_.message)}}y.page=c,y.browser=o;try{await Wr(y)}catch(_){De(_)||/CDP unrecoverable/.test(_.message||"")?(console.error(`
|
|
77
|
-
\u274C Apply phase ended: CDP channel could not be recovered after ${
|
|
77
|
+
\u274C Apply phase ended: CDP channel could not be recovered after ${S.cdpRecoveries} page recoveries and ${S.browserRestarts} browser restarts.`),console.error(` Last error: ${_.message}`)):/Session expired/i.test(_.message||"")?(console.error(`
|
|
78
78
|
\u274C Apply phase ended: ${_.message}`),r=_):console.error(`
|
|
79
|
-
\u26A0 Apply phase crashed: ${_.message}`)}c=y.page,o=y.browser}let C=
|
|
80
|
-
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SESSION SUMMARY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let _ of n)console.log(` ${_}`);console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let P=!!o&&o.isConnected?.()!==!1?
|
|
81
|
-
\u26A0 Skipping recruiter funnel \u2014 ${P}.`),console.log(` ${A.unprocessed} recruiters saved for next run.`),n.push(`Funnel: skipped (${P})`));let{markProfileProcessed:H}=await Promise.resolve().then(()=>(vt(),io)),{canSendConnection:J,getQuotaStatus:re}=await Promise.resolve().then(()=>(Ue()
|
|
79
|
+
\u26A0 Apply phase crashed: ${_.message}`)}c=y.page,o=y.browser}let C=S.submitted+S.skippedByLifebot+S.failed+S.mismatch+S.alreadyApplied+S.expired+S.noApplyButton,w=S.attempted-C,A=Ce("recruiters-from-jobs");n.push(`Jobs attempted: ${S.attempted}`),n.push(`Successfully applied: ${S.submitted}`),n.push(`Skipped by Lifebot: ${S.skippedByLifebot}`),n.push(`Failed (form errors): ${S.failed}`),S.mismatch>0&&n.push(`Mismatch (wrong panel): ${S.mismatch}`),S.alreadyApplied>0&&n.push(`Already applied: ${S.alreadyApplied}`),S.expired>0&&n.push(`Expired (closed): ${S.expired}`),S.noApplyButton>0&&n.push(`No Apply button: ${S.noApplyButton}`),w>0&&n.push(`Unaccounted: ${w}`),n.push(`Daily limit reached: ${S.dailyLimitHit?"Yes":"No"}`),S.cdpRecoveries>0&&n.push(`Page recoveries (CDP): ${S.cdpRecoveries}`),S.browserRestarts>0&&n.push(`Browser restarts: ${S.browserRestarts}`),n.push(`Recruiters found: ${gt}`),n.push(`Recruiters total: ${A.total} (${A.unprocessed} unprocessed)`),console.log(`
|
|
80
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SESSION SUMMARY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let _ of n)console.log(` ${_}`);console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let P=!!o&&o.isConnected?.()!==!1?S.fatalAuthExpired==="linkedin"?"LinkedIn session expired (run: ilml linkedin login)":S.fatalAuthExpired==="ilml"?"iLiveMyLife token expired (run: ilml login)":null:"browser is not in a usable state",G=!P;G||(console.log(`
|
|
81
|
+
\u26A0 Skipping recruiter funnel \u2014 ${P}.`),console.log(` ${A.unprocessed} recruiters saved for next run.`),n.push(`Funnel: skipped (${P})`));let{markProfileProcessed:H}=await Promise.resolve().then(()=>(vt(),io)),{canSendConnection:J,getQuotaStatus:re}=await Promise.resolve().then(()=>(Ue(),xo)),K=()=>({message:Or,useCustomMessage:qr,maxConnections:Pr,excludeLocations:Yt,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async(_,O,I)=>{H("recruiters-from-jobs",_.profileUrl,{status:I.reason,connectionSent:I.connectionSent,withCustomMessage:I.withCustomMessage,message:I.messageSent,method:I.method,reason:I.reason,error:I.error,profileInfo:I.profileInfo},_._fromDate||null)}});if(G&&A.unprocessed>0){console.log(`
|
|
82
82
|
--- Funnel: today's recruiters (${A.unprocessed}) ---`),Yt.length>0&&console.log(` Excluding locations: ${Yt.join(", ")}`);let _=ze("recruiters-from-jobs");await Rt(c,_,K())}let me=J();if(G&&me.allowed){let _=Ke("recruiters-from-jobs"),O=new Date().toISOString().split("T")[0],I=_.filter(D=>D._fromDate!==O);if(I.length>0){let D=re();console.log(`
|
|
83
83
|
--- Funnel: backfill from previous days (${I.length} unprocessed) ---`),console.log(` Quota remaining: ${D.daily.remaining} today, ${D.weekly.remaining} this week`),await Rt(c,I,{...K(),maxConnections:D.daily.remaining})}}let B=re();console.log(`
|
|
84
84
|
\u2705 Funnel done. Quota: ${B.daily.remaining}/${B.daily.max} today, ${B.weekly.remaining}/${B.weekly.max} this week`),n.push(`Funnel quota: ${B.daily.remaining}/${B.daily.max} today, ${B.weekly.remaining}/${B.weekly.max} week`)}catch(i){r=i,console.error(`
|
|
85
|
-
\u274C Apply session ended with error: ${i.message}`),i.stack&&console.error(i.stack)}Zo(t,r?"error":"success",{summaryLines:n,dailyLimitHit:
|
|
85
|
+
\u274C Apply session ended with error: ${i.message}`),i.stack&&console.error(i.stack)}Zo(t,r?"error":"success",{summaryLines:n,dailyLimitHit:S.dailyLimitHit,attempted:S.attempted,submitted:S.submitted,failed:S.failed,skippedByLifebot:S.skippedByLifebot},r?r.message:null);try{await o?.close()}catch{}r&&process.exit(1)})();
|
package/ilml-plugin.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ilml-plugin-linkedin",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.0",
|
|
4
4
|
"description": "ilml plugin: pull your LinkedIn graph (connections, threads, notes) into iLiveMyLife and run inbox sync, AI-drafted replies, Easy Apply, and recruiter outreach from the terminal.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|