ilml-plugin-linkedin 1.20.4 → 1.20.6
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 +6 -0
- package/dist/connect.mjs +60 -60
- package/dist/enrichProfile.mjs +10 -10
- package/dist/enrichProfiles.mjs +45 -45
- package/dist/funnelRunner.mjs +39 -39
- package/dist/messageBot.mjs +51 -51
- package/dist/readPost.mjs +10 -10
- package/dist/run.mjs +58 -58
- package/dist/scout.mjs +41 -41
- package/dist/syncAll.mjs +97 -97
- package/dist/syncConnections.mjs +45 -45
- package/dist/verifyAbout.mjs +13 -13
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +37 -37
- package/dist/visit.mjs +44 -44
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/run.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var hi=Object.defineProperty;var pe=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{for(var o in t)hi(e,o,{get:t[o],enumerable:!0})};async function w(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}function an(e){return parseInt(e,10)||0}async function oe(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let n=r.innerText||"",i=n.includes("Premium")||n.includes("premium")||n.includes("Upgrade")||n.includes("upgrade"),s=n.includes("Try for")||n.includes("free trial")||n.includes("/month")||n.includes("per month")||n.includes("Start my")||n.includes("Subscribe"),a=n.includes("Get hired faster")||n.includes("Get hired 2x");if(i||s||a){let l=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:n.substring(0,80)};let c=r.querySelectorAll("button");for(let u of c){let f=u.innerText?.trim().toLowerCase()||"",d=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return u.click(),{dismissed:!0,matched:n.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var Ue=pe(()=>{});var pn={};te(pn,{default:()=>xi,getAllUnprocessedProfiles:()=>_t,getSummary:()=>He,getUnprocessedProfiles:()=>$t,listFiles:()=>fn,loadProfiles:()=>At,markProfileProcessed:()=>dn,saveProfile:()=>lt,saveProfiles:()=>un});import"dotenv/config";import*as H from"fs";import*as ne from"path";import{fileURLToPath as wi}from"url";function st(){H.existsSync(me)||H.mkdirSync(me,{recursive:!0})}function vi(e,t){try{let o=`${e}-${ro()}.json`,r=H.readdirSync(me).filter(i=>i.startsWith(e)&&i.endsWith(".json")&&i!==o),n=0;for(let i of r)JSON.parse(H.readFileSync(ne.join(me,i),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function ro(){return new Date().toISOString().split("T")[0]}function io(e,t=null){let o=t||ro();return ne.join(me,`${e}-${o}.json`)}function At(e,t=null){st();let o=io(e,t);try{if(H.existsSync(o)){let r=H.readFileSync(o,"utf-8"),n=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${n.profiles.length} profiles from ${o}`),n.profiles}}catch(r){console.error(`Error loading profiles from ${o}:`,r.message)}return[]}function lt(e,t){st();let o=io(e),r={source:e,date:ro(),lastUpdated:new Date().toISOString(),profiles:[]};try{H.existsSync(o)&&(r=JSON.parse(H.readFileSync(o,"utf-8")))}catch(s){console.error(`Error reading ${o}:`,s.message)}if(r.profiles.some(s=>s.profileUrl===t.profileUrl))return!1;let i=vi(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:i}),r.lastUpdated=new Date().toISOString();try{H.writeFileSync(o,JSON.stringify(r,null,2));let s=i>0?` (seen ${i} day${i>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${s} (total: ${r.profiles.length})`),!0}catch(s){return console.error(`Error saving to ${o}:`,s.message),!1}}function un(e,t){let o=0;for(let r of t)lt(e,r)&&o++;return o}function $t(e,t=null){return At(e,t).filter(r=>!r.processed)}function dn(e,t,o,r=null){st();let n=io(e,r);try{if(!H.existsSync(n))return;let i=JSON.parse(H.readFileSync(n,"utf-8")),s=i.profiles.find(a=>a.profileUrl===t);if(s){if(s.processed=!0,s.processedAt=new Date().toISOString(),typeof o=="string")s.status=o;else if(typeof o=="object"){if(s.status=o.status,o.profileInfo){let a=o.profileInfo;a.name&&(s.name=a.name),a.title&&(s.title=a.title),a.location&&(s.location=a.location),a.company&&(s.company=a.company),a.connectionDegree&&(s.connectionDegree=a.connectionDegree),a.connectionsCount&&(s.connectionsCount=a.connectionsCount),a.mutualConnections&&(s.mutualConnections=a.mutualConnections),a.photoUrl&&(s.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(s.hasVerifiedBadge=a.hasVerifiedBadge)}s.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}i.lastUpdated=new Date().toISOString(),H.writeFileSync(n,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function He(e){let t=At(e),o=t.filter(n=>n.processed),r=t.filter(n=>!n.processed);return{total:t.length,processed:o.length,unprocessed:r.length,statuses:o.reduce((n,i)=>(n[i.status]=(n[i.status]||0)+1,n),{})}}function fn(){st();try{return H.readdirSync(me).filter(t=>t.endsWith(".json")).map(t=>{let[o,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let n=JSON.parse(H.readFileSync(ne.join(me,t),"utf-8"));return{file:t,source:o,date:r,count:n.profiles?.length||0,unprocessed:n.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:o,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function _t(e){st();let t=[];try{let n=H.readdirSync(me).filter(i=>i.startsWith(e+"-")&&i.endsWith(".json")).sort().reverse();for(let i of n)try{let s=JSON.parse(H.readFileSync(ne.join(me,i),"utf-8"));s.profiles&&t.push({file:i,date:s.date,profiles:s.profiles})}catch{}}catch{return[]}let o=new Set,r=[];for(let{date:n,profiles:i}of t)for(let s of i)!s.processed&&s.profileUrl&&!o.has(s.profileUrl)&&(o.add(s.profileUrl),r.push({...s,_fromDate:n}));return r}var Si,ki,me,xi,so=pe(()=>{Si=wi(import.meta.url),ki=ne.dirname(ne.dirname(Si)),me=process.env.DATA_DIR?ne.resolve(process.env.DATA_DIR,"collected-profiles"):ne.join(ki,"collected-profiles");xi={loadProfiles:At,saveProfile:lt,saveProfiles:un,getUnprocessedProfiles:$t,getAllUnprocessedProfiles:_t,markProfileProcessed:dn,getSummary:He,listFiles:fn}});import{getPluginConfig as Ci}from"@ilivemylife/graph-sdk";var Ei,ke,he,lo,ao,co=pe(async()=>{Ei=await Ci();for(let[e,t]of Object.entries(Ei))process.env[e]===void 0&&(process.env[e]=t);ke=process.env.LINKEDIN_NAME,he=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),lo=Object.freeze(new Set([he.DRAFT,he.CONFIRMED,he.NEEDS_REVIEW])),ao=Object.freeze(new Set([he.DRAFT,he.CONFIRMED,he.REJECTED,he.NEEDS_REVIEW]))});var Dn={};te(Dn,{addEncounter:()=>Ke,addProfileAlias:()=>Pt,atomicWriteJSON:()=>ge,canSendConnection:()=>ut,commitDataSnapshot:()=>In,default:()=>Fi,getAllApplications:()=>Tn,getPersonStatus:()=>Lt,getQuestionStats:()=>Rn,getQuotaStatus:()=>dt,getRecentConnections:()=>qt,linkPersonToJob:()=>jt,loadApplicationQuestions:()=>bo,loadConversations:()=>xn,loadJobs:()=>Rt,loadPeople:()=>Q,loadProfileHistory:()=>vn,loadQuota:()=>Ft,loadSyncState:()=>An,logApplicationQuestions:()=>ze,migrateFromDailyFiles:()=>En,profileSlug:()=>ve,recordConnectionSent:()=>Ot,resetCaches:()=>yo,resolveCanonicalKey:()=>xe,safeLoadJSON:()=>Le,saveConversations:()=>Cn,saveJobs:()=>It,savePeople:()=>Ee,saveQuota:()=>go,saveSyncState:()=>$n,updateConnectionStatus:()=>Nt,upsertJob:()=>Dt,upsertPerson:()=>Ce});import"dotenv/config";import*as U from"fs";import*as V from"path";import{fileURLToPath as Ai}from"url";import{execSync as uo}from"child_process";function yo(){Ve=null,Ge=null,ye=null,je=null,We=null,De=null}function Z(){U.existsSync(z)||U.mkdirSync(z,{recursive:!0})}function ge(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";U.writeFileSync(r,o);for(let n=0;n<3;n++)try{U.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Le(e,t){if(!U.existsSync(e))return null;try{let o=JSON.parse(U.readFileSync(e,"utf-8"));try{U.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${V.resolve(e)}`);let r=e+".backup";if(U.existsSync(r))try{let n=JSON.parse(U.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{U.copyFileSync(r,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{U.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ye(){return new Date().toISOString().split("T")[0]}function ve(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function mn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function xe(e,t,o=null){if(!t||e[t])return t;let r=ve(t);if(!r)return t;let n=null;for(let[i,s]of Object.entries(e)){if(ve(s.profileUrl||i)===r)return i;!n&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}if(n){let i=mn(o),s=mn(e[n].name);if(i&&s&&i===s)return n}return t}function Ri(){U.existsSync(ho)||U.mkdirSync(ho,{recursive:!0})}function kn(e){let t=ve(e);return t?V.join(ho,`${t}.json`):null}function vn(e){let t=kn(e);return t?Le(t,`profile-history/${ve(e)}.json`)||[]:[]}function Ii(e,t){let o=kn(e);if(!o)return;Ri();let r=vn(e);r.unshift(t);try{ge(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${ve(e)}: ${n.message}`)}}function hn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function yn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Di(e,t){if(!e)return[];let o=[];for(let r of Ti){let n=e[r],i=t[r];hn(n)||hn(i)||yn(n)!==yn(i)&&o.push(r)}return o}function ji(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[r,n]of Object.entries(e))t.has(r)||(o[r]=n);return o}function Q(){return Ve||(Z(),Ve=Le(fo,"people.json")||{},Ve)}function Ee(e){Z(),Ve=e;try{ge(fo,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${V.resolve(fo)}`)}}function Rt(){return Ge||(Z(),Ge=Le(po,"jobs.json")||{},Ge)}function It(e){Z(),Ge=e;try{ge(po,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${V.resolve(po)}`)}}function xn(){return je||(Z(),je=Le(Tt,"conversations.json")||{},Li(je),je)}function Li(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let n=(o.messages||[]).find(i=>i.status==="draft");n&&o.draftStatus&&o.draftStatus!=="pending"&&(n.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{ge(Tt,e)}catch{}}}function Cn(e){Z(),je=e;try{ge(Tt,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${V.resolve(Tt)}`)}}function Ce(e,t={}){if(!e)return null;let o=Q(),r=Ye(),n=new Date().toISOString(),i=xe(o,e,t.name),s=o[i];if(s){let a=Di(s,t);a.length>0&&(Ii(i,{capturedAt:n,previousLastUpdated:s.lastUpdated||null,changedFields:a,snapshot:ji(s)}),s.lastSnapshotAt=n),s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=n,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let l of Sn)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(s[l])&&s[l].length>0)continue;s[l]=t[l]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=n)}else o[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return Ee(o),o[i]}function Dt(e,t={}){if(!e)return null;let o=Rt(),r=Ye(),n=o[e];if(n){let i=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let s of i)t[s]!=null&&(n[s]=t[s])}else o[e]={title:t.title||null,company:t.company||null,location:t.location||null,salary:t.salary||null,url:t.url||null,applied:t.applied||!1,appliedDate:t.appliedDate||r,recruiterUrl:t.recruiterUrl||null,firstSeen:r};return It(o),o[e]}function jt(e,t){if(!e||!t)return;let o=Q(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),Ee(o)))}function Ke(e,t){if(!e||!t)return;let o=Q(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let i={date:Ye(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!r.encounters.some(a=>a.date===i.date&&a.source===i.source&&a.action===i.action&&(a.jobId||"")===(i.jobId||""))&&(r.encounters.push(i),r.lastUpdated=new Date().toISOString(),Ee(o))}function Lt(e){return e&&Q()[e]?.connectionStatus||null}function Nt(e,t,o={}){if(!e)return;if(o.profileInfo)Ce(e,o.profileInfo);else{let a=Q(),l=xe(a,e,o.profileInfo?.name);a[l]||Ce(e,{})}let r=Q(),n=xe(r,e,o.profileInfo?.name),i=r[n];if(!i)return;let s=Ye();i.connectionStatus=t,t==="connected"?i.connectionDate=s:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=s)),i.connectionMethod=o.method||i.connectionMethod,i.messageSent=o.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),Ee(r)}function Pt(e,t,o={}){if(o.dryRun||!e||!t)return;let r=ve(t);if(!r)return;let n=Q(),i=xe(n,e),s=n[i];if(!s)return;let a=ve(s.profileUrl||i);r!==a&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(r)||(s.aliases.push(r),s.lastUpdated=new Date().toISOString(),Ee(n)))}function Ft(){return ye||(Z(),ye=Le(gn,"quota.json"),(!ye||!ye.connections)&&(ye={connections:[]}),ye)}function go(e){Z(),ye=e;try{ge(gn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Ot(e,t="unknown"){let o=Ft(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),go(o)}function qt(){let e=Ft(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function ut(){let e=qt(),t=Ye(),o=e.filter(l=>l.date===t).length,r=e.length,n=o>=at,i=r>=ct,s=!n&&!i,a={allowed:s,daily:{sent:o,max:at},weekly:{sent:r,max:ct}};return s||(a.reason=n?`Daily limit reached (${o}/${at})`:`Weekly limit reached (${r}/${ct})`),a}function dt(){let e=qt(),t=Ye(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:at,remaining:at-o},weekly:{sent:r,max:ct,remaining:ct-r}}}function Ni(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function En(){Z();let e=U.readdirSync(z).filter(i=>i.endsWith(".json")&&i!=="people.json"&&i!=="jobs.json"&&i!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
|
|
1
|
+
var wi=Object.defineProperty;var fe=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{for(var o in t)wi(e,o,{get:t[o],enumerable:!0})};async function w(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}async function io(e,t,{timeout:o=45e3,poll:r=1e3,label:n="page"}={}){let i=Date.now();for(;Date.now()-i<o;){try{if(await e.evaluate(a=>!!document.querySelector(a),t)){let a=Date.now()-i;return a>6e3&&console.log(` (waited ${Math.round(a/1e3)}s for LinkedIn to finish loading ${n})`),!0}}catch{}await new Promise(s=>setTimeout(s,r))}return!1}function At(e){return Si.test(e||"")}async function it(e,{readySelector:t,label:o="page",timeout:r=45e3}={}){let n=await io(e,t,{timeout:r,label:o});if(!n&&At(e.url())){let i=new Error(`Session expired (${o}) \u2014 redirected to login. Run: ilml linkedin login`);throw i.code="SESSION_EXPIRED",i}return n}async function so(e,t,{readySelector:o,label:r="page",timeout:n=45e3,gotoTimeout:i=6e4}={}){return await e.goto(t,{waitUntil:"domcontentloaded",timeout:i}),it(e,{readySelector:o,label:r,timeout:n})}function fn(e){return parseInt(e,10)||0}async function oe(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let n=r.innerText||"",i=n.includes("Premium")||n.includes("premium")||n.includes("Upgrade")||n.includes("upgrade"),s=n.includes("Try for")||n.includes("free trial")||n.includes("/month")||n.includes("per month")||n.includes("Start my")||n.includes("Subscribe"),a=n.includes("Get hired faster")||n.includes("Get hired 2x");if(i||s||a){let l=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:n.substring(0,80)};let c=r.querySelectorAll("button");for(let u of c){let f=u.innerText?.trim().toLowerCase()||"",d=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return u.click(),{dismissed:!0,matched:n.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var Si,Ue=fe(()=>{Si=/\/authwall|\/login|\/checkpoint|\/uas\/login/});var gn={};te(gn,{default:()=>$i,getAllUnprocessedProfiles:()=>Rt,getSummary:()=>He,getUnprocessedProfiles:()=>Tt,listFiles:()=>yn,loadProfiles:()=>$t,markProfileProcessed:()=>hn,saveProfile:()=>at,saveProfiles:()=>mn});import"dotenv/config";import*as H from"fs";import*as ne from"path";import{fileURLToPath as Ci}from"url";function lt(){H.existsSync(pe)||H.mkdirSync(pe,{recursive:!0})}function _i(e,t){try{let o=`${e}-${ao()}.json`,r=H.readdirSync(pe).filter(i=>i.startsWith(e)&&i.endsWith(".json")&&i!==o),n=0;for(let i of r)JSON.parse(H.readFileSync(ne.join(pe,i),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function ao(){return new Date().toISOString().split("T")[0]}function co(e,t=null){let o=t||ao();return ne.join(pe,`${e}-${o}.json`)}function $t(e,t=null){lt();let o=co(e,t);try{if(H.existsSync(o)){let r=H.readFileSync(o,"utf-8"),n=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${n.profiles.length} profiles from ${o}`),n.profiles}}catch(r){console.error(`Error loading profiles from ${o}:`,r.message)}return[]}function at(e,t){lt();let o=co(e),r={source:e,date:ao(),lastUpdated:new Date().toISOString(),profiles:[]};try{H.existsSync(o)&&(r=JSON.parse(H.readFileSync(o,"utf-8")))}catch(s){console.error(`Error reading ${o}:`,s.message)}if(r.profiles.some(s=>s.profileUrl===t.profileUrl))return!1;let i=_i(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:i}),r.lastUpdated=new Date().toISOString();try{H.writeFileSync(o,JSON.stringify(r,null,2));let s=i>0?` (seen ${i} day${i>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${s} (total: ${r.profiles.length})`),!0}catch(s){return console.error(`Error saving to ${o}:`,s.message),!1}}function mn(e,t){let o=0;for(let r of t)at(e,r)&&o++;return o}function Tt(e,t=null){return $t(e,t).filter(r=>!r.processed)}function hn(e,t,o,r=null){lt();let n=co(e,r);try{if(!H.existsSync(n))return;let i=JSON.parse(H.readFileSync(n,"utf-8")),s=i.profiles.find(a=>a.profileUrl===t);if(s){if(s.processed=!0,s.processedAt=new Date().toISOString(),typeof o=="string")s.status=o;else if(typeof o=="object"){if(s.status=o.status,o.profileInfo){let a=o.profileInfo;a.name&&(s.name=a.name),a.title&&(s.title=a.title),a.location&&(s.location=a.location),a.company&&(s.company=a.company),a.connectionDegree&&(s.connectionDegree=a.connectionDegree),a.connectionsCount&&(s.connectionsCount=a.connectionsCount),a.mutualConnections&&(s.mutualConnections=a.mutualConnections),a.photoUrl&&(s.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(s.hasVerifiedBadge=a.hasVerifiedBadge)}s.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}i.lastUpdated=new Date().toISOString(),H.writeFileSync(n,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function He(e){let t=$t(e),o=t.filter(n=>n.processed),r=t.filter(n=>!n.processed);return{total:t.length,processed:o.length,unprocessed:r.length,statuses:o.reduce((n,i)=>(n[i.status]=(n[i.status]||0)+1,n),{})}}function yn(){lt();try{return H.readdirSync(pe).filter(t=>t.endsWith(".json")).map(t=>{let[o,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let n=JSON.parse(H.readFileSync(ne.join(pe,t),"utf-8"));return{file:t,source:o,date:r,count:n.profiles?.length||0,unprocessed:n.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:o,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function Rt(e){lt();let t=[];try{let n=H.readdirSync(pe).filter(i=>i.startsWith(e+"-")&&i.endsWith(".json")).sort().reverse();for(let i of n)try{let s=JSON.parse(H.readFileSync(ne.join(pe,i),"utf-8"));s.profiles&&t.push({file:i,date:s.date,profiles:s.profiles})}catch{}}catch{return[]}let o=new Set,r=[];for(let{date:n,profiles:i}of t)for(let s of i)!s.processed&&s.profileUrl&&!o.has(s.profileUrl)&&(o.add(s.profileUrl),r.push({...s,_fromDate:n}));return r}var Ei,Ai,pe,$i,uo=fe(()=>{Ei=Ci(import.meta.url),Ai=ne.dirname(ne.dirname(Ei)),pe=process.env.DATA_DIR?ne.resolve(process.env.DATA_DIR,"collected-profiles"):ne.join(Ai,"collected-profiles");$i={loadProfiles:$t,saveProfile:at,saveProfiles:mn,getUnprocessedProfiles:Tt,getAllUnprocessedProfiles:Rt,markProfileProcessed:hn,getSummary:He,listFiles:yn}});import{getPluginConfig as Ti}from"@ilivemylife/graph-sdk";var Ri,we,me,fo,po,mo=fe(async()=>{Ri=await Ti();for(let[e,t]of Object.entries(Ri))process.env[e]===void 0&&(process.env[e]=t);we=process.env.LINKEDIN_NAME,me=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),fo=Object.freeze(new Set([me.DRAFT,me.CONFIRMED,me.NEEDS_REVIEW])),po=Object.freeze(new Set([me.DRAFT,me.CONFIRMED,me.REJECTED,me.NEEDS_REVIEW]))});var Pn={};te(Pn,{addEncounter:()=>Ke,addProfileAlias:()=>Ot,atomicWriteJSON:()=>ye,canSendConnection:()=>dt,commitDataSnapshot:()=>Nn,default:()=>Bi,getAllApplications:()=>Dn,getPersonStatus:()=>Pt,getQuestionStats:()=>Ln,getQuotaStatus:()=>ft,getRecentConnections:()=>Ut,linkPersonToJob:()=>Nt,loadApplicationQuestions:()=>vo,loadConversations:()=>_n,loadJobs:()=>jt,loadPeople:()=>Q,loadProfileHistory:()=>An,loadQuota:()=>qt,loadSyncState:()=>Rn,logApplicationQuestions:()=>ze,migrateFromDailyFiles:()=>Tn,profileSlug:()=>Se,recordConnectionSent:()=>Mt,resetCaches:()=>So,resolveCanonicalKey:()=>ke,safeLoadJSON:()=>Le,saveConversations:()=>$n,saveJobs:()=>Dt,savePeople:()=>xe,saveQuota:()=>ko,saveSyncState:()=>In,updateConnectionStatus:()=>Ft,upsertJob:()=>Lt,upsertPerson:()=>ve});import"dotenv/config";import*as q from"fs";import*as V from"path";import{fileURLToPath as Ii}from"url";import{execSync as ho}from"child_process";function So(){Ve=null,Ge=null,he=null,De=null,We=null,je=null}function Z(){q.existsSync(z)||q.mkdirSync(z,{recursive:!0})}function ye(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";q.writeFileSync(r,o);for(let n=0;n<3;n++)try{q.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Le(e,t){if(!q.existsSync(e))return null;try{let o=JSON.parse(q.readFileSync(e,"utf-8"));try{q.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${V.resolve(e)}`);let r=e+".backup";if(q.existsSync(r))try{let n=JSON.parse(q.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{q.copyFileSync(r,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{q.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ye(){return new Date().toISOString().split("T")[0]}function Se(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function bn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function ke(e,t,o=null){if(!t||e[t])return t;let r=Se(t);if(!r)return t;let n=null;for(let[i,s]of Object.entries(e)){if(Se(s.profileUrl||i)===r)return i;!n&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}if(n){let i=bn(o),s=bn(e[n].name);if(i&&s&&i===s)return n}return t}function Ni(){q.existsSync(wo)||q.mkdirSync(wo,{recursive:!0})}function En(e){let t=Se(e);return t?V.join(wo,`${t}.json`):null}function An(e){let t=En(e);return t?Le(t,`profile-history/${Se(e)}.json`)||[]:[]}function Pi(e,t){let o=En(e);if(!o)return;Ni();let r=An(e);r.unshift(t);try{ye(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${Se(e)}: ${n.message}`)}}function wn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Sn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Fi(e,t){if(!e)return[];let o=[];for(let r of Li){let n=e[r],i=t[r];wn(n)||wn(i)||Sn(n)!==Sn(i)&&o.push(r)}return o}function Oi(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[r,n]of Object.entries(e))t.has(r)||(o[r]=n);return o}function Q(){return Ve||(Z(),Ve=Le(yo,"people.json")||{},Ve)}function xe(e){Z(),Ve=e;try{ye(yo,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${V.resolve(yo)}`)}}function jt(){return Ge||(Z(),Ge=Le(go,"jobs.json")||{},Ge)}function Dt(e){Z(),Ge=e;try{ye(go,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${V.resolve(go)}`)}}function _n(){return De||(Z(),De=Le(It,"conversations.json")||{},qi(De),De)}function qi(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let n=(o.messages||[]).find(i=>i.status==="draft");n&&o.draftStatus&&o.draftStatus!=="pending"&&(n.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{ye(It,e)}catch{}}}function $n(e){Z(),De=e;try{ye(It,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${V.resolve(It)}`)}}function ve(e,t={}){if(!e)return null;let o=Q(),r=Ye(),n=new Date().toISOString(),i=ke(o,e,t.name),s=o[i];if(s){let a=Fi(s,t);a.length>0&&(Pi(i,{capturedAt:n,previousLastUpdated:s.lastUpdated||null,changedFields:a,snapshot:Oi(s)}),s.lastSnapshotAt=n),s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=n,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let l of Cn)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(s[l])&&s[l].length>0)continue;s[l]=t[l]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=n)}else o[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return xe(o),o[i]}function Lt(e,t={}){if(!e)return null;let o=jt(),r=Ye(),n=o[e];if(n){let i=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let s of i)t[s]!=null&&(n[s]=t[s])}else o[e]={title:t.title||null,company:t.company||null,location:t.location||null,salary:t.salary||null,url:t.url||null,applied:t.applied||!1,appliedDate:t.appliedDate||r,recruiterUrl:t.recruiterUrl||null,firstSeen:r};return Dt(o),o[e]}function Nt(e,t){if(!e||!t)return;let o=Q(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),xe(o)))}function Ke(e,t){if(!e||!t)return;let o=Q(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let i={date:Ye(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!r.encounters.some(a=>a.date===i.date&&a.source===i.source&&a.action===i.action&&(a.jobId||"")===(i.jobId||""))&&(r.encounters.push(i),r.lastUpdated=new Date().toISOString(),xe(o))}function Pt(e){return e&&Q()[e]?.connectionStatus||null}function Ft(e,t,o={}){if(!e)return;if(o.profileInfo)ve(e,o.profileInfo);else{let a=Q(),l=ke(a,e,o.profileInfo?.name);a[l]||ve(e,{})}let r=Q(),n=ke(r,e,o.profileInfo?.name),i=r[n];if(!i)return;let s=Ye();i.connectionStatus=t,t==="connected"?i.connectionDate=s:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=s)),i.connectionMethod=o.method||i.connectionMethod,i.messageSent=o.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),xe(r)}function Ot(e,t,o={}){if(o.dryRun||!e||!t)return;let r=Se(t);if(!r)return;let n=Q(),i=ke(n,e),s=n[i];if(!s)return;let a=Se(s.profileUrl||i);r!==a&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(r)||(s.aliases.push(r),s.lastUpdated=new Date().toISOString(),xe(n)))}function qt(){return he||(Z(),he=Le(kn,"quota.json"),(!he||!he.connections)&&(he={connections:[]}),he)}function ko(e){Z(),he=e;try{ye(kn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Mt(e,t="unknown"){let o=qt(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),ko(o)}function Ut(){let e=qt(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function dt(){let e=Ut(),t=Ye(),o=e.filter(l=>l.date===t).length,r=e.length,n=o>=ct,i=r>=ut,s=!n&&!i,a={allowed:s,daily:{sent:o,max:ct},weekly:{sent:r,max:ut}};return s||(a.reason=n?`Daily limit reached (${o}/${ct})`:`Weekly limit reached (${r}/${ut})`),a}function ft(){let e=Ut(),t=Ye(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:ct,remaining:ct-o},weekly:{sent:r,max:ut,remaining:ut-r}}}function Mi(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function Tn(){Z();let e=q.readdirSync(z).filter(i=>i.endsWith(".json")&&i!=="people.json"&&i!=="jobs.json"&&i!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
|
|
2
2
|
Migrating from ${e.length} daily files...
|
|
3
|
-
`);let t=Q(),o=
|
|
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
|
|
3
|
+
`);let t=Q(),o=jt(),r=0,n=0;e.sort();for(let i of e){let s=V.join(z,i),a;try{a=JSON.parse(q.readFileSync(s,"utf-8"))}catch(u){console.log(` Skipping ${i}: ${u.message}`);continue}let l=a.date||i.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,c=a.source||i.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!a.profiles||!Array.isArray(a.profiles)){console.log(` Skipping ${i}: no profiles array`);continue}console.log(` ${i}: ${a.profiles.length} profiles`);for(let u of a.profiles){let f=u.profileUrl;if(!f)continue;let d=t[f];if(d){d.seenCount=(d.seenCount||1)+1,l&&(!d.lastSeen||l>d.lastSeen)&&(d.lastSeen=l),l&&(!d.firstSeen||l<d.firstSeen)&&(d.firstSeen=l),c&&!d.sources?.includes(c)&&(d.sources=d.sources||[],d.sources.push(c));for(let p of Cn)u[p]!=null&&(d[p]=u[p]);u.status&&u.processed&&(d.connectionStatus=u.status,d.connectionDate=l,u.funnelResult&&(d.connectionMethod=u.funnelResult.method||d.connectionMethod,d.messageSent=u.funnelResult.message||d.messageSent)),d.lastUpdated=new Date().toISOString()}else t[f]={name:u.name||null,title:u.title||null,location:u.location||null,company:u.company||null,connectionDegree:u.connectionDegree||null,connectionsCount:u.connectionsCount||null,mutualConnections:u.mutualConnections||null,photoUrl:u.photoUrl||null,hasVerifiedBadge:u.hasVerifiedBadge||!1,firstSeen:l,lastSeen:l,seenCount:1,sources:c?[c]:[],connectionStatus:u.processed&&u.status||null,connectionDate:u.processed?l:null,connectionMethod:u.funnelResult?.method||null,messageSent:u.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(u.fromJob?.url){let p=Mi(u.fromJob.url);p&&(t[f].jobIds||(t[f].jobIds=[]),t[f].jobIds.includes(p)||t[f].jobIds.push(p),o[p]?o[p].recruiterUrl||(o[p].recruiterUrl=f):(o[p]={title:u.fromJob.title||null,company:u.fromJob.company||null,location:null,salary:null,url:u.fromJob.url,applied:!0,appliedDate:l,recruiterUrl:f,firstSeen:l},n++))}}}return xe(t),Dt(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 Rn(){return We||(Z(),We=Le(vn,"sync-state.json")||{},We)}function In(e){Z(),We=e;try{ye(vn,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function vo(){if(je)return je;Z();try{q.existsSync(bo)&&(je=JSON.parse(q.readFileSync(bo,"utf-8")))}catch{}return je||(je={}),je}function jn(e){return Array.isArray(e.applications)}function Dn(){let e=vo();if(jn(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function ze(e){if(!e||!e.questions||e.questions.length===0)return;let t=vo(),o=e.jobId||"unknown",n={applicationId:`${o}_${Date.now()}`,date:new Date().toISOString(),result:e.result||"submitted",formPages:e.formPages||null,duration:e.duration||null,retries:e.retries||0,failedField:e.failedField||null,questionCount:e.questions.length,questions:e.questions.map(i=>{let s={type:i.type||"input",question:i.labelText||i.question||"",answer:i.answer||""};return i.options&&(i.options.length<=Ui?s.options=i.options:s.optionsOmitted=!0),i.page&&(s.page=i.page),i.wasPreFilled&&(s.wasPreFilled=!0),i.wasRetry&&(s.wasRetry=!0),typeof i.isRequired=="boolean"&&(s.isRequired=i.isRequired),i.wasOptional&&(s.wasOptional=!0),s})};jn(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{ye(bo,t)}catch(i){console.error(`[!] Failed to save application-questions.json: ${i.message}`)}}function Ln(){let e=Dn(),t=new Map;for(let i of e)for(let s of i.questions||[]){let a=s.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:s.question,count:0,answers:new Map});let l=t.get(a);l.count++;let c=(s.answer||"").trim();l.answers.set(c,(l.answers.get(c)||0)+1)}let o=[...t.values()].sort((i,s)=>s.count-i.count),r=o.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((s,a)=>a[1]-s[1])[0]?.[0]||""})),n=o.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((s,a)=>a[1]-s[1]).map(([s,a])=>`${s} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:n}}function Nn(e){if(q.existsSync(V.join(z,".git")))try{let t={cwd:z,stdio:"pipe",timeout:1e4};ho("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{ho("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');ho(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var ji,Di,z,yo,go,kn,It,vn,bo,wo,xn,ct,ut,Ve,Ge,he,De,We,je,Cn,Li,Ui,Bi,Qe=fe(async()=>{await mo();ji=Ii(import.meta.url),Di=V.dirname(V.dirname(ji)),z=process.env.DATA_DIR?V.resolve(process.env.DATA_DIR,"collected-profiles"):V.join(Di,"collected-profiles"),yo=V.join(z,"people.json"),go=V.join(z,"jobs.json"),kn=V.join(z,"quota.json"),It=V.join(z,"conversations.json"),vn=V.join(z,"sync-state.json"),bo=V.join(z,"application-questions.json"),wo=V.join(z,"profile-history"),xn=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},ct=xn(process.env.CONNECT_MAX_DAILY,20),ut=xn(process.env.CONNECT_MAX_WEEKLY,100),Ve=null,Ge=null,he=null,De=null,We=null,je=null;Cn=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],Li=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];Ui=50;Bi={loadPeople:Q,savePeople:xe,loadJobs:jt,saveJobs:Dt,loadConversations:_n,saveConversations:$n,upsertPerson:ve,upsertJob:Lt,linkPersonToJob:Nt,addEncounter:Ke,getPersonStatus:Pt,updateConnectionStatus:Ft,addProfileAlias:Ot,resolveCanonicalKey:ke,migrateFromDailyFiles:Tn,loadQuota:qt,saveQuota:ko,recordConnectionSent:Mt,canSendConnection:dt,getRecentConnections:Ut,getQuotaStatus:ft,loadSyncState:Rn,saveSyncState:In,commitDataSnapshot:Nn,logApplicationQuestions:ze,getQuestionStats:Ln}});var Fn={};te(Fn,{extractCertificationsFromDetails:()=>Wi,extractEducationFromDetails:()=>Vi,extractExperienceFromDetails:()=>Ji,extractFeaturedFromDetails:()=>Hi,extractRecommendationsFromDetails:()=>Yi,extractSkillsFromDetails:()=>Gi});async function Ji(e,t){let o=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await it(e,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await w(1e3);for(let n=0;n<5;n++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(900);await w(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let i of document.querySelectorAll("button"))if(/^Load more$/i.test((i.textContent||"").trim()))return i.click(),!0;return!1});)r++,await w(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await e.evaluate(()=>{let n=document.querySelector("main");if(!n)return[];function i(c){let u=[];for(let f of c.querySelectorAll("div")){let d=Array.from(f.children).filter(m=>m.tagName==="DIV");if(d.length<3)continue;let p=d.filter(m=>(m.textContent||"").trim().length>50);p.length<3||(f.textContent||"").length<500||u.push({el:f,count:p.length,totalText:(f.textContent||"").length})}return u.sort((f,d)=>d.count-f.count||f.totalText-d.totalText),u[0]?.el}let s=i(n);if(!s)return[];let a=Array.from(s.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function l(c){let u=c[0]||null,f=null,d=null;if(c[1]){let A=c[1].split("\xB7").map(T=>T.trim());f=A[0]||null,A[1]&&(d=A[1])}let p=c.findIndex(A=>/(\d{4}|present)/i.test(A)&&/(-|–|—)/i.test(A)&&A.length<80),m=null,h=null;if(p>=0){let A=c[p].split("\xB7").map(T=>T.trim());m=A[0]||null,A[1]&&(h=A[1])}let g=null,y=-1;if(p>=0&&c[p+1]){let A=c[p+1],T=/^[>*\-•]|^>/.test(A),D=/https?:\/\//.test(A),K=/\d{4}/.test(A),U=/,/.test(A)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(A);!T&&!D&&!K&&A.length<100&&U&&(g=A,y=p+1)}let S=null,x=-1,b=c[c.length-1];if(b&&/and\s+\+\d+\s+skills?$/i.test(b)){x=c.length-1;let A=b.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);A&&(S={listed:A[1].split(",").map(T=>T.trim()),additional:parseInt(A[2],10)})}let E=new Set([0,1,p,y,x].filter(A=>A>=0)),R=c.filter((A,T)=>!E.has(T)),L=R.length>0?R.join(`
|
|
5
5
|
|
|
6
|
-
`):null;return{title:
|
|
7
|
-
`).map(
|
|
8
|
-
${
|
|
6
|
+
`):null;return{title:u,company:f,employmentType:d,dates:m,duration:h,location:g,description:L,skills:S,_raw:c}}return a.map(c=>{let f=(c.innerText||"").trim().split(`
|
|
7
|
+
`).map(d=>d.trim()).filter(d=>d&&d.length<5e3);return l(f)}).filter(c=>c.title)})}catch(r){if(/session expired|bounced to|authwall|checkpoint/i.test(r.message||""))throw r;return console.error(`extractExperienceFromDetails failed for ${t}: ${r.message?.slice(0,120)}`),[]}}async function pt(e,t,o){let r=t.replace(/\/+$/,"")+`/details/${o}/`;await e.goto(r,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let n=e.url();if(/\/(login|authwall|checkpoint)/i.test(n))throw new Error(`Session expired \u2014 bounced to ${n} when fetching /details/${o}/`);if(!n.toLowerCase().includes(`/details/${o.toLowerCase()}/`))throw new Error(`Section /details/${o}/ not available on profile (landed on ${n})`);for(let s=0;s<4;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);await w(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)i++,await w(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function ht(e,t,o,r){try{return await r()}catch(n){let i=n.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw n;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${o} failed for ${e}: ${i.slice(0,120)}`),[])}}async function Hi(e,t){return ht(t,"featured","extractFeaturedFromDetails",async()=>(await pt(e,t,"featured"),await e.evaluate(`(() => {
|
|
8
|
+
${mt}
|
|
9
9
|
|
|
10
10
|
const main = document.querySelector('main');
|
|
11
11
|
if (!main) return [];
|
|
@@ -45,8 +45,8 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
|
|
|
45
45
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
46
46
|
return true;
|
|
47
47
|
});
|
|
48
|
-
})()`)))}async function
|
|
49
|
-
${
|
|
48
|
+
})()`)))}async function Vi(e,t){return ht(t,"education","extractEducationFromDetails",async()=>(await pt(e,t,"education"),await e.evaluate(`(() => {
|
|
49
|
+
${mt}
|
|
50
50
|
|
|
51
51
|
const main = document.querySelector('main');
|
|
52
52
|
if (!main) return [];
|
|
@@ -82,8 +82,8 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
|
|
|
82
82
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
83
83
|
return true;
|
|
84
84
|
});
|
|
85
|
-
})()`)))}async function
|
|
86
|
-
${
|
|
85
|
+
})()`)))}async function Gi(e,t){return ht(t,"skills","extractSkillsFromDetails",async()=>(await pt(e,t,"skills"),await e.evaluate(`(() => {
|
|
86
|
+
${mt}
|
|
87
87
|
|
|
88
88
|
const main = document.querySelector('main');
|
|
89
89
|
if (!main) return [];
|
|
@@ -114,8 +114,8 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
|
|
|
114
114
|
skills.push({ name, endorsements, _raw: lines });
|
|
115
115
|
}
|
|
116
116
|
return skills;
|
|
117
|
-
})()`)))}async function
|
|
118
|
-
${
|
|
117
|
+
})()`)))}async function Wi(e,t){return ht(t,"certifications","extractCertificationsFromDetails",async()=>(await pt(e,t,"certifications"),await e.evaluate(`(() => {
|
|
118
|
+
${mt}
|
|
119
119
|
|
|
120
120
|
const main = document.querySelector('main');
|
|
121
121
|
if (!main) return [];
|
|
@@ -139,8 +139,8 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
|
|
|
139
139
|
|
|
140
140
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
141
141
|
}).filter(e => e.name);
|
|
142
|
-
})()`)))}async function
|
|
143
|
-
${
|
|
142
|
+
})()`)))}async function Yi(e,t){return ht(t,"recommendations","extractRecommendationsFromDetails",async()=>(await pt(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
143
|
+
${mt}
|
|
144
144
|
|
|
145
145
|
const main = document.querySelector('main');
|
|
146
146
|
if (!main) return [];
|
|
@@ -175,7 +175,7 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
|
|
|
175
175
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
176
176
|
return true;
|
|
177
177
|
});
|
|
178
|
-
})()`)))}var
|
|
178
|
+
})()`)))}var mt,On=fe(()=>{Ue();mt=`
|
|
179
179
|
function findEntryContainer(root) {
|
|
180
180
|
const candidates = [];
|
|
181
181
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -238,18 +238,18 @@ function findEntryContainer(root) {
|
|
|
238
238
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
239
239
|
return candidates[0]?.el;
|
|
240
240
|
}
|
|
241
|
-
`});var On={};te(On,{BLOCK_MARKERS:()=>Nn,dedupeAndCap:()=>Fn,extractSidePanelProfiles:()=>Hi,normalizeFundUrl:()=>Mt,normalizeProfileUrl:()=>Xe,scanRelatedBlocks:()=>Pn});function Xe(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let o=t[1].trim();return o?`https://www.linkedin.com/in/${o}/`:null}function Mt(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function Pn(e,t){let o=t||(typeof document<"u"?document:null);if(!o)return[];let r=c=>(c||"").replace(/\s+/g," ").trim(),n=c=>{let u=String(c||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},i=c=>r(c).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),s=c=>{let u=c,f=null;for(let d=0;d<6&&u.parentElement;d++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){f||(f=u);let p=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(p))return u}return f||c.parentElement},a=[],l=Array.from(o.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let c of l){let u=r(c.textContent).toLowerCase();if(!u)continue;let f=e.find(([g])=>u.includes(g));if(!f)continue;let d=f[1],p=s(c);if(!p)continue;let m=0,h=new Set;for(let g of Array.from(p.querySelectorAll('a[href*="/in/"]'))){let y=g.href||g.getAttribute("href")||"",S=n(y);if(!S)continue;let v=g.querySelector('span[aria-hidden="true"]'),b=r(v?v.textContent:g.getAttribute("aria-label")||g.textContent),E=i(b);if(!E||h.has(S))continue;h.add(S);let R="",I=b.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(I&&(R=r(I[1])),!R){let O=g.closest("li")||g.parentElement;O&&(R=Array.from(O.querySelectorAll("p, span")).map(T=>r(T.textContent)).filter(T=>T&&T!==E&&!/^view\b/i.test(T)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(T)&&/[a-z]/i.test(T)&&T.length>2)[0]||"")}a.push({href:y,name:E,headline:R,block:d,rank:m++})}}return a}function Fn(e,t={}){let o=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,r=Xe(t.seedUrl||""),n=new Map,i={};for(let s of e||[]){let a=Xe(s.href);a&&(r&&a===r||(i[s.block]=i[s.block]||0,!(i[s.block]>=o)&&(n.has(a)||(i[s.block]++,n.set(a,{url:a,name:s.name,headline:s.headline||null,block:s.block,rank:s.rank})))))}return Array.from(n.values())}async function Hi(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(r=>setTimeout(r,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(r=>setTimeout(r,1200))}catch{}let o;try{o=await e.evaluate(Pn,Nn)}catch{return[]}return Fn(o,t)}var Nn,wo=pe(()=>{Nn=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"]]});var Hn={};te(Hn,{getJobDecision:()=>Ao,getLastVisit:()=>es,getScoutStats:()=>ts,loadCompanies:()=>$o,loadDiscoveredPeople:()=>St,loadJobDecisions:()=>Eo,loadScoutedJobs:()=>xo,loadVisitLog:()=>Ht,recordCompany:()=>Xi,recordDiscoveredEdge:()=>zi,recordDiscoveredEdges:()=>Qi,recordVisit:()=>Zi,resetCaches:()=>vo,saveCompany:()=>Jt,saveDiscoveredPerson:()=>Yi,saveScoutedJob:()=>Co,setJobDecision:()=>Fe});import"dotenv/config";import*as re from"fs";import*as ee from"path";import{fileURLToPath as Vi}from"url";function Ae(){re.existsSync(Pe)||re.mkdirSync(Pe,{recursive:!0})}function $e(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";re.writeFileSync(r,o);for(let n=0;n<3;n++)try{re.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function wt(e){try{if(re.existsSync(e))return JSON.parse(re.readFileSync(e,"utf-8"))}catch{}return null}function vo(){ht=null,yt=null,gt=null,bt=null,Ne=null}function xo(){return ht||(ht=wt(qn)||{},ht)}function Co(e,t){if(!e)return;Ae();let o=xo(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[n,i]of Object.entries(t))i!=null&&(o[e][n]=i);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{$e(qn,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}function Eo(){return yt||(yt=wt(Un)||{},yt)}function Fe(e,t,o={}){if(!e||!t)return;Ae();let r=Eo(),n=new Date().toISOString().slice(0,10);r[e]?(r[e].status=t,r[e].updatedAt=n,o.reason&&(r[e].reason=o.reason),o.score!=null&&(r[e].score=o.score),o.source&&(r[e].source=o.source)):r[e]={status:t,decidedAt:n,updatedAt:n,reason:o.reason||null,score:o.score??null,source:o.source||null};try{$e(Un,r)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function Ao(e){return Eo()[e]||null}function St(){return gt||(gt=wt(Bt)||{},gt)}function Ze(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Bn(e,t){let o=Xe(t)||t;if(e[o])return o;let r=Ze(t);if(!r)return o;let n=null;for(let[i,s]of Object.entries(e)){if(Ze(s&&(s.canonicalUrl||s.profileUrl)||i)===r)return i;!n&&s&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}return n||o}function Yi(e,t){if(!e)return;Ae();let o=St(),r=new Date().toISOString().slice(0,10),n=Bn(o,e),i=Ze(e);if(o[n]){let s=o[n];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),i&&Ze(s.canonicalUrl||s.profileUrl||n)!==i&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(i)||s.aliases.push(i)),s.lastSeen=r,s.seenCount=(s.seenCount||1)+1}else o[n]={canonicalUrl:n,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:r,lastSeen:r,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{$e(Bt,o)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function Ki(e,t){let o=e.kind||"similar-panel";return o==="list-post"?{edge:{kind:o,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:r=>r.kind==="list-post"&&r.postUrl===(e.postUrl||null)&&r.fund===(e.fund||null)}:o==="scout"?{edge:{kind:o,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:r=>r.kind==="scout"&&r.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:r=>r.kind!=="list-post"&&r.kind!=="scout"&&r.seedUrl===(e.seedUrl||null)&&r.block===(e.block||"unknown")}}function Jn(e,t,o={},r){if(!t)return;let n=Ze(t);t=Bn(e,t);let i=o.seedUrl?{...o,seedUrl:Xe(o.seedUrl)||o.seedUrl}:o,s=r.slice(0,10),{edge:a,match:l}=Ki(i,r),c=e[t];c||(c=e[t]={canonicalUrl:t,aliases:[],name:o.name||null,headline:o.headline||null,location:o.location||null,company:o.company||null,companyUrl:o.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:a.kind,sources:[],connectionsCount:o.connectionsCount??null,selectivity:o.selectivity||"unknown",connectGate:o.connectGate||"unknown",score:null,fitScore:null,isConnected:o.isConnected||!1,graphRefs:[],note:o.note||"",whyUseful:o.whyUseful||"",extra:{},source:a.kind,role:Array.isArray(o.categories)&&o.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:s,firstSeen:s,lastSeen:s}),o.name&&(c.name=o.name),o.headline&&(!c.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(c.headline))&&(c.headline=o.headline),o.location&&(c.location=c.location||o.location),o.company&&(c.company=o.company),o.companyUrl&&(c.companyUrl=c.companyUrl||o.companyUrl),o.isConnected!=null&&(c.isConnected=o.isConnected),o.connectionsCount!=null&&(c.connectionsCount=o.connectionsCount),o.selectivity&&o.selectivity!=="unknown"&&(c.selectivity=o.selectivity),o.connectGate&&o.connectGate!=="unknown"&&(c.connectGate=o.connectGate),o.note&&!c.note&&(c.note=o.note),o.whyUseful&&!c.whyUseful&&(c.whyUseful=o.whyUseful),o.extra&&typeof o.extra=="object"&&(c.extra={...c.extra||{},...o.extra}),Array.isArray(c.sources)||(c.sources=[]);let u=c.sources.find(l);if(u?(a.rank!=null&&(u.rank==null||a.rank<u.rank)&&(u.rank=a.rank),u.at=a.at):c.sources.push(a),Array.isArray(c.categories)||(c.categories=[]),Array.isArray(c.sectors)||(c.sectors=[]),Array.isArray(c.aliases)||(c.aliases=[]),Array.isArray(c.graphRefs)||(c.graphRefs=[]),So(c.categories,o.category),Ut(c.categories,o.categories),Ut(c.sectors,o.sectors),Ut(c.aliases,o.aliases),n&&Ze(c.canonicalUrl||t)!==n&&So(c.aliases,n),Ut(c.graphRefs,o.graphRefs),Array.isArray(o.affiliations)){Array.isArray(c.affiliations)||(c.affiliations=[]);for(let f of o.affiliations)!f||!f.companyKey||c.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||c.affiliations.push(f)}c.lastSeen=s,c.seenCount=(c.seenCount||0)+1}function zi(e,t={}){if(!e)return;Ae();let o=St();Jn(o,e,t,new Date().toISOString());try{$e(Bt,o)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function Qi(e){if(!Array.isArray(e)||e.length===0)return;Ae();let t=St(),o=new Date().toISOString(),r=0;for(let n of e)!n||!n.url||(Jn(t,n.url,n,o),r++);if(r)try{$e(Bt,t)}catch(n){console.error(`[!] Failed to save discovered-people.json: ${n.message}`)}}function Xi(e={}){if(!e||!e.name)return;Ae();let t=e.key||Mt(e.website)||Mt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,o=$o(),r=new Date().toISOString().slice(0,10),n=(l,c)=>{c&&Array.isArray(l)&&!l.includes(c)&&l.push(c)},i=(l,c)=>{if(Array.isArray(c))for(let u of c)n(l,u)},s=o[t];s||(s=o[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:r,lastSeen:r}),e.name&&(s.name=e.name),e.website&&(s.website=s.website||e.website),e.linkedinUrl&&(s.linkedinUrl=s.linkedinUrl||e.linkedinUrl);for(let l of["size","check","stage","location","industries","about"])e[l]&&!s[l]&&(s[l]=e[l]);e.note&&!s.note&&(s.note=e.note),e.whyUseful&&!s.whyUseful&&(s.whyUseful=e.whyUseful),e.fitScore!=null&&(s.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(s.extra={...s.extra||{},...e.extra});for(let l of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(s[l])||(s[l]=[]),i(s[l],e[l]);Array.isArray(s.people)||(s.people=[]);let a=l=>{if(!l||!l.url)return;let c=s.people.find(u=>u.url===l.url&&(u.role||null)===(l.role||null));c?l.current!=null&&(c.current=l.current):s.people.push({url:l.url,name:l.name||null,role:l.role||null,current:l.current??null,from:l.from??null,to:l.to??null})};(e.people||[]).forEach(a),(e.partners||[]).forEach(l=>a({url:l.url,name:l.name,role:"Partner",current:!0})),Array.isArray(s.portfolio)||(s.portfolio=[]);for(let l of e.portfolio||[]){let c=l&&(l.key||l.name);c&&!s.portfolio.some(u=>(u.key||u.name)===c)&&s.portfolio.push(l)}s.lastSeen=r,s.seenCount=(s.seenCount||0)+1;try{$e(ko,o)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function $o(){return bt||(bt=wt(ko)||{},bt)}function Jt(e,t){if(!e)return;Ae();let o=$o(),r=new Date().toISOString().slice(0,10);if(o[e]){let n=o[e];t.name&&(n.name=t.name),t.about&&(n.about=t.about),t.size&&(n.size=t.size),t.industries&&(n.industries=t.industries),t.jobId&&(n.jobIds||(n.jobIds=[]),n.jobIds.includes(t.jobId)||n.jobIds.push(t.jobId)),t.recruiterUrl&&(n.recruiterUrls||(n.recruiterUrls=[]),n.recruiterUrls.includes(t.recruiterUrl)||n.recruiterUrls.push(t.recruiterUrl)),n.lastSeen=r,n.jobCount=n.jobIds?.length||0}else o[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:r,lastSeen:r,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{$e(ko,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}function Ht(){return Ne||(Ne=wt(Mn)||{visits:[]},Array.isArray(Ne.visits)||(Ne.visits=[]),Ne)}function Zi(e,t={}){if(!e)return;Ae();let o=Ht();o.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let r=Date.now()-90*24*60*60*1e3;o.visits=o.visits.filter(n=>new Date(n.date).getTime()>r);try{$e(Mn,o)}catch(n){console.error(`[!] Failed to save visit-log.json: ${n.message}`)}}function es(e){let t=Ht();for(let o=t.visits.length-1;o>=0;o--)if(t.visits[o].profileUrl===e)return t.visits[o].date;return null}function ts(){let e=xo(),t=St(),o=Object.values(e),r=Object.values(t),n={};for(let d of o)d.company&&(n[d.company]=(n[d.company]||0)+1);let i=Object.entries(n).sort((d,p)=>p[1]-d[1]).slice(0,5).map(([d,p])=>`${d} (${p})`),s={};for(let d of o)for(let p of d.techStack||[])s[p]=(s[p]||0)+1;let a=Object.entries(s).sort((d,p)=>p[1]-d[1]).slice(0,8).map(([d,p])=>`${d} (${p})`),l=Ht(),c=new Date().toISOString().slice(0,10),u=l.visits.filter(d=>d.date.startsWith(c)).length,f=new Set(l.visits.map(d=>d.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:r.length,topCompanies:i,topTech:a,totalVisited:f,todayVisited:u,lastScoutDate:o.length>0?o.sort((d,p)=>(p.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var Gi,Wi,Pe,qn,Bt,Mn,ko,Un,ht,yt,gt,So,Ut,bt,Ne,Vt=pe(()=>{wo();Gi=Vi(import.meta.url),Wi=ee.dirname(ee.dirname(Gi)),Pe=process.env.DATA_DIR?ee.resolve(process.env.DATA_DIR,"market-research"):ee.join(Wi,"market-research"),qn=ee.join(Pe,"scouted-jobs.json"),Bt=ee.join(Pe,"discovered-people.json"),Mn=ee.join(Pe,"visit-log.json"),ko=ee.join(Pe,"companies.json"),Un=ee.join(Pe,"job-decisions.json");ht=null;yt=null;gt=null;So=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Ut=(e,t)=>{if(Array.isArray(t))for(let o of t)So(e,o)};bt=null;Ne=null});var tr={};te(tr,{computeEngagement:()=>To,detectCategory:()=>Wn,detectCategoryFromTitle:()=>Gt,determineAction:()=>Zn,determineLastMessageBy:()=>Kn,determineSituation:()=>Yn,enrichConversation:()=>os,enrichPerson:()=>as,enrichPersonContext:()=>er,extractAutoTags:()=>Qn,generateSummary:()=>zn,normPreview:()=>_o});function os(e,t,o){if(!e)return e;let n=(e.messages||[]).filter(l=>!ao.has(l.status)),i=rs(t,e.profileUrl,o),s=Kn(n,t);if(e.lastMessageBy=s,e.conversationStatus=s==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=Wn(n,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=Yn(n,s,t),n.length>0){let l=n[n.length-1];e.lastMessageTime=l.time}if(n.length>0&&!e.initiatedBy){let l=n[0];l.sender===ke?e.initiatedBy="us":l.sender!=="Unknown"&&l.sender!==""&&(e.initiatedBy="them")}e.engagement=To(n,t),e.personContext=er(i),e.summary=zn(e,t,i),e.autoTags=Qn(e,t,i);let a=Zn(e);return e.actionNeeded=a.action,e.actionDetail=a.detail,e.suggestedPriority=ns(e),e}function Wn(e,t,o){if(!e||e.length===0)return o?.title?Gt(o.title):null;let r=e.filter(n=>n.sender!==ke&&n.sender!=="Unknown"&&n.sender!=="").map(n=>n.text).join(" ");for(let[n,i]of Object.entries(Gn))if(i.theirMessages){for(let s of i.theirMessages)if(s.test(r))return n}if(o?.title){let n=Gt(o.title);if(n)return n}return null}function Gt(e){if(!e)return null;for(let[t,o]of Object.entries(Gn))if(o.title){for(let r of o.title)if(r.test(e))return t}return null}function Yn(e,t,o){if(!e||e.length===0)return"no_messages";let r=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return Vn.test(r.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let n=[...e].reverse().find(i=>i.sender!==ke&&i.sender!=="Unknown");return Vn.test(n?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Kn(e,t){if(!e||e.length===0)return"them";let o=[...e].map(n=>({m:n,t:Date.parse(n.time)})).filter(n=>Number.isFinite(n.t)).sort((n,i)=>i.t-n.t).map(n=>n.m),r=o.length>0?o:[...e].reverse();for(let n of r){let i=n.sender;if(i===ke)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function zn(e,t,o){let r=e.messages||[];if(r.length===0)return null;let n=[],i=e.category,s=o?.title,a=o?.company,l=o?.location;i==="recruiter"&&a?n.push(`Recruiter from ${a}`):i==="hiring_manager"&&a?n.push(`Hiring manager at ${a}`):i==="founder"&&a?n.push(`Founder of ${a}`):i&&s?n.push(`${Ro(i)}: ${et(s,40)}`):s?n.push(et(s,50)):n.push(t.split(" ")[0]);let c=r.filter(m=>m.sender!==ke&&m.sender!=="Unknown").map(m=>m.text).join(" "),u=is(c),f=ss(c),d=ls(c),p=[];return u&&p.push(u),d&&d!==l&&p.push(d),f&&p.push(f),p.length>0&&n.push(p.join(", ")),e.situation==="they_want_to_schedule_call"?n.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?n.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?n.push("needs reply"):e.conversationStatus==="awaiting_reply"&&n.push("waiting on them"),n.join(". ").replace(/\.\./g,".")}function Qn(e,t,o){let r=[],n=(e.messages||[]).filter(c=>!ao.has(c.status)),i=n.map(c=>c.text).join(" "),s=n.filter(c=>c.sender!==ke&&c.sender!=="Unknown").map(c=>c.text).join(" "),a=Xn(s,o?.location);r.push(...a),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&r.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&r.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&r.push("remote"),/\b(hybrid)\b/i.test(i)&&r.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&r.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&r.push("java"),/\b(python)\b/i.test(i)&&r.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&r.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&r.push("backend"),/\b(full.?stack)\b/i.test(i)&&r.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&r.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&r.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&r.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&r.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&r.push("has-salary");let l=e.engagement||To(n,t);return l.messageCount>=6&&r.push("active-thread"),l.theirCount===0&&l.ourCount>0&&r.push("no-response"),l.ourCount===0&&l.theirCount>0&&r.push("unanswered"),e.situation==="they_want_to_schedule_call"&&r.push("hot-lead"),(e.messages||[]).some(c=>lo.has(c.status))&&r.push("has-draft"),[...new Set(r)]}function Xn(e,t){let o=[],r=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],n=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let s of r)i.includes(s)&&o.push(s.replace(/\s+/g,"-"));for(let[s,a]of n)i.includes(s)&&o.push(a);return o}function Zn(e){let{category:t,situation:o,conversationStatus:r}=e;if(e.dismissedAtPreview&&_o(e.lastMessagePreview)===_o(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let n=(e.messages||[]).find(i=>lo.has(i.status));return n?n.status===he.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:r==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:o==="no_messages"?{action:"none",detail:"No messages read yet."}:o==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:o==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${Ro(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:o==="active_conversation_needs_our_reply"||o==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function To(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let o=0,r=0,n=0,i=!1,s=!1,a=e.map(l=>l.text).join(" ");for(let l of e)l.sender===ke?o++:l.sender==="Unknown"||l.sender===""?n++:r++;return i=/\b(job|role|position|opening)\b/i.test(a),s=/\$[\d,]+|\d+k|\d+\/hr/i.test(a),{messageCount:e.length,theirCount:r,ourCount:o,unknownCount:n,hasJob:i,hasSalary:s}}function er(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function ns(e){let{category:t,situation:o,engagement:r}=e;return o==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(o==="active_conversation_needs_our_reply"||o==="needs_our_reply")?r?.messageCount>=4?"high":"medium":t==="recruiter"&&o==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function rs(e,t,o){if(!o)return null;if(t&&o[t])return o[t];if(t){let n=xe(o,t,e);if(o[n])return o[n]}if(!e)return null;let r=Object.values(o).filter(n=>n.name===e);return r.length===1?r[0]:null}function _o(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Ro(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function et(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function is(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let o=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return o?o[1]:null}function ss(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function ls(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function as(e,t){if(!e)return e;if(e.categorySource!=="manual"){let r=Gt(e.title);r&&(e.category=r,e.categorySource=e.categorySource||"title")}cs(e),e.personSummary=us(e),e.personAutoTags=ds(e);let o=fs(e);return e.personActionNeeded=o.action,e.personActionDetail=o.detail,e.personPriorityManual||(e.personPriority=ps(e)),e}function cs(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(o=>o.jobTitle).sort((o,r)=>(r.date||"").localeCompare(o.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function us(e){let t=[],o=e.category,r=e.title,n=e.company,i=e.location;if(o==="recruiter"&&n?t.push(`Recruiter at ${n}`):o==="hiring_manager"&&n?t.push(`Hiring manager at ${n}`):o==="founder"&&n?t.push(`Founder of ${n}`):r&&n?t.push(`${et(r,40)} at ${et(n,30)}`):r?t.push(et(r,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let s=new Date(e.connectionDate);if(!isNaN(s)){let a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${a[s.getMonth()]} ${s.getDate()}`)}}if(e.jobCount>0){let s=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(s+=` (last: ${et(e.lastJobTitle,30)}`,e.lastJobDate){let a=new Date(e.lastJobDate);isNaN(a)||(s+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][a.getMonth()]} ${a.getDate()}`)}s+=")"}t.push(s)}return t.join(". ").replace(/\.\./g,".")||null}function ds(e){let t=[],o=[e.title,e.company,e.location].filter(Boolean).join(" "),r=Xn("",e.location);return t.push(...r),e.category&&t.push(e.category),/\b(java)\b/i.test(o)&&!/javascript/i.test(o)&&t.push("java"),/\b(python)\b/i.test(o)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(o)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(o)&&t.push("backend"),/\b(full.?stack)\b/i.test(o)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(o)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(o)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(o)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(o)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(o)&&t.push("staffing"),[...new Set(t)]}function fs(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${Ro(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function ps(e){let t=e.category;if(!t)return null;let o=ms(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&o?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&o?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function ms(e,t){if(!e.connectionDate)return!1;let o=new Date(e.connectionDate);if(isNaN(o))return!1;let r=new Date;return r.setDate(r.getDate()-t),o>=r}var Gn,Vn,or=pe(async()=>{await co();await Qe();Gn={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};Vn=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var rr={};te(rr,{DEFAULT_PROFILE_INTERESTS:()=>nr,computeFit:()=>gs,detectSectors:()=>ys});function ys(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),o=[];for(let[r,n]of Object.entries(hs))n.some(i=>i.test(t))&&o.push(r);return o}function gs(e,t=nr){if(!Array.isArray(e)||e.length===0)return 0;let o=i=>typeof i=="number"&&Number.isFinite(i)?i:0,r=Math.max(1,...Object.values(t||{}).map(o)),n=0;for(let i of e){let s=o(t&&t[i]);s>n&&(n=s)}return Math.min(1,n/r)}var hs,nr,ir=pe(()=>{hs={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};nr={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});Ue();import zr from"puppeteer";import*as ii from"fs";import{createGraphClient as yi,resolveToken as gi}from"@ilivemylife/graph-sdk";import{config as bi}from"dotenv";bi();var cn=gi()||process.env.TOKEN;cn||(console.error(`
|
|
241
|
+
`});var Bn={};te(Bn,{BLOCK_MARKERS:()=>qn,dedupeAndCap:()=>Un,extractSidePanelProfiles:()=>Ki,normalizeFundUrl:()=>Bt,normalizeProfileUrl:()=>Xe,scanRelatedBlocks:()=>Mn});function Xe(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let o=t[1].trim();return o?`https://www.linkedin.com/in/${o}/`:null}function Bt(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function Mn(e,t){let o=t||(typeof document<"u"?document:null);if(!o)return[];let r=c=>(c||"").replace(/\s+/g," ").trim(),n=c=>{let u=String(c||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},i=c=>r(c).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),s=c=>{let u=c,f=null;for(let d=0;d<6&&u.parentElement;d++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){f||(f=u);let p=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(p))return u}return f||c.parentElement},a=[],l=Array.from(o.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let c of l){let u=r(c.textContent).toLowerCase();if(!u)continue;let f=e.find(([g])=>u.includes(g));if(!f)continue;let d=f[1],p=s(c);if(!p)continue;let m=0,h=new Set;for(let g of Array.from(p.querySelectorAll('a[href*="/in/"]'))){let y=g.href||g.getAttribute("href")||"",S=n(y);if(!S)continue;let x=g.querySelector('span[aria-hidden="true"]'),b=r(x?x.textContent:g.getAttribute("aria-label")||g.textContent),E=i(b);if(!E||h.has(S))continue;h.add(S);let R="",L=b.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(L&&(R=r(L[1])),!R){let A=g.closest("li")||g.parentElement;A&&(R=Array.from(A.querySelectorAll("p, span")).map(D=>r(D.textContent)).filter(D=>D&&D!==E&&!/^view\b/i.test(D)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(D)&&/[a-z]/i.test(D)&&D.length>2)[0]||"")}a.push({href:y,name:E,headline:R,block:d,rank:m++})}}return a}function Un(e,t={}){let o=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,r=Xe(t.seedUrl||""),n=new Map,i={};for(let s of e||[]){let a=Xe(s.href);a&&(r&&a===r||(i[s.block]=i[s.block]||0,!(i[s.block]>=o)&&(n.has(a)||(i[s.block]++,n.set(a,{url:a,name:s.name,headline:s.headline||null,block:s.block,rank:s.rank})))))}return Array.from(n.values())}async function Ki(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(r=>setTimeout(r,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(r=>setTimeout(r,1200))}catch{}let o;try{o=await e.evaluate(Mn,qn)}catch{return[]}return Un(o,t)}var qn,xo=fe(()=>{qn=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"]]});var Yn={};te(Yn,{getJobDecision:()=>Ro,getLastVisit:()=>is,getScoutStats:()=>ss,loadCompanies:()=>Io,loadDiscoveredPeople:()=>kt,loadJobDecisions:()=>To,loadScoutedJobs:()=>_o,loadVisitLog:()=>Gt,recordCompany:()=>ns,recordDiscoveredEdge:()=>ts,recordDiscoveredEdges:()=>os,recordVisit:()=>rs,resetCaches:()=>Ao,saveCompany:()=>Vt,saveDiscoveredPerson:()=>Zi,saveScoutedJob:()=>$o,setJobDecision:()=>Fe});import"dotenv/config";import*as re from"fs";import*as ee from"path";import{fileURLToPath as zi}from"url";function Ce(){re.existsSync(Pe)||re.mkdirSync(Pe,{recursive:!0})}function Ee(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";re.writeFileSync(r,o);for(let n=0;n<3;n++)try{re.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function St(e){try{if(re.existsSync(e))return JSON.parse(re.readFileSync(e,"utf-8"))}catch{}return null}function Ao(){yt=null,gt=null,bt=null,wt=null,Ne=null}function _o(){return yt||(yt=St(Jn)||{},yt)}function $o(e,t){if(!e)return;Ce();let o=_o(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[n,i]of Object.entries(t))i!=null&&(o[e][n]=i);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{Ee(Jn,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}function To(){return gt||(gt=St(Vn)||{},gt)}function Fe(e,t,o={}){if(!e||!t)return;Ce();let r=To(),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{Ee(Vn,r)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function Ro(e){return To()[e]||null}function kt(){return bt||(bt=St(Ht)||{},bt)}function Ze(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Gn(e,t){let o=Xe(t)||t;if(e[o])return o;let r=Ze(t);if(!r)return o;let n=null;for(let[i,s]of Object.entries(e)){if(Ze(s&&(s.canonicalUrl||s.profileUrl)||i)===r)return i;!n&&s&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}return n||o}function Zi(e,t){if(!e)return;Ce();let o=kt(),r=new Date().toISOString().slice(0,10),n=Gn(o,e),i=Ze(e);if(o[n]){let s=o[n];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),i&&Ze(s.canonicalUrl||s.profileUrl||n)!==i&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(i)||s.aliases.push(i)),s.lastSeen=r,s.seenCount=(s.seenCount||1)+1}else o[n]={canonicalUrl:n,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:r,lastSeen:r,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{Ee(Ht,o)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function es(e,t){let o=e.kind||"similar-panel";return o==="list-post"?{edge:{kind:o,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:r=>r.kind==="list-post"&&r.postUrl===(e.postUrl||null)&&r.fund===(e.fund||null)}:o==="scout"?{edge:{kind:o,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:r=>r.kind==="scout"&&r.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:r=>r.kind!=="list-post"&&r.kind!=="scout"&&r.seedUrl===(e.seedUrl||null)&&r.block===(e.block||"unknown")}}function Wn(e,t,o={},r){if(!t)return;let n=Ze(t);t=Gn(e,t);let i=o.seedUrl?{...o,seedUrl:Xe(o.seedUrl)||o.seedUrl}:o,s=r.slice(0,10),{edge:a,match:l}=es(i,r),c=e[t];c||(c=e[t]={canonicalUrl:t,aliases:[],name:o.name||null,headline:o.headline||null,location:o.location||null,company:o.company||null,companyUrl:o.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:a.kind,sources:[],connectionsCount:o.connectionsCount??null,selectivity:o.selectivity||"unknown",connectGate:o.connectGate||"unknown",score:null,fitScore:null,isConnected:o.isConnected||!1,graphRefs:[],note:o.note||"",whyUseful:o.whyUseful||"",extra:{},source:a.kind,role:Array.isArray(o.categories)&&o.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:s,firstSeen:s,lastSeen:s}),o.name&&(c.name=o.name),o.headline&&(!c.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(c.headline))&&(c.headline=o.headline),o.location&&(c.location=c.location||o.location),o.company&&(c.company=o.company),o.companyUrl&&(c.companyUrl=c.companyUrl||o.companyUrl),o.isConnected!=null&&(c.isConnected=o.isConnected),o.connectionsCount!=null&&(c.connectionsCount=o.connectionsCount),o.selectivity&&o.selectivity!=="unknown"&&(c.selectivity=o.selectivity),o.connectGate&&o.connectGate!=="unknown"&&(c.connectGate=o.connectGate),o.note&&!c.note&&(c.note=o.note),o.whyUseful&&!c.whyUseful&&(c.whyUseful=o.whyUseful),o.extra&&typeof o.extra=="object"&&(c.extra={...c.extra||{},...o.extra}),Array.isArray(c.sources)||(c.sources=[]);let u=c.sources.find(l);if(u?(a.rank!=null&&(u.rank==null||a.rank<u.rank)&&(u.rank=a.rank),u.at=a.at):c.sources.push(a),Array.isArray(c.categories)||(c.categories=[]),Array.isArray(c.sectors)||(c.sectors=[]),Array.isArray(c.aliases)||(c.aliases=[]),Array.isArray(c.graphRefs)||(c.graphRefs=[]),Co(c.categories,o.category),Jt(c.categories,o.categories),Jt(c.sectors,o.sectors),Jt(c.aliases,o.aliases),n&&Ze(c.canonicalUrl||t)!==n&&Co(c.aliases,n),Jt(c.graphRefs,o.graphRefs),Array.isArray(o.affiliations)){Array.isArray(c.affiliations)||(c.affiliations=[]);for(let f of o.affiliations)!f||!f.companyKey||c.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||c.affiliations.push(f)}c.lastSeen=s,c.seenCount=(c.seenCount||0)+1}function ts(e,t={}){if(!e)return;Ce();let o=kt();Wn(o,e,t,new Date().toISOString());try{Ee(Ht,o)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function os(e){if(!Array.isArray(e)||e.length===0)return;Ce();let t=kt(),o=new Date().toISOString(),r=0;for(let n of e)!n||!n.url||(Wn(t,n.url,n,o),r++);if(r)try{Ee(Ht,t)}catch(n){console.error(`[!] Failed to save discovered-people.json: ${n.message}`)}}function ns(e={}){if(!e||!e.name)return;Ce();let t=e.key||Bt(e.website)||Bt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,o=Io(),r=new Date().toISOString().slice(0,10),n=(l,c)=>{c&&Array.isArray(l)&&!l.includes(c)&&l.push(c)},i=(l,c)=>{if(Array.isArray(c))for(let u of c)n(l,u)},s=o[t];s||(s=o[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:r,lastSeen:r}),e.name&&(s.name=e.name),e.website&&(s.website=s.website||e.website),e.linkedinUrl&&(s.linkedinUrl=s.linkedinUrl||e.linkedinUrl);for(let l of["size","check","stage","location","industries","about"])e[l]&&!s[l]&&(s[l]=e[l]);e.note&&!s.note&&(s.note=e.note),e.whyUseful&&!s.whyUseful&&(s.whyUseful=e.whyUseful),e.fitScore!=null&&(s.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(s.extra={...s.extra||{},...e.extra});for(let l of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(s[l])||(s[l]=[]),i(s[l],e[l]);Array.isArray(s.people)||(s.people=[]);let a=l=>{if(!l||!l.url)return;let c=s.people.find(u=>u.url===l.url&&(u.role||null)===(l.role||null));c?l.current!=null&&(c.current=l.current):s.people.push({url:l.url,name:l.name||null,role:l.role||null,current:l.current??null,from:l.from??null,to:l.to??null})};(e.people||[]).forEach(a),(e.partners||[]).forEach(l=>a({url:l.url,name:l.name,role:"Partner",current:!0})),Array.isArray(s.portfolio)||(s.portfolio=[]);for(let l of e.portfolio||[]){let c=l&&(l.key||l.name);c&&!s.portfolio.some(u=>(u.key||u.name)===c)&&s.portfolio.push(l)}s.lastSeen=r,s.seenCount=(s.seenCount||0)+1;try{Ee(Eo,o)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function Io(){return wt||(wt=St(Eo)||{},wt)}function Vt(e,t){if(!e)return;Ce();let o=Io(),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{Ee(Eo,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}function Gt(){return Ne||(Ne=St(Hn)||{visits:[]},Array.isArray(Ne.visits)||(Ne.visits=[]),Ne)}function rs(e,t={}){if(!e)return;Ce();let o=Gt();o.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let r=Date.now()-90*24*60*60*1e3;o.visits=o.visits.filter(n=>new Date(n.date).getTime()>r);try{Ee(Hn,o)}catch(n){console.error(`[!] Failed to save visit-log.json: ${n.message}`)}}function is(e){let t=Gt();for(let o=t.visits.length-1;o>=0;o--)if(t.visits[o].profileUrl===e)return t.visits[o].date;return null}function ss(){let e=_o(),t=kt(),o=Object.values(e),r=Object.values(t),n={};for(let d of o)d.company&&(n[d.company]=(n[d.company]||0)+1);let i=Object.entries(n).sort((d,p)=>p[1]-d[1]).slice(0,5).map(([d,p])=>`${d} (${p})`),s={};for(let d of o)for(let p of d.techStack||[])s[p]=(s[p]||0)+1;let a=Object.entries(s).sort((d,p)=>p[1]-d[1]).slice(0,8).map(([d,p])=>`${d} (${p})`),l=Gt(),c=new Date().toISOString().slice(0,10),u=l.visits.filter(d=>d.date.startsWith(c)).length,f=new Set(l.visits.map(d=>d.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:r.length,topCompanies:i,topTech:a,totalVisited:f,todayVisited:u,lastScoutDate:o.length>0?o.sort((d,p)=>(p.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var Qi,Xi,Pe,Jn,Ht,Hn,Eo,Vn,yt,gt,bt,Co,Jt,wt,Ne,Wt=fe(()=>{xo();Qi=zi(import.meta.url),Xi=ee.dirname(ee.dirname(Qi)),Pe=process.env.DATA_DIR?ee.resolve(process.env.DATA_DIR,"market-research"):ee.join(Xi,"market-research"),Jn=ee.join(Pe,"scouted-jobs.json"),Ht=ee.join(Pe,"discovered-people.json"),Hn=ee.join(Pe,"visit-log.json"),Eo=ee.join(Pe,"companies.json"),Vn=ee.join(Pe,"job-decisions.json");yt=null;gt=null;bt=null;Co=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Jt=(e,t)=>{if(Array.isArray(t))for(let o of t)Co(e,o)};wt=null;Ne=null});var ir={};te(ir,{computeEngagement:()=>Do,detectCategory:()=>Qn,detectCategoryFromTitle:()=>Yt,determineAction:()=>nr,determineLastMessageBy:()=>Zn,determineSituation:()=>Xn,enrichConversation:()=>ls,enrichPerson:()=>ps,enrichPersonContext:()=>rr,extractAutoTags:()=>tr,generateSummary:()=>er,normPreview:()=>jo});function ls(e,t,o){if(!e)return e;let n=(e.messages||[]).filter(l=>!po.has(l.status)),i=cs(t,e.profileUrl,o),s=Zn(n,t);if(e.lastMessageBy=s,e.conversationStatus=s==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=Qn(n,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=Xn(n,s,t),n.length>0){let l=n[n.length-1];e.lastMessageTime=l.time}if(n.length>0&&!e.initiatedBy){let l=n[0];l.sender===we?e.initiatedBy="us":l.sender!=="Unknown"&&l.sender!==""&&(e.initiatedBy="them")}e.engagement=Do(n,t),e.personContext=rr(i),e.summary=er(e,t,i),e.autoTags=tr(e,t,i);let a=nr(e);return e.actionNeeded=a.action,e.actionDetail=a.detail,e.suggestedPriority=as(e),e}function Qn(e,t,o){if(!e||e.length===0)return o?.title?Yt(o.title):null;let r=e.filter(n=>n.sender!==we&&n.sender!=="Unknown"&&n.sender!=="").map(n=>n.text).join(" ");for(let[n,i]of Object.entries(zn))if(i.theirMessages){for(let s of i.theirMessages)if(s.test(r))return n}if(o?.title){let n=Yt(o.title);if(n)return n}return null}function Yt(e){if(!e)return null;for(let[t,o]of Object.entries(zn))if(o.title){for(let r of o.title)if(r.test(e))return t}return null}function Xn(e,t,o){if(!e||e.length===0)return"no_messages";let r=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return Kn.test(r.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let n=[...e].reverse().find(i=>i.sender!==we&&i.sender!=="Unknown");return Kn.test(n?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Zn(e,t){if(!e||e.length===0)return"them";let o=[...e].map(n=>({m:n,t:Date.parse(n.time)})).filter(n=>Number.isFinite(n.t)).sort((n,i)=>i.t-n.t).map(n=>n.m),r=o.length>0?o:[...e].reverse();for(let n of r){let i=n.sender;if(i===we)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function er(e,t,o){let r=e.messages||[];if(r.length===0)return null;let n=[],i=e.category,s=o?.title,a=o?.company,l=o?.location;i==="recruiter"&&a?n.push(`Recruiter from ${a}`):i==="hiring_manager"&&a?n.push(`Hiring manager at ${a}`):i==="founder"&&a?n.push(`Founder of ${a}`):i&&s?n.push(`${Lo(i)}: ${et(s,40)}`):s?n.push(et(s,50)):n.push(t.split(" ")[0]);let c=r.filter(m=>m.sender!==we&&m.sender!=="Unknown").map(m=>m.text).join(" "),u=us(c),f=ds(c),d=fs(c),p=[];return u&&p.push(u),d&&d!==l&&p.push(d),f&&p.push(f),p.length>0&&n.push(p.join(", ")),e.situation==="they_want_to_schedule_call"?n.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?n.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?n.push("needs reply"):e.conversationStatus==="awaiting_reply"&&n.push("waiting on them"),n.join(". ").replace(/\.\./g,".")}function tr(e,t,o){let r=[],n=(e.messages||[]).filter(c=>!po.has(c.status)),i=n.map(c=>c.text).join(" "),s=n.filter(c=>c.sender!==we&&c.sender!=="Unknown").map(c=>c.text).join(" "),a=or(s,o?.location);r.push(...a),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&r.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&r.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&r.push("remote"),/\b(hybrid)\b/i.test(i)&&r.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&r.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&r.push("java"),/\b(python)\b/i.test(i)&&r.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&r.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&r.push("backend"),/\b(full.?stack)\b/i.test(i)&&r.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&r.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&r.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&r.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&r.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&r.push("has-salary");let l=e.engagement||Do(n,t);return l.messageCount>=6&&r.push("active-thread"),l.theirCount===0&&l.ourCount>0&&r.push("no-response"),l.ourCount===0&&l.theirCount>0&&r.push("unanswered"),e.situation==="they_want_to_schedule_call"&&r.push("hot-lead"),(e.messages||[]).some(c=>fo.has(c.status))&&r.push("has-draft"),[...new Set(r)]}function or(e,t){let o=[],r=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],n=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let s of r)i.includes(s)&&o.push(s.replace(/\s+/g,"-"));for(let[s,a]of n)i.includes(s)&&o.push(a);return o}function nr(e){let{category:t,situation:o,conversationStatus:r}=e;if(e.dismissedAtPreview&&jo(e.lastMessagePreview)===jo(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let n=(e.messages||[]).find(i=>fo.has(i.status));return n?n.status===me.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:r==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:o==="no_messages"?{action:"none",detail:"No messages read yet."}:o==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:o==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${Lo(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:o==="active_conversation_needs_our_reply"||o==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function Do(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let o=0,r=0,n=0,i=!1,s=!1,a=e.map(l=>l.text).join(" ");for(let l of e)l.sender===we?o++:l.sender==="Unknown"||l.sender===""?n++:r++;return i=/\b(job|role|position|opening)\b/i.test(a),s=/\$[\d,]+|\d+k|\d+\/hr/i.test(a),{messageCount:e.length,theirCount:r,ourCount:o,unknownCount:n,hasJob:i,hasSalary:s}}function rr(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function as(e){let{category:t,situation:o,engagement:r}=e;return o==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(o==="active_conversation_needs_our_reply"||o==="needs_our_reply")?r?.messageCount>=4?"high":"medium":t==="recruiter"&&o==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function cs(e,t,o){if(!o)return null;if(t&&o[t])return o[t];if(t){let n=ke(o,t,e);if(o[n])return o[n]}if(!e)return null;let r=Object.values(o).filter(n=>n.name===e);return r.length===1?r[0]:null}function jo(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Lo(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function et(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function us(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let o=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return o?o[1]:null}function ds(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function fs(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function ps(e,t){if(!e)return e;if(e.categorySource!=="manual"){let r=Yt(e.title);r&&(e.category=r,e.categorySource=e.categorySource||"title")}ms(e),e.personSummary=hs(e),e.personAutoTags=ys(e);let o=gs(e);return e.personActionNeeded=o.action,e.personActionDetail=o.detail,e.personPriorityManual||(e.personPriority=bs(e)),e}function ms(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(o=>o.jobTitle).sort((o,r)=>(r.date||"").localeCompare(o.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function hs(e){let t=[],o=e.category,r=e.title,n=e.company,i=e.location;if(o==="recruiter"&&n?t.push(`Recruiter at ${n}`):o==="hiring_manager"&&n?t.push(`Hiring manager at ${n}`):o==="founder"&&n?t.push(`Founder of ${n}`):r&&n?t.push(`${et(r,40)} at ${et(n,30)}`):r?t.push(et(r,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let s=new Date(e.connectionDate);if(!isNaN(s)){let a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${a[s.getMonth()]} ${s.getDate()}`)}}if(e.jobCount>0){let s=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(s+=` (last: ${et(e.lastJobTitle,30)}`,e.lastJobDate){let a=new Date(e.lastJobDate);isNaN(a)||(s+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][a.getMonth()]} ${a.getDate()}`)}s+=")"}t.push(s)}return t.join(". ").replace(/\.\./g,".")||null}function ys(e){let t=[],o=[e.title,e.company,e.location].filter(Boolean).join(" "),r=or("",e.location);return t.push(...r),e.category&&t.push(e.category),/\b(java)\b/i.test(o)&&!/javascript/i.test(o)&&t.push("java"),/\b(python)\b/i.test(o)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(o)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(o)&&t.push("backend"),/\b(full.?stack)\b/i.test(o)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(o)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(o)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(o)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(o)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(o)&&t.push("staffing"),[...new Set(t)]}function gs(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${Lo(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function bs(e){let t=e.category;if(!t)return null;let o=ws(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&o?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&o?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function ws(e,t){if(!e.connectionDate)return!1;let o=new Date(e.connectionDate);if(isNaN(o))return!1;let r=new Date;return r.setDate(r.getDate()-t),o>=r}var zn,Kn,sr=fe(async()=>{await mo();await Qe();zn={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};Kn=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var ar={};te(ar,{DEFAULT_PROFILE_INTERESTS:()=>lr,computeFit:()=>vs,detectSectors:()=>ks});function ks(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),o=[];for(let[r,n]of Object.entries(Ss))n.some(i=>i.test(t))&&o.push(r);return o}function vs(e,t=lr){if(!Array.isArray(e)||e.length===0)return 0;let o=i=>typeof i=="number"&&Number.isFinite(i)?i:0,r=Math.max(1,...Object.values(t||{}).map(o)),n=0;for(let i of e){let s=o(t&&t[i]);s>n&&(n=s)}return Math.min(1,n/r)}var Ss,lr,cr=fe(()=>{Ss={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};lr={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});Ue();import ei from"puppeteer";import*as ci from"fs";import{createGraphClient as ki,resolveToken as vi}from"@ilivemylife/graph-sdk";import{config as xi}from"dotenv";xi();var pn=vi()||process.env.TOKEN;pn||(console.error(`
|
|
242
242
|
[FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
|
|
243
243
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
244
244
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
245
|
-
`),process.exit(1));var Ie=yi({token:cn});var Be=12e4;async function Je(e,{retries:t=2}={}){let o=process.env.NODE_EASY_APPLY_MAIN;if(!o||o.startsWith("YOUR_"))throw new Error('NODE_EASY_APPLY_MAIN is not configured in .env. Create a node in iLiveMyLife, add "assist" tag, and set the node ID in .env. See README.md for setup instructions.');for(let r=1;r<=t;r++)try{let n=await Ie.askLifebot(o,e,{timeout:Be});return Be=Math.max(12e4,Be*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){Be=Math.min(Be*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(Be/1e3)}s...`);continue}throw n}}async function no(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let o=`Job application form field "${e}" \u2014 reply with ONLY the value to fill in, nothing else. `;return t&&(t==="Enter a decimal number larger than 0.0"&&(t="Enter a decimal number larger than 0"),o+=`Additional info: ${t}`),await Je(o)}async function Et(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Je(o)}async function it(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Je(o)}so();import{LIFEBOT_MESSAGE_TYPES as Qr}from"@ilivemylife/graph-sdk";Ue();await Qe();async function lr(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function sr(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function bs(e,t,o={}){let{extractExperience:r=!1,extractFeatured:n=!1,extractEducation:i=!1,extractSkills:s=!1,extractRecommendations:a=!1,extractCertifications:l=!1}=o;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await oe(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await lr(e,t));let u=0;for(let b=0;b<2;b++){let E=await e.evaluate(()=>document.body.scrollHeight);for(let I=1;I<=6;I++)await e.evaluate(O=>window.scrollTo(0,O),E*I/6),await w(900);let R=await e.evaluate(()=>document.body.scrollHeight);if(R===u)break;u=R}await w(800);let f=null;try{let b=e.url();b&&/\/in\/[^/?#]/.test(b)&&(f=b.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let b=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),E=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),R=_=>{let D=(_||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(D)},I={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},O=document.querySelector("main");if(!O)return I;let A=[...Array.from(O.querySelectorAll("h1")),...Array.from(O.querySelectorAll("h2"))],T=Array.from(O.querySelectorAll("h2")),Y=A.find(_=>{let D=_.textContent&&_.textContent.trim(),L=(D||"").replace(/\s*\(\d+\)$/,"").trim();return D&&D.length>1&&D.length<100&&!b.has(L)&&!E.has(L)}),K=Y?Y.textContent.trim():null,M=Y?Y.parentElement:null;for(;M&&M!==O&&!Array.from(M.children).filter(D=>D.tagName==="P").some(D=>{let L=D.textContent&&D.textContent.trim();return L&&L.length>5&&!R(L)});)M=M.parentElement;let $=null,W=null,N=null,q=null;if(M&&M!==O){let _=Array.from(M.children).filter(L=>L.tagName==="P").filter(L=>{let Se=L.textContent&&L.textContent.trim();return Se&&Se.length>5&&!R(Se)});if(_[0]&&($=_[0].textContent.trim()),_[1]){let L=_[1].textContent.trim().split(/\s*[·•]\s*/);W=L[0]||null,L.length>1&&(N=L.slice(1).join(" \xB7 "))}let D=Array.from(M.children).filter(L=>L.tagName==="DIV");for(let L=D.length-1;L>=0;L--){let Se=D[L].textContent&&D[L].textContent.trim();if(Se&&!(K&&Se.startsWith(K))&&(q=Se.split(/[·•]/)[0].trim(),q))break}}let G=null;if(M){let _=M.querySelectorAll("p, span, div");for(let D of _){let L=(D.textContent||"").trim().replace(/^[·•]\s*/,"");if(L==="1st"||L==="2nd"||L==="3rd"){G=L;break}}}let x=!!O.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),j=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=j&&j.src||null,B=O.textContent||"",J=null,fe=B.match(/(\d+\+?)\s+connections\b/i);fe&&(J=fe[1]+" connections");let we=null,en=B.match(/(\d+)\s+mutual connection/i),tn=B.match(/and\s+(\d+)\s+other mutual/i),ui=B.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);en?we=parseInt(en[1],10):tn?we=2+parseInt(tn[1],10):ui&&(we=2);let on=null,nn=null,rn=T.find(_=>_.textContent&&_.textContent.trim()==="About");if(rn){let _=rn.parentElement;for(;_&&_.tagName!=="SECTION";)_=_.parentElement;if(_){let D=(_.textContent||"").trim();D=D.replace(/^About\s*/,"").trim();let L=D.match(/Top skills\s*(.+?)$/i);if(L){let oo=L[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(mi=>mi.trim()).filter(Boolean);oo.length>0&&oo.length<10&&(nn=oo)}D=D.split(/\n?…\s*more/i)[0].trim(),D=D.split(/\n?\.\.\.\s*more/i)[0].trim(),D=D.split(/\bTop skills\b/i)[0].trim(),D=D.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),on=D||null}}let sn=null,ln=T.find(_=>_.textContent&&_.textContent.trim()==="Activity");if(ln){let _=ln.parentElement;for(;_&&_.tagName!=="SECTION";)_=_.parentElement;if(_){let D=(_.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);D&&(sn=parseInt(D[1].replace(/,/g,""),10))}}let di=[...new Set(T.map(_=>(_.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(_=>_&&_.length>1&&_.length<60&&_!==K).filter(_=>b.has(_)))],rt=document.body.textContent||"",fi=/#OpenToWork\b/i.test(rt)||/\bOpen to work\b/.test(rt),pi=/#Hiring\b/i.test(rt)||/\bI'?m hiring\b/i.test(rt)||/\bWe are hiring\b/i.test(rt);return{name:K,title:$,location:q,currentCompany:W,currentSchool:N,connectionDegree:G,hasVerifiedBadge:x,photoUrl:P,connectionsLevel:J,mutualConnectionsCount:we,followers:sn,openToWork:fi,hiring:pi,about:on,topSkills:nn,availableSections:di}});console.log(`Viewed: ${d.name} - ${d.title}`);let p=null,m=null,h=null,g=null,y=null,S=null;if(r||n||i||s||a||l){let b=await Promise.resolve().then(()=>(Ln(),jn));r&&(p=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),n&&(m=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),i&&(h=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),s&&(g=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${g.length} entries`)),a&&(y=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),l&&(S=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...p!==null&&{experience:p},...m!==null&&{featured:m},...h!==null&&{education:h},...g!==null&&{skillsFull:g},...y!==null&&{recommendations:y},...S!==null&&{certifications:S}}}catch(c){console.error(`Error viewing profile ${t}:`,c.message);try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(c.message||""))throw c;return null}}async function tt(e,{detail:t=!1}={}){let o=()=>e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=f=>f&&!f.closest(n),s=f=>Array.from(document.querySelectorAll(f)).filter(i),a=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,c=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:a.length,pendingLabels:a.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!c};return a.length>0?{status:"pending",debug:u}:l&&!c?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),r=await o();return!r.debug.pendingCount&&!r.debug.hasMessageBtn&&!r.debug.hasConnectBtn&&(await w(1500),r=await o()),console.log(" DEBUG connection status:",JSON.stringify(r.debug)),t?r:r.status}async function Io(e){let t=null,o=await e.evaluate(()=>{let c=document.querySelector("h1")?.textContent?.trim();if(c&&!c.includes("notification"))return c;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(c=u.textContent?.trim(),c&&!c.includes("notification")))return c;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let c=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});c.count>0&&console.log(` S0: ${c.count} custom-invite links: ${JSON.stringify(c.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),p=f.toLowerCase().split(" ")[0],m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let g=h.getBoundingClientRect();if(g.width===0||g.height===0||h.closest(m))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(p))return h}return null},o);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(o){let c=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${c}"`);let u=await e.evaluate(d=>{let p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(g=>{let y=g.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&p.test(y)}).map(g=>g.getAttribute("aria-label")?.slice(0,50))},c);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let p=document.querySelectorAll("button[aria-label]"),m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',h=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of p){if(g.closest(m))continue;let y=g.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&h.test(y))return g}return null},c);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let c=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();c.includes("invite")&&!c.includes(u)&&(console.log(` Skipping primary button: wrong person (${c})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let n=o?o.split(" ")[0].toLowerCase():"",i=null;for(let c of r){let u=await e.evaluate((f,d)=>{let p=f.className.includes("muted"),m=f.className.includes("sticky-header")||f.className.includes("sticky"),h=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,g=(f.getAttribute("aria-label")||"").toLowerCase(),y=g.includes("invite"),S=d?g.includes(d):!0;return{isMuted:p,isStickyHeader:m,inRecommendations:h,hasInvite:y,matchesName:S,ariaLabel:g}},c,n);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=c;break}}for(let c of r)c!==i&&await c.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let s=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let c of a){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),p=d.width>0&&d.height>0,m=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:m,top:d.top}},c);if(u.isVisible&&!u.isInStickyHeader){s=c,console.log(" Found More button by ID pattern (main)");break}}for(let c of a)c!==s&&await c.dispose().catch(()=>{});if(!s&&a.length>0&&(s=a[a.length-1],console.log(" Found More button by ID pattern (last)")),s||(s=await e.$('button[aria-label="More actions"]'),s&&console.log(" Found More button by aria-label")),!s){let c=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(p=>{let m=p.innerText?.trim(),h=p.getAttribute("aria-label")||"",g=p.getBoundingClientRect();return g.top<100||g.top>600||g.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let p=0;p<8&&d;p++){for(let m of d.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==f)return m;d=d.parentElement}return null});s=c?.asElement?.()||null,s||await c?.dispose?.().catch(()=>{}),s&&console.log(" Found More button by text (near profile actions)")}if(s)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),s),await w(500),await e.evaluate(d=>d.click(),s),await w(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let p=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let m of p){let h=m.querySelector('a[href*="custom-invite"]');if(h)return h;for(let g of m.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let m of d)for(let h of m.querySelectorAll('[role="menuitem"], a, div')){let g=h.innerText?.trim();g&&g.length<40&&p.push(g)}return[...new Set(p)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(c){console.log(" More dropdown click failed:",c.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(c=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(c||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let p=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(p))continue;let m=d.getBoundingClientRect();if(!(m.width===0||m.height===0)){if(p.includes("invite")){if(f&&p.includes(f))return d;continue}if(p==="connect")return d}}return null},o||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function ws(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let o=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),n=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV",s=(o.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(s))return console.log(` \u2717 Guard: refusing a non-connect control ("${o.ariaLabel}")`),"wrong_target";if(s.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!s.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${o.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(n){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await w(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await w(3e3)):(await e.evaluate(u=>u.click(),t),await w(3e3));let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let l=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),c=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${c}`:` \u26A0 No modal after connect click \u2014 ${c}`),"success"}async function Ss(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await w(1500);let o=await Io(e);if(o){await e.evaluate(n=>n.click(),o),await w(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r)return await ot(e,r)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function ot(e,t){let o='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',r=()=>e.evaluate(s=>{let a=l=>!!(l&&l.querySelector(s));return!(a(document)||a(document.querySelector("#interop-outlet")?.shadowRoot))},o),n=()=>e.evaluate(()=>{for(let s of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(s.innerText||""))return!0;return!1}),i=async()=>{let s=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(s)return s;let a=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,o);return s=a?.asElement?.()||null,s||await a?.dispose?.().catch(()=>{}),s};for(let s=0;s<2;s++){try{await t.evaluate(a=>a.click())}catch{}if(await w(3e3),await n())return!1;if(await r())return!0;if(s===0){let a=await i();if(!a)return await r();t=a,await w(600)}}return await r()}async function ks(e,t,o={}){let{source:r="unknown",skipQuotaGate:n=!1,skipQuotaRecord:i=!1}=o;if(!n){let a=ut();if(!a.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${a.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:a.reason,profileInfo:null}}let s=await vs(e,t,o);return s.connectionSent&&!i&&Ot(t,r),s}async function vs(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,skipIfPending:i=!0,skipIfConnected:s=!0,excludeLocations:a=[]}=o,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
246
|
-
--- Connecting: ${c} ---`),a.length>0){let y=Q()[t]?.location;if(sr(y,a))return console.log(` \u26A0 Excluded location (stored): ${y}`),l.reason="excluded_location",l.profileInfo={location:y},l}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(5e3),await oe(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await lr(e,t),await w(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(wo(),On)),{recordDiscoveredEdges:v}=await Promise.resolve().then(()=>(Vt(),Hn)),{detectCategoryFromTitle:b}=await or().then(()=>tr),{detectSectors:E}=await Promise.resolve().then(()=>(ir(),rr)),R=S(t)||t,I=await y(e,{seedUrl:R}),O=I.map(A=>{let T=A.headline?b(A.headline):null;return{url:A.url,seedUrl:R,block:A.block,rank:A.rank,name:A.name,headline:A.headline,categories:T?[T]:[],sectors:E(A.headline||"")}});v(O),I.length&&console.log(` \xB7 discovery: harvested ${I.length} related profiles`)}catch(y){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${y.message}`)}l.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),S=x=>{let j=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(j)},v={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},b=document.querySelector("main");if(!b)return v;let E=[...Array.from(b.querySelectorAll("h1")),...Array.from(b.querySelectorAll("h2"))],R=Array.from(b.querySelectorAll("h2")),I=E.find(x=>{let j=x.textContent&&x.textContent.trim();return j&&j.length>1&&j.length<100&&!y.has(j)&&j!=="0 notifications"}),O=I?I.textContent.trim():null,A=I?I.parentElement:null;for(;A&&A!==b&&!Array.from(A.children).filter(P=>P.tagName==="P").some(P=>{let B=P.textContent&&P.textContent.trim();return B&&B.length>5&&!S(B)});)A=A.parentElement;let T=null,Y=null,K=null;if(A&&A!==b){let x=Array.from(A.children),j=x.filter(B=>B.tagName==="P").filter(B=>{let J=B.textContent&&B.textContent.trim();return J&&J.length>5&&!S(J)});j[0]&&(T=j[0].textContent.trim()),j[1]&&(Y=j[1].textContent.trim());let P=x.filter(B=>B.tagName==="DIV");for(let B=P.length-1;B>=0;B--){let J=P[B].textContent&&P[B].textContent.trim();if(J&&!(O&&J.startsWith(O))&&(K=J.split(/[·•]/)[0].trim(),K))break}}let M=null;if(A){let x=A.querySelectorAll("p, span, div");for(let j of x){let P=(j.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){M=P;break}}}let $=null,W=R.find(x=>x.textContent&&x.textContent.trim()==="About");if(W){let x=W.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;x&&($=(x.textContent||"").trim().replace(/^About\s*/,"").trim()||null,$&&($=$.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let N=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),q=N&&N.src||null,G=!!b.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:O,title:T,location:K,about:$,company:Y,connectionDegree:M,connectionsCount:null,mutualConnections:null,photoUrl:q,hasVerifiedBadge:G}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(l.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(a.length>0){let y=l.profileInfo?.location,S=Q()[t]?.location,v=y||S;if(sr(v,a))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${v}`),l.reason="excluded_location",l;!y&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await tt(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await oe(e);let d=await Io(e);if(d||await oe(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),d=await Io(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!d){let y=await tt(e,{detail:!0});return s&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=d.method;let p=await ws(e,d.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let y=await tt(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await oe(e),await w(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(b=>b.scrollIntoView({behavior:"smooth",block:"center"}),S),await w(500),await S.click().catch(()=>e.evaluate(b=>b.click(),S)),await w(2e3);let v=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(v){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(R=>R.click(),v),await w(3e3);let b=e.url();if(b.includes("/premium/")||b.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),l.reason="premium_required",l;if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),l.reason="premium_required",l}catch(v){return console.log(" More dropdown failed:",v.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of y){let v=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!v)continue;let b=(v.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(b)||v.querySelector('input[type="email"], input[name="email"]'))return!0;let E=v.querySelector('button[aria-label="Send without a note"]');if(E&&(E.disabled||E.getAttribute("aria-disabled")==="true"||(E.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let y=await e.$('button[aria-label="Dismiss"]');if(y)try{await y.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await w(500),l.reason="email_required",l}let h=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!h&&!g){let y=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let v=S.querySelector('button[aria-label="Add a note"]'),b=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!v,sendWithout:!!b}});if(y.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=S?.asElement?.()||null,h||await S.dispose().catch(()=>{})}if(y.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=S?.asElement?.()||null,g||await S.dispose().catch(()=>{})}}if(n)if(h&&r){if(console.log(" Adding personalized note..."),await h.click(),await w(1500),await e.$("div.modal-upsell")){let v=await Ss(e);return l.success=v,l.connectionSent=v,l.reason=v?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let v=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),b=r.replace("{name}",v);await S.type(b,{delay:20}),await w(500);let E=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(E)return await ot(e,E)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=b,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(g)return console.log(" Sending without note..."),await ot(e,g)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(h&&!r){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await ot(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let y=g;if(y)return await ot(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3)),await oe(e),await w(500);let S=await e.$$('button[id*="profile-overflow-action"]'),v=null;for(let b of S){let E=await e.evaluate(R=>{let I=R.getBoundingClientRect();return{visible:I.width>0&&I.height>0,inSticky:!!R.closest('.sticky-header, [class*="sticky"]')}},b);if(E.visible&&!E.inSticky){v=b;break}}!v&&S.length>0&&(v=S[S.length-1]);for(let b of S)b!==v&&await b.dispose().catch(()=>{});if(v)try{await e.evaluate(E=>E.scrollIntoView({behavior:"smooth",block:"center"}),v),await w(500),await v.click().catch(()=>e.evaluate(E=>E.click(),v)),await w(2e3);let b=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(b){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(O=>O.click(),b),await w(3e3);let E=e.url();if(E.includes("/premium/")||E.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await tt(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let I=await e.$('button[aria-label="Send without a note"]');if(I)return console.log(" Modal appeared via More dropdown, sending without note..."),await ot(e,I)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(b){console.log(" More dropdown fallback failed:",b.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(c){console.error(` \u2717 Error: ${c.message}`),l.reason="error",l.error=c.message;let u=c.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{l.fatal=!0}return l}}async function Do(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:i=20,viewOnly:s=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:l=null,excludeLocations:c=[],source:u="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
247
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${s?"View Only":`Connect (max ${i})`}`),s||console.log(`Custom messages: ${n?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!s){let p=
|
|
245
|
+
`),process.exit(1));var Ie=ki({token:pn});var Be=12e4;async function Je(e,{retries:t=2}={}){let o=process.env.NODE_EASY_APPLY_MAIN;if(!o||o.startsWith("YOUR_"))throw new Error('NODE_EASY_APPLY_MAIN is not configured in .env. Create a node in iLiveMyLife, add "assist" tag, and set the node ID in .env. See README.md for setup instructions.');for(let r=1;r<=t;r++)try{let n=await Ie.askLifebot(o,e,{timeout:Be});return Be=Math.max(12e4,Be*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){Be=Math.min(Be*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(Be/1e3)}s...`);continue}throw n}}async function lo(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let o=`Job application form field "${e}" \u2014 reply with ONLY the value to fill in, nothing else. `;return t&&(t==="Enter a decimal number larger than 0.0"&&(t="Enter a decimal number larger than 0"),o+=`Additional info: ${t}`),await Je(o)}async function _t(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Je(o)}async function st(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Je(o)}uo();import{LIFEBOT_MESSAGE_TYPES as ti}from"@ilivemylife/graph-sdk";Ue();await Qe();async function dr(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function ur(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function xs(e,t,o={}){let{extractExperience:r=!1,extractFeatured:n=!1,extractEducation:i=!1,extractSkills:s=!1,extractRecommendations:a=!1,extractCertifications:l=!1}=o;try{await so(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await w(1500),await oe(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await dr(e,t));let u=0;for(let b=0;b<2;b++){let E=await e.evaluate(()=>document.body.scrollHeight);for(let L=1;L<=6;L++)await e.evaluate(A=>window.scrollTo(0,A),E*L/6),await w(900);let R=await e.evaluate(()=>document.body.scrollHeight);if(R===u)break;u=R}await w(800);let f=null;try{let b=e.url();b&&/\/in\/[^/?#]/.test(b)&&(f=b.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let b=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),E=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),R=$=>{let j=($||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(j)},L={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},A=document.querySelector("main");if(!A)return L;let T=[...Array.from(A.querySelectorAll("h1")),...Array.from(A.querySelectorAll("h2"))],D=Array.from(A.querySelectorAll("h2")),K=T.find($=>{let j=$.textContent&&$.textContent.trim(),N=(j||"").replace(/\s*\(\d+\)$/,"").trim();return j&&j.length>1&&j.length<100&&!b.has(N)&&!E.has(N)}),U=K?K.textContent.trim():null,_=K?K.parentElement:null;for(;_&&_!==A&&!Array.from(_.children).filter(j=>j.tagName==="P").some(j=>{let N=j.textContent&&j.textContent.trim();return N&&N.length>5&&!R(N)});)_=_.parentElement;let M=null,F=null,B=null,G=null;if(_&&_!==A){let $=Array.from(_.children).filter(N=>N.tagName==="P").filter(N=>{let be=N.textContent&&N.textContent.trim();return be&&be.length>5&&!R(be)});if($[0]&&(M=$[0].textContent.trim()),$[1]){let N=$[1].textContent.trim().split(/\s*[·•]\s*/);F=N[0]||null,N.length>1&&(B=N.slice(1).join(" \xB7 "))}let j=Array.from(_.children).filter(N=>N.tagName==="DIV");for(let N=j.length-1;N>=0;N--){let be=j[N].textContent&&j[N].textContent.trim();if(be&&!(U&&be.startsWith(U))&&(G=be.split(/[·•]/)[0].trim(),G))break}}let W=null;if(_){let $=_.querySelectorAll("p, span, div");for(let j of $){let N=(j.textContent||"").trim().replace(/^[·•]\s*/,"");if(N==="1st"||N==="2nd"||N==="3rd"){W=N;break}}}let v=!!A.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),I=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Y=I&&I.src||null,O=A.textContent||"",J=null,Te=O.match(/(\d+\+?)\s+connections\b/i);Te&&(J=Te[1]+" connections");let Re=null,rn=O.match(/(\d+)\s+mutual connection/i),sn=O.match(/and\s+(\d+)\s+other mutual/i),mi=O.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);rn?Re=parseInt(rn[1],10):sn?Re=2+parseInt(sn[1],10):mi&&(Re=2);let ln=null,an=null,cn=D.find($=>$.textContent&&$.textContent.trim()==="About");if(cn){let $=cn.parentElement;for(;$&&$.tagName!=="SECTION";)$=$.parentElement;if($){let j=($.textContent||"").trim();j=j.replace(/^About\s*/,"").trim();let N=j.match(/Top skills\s*(.+?)$/i);if(N){let ro=N[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(bi=>bi.trim()).filter(Boolean);ro.length>0&&ro.length<10&&(an=ro)}j=j.split(/\n?…\s*more/i)[0].trim(),j=j.split(/\n?\.\.\.\s*more/i)[0].trim(),j=j.split(/\bTop skills\b/i)[0].trim(),j=j.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),ln=j||null}}let un=null,dn=D.find($=>$.textContent&&$.textContent.trim()==="Activity");if(dn){let $=dn.parentElement;for(;$&&$.tagName!=="SECTION";)$=$.parentElement;if($){let j=($.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);j&&(un=parseInt(j[1].replace(/,/g,""),10))}}let hi=[...new Set(D.map($=>($.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter($=>$&&$.length>1&&$.length<60&&$!==U).filter($=>b.has($)))],rt=document.body.textContent||"",yi=/#OpenToWork\b/i.test(rt)||/\bOpen to work\b/.test(rt),gi=/#Hiring\b/i.test(rt)||/\bI'?m hiring\b/i.test(rt)||/\bWe are hiring\b/i.test(rt);return{name:U,title:M,location:G,currentCompany:F,currentSchool:B,connectionDegree:W,hasVerifiedBadge:v,photoUrl:Y,connectionsLevel:J,mutualConnectionsCount:Re,followers:un,openToWork:yi,hiring:gi,about:ln,topSkills:an,availableSections:hi}});console.log(`Viewed: ${d.name} - ${d.title}`);let p=null,m=null,h=null,g=null,y=null,S=null;if(r||n||i||s||a||l){let b=await Promise.resolve().then(()=>(On(),Fn));r&&(p=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),n&&(m=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),i&&(h=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),s&&(g=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${g.length} entries`)),a&&(y=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),l&&(S=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...p!==null&&{experience:p},...m!==null&&{featured:m},...h!==null&&{education:h},...g!==null&&{skillsFull:g},...y!==null&&{recommendations:y},...S!==null&&{certifications:S}}}catch(c){console.error(`Error viewing profile ${t}:`,c.message);try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(c.message||""))throw c;return null}}async function tt(e,{detail:t=!1}={}){let o=()=>e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=f=>f&&!f.closest(n),s=f=>Array.from(document.querySelectorAll(f)).filter(i),a=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,c=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:a.length,pendingLabels:a.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!c};return a.length>0?{status:"pending",debug:u}:l&&!c?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),r=await o();return!r.debug.pendingCount&&!r.debug.hasMessageBtn&&!r.debug.hasConnectBtn&&(await w(1500),r=await o()),console.log(" DEBUG connection status:",JSON.stringify(r.debug)),t?r:r.status}async function No(e){let t=null,o=await e.evaluate(()=>{let c=document.querySelector("h1")?.textContent?.trim();if(c&&!c.includes("notification"))return c;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(c=u.textContent?.trim(),c&&!c.includes("notification")))return c;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let c=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});c.count>0&&console.log(` S0: ${c.count} custom-invite links: ${JSON.stringify(c.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),p=f.toLowerCase().split(" ")[0],m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let g=h.getBoundingClientRect();if(g.width===0||g.height===0||h.closest(m))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(p))return h}return null},o);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(o){let c=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${c}"`);let u=await e.evaluate(d=>{let p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(g=>{let y=g.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&p.test(y)}).map(g=>g.getAttribute("aria-label")?.slice(0,50))},c);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let p=document.querySelectorAll("button[aria-label]"),m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',h=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of p){if(g.closest(m))continue;let y=g.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&h.test(y))return g}return null},c);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let c=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();c.includes("invite")&&!c.includes(u)&&(console.log(` Skipping primary button: wrong person (${c})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let n=o?o.split(" ")[0].toLowerCase():"",i=null;for(let c of r){let u=await e.evaluate((f,d)=>{let p=f.className.includes("muted"),m=f.className.includes("sticky-header")||f.className.includes("sticky"),h=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,g=(f.getAttribute("aria-label")||"").toLowerCase(),y=g.includes("invite"),S=d?g.includes(d):!0;return{isMuted:p,isStickyHeader:m,inRecommendations:h,hasInvite:y,matchesName:S,ariaLabel:g}},c,n);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=c;break}}for(let c of r)c!==i&&await c.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let s=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let c of a){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),p=d.width>0&&d.height>0,m=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:m,top:d.top}},c);if(u.isVisible&&!u.isInStickyHeader){s=c,console.log(" Found More button by ID pattern (main)");break}}for(let c of a)c!==s&&await c.dispose().catch(()=>{});if(!s&&a.length>0&&(s=a[a.length-1],console.log(" Found More button by ID pattern (last)")),s||(s=await e.$('button[aria-label="More actions"]'),s&&console.log(" Found More button by aria-label")),!s){let c=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(p=>{let m=p.innerText?.trim(),h=p.getAttribute("aria-label")||"",g=p.getBoundingClientRect();return g.top<100||g.top>600||g.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let p=0;p<8&&d;p++){for(let m of d.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==f)return m;d=d.parentElement}return null});s=c?.asElement?.()||null,s||await c?.dispose?.().catch(()=>{}),s&&console.log(" Found More button by text (near profile actions)")}if(s)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),s),await w(500),await e.evaluate(d=>d.click(),s),await w(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let p=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let m of p){let h=m.querySelector('a[href*="custom-invite"]');if(h)return h;for(let g of m.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let m of d)for(let h of m.querySelectorAll('[role="menuitem"], a, div')){let g=h.innerText?.trim();g&&g.length<40&&p.push(g)}return[...new Set(p)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(c){console.log(" More dropdown click failed:",c.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(c=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(c||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let p=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(p))continue;let m=d.getBoundingClientRect();if(!(m.width===0||m.height===0)){if(p.includes("invite")){if(f&&p.includes(f))return d;continue}if(p==="connect")return d}}return null},o||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Cs(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let o=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),n=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV",s=(o.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(s))return console.log(` \u2717 Guard: refusing a non-connect control ("${o.ariaLabel}")`),"wrong_target";if(s.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!s.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${o.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(n){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await w(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await w(3e3)):(await e.evaluate(u=>u.click(),t),await w(3e3));let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let l=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),c=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${c}`:` \u26A0 No modal after connect click \u2014 ${c}`),"success"}async function Es(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await w(1500);let o=await No(e);if(o){await e.evaluate(n=>n.click(),o),await w(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r)return await ot(e,r)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function ot(e,t){let o='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',r=()=>e.evaluate(s=>{let a=l=>!!(l&&l.querySelector(s));return!(a(document)||a(document.querySelector("#interop-outlet")?.shadowRoot))},o),n=()=>e.evaluate(()=>{for(let s of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(s.innerText||""))return!0;return!1}),i=async()=>{let s=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(s)return s;let a=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,o);return s=a?.asElement?.()||null,s||await a?.dispose?.().catch(()=>{}),s};for(let s=0;s<2;s++){try{await t.evaluate(a=>a.click())}catch{}if(await w(3e3),await n())return!1;if(await r())return!0;if(s===0){let a=await i();if(!a)return await r();t=a,await w(600)}}return await r()}async function As(e,t,o={}){let{source:r="unknown",skipQuotaGate:n=!1,skipQuotaRecord:i=!1}=o;if(!n){let a=dt();if(!a.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${a.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:a.reason,profileInfo:null}}let s=await _s(e,t,o);return s.connectionSent&&!i&&Mt(t,r),s}async function _s(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,skipIfPending:i=!0,skipIfConnected:s=!0,excludeLocations:a=[]}=o,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
246
|
+
--- Connecting: ${c} ---`),a.length>0){let y=Q()[t]?.location;if(ur(y,a))return console.log(` \u26A0 Excluded location (stored): ${y}`),l.reason="excluded_location",l.profileInfo={location:y},l}try{await so(e,t,{readySelector:".pvs-profile-actions, .pv-top-card-v2-ctas, .pv-top-card, section.pv-top-card",label:"profile"})}catch(y){if(y.code==="SESSION_EXPIRED")return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),l.reason="session_expired",l.fatal=!0,l;throw y}if(await w(2e3),await oe(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await dr(e,t),await w(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(xo(),Bn)),{recordDiscoveredEdges:x}=await Promise.resolve().then(()=>(Wt(),Yn)),{detectCategoryFromTitle:b}=await sr().then(()=>ir),{detectSectors:E}=await Promise.resolve().then(()=>(cr(),ar)),R=S(t)||t,L=await y(e,{seedUrl:R}),A=L.map(T=>{let D=T.headline?b(T.headline):null;return{url:T.url,seedUrl:R,block:T.block,rank:T.rank,name:T.name,headline:T.headline,categories:D?[D]:[],sectors:E(T.headline||"")}});x(A),L.length&&console.log(` \xB7 discovery: harvested ${L.length} related profiles`)}catch(y){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${y.message}`)}l.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),S=v=>{let I=(v||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(I)},x={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},b=document.querySelector("main");if(!b)return x;let E=[...Array.from(b.querySelectorAll("h1")),...Array.from(b.querySelectorAll("h2"))],R=Array.from(b.querySelectorAll("h2")),L=E.find(v=>{let I=v.textContent&&v.textContent.trim();return I&&I.length>1&&I.length<100&&!y.has(I)&&I!=="0 notifications"}),A=L?L.textContent.trim():null,T=L?L.parentElement:null;for(;T&&T!==b&&!Array.from(T.children).filter(Y=>Y.tagName==="P").some(Y=>{let O=Y.textContent&&Y.textContent.trim();return O&&O.length>5&&!S(O)});)T=T.parentElement;let D=null,K=null,U=null;if(T&&T!==b){let v=Array.from(T.children),I=v.filter(O=>O.tagName==="P").filter(O=>{let J=O.textContent&&O.textContent.trim();return J&&J.length>5&&!S(J)});I[0]&&(D=I[0].textContent.trim()),I[1]&&(K=I[1].textContent.trim());let Y=v.filter(O=>O.tagName==="DIV");for(let O=Y.length-1;O>=0;O--){let J=Y[O].textContent&&Y[O].textContent.trim();if(J&&!(A&&J.startsWith(A))&&(U=J.split(/[·•]/)[0].trim(),U))break}}let _=null;if(T){let v=T.querySelectorAll("p, span, div");for(let I of v){let Y=(I.textContent||"").trim().replace(/^[·•]\s*/,"");if(Y==="1st"||Y==="2nd"||Y==="3rd"){_=Y;break}}}let M=null,F=R.find(v=>v.textContent&&v.textContent.trim()==="About");if(F){let v=F.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;v&&(M=(v.textContent||"").trim().replace(/^About\s*/,"").trim()||null,M&&(M=M.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let B=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),G=B&&B.src||null,W=!!b.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:A,title:D,location:U,about:M,company:K,connectionDegree:_,connectionsCount:null,mutualConnections:null,photoUrl:G,hasVerifiedBadge:W}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(l.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(a.length>0){let y=l.profileInfo?.location,S=Q()[t]?.location,x=y||S;if(ur(x,a))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${x}`),l.reason="excluded_location",l;!y&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await tt(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await oe(e);let d=await No(e);if(d||await oe(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),d=await No(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!d){let y=await tt(e,{detail:!0});return s&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=d.method;let p=await Cs(e,d.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let y=await tt(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await oe(e),await w(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(b=>b.scrollIntoView({behavior:"smooth",block:"center"}),S),await w(500),await S.click().catch(()=>e.evaluate(b=>b.click(),S)),await w(2e3);let x=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(x){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(R=>R.click(),x),await w(3e3);let b=e.url();if(b.includes("/premium/")||b.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),l.reason="premium_required",l;if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),l.reason="premium_required",l}catch(x){return console.log(" More dropdown failed:",x.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of y){let x=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!x)continue;let b=(x.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(b)||x.querySelector('input[type="email"], input[name="email"]'))return!0;let E=x.querySelector('button[aria-label="Send without a note"]');if(E&&(E.disabled||E.getAttribute("aria-disabled")==="true"||(E.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let y=await e.$('button[aria-label="Dismiss"]');if(y)try{await y.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await w(500),l.reason="email_required",l}let h=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!h&&!g){let y=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let x=S.querySelector('button[aria-label="Add a note"]'),b=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!x,sendWithout:!!b}});if(y.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=S?.asElement?.()||null,h||await S.dispose().catch(()=>{})}if(y.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=S?.asElement?.()||null,g||await S.dispose().catch(()=>{})}}if(n)if(h&&r){if(console.log(" Adding personalized note..."),await h.click(),await w(1500),await e.$("div.modal-upsell")){let x=await Es(e);return l.success=x,l.connectionSent=x,l.reason=x?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let x=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),b=r.replace("{name}",x);await S.type(b,{delay:20}),await w(500);let E=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(E)return await ot(e,E)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=b,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(g)return console.log(" Sending without note..."),await ot(e,g)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(h&&!r){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await ot(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let y=g;if(y)return await ot(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3)),await oe(e),await w(500);let S=await e.$$('button[id*="profile-overflow-action"]'),x=null;for(let b of S){let E=await e.evaluate(R=>{let L=R.getBoundingClientRect();return{visible:L.width>0&&L.height>0,inSticky:!!R.closest('.sticky-header, [class*="sticky"]')}},b);if(E.visible&&!E.inSticky){x=b;break}}!x&&S.length>0&&(x=S[S.length-1]);for(let b of S)b!==x&&await b.dispose().catch(()=>{});if(x)try{await e.evaluate(E=>E.scrollIntoView({behavior:"smooth",block:"center"}),x),await w(500),await x.click().catch(()=>e.evaluate(E=>E.click(),x)),await w(2e3);let b=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(b){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(A=>A.click(),b),await w(3e3);let E=e.url();if(E.includes("/premium/")||E.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await tt(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let L=await e.$('button[aria-label="Send without a note"]');if(L)return console.log(" Modal appeared via More dropdown, sending without note..."),await ot(e,L)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(b){console.log(" More dropdown fallback failed:",b.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(c){console.error(` \u2717 Error: ${c.message}`),l.reason="error",l.error=c.message;let u=c.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{l.fatal=!0}return l}}async function Po(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:i=20,viewOnly:s=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:l=null,excludeLocations:c=[],source:u="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
247
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${s?"View Only":`Connect (max ${i})`}`),s||console.log(`Custom messages: ${n?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!s){let p=ft();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let d=0;for(let p=0;p<t.length;p++){let m=t[p];try{if(e.isClosed()){console.log(`
|
|
248
248
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
249
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let h=
|
|
249
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let h=Pt(m.profileUrl);if(h==="pending"||h==="connected"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${m.name||m.profileUrl} \u2014 skipped (db: ${h})`),h==="pending"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,l&&await l(m,f,{success:!1,reason:h,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${m.name||m.profileUrl}`);let g=null;if(s){let y=await xs(e,m.profileUrl);y?(ve(m.profileUrl,{...y,source:u}),f.viewed++,g={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(f.errors++,g={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let y=dt();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(g=await As(e,m.profileUrl,{message:r,useCustomMessage:n,excludeLocations:c,source:u,skipQuotaGate:!0}),g.success)f.connectionsSent++;else switch(g.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(g?.fatal){console.log(`
|
|
250
250
|
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(g?.reason==="error"){if(d++,d>=3){console.log(`
|
|
251
|
-
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(g&&g.reason&&(
|
|
252
|
-
=== Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!s){let p=dt();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return f}await Qe();Ue();async function ar(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let n=null,i=null;for(let f of r)if(n=document.querySelector(f),n){i=f;break}if(!n){let f=document.querySelector("li.scaffold-layout__list-item");if(f){let d=f.parentElement;for(;d&&d!==document.body;){if(d.scrollHeight>d.clientHeight){n=d,i="parent of li.scaffold-layout__list-item";break}d=d.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let s=n.scrollTop,a=300,l=300,c=50,u=0;for(;u<c&&(n.scrollBy(0,a),await new Promise(f=>setTimeout(f,l)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)u++;return{found:!0,usedSelector:i,initialScroll:s,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:u}},t)}async function cr(e,{easyApplyOnly:t=!0}={}){let o=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(n=>{let s=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=n.querySelector("a.job-card-container__link");if(a){let l=a.getAttribute("href").split("?")[0],c=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),u=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),f=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),d=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:l,isEasyApply:s,applyType:s?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${l}`,jobTitle:c,companyName:u,location:f,salary:d||null,jobLink:s?a.href:null}}return{isEasyApply:!1}})});return t?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function ur(e){let t=await e.evaluate(()=>{let o=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(o&&!o.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return o.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",t.success?t.pageState:t.reason),t.success&&await w(2e3),t.success}async function jo(e,t){let o=e.url();if(o.includes("/jobs/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let n=e.url();if(!n.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${n.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function dr(e,t,o,r){for(let n of t){await jo(e,r)&&(await oe(e),await w(2e3));let s=await e.$(`a[data-control-id="${n.dataId}"]`),a="dataId";if(!s){let l=n.id?.match(/\d+/)?.[0];l&&(s=await e.$(`a[href*="/jobs/view/${l}/"]`),s&&(a="href"))}if(s){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${n.jobTitle}`);let l=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await e.evaluate(d=>d.scrollIntoView({block:"center"}),s),await w(300),await s.click(),await w(1500);let c=!1;for(let d=0;d<8;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){c=!0;break}await w(500)}if(!c){await e.evaluate(d=>d.click(),s),await w(1500);for(let d=0;d<6;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){c=!0;break}await w(500)}c||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let u=await e.evaluate(()=>{let d=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of d)for(let m of p.querySelectorAll("button")){let h=m.innerText?.trim();if(h==="Continue applying"||h==="Got it"||h==="Dismiss")return m.click(),h}return null});u&&console.log(` Dismissed popup before processing (${u})`);let{keepGoing:f}=await o(e,n);if(!f)return{keepGoing:!1}}else{let l=n.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${n.jobTitle||n.id} (dataId=${n.dataId}, jobId=${l})`)}}return{keepGoing:!0}}async function fr(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=t.querySelector(".hirer-card__hirer-information");if(o){let s=o.querySelector('a[href*="/in/"]'),a=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(s)return{name:a?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let s=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(s)return{name:r.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"poster_name"}}let n=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(n){let s=n.querySelector('a[href*="/in/"]');if(s)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"people_section"}}let i=t.querySelectorAll('a[href*="/in/"]');for(let s of i){let a=s.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:s.href?.split("?")[0],source:"details_link"}}return null})}async function pr(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},i=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let J of i){let fe=J.querySelector(".job-criteria__subheader")?.textContent?.trim(),we=J.querySelector(".job-criteria__text")?.textContent?.trim();fe&&we&&(n[fe.toLowerCase()]=we)}let s=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],a=[];for(let J of s)new RegExp("\\b"+J.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(J.replace(/\\\+/g,"+"));let c=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,f=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,d=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=d?.innerText?.trim()||null,h=(d?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",v=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,b=y.match(/(\d[\d,]*)\s+applicant/i),E=b?parseInt(b[1].replace(/,/g,"")):null,R=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),I=Array.from(R).map(J=>J.innerText?.trim()?.replace(/\s+/g," ")),A=I.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,T=I.join(" ")+" "+y,Y=/\bremote\b/i.test(T)?"remote":/\bhybrid\b/i.test(T)?"hybrid":/\bon-?site\b/i.test(T)?"onsite":null,K=/\bcontract\b/i.test(T)?"contract":/\bfull-?time\b/i.test(T)?"full-time":/\bpart-?time\b/i.test(T)?"part-time":/\bfreelance\b/i.test(T)?"freelance":/\btemporary\b/i.test(T)?"temporary":null,$=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",N=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",q=($+" "+r+" "+N).toLowerCase(),G=$.toLowerCase(),x=[];/\bremote\b/.test(q)&&x.push("remote"),/\bhybrid\b/.test(q)&&x.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(q)&&x.push("onsite"),(x.length===0||!x.includes("remote")&&!x.includes("hybrid")&&!x.includes("onsite"))&&/remote/i.test(N)&&x.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(G)&&x.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(G)&&x.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(G)&&!x.includes("managerial")&&x.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(G)?x.push("junior"):/\b(senior|sr\.?)\b/i.test(G)?x.push("senior"):/\b(staff|principal|distinguished)\b/i.test(G)?x.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(G)?x.push("executive"):/\b(lead|team lead)\b/i.test(G)&&x.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(q)&&x.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(q)&&x.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(q)&&x.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(q)&&x.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(q)&&x.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(q)&&x.push("mobile"),/\b(architect)\b/i.test(G)&&x.push("architect"),/\b(consultant|consulting)\b/i.test(G)&&x.push("consultant");let j=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(j)||/\bcontract\b/i.test(q))&&x.push("contract"),/full.?time|permanent/i.test(j)&&x.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(N)&&x.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(N)&&x.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&x.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:f,companyName:p,companyUrl:h?h.startsWith("/")?"https://www.linkedin.com"+h:h:null,aboutCompany:c,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:v,applicantCount:E,companySize:A,workplaceType:Y,contractType:K,techStack:[...new Set(a)],jobTags:[...new Set(x)]}})}Vt();import"dotenv/config";import*as C from"fs";import*as Uo from"os";import*as F from"path";import{fileURLToPath as Gs}from"url";var Po={};te(Po,{NAME:()=>Cs,VERSION:()=>xs,up:()=>$s});import*as ie from"fs";import*as Wt from"path";var xs=1,Cs="normalize-jobs-and-questions",Es=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],As=50;function Lo(e){return ie.existsSync(e)?JSON.parse(ie.readFileSync(e,"utf-8")):null}function No(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ie.writeFileSync(r,o)}catch(n){try{ie.unlinkSync(r)}catch{}throw n}try{ie.renameSync(r,e)}catch(n){try{ie.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function $s(e,t){let o=Wt.join(e,"jobs.json"),r=Wt.join(t,"scouted-jobs.json"),n=Wt.join(e,"application-questions.json"),i=Lo(o)||{},s=Lo(r)||{},a=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let f=s[u],d=i[u];for(let p of Es)f[p]!=null&&d[p]==null&&(d[p]=f[p]);l.push(u),a++}a>0?(No(o,i),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let c=Lo(n);if(c&&Array.isArray(c.applications)){let u={},f=0;for(let d of c.applications){let p=d.jobId||"unknown";u[p]||(u[p]={applications:[]});let m=(d.questions||[]).map(h=>{let g={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=As?g.options=h.options:(g.optionsOmitted=!0,f++)),h.page&&(g.page=h.page),h.wasPreFilled&&(g.wasPreFilled=!0),h.wasRetry&&(g.wasRetry=!0),g});u[p].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||m.length,questions:m})}No(n,u),console.log(` Phase 2: Rekeyed ${c.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else c&&!c.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let u of l)delete s[u];No(r,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Fo={};te(Fo,{NAME:()=>Ts,VERSION:()=>_s,up:()=>Ds});import*as se from"fs";import*as mr from"path";var _s=2,Ts="reset-unread-flags";function Rs(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function Is(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{se.writeFileSync(r,o)}catch(n){try{se.unlinkSync(r)}catch{}throw n}try{se.renameSync(r,e)}catch(n){try{se.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function Ds(e){let t=mr.join(e,"conversations.json"),o=Rs(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let r=0;for(let n of Object.keys(o))o[n].unread===!0&&(o[n].unread=!1,r++);if(r===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Is(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Oo={};te(Oo,{NAME:()=>Ls,VERSION:()=>js,up:()=>qs});import*as le from"fs";import*as hr from"path";var js=3,Ls="recompute-last-message-by",Ns=new Set(["draft","confirmed","rejected","needs_review"]);function Ps(e){return le.existsSync(e)?JSON.parse(le.readFileSync(e,"utf-8")):null}function Fs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{le.writeFileSync(r,o)}catch(n){try{le.unlinkSync(r)}catch{}throw n}try{le.renameSync(r,e)}catch(n){try{le.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}function Os(e,t){if(!e||e.length===0)return"them";let o=e.filter(i=>!Ns.has(i.status));if(o.length===0)return"them";let r=o.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),n=r.length>0?r:[...o].reverse();for(let i of n){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function qs(e){let t=hr.join(e,"conversations.json"),o=Ps(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let r=process.env.LINKEDIN_NAME;if(!r||typeof r!="string"||!r.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let n=0,i=0,s=0;for(let a of Object.keys(o)){let l=o[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let c=Array.isArray(l.messages)?l.messages:[],u=Os(c,r),f=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=f,n++}if(n===0){console.log(" No conversations to recompute.");return}Fs(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var qo={};te(qo,{NAME:()=>Us,VERSION:()=>Ms,up:()=>Vs});import*as ae from"fs";import*as yr from"path";var Ms=4,Us="split-connection-timestamps",Bs=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Js(e){if(!ae.existsSync(e))return null;let t=ae.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Hs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ae.writeFileSync(r,o)}catch(n){try{ae.unlinkSync(r)}catch{}throw n}try{ae.renameSync(r,e)}catch(n){try{ae.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function Vs(e){let t=yr.join(e,"people.json"),o=Js(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let r=0,n=0;for(let i of Object.keys(o)){let s=o[i];!s||typeof s!="object"||(n++,Bs.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,r++))}if(r===0){console.log(` Scanned ${n} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Hs(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${r} still-pending people (of ${n} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Qe();Vt();var Ws=Gs(import.meta.url),Ys=F.dirname(Ws),Ks=F.dirname(F.dirname(Ys));function zs(e){return e&&(e==="~"?Uo.homedir():e.startsWith("~/")||e.startsWith("~\\")?F.join(Uo.homedir(),e.slice(2)):e)}var ue=process.env.DATA_DIR?F.resolve(zs(process.env.DATA_DIR)):Ks,qe=F.join(ue,"collected-profiles"),Me=F.join(ue,"market-research"),X=F.join(ue,".schema-version"),gr=[F.join(qe,".schema-version"),F.join(Me,".schema-version")],_e=4,be=[{version:1,module:Po},{version:2,module:Fo},{version:3,module:Oo},{version:4,module:qo}];(function(){be.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of be){if(!Number.isInteger(r.version)||r.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(r.version)} (must be positive integer)`);if(t.has(r.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${r.version}`);t.add(r.version);let n=r.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${r.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==r.version)throw new Error(`MIGRATION_REGISTRY: v${r.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=be.length?be[be.length-1].version:0;if(o!==_e)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${_e}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<be.length;r++){let n=r+1;if(be[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${be[r].version}`)}})();function kr(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
251
|
+
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(g&&g.reason&&(Ft(m.profileUrl,g.reason,{method:g.method,messageSent:g.messageSent,profileInfo:g.profileInfo}),g.resolvedUrl&&Ot(m.profileUrl,g.resolvedUrl),Ke(m.profileUrl,{source:u||"funnel",jobId:m.jobId||m.fromJob?.jobId||null,jobTitle:m.fromJob?.title||null,jobCompany:m.fromJob?.company||null,action:g.reason})),l&&await l(m,f,g),p<t.length-1){let y=a+Math.random()*2e3;await w(y)}}if(console.log(`
|
|
252
|
+
=== Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!s){let p=ft();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return f}await Qe();Ue();async function fr(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let n=null,i=null;for(let f of r)if(n=document.querySelector(f),n){i=f;break}if(!n){let f=document.querySelector("li.scaffold-layout__list-item");if(f){let d=f.parentElement;for(;d&&d!==document.body;){if(d.scrollHeight>d.clientHeight){n=d,i="parent of li.scaffold-layout__list-item";break}d=d.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let s=n.scrollTop,a=300,l=300,c=50,u=0;for(;u<c&&(n.scrollBy(0,a),await new Promise(f=>setTimeout(f,l)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)u++;return{found:!0,usedSelector:i,initialScroll:s,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:u}},t)}async function pr(e,{easyApplyOnly:t=!0}={}){let o=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(n=>{let s=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=n.querySelector("a.job-card-container__link");if(a){let l=a.getAttribute("href").split("?")[0],c=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),u=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),f=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),d=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:l,isEasyApply:s,applyType:s?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${l}`,jobTitle:c,companyName:u,location:f,salary:d||null,jobLink:s?a.href:null}}return{isEasyApply:!1}})});return t?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function mr(e){let t=await e.evaluate(()=>{let o=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(o&&!o.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return o.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",t.success?t.pageState:t.reason),t.success&&await w(2e3),t.success}async function Fo(e,t){let o=e.url();if(o.includes("/jobs/"))return!1;if(At(o)){if(!await io(e,".scaffold-layout__main, main.scaffold-layout__main, .jobs-search-results-list",{timeout:45e3,label:"job search"})&&At(e.url()))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");if(e.url().includes("/jobs/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(2e3)),!e.url().includes("/jobs/"))throw new Error(`Session expired \u2014 could not return to job search (landed on ${e.url().slice(0,60)}). Run: ilml linkedin login`);return!0}console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();if(!r.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${r.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function hr(e,t,o,r){for(let n of t){await Fo(e,r)&&(await oe(e),await w(2e3));let s=await e.$(`a[data-control-id="${n.dataId}"]`),a="dataId";if(!s){let l=n.id?.match(/\d+/)?.[0];l&&(s=await e.$(`a[href*="/jobs/view/${l}/"]`),s&&(a="href"))}if(s){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${n.jobTitle}`);let l=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await e.evaluate(d=>d.scrollIntoView({block:"center"}),s),await w(300),await s.click(),await w(1500);let c=!1;for(let d=0;d<8;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){c=!0;break}await w(500)}if(!c){await e.evaluate(d=>d.click(),s),await w(1500);for(let d=0;d<6;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){c=!0;break}await w(500)}c||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let u=await e.evaluate(()=>{let d=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of d)for(let m of p.querySelectorAll("button")){let h=m.innerText?.trim();if(h==="Continue applying"||h==="Got it"||h==="Dismiss")return m.click(),h}return null});u&&console.log(` Dismissed popup before processing (${u})`);let{keepGoing:f}=await o(e,n);if(!f)return{keepGoing:!1}}else{let l=n.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${n.jobTitle||n.id} (dataId=${n.dataId}, jobId=${l})`)}}return{keepGoing:!0}}async function yr(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=t.querySelector(".hirer-card__hirer-information");if(o){let s=o.querySelector('a[href*="/in/"]'),a=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(s)return{name:a?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let s=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(s)return{name:r.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"poster_name"}}let n=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(n){let s=n.querySelector('a[href*="/in/"]');if(s)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"people_section"}}let i=t.querySelectorAll('a[href*="/in/"]');for(let s of i){let a=s.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:s.href?.split("?")[0],source:"details_link"}}return null})}async function gr(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},i=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let J of i){let Te=J.querySelector(".job-criteria__subheader")?.textContent?.trim(),Re=J.querySelector(".job-criteria__text")?.textContent?.trim();Te&&Re&&(n[Te.toLowerCase()]=Re)}let s=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],a=[];for(let J of s)new RegExp("\\b"+J.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(J.replace(/\\\+/g,"+"));let c=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,f=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,d=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=d?.innerText?.trim()||null,h=(d?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",x=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,b=y.match(/(\d[\d,]*)\s+applicant/i),E=b?parseInt(b[1].replace(/,/g,"")):null,R=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),L=Array.from(R).map(J=>J.innerText?.trim()?.replace(/\s+/g," ")),T=L.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,D=L.join(" ")+" "+y,K=/\bremote\b/i.test(D)?"remote":/\bhybrid\b/i.test(D)?"hybrid":/\bon-?site\b/i.test(D)?"onsite":null,U=/\bcontract\b/i.test(D)?"contract":/\bfull-?time\b/i.test(D)?"full-time":/\bpart-?time\b/i.test(D)?"part-time":/\bfreelance\b/i.test(D)?"freelance":/\btemporary\b/i.test(D)?"temporary":null,M=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",B=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",G=(M+" "+r+" "+B).toLowerCase(),W=M.toLowerCase(),v=[];/\bremote\b/.test(G)&&v.push("remote"),/\bhybrid\b/.test(G)&&v.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(G)&&v.push("onsite"),(v.length===0||!v.includes("remote")&&!v.includes("hybrid")&&!v.includes("onsite"))&&/remote/i.test(B)&&v.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(W)&&v.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(W)&&v.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(W)&&!v.includes("managerial")&&v.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(W)?v.push("junior"):/\b(senior|sr\.?)\b/i.test(W)?v.push("senior"):/\b(staff|principal|distinguished)\b/i.test(W)?v.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(W)?v.push("executive"):/\b(lead|team lead)\b/i.test(W)&&v.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(G)&&v.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(G)&&v.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(G)&&v.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(G)&&v.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(G)&&v.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(G)&&v.push("mobile"),/\b(architect)\b/i.test(W)&&v.push("architect"),/\b(consultant|consulting)\b/i.test(W)&&v.push("consultant");let I=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(I)||/\bcontract\b/i.test(G))&&v.push("contract"),/full.?time|permanent/i.test(I)&&v.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(B)&&v.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(B)&&v.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&v.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:f,companyName:p,companyUrl:h?h.startsWith("/")?"https://www.linkedin.com"+h:h:null,aboutCompany:c,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:x,applicantCount:E,companySize:T,workplaceType:K,contractType:U,techStack:[...new Set(a)],jobTags:[...new Set(v)]}})}Wt();import"dotenv/config";import*as C from"fs";import*as Vo from"os";import*as P from"path";import{fileURLToPath as Qs}from"url";var Mo={};te(Mo,{NAME:()=>Ts,VERSION:()=>$s,up:()=>js});import*as ie from"fs";import*as Kt from"path";var $s=1,Ts="normalize-jobs-and-questions",Rs=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Is=50;function Oo(e){return ie.existsSync(e)?JSON.parse(ie.readFileSync(e,"utf-8")):null}function qo(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ie.writeFileSync(r,o)}catch(n){try{ie.unlinkSync(r)}catch{}throw n}try{ie.renameSync(r,e)}catch(n){try{ie.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function js(e,t){let o=Kt.join(e,"jobs.json"),r=Kt.join(t,"scouted-jobs.json"),n=Kt.join(e,"application-questions.json"),i=Oo(o)||{},s=Oo(r)||{},a=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let f=s[u],d=i[u];for(let p of Rs)f[p]!=null&&d[p]==null&&(d[p]=f[p]);l.push(u),a++}a>0?(qo(o,i),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let c=Oo(n);if(c&&Array.isArray(c.applications)){let u={},f=0;for(let d of c.applications){let p=d.jobId||"unknown";u[p]||(u[p]={applications:[]});let m=(d.questions||[]).map(h=>{let g={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=Is?g.options=h.options:(g.optionsOmitted=!0,f++)),h.page&&(g.page=h.page),h.wasPreFilled&&(g.wasPreFilled=!0),h.wasRetry&&(g.wasRetry=!0),g});u[p].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||m.length,questions:m})}qo(n,u),console.log(` Phase 2: Rekeyed ${c.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else c&&!c.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let u of l)delete s[u];qo(r,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Uo={};te(Uo,{NAME:()=>Ls,VERSION:()=>Ds,up:()=>Fs});import*as se from"fs";import*as br from"path";var Ds=2,Ls="reset-unread-flags";function Ns(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function Ps(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{se.writeFileSync(r,o)}catch(n){try{se.unlinkSync(r)}catch{}throw n}try{se.renameSync(r,e)}catch(n){try{se.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function Fs(e){let t=br.join(e,"conversations.json"),o=Ns(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}Ps(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Bo={};te(Bo,{NAME:()=>qs,VERSION:()=>Os,up:()=>Hs});import*as le from"fs";import*as wr from"path";var Os=3,qs="recompute-last-message-by",Ms=new Set(["draft","confirmed","rejected","needs_review"]);function Us(e){return le.existsSync(e)?JSON.parse(le.readFileSync(e,"utf-8")):null}function Bs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{le.writeFileSync(r,o)}catch(n){try{le.unlinkSync(r)}catch{}throw n}try{le.renameSync(r,e)}catch(n){try{le.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}function Js(e,t){if(!e||e.length===0)return"them";let o=e.filter(i=>!Ms.has(i.status));if(o.length===0)return"them";let r=o.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),n=r.length>0?r:[...o].reverse();for(let i of n){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function Hs(e){let t=wr.join(e,"conversations.json"),o=Us(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let r=process.env.LINKEDIN_NAME;if(!r||typeof r!="string"||!r.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let n=0,i=0,s=0;for(let a of Object.keys(o)){let l=o[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let c=Array.isArray(l.messages)?l.messages:[],u=Js(c,r),f=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=f,n++}if(n===0){console.log(" No conversations to recompute.");return}Bs(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Jo={};te(Jo,{NAME:()=>Gs,VERSION:()=>Vs,up:()=>zs});import*as ae from"fs";import*as Sr from"path";var Vs=4,Gs="split-connection-timestamps",Ws=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ys(e){if(!ae.existsSync(e))return null;let t=ae.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Ks(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ae.writeFileSync(r,o)}catch(n){try{ae.unlinkSync(r)}catch{}throw n}try{ae.renameSync(r,e)}catch(n){try{ae.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function zs(e){let t=Sr.join(e,"people.json"),o=Ys(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let r=0,n=0;for(let i of Object.keys(o)){let s=o[i];!s||typeof s!="object"||(n++,Ws.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,r++))}if(r===0){console.log(` Scanned ${n} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ks(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${r} still-pending people (of ${n} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Qe();Wt();var Xs=Qs(import.meta.url),Zs=P.dirname(Xs),el=P.dirname(P.dirname(Zs));function tl(e){return e&&(e==="~"?Vo.homedir():e.startsWith("~/")||e.startsWith("~\\")?P.join(Vo.homedir(),e.slice(2)):e)}var ue=process.env.DATA_DIR?P.resolve(tl(process.env.DATA_DIR)):el,qe=P.join(ue,"collected-profiles"),Me=P.join(ue,"market-research"),X=P.join(ue,".schema-version"),kr=[P.join(qe,".schema-version"),P.join(Me,".schema-version")],Ae=4,ge=[{version:1,module:Mo},{version:2,module:Uo},{version:3,module:Bo},{version:4,module:Jo}];(function(){ge.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of ge){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=ge.length?ge[ge.length-1].version:0;if(o!==Ae)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${Ae}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<ge.length;r++){let n=r+1;if(ge[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${ge[r].version}`)}})();function Er(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
253
253
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
254
254
|
`),process.exit(1));try{C.mkdirSync(ue,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
255
255
|
[FATAL] Cannot create DATA_DIR (${ue}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
@@ -259,63 +259,63 @@ function findEntryContainer(root) {
|
|
|
259
259
|
[FATAL] DATA_DIR (${ue}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
260
260
|
`),process.exit(1));for(let t of[qe,Me]){let o;try{o=C.lstatSync(t)}catch(r){if(r.code==="ENOENT")continue;throw r}o.isSymbolicLink()&&(console.error(`
|
|
261
261
|
[FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
|
|
262
|
-
`),process.exit(1))}}var Oe=
|
|
262
|
+
`),process.exit(1))}}var Oe=P.join(ue,".migration-lock");function ol(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return C.writeFileSync(Oe,e,{flag:"wx"}),!0}catch(r){if(r.code!=="EEXIST")throw r}let t;try{t=JSON.parse(C.readFileSync(Oe,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let r=!1;try{process.kill(t.pid,0),r=!0}catch(s){s.code==="EPERM"&&(r=!0)}let n=24*60*60*1e3,i=1/0;if(t.startedAt){let s=Date.parse(t.startedAt);Number.isNaN(s)||(i=Date.now()-s)}r&&i<n&&(console.error(`
|
|
263
263
|
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Oe}
|
|
264
264
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
265
|
-
`),process.exit(1)),r&&i>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=Oe+".tmp";try{return C.writeFileSync(o,e),C.renameSync(o,Oe),!0}catch(r){try{C.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${r.message}`)}}function
|
|
265
|
+
`),process.exit(1)),r&&i>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=Oe+".tmp";try{return C.writeFileSync(o,e),C.renameSync(o,Oe),!0}catch(r){try{C.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${r.message}`)}}function Go(){try{if(JSON.parse(C.readFileSync(Oe,"utf-8")).pid!==process.pid)return;C.unlinkSync(Oe)}catch{}}var vr=!1;function nl(){if(vr)return;vr=!0;let e=()=>{try{Go()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function rl(){if(C.existsSync(X))return;let e=[],t=[];for(let i of kr)if(C.existsSync(i))try{e.push({file:i,schema:zt(i)})}catch(s){t.push({file:i,err:s.message})}if(t.length>0){console.error(`
|
|
266
266
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
|
|
267
267
|
Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
|
|
268
268
|
`),process.exit(1)}if(e.length===0)return;let o=e.map(i=>i.schema.version);if(new Set(o).size>1){console.error(`
|
|
269
269
|
[FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
270
|
-
`),process.exit(1)}let r=e[0].schema,n=X+".tmp";try{C.writeFileSync(n,JSON.stringify(r,null,2)),C.renameSync(n,X)}catch(i){try{C.unlinkSync(n)}catch{}throw i}for(let i of
|
|
270
|
+
`),process.exit(1)}let r=e[0].schema,n=X+".tmp";try{C.writeFileSync(n,JSON.stringify(r,null,2)),C.renameSync(n,X)}catch(i){try{C.unlinkSync(n)}catch{}throw i}for(let i of kr)if(C.existsSync(i))try{C.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${X}`)}function il(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 zt(e){let t=C.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function xr(){if(rl(),!C.existsSync(X))return{version:0,migrations:[]};let e;try{e=zt(X)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
271
271
|
[FATAL] ${X} is not valid JSON: ${o.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
272
|
-
`),process.exit(1)}let t=
|
|
272
|
+
`),process.exit(1)}let t=il(e);return t===null&&(console.error(`
|
|
273
273
|
[FATAL] ${X} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
274
|
-
`),process.exit(1)),t}function
|
|
275
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
276
|
-
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${
|
|
274
|
+
`),process.exit(1)),t}function Ar(e){try{C.chmodSync(e,384)}catch{}}function sl(e){if(Er(),C.existsSync(X))try{if(C.lstatSync(X).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${X}. 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=X+".tmp";try{C.writeFileSync(t,JSON.stringify(e,null,2)),Ar(t),C.renameSync(t,X)}catch(o){try{C.unlinkSync(t)}catch{}throw o}}function Cr(e,t){if(!C.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,r=C.readdirSync(e).filter(a=>{let l=a.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return C.statSync(P.join(e,a)).isFile()}catch{return!1}}),n=0,i=0,s=[];for(let a of r){let l=P.join(e,a),c=P.join(e,a+o);if(C.existsSync(c)){i++;continue}try{$r(l,c),n++}catch(u){s.push({file:a,err:u.message})}}if(s.length>0){let a=new Error(`Failed to back up ${s.length} file(s) in ${P.basename(e)}/: `+s.map(l=>`${l.file} (${l.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(n>0||i>0){let a=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${n} files in ${P.basename(e)}/ (${o})${a}`)}}var Ho=!1;async function _r(){if(Ho)return;Er(),dl();let t=xr().version;if(t===Ae){Ho=!0;return}nl(),ol(),process.on("exit",Go),t>Ae&&(console.error(`
|
|
275
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${Ae}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
|
|
276
|
+
`),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${Ae}.
|
|
277
277
|
`),process.exit(1)),console.log(`
|
|
278
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
278
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${Ae}`);let o=fl();if(!o.ok){console.error(`
|
|
279
279
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let n of o.broken)console.error(` ${n.dir}/${n.file}: ${n.err}`);console.error(`
|
|
280
280
|
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
281
|
-
`),process.exit(1)}let r=
|
|
282
|
-
Running migration v${String(n.version).padStart(3,"0")}...`);let i=`v${String(n.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{
|
|
281
|
+
`),process.exit(1)}let r=ge.filter(n=>n.version>t);for(let n of r){console.log(`
|
|
282
|
+
Running migration v${String(n.version).padStart(3,"0")}...`);let i=`v${String(n.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{Cr(qe,n.version),Cr(Me,n.version)}catch(l){console.error(`
|
|
283
283
|
[FATAL] Pre-migration backup failed for ${i}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
284
284
|
`),process.exit(1)}let a=n.module;try{await a.up(qe,Me)}catch(l){console.error(`
|
|
285
|
-
[FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let c=
|
|
285
|
+
[FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let c=pl(s);c.ok?(console.error(` \u2713 Auto-rollback restored ${c.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
286
286
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${c.error}`),console.error(` Manual recovery: copy *${s} files back over the originals.
|
|
287
287
|
`))}catch(c){console.error(` [!] Auto-rollback CRASHED while restoring: ${c.message}`),console.error(` Manual recovery: copy *${s} files back over the originals.
|
|
288
|
-
`)}process.exit(1)}try{let l=new Date().toISOString(),c={version:n.version,name:a.NAME||i,appliedAt:l},u=
|
|
288
|
+
`)}process.exit(1)}try{let l=new Date().toISOString(),c={version:n.version,name:a.NAME||i,appliedAt:l},u=xr();u.version=n.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(c),sl(u)}catch(l){console.error(`
|
|
289
289
|
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${n.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
290
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{
|
|
291
|
-
\u2713 Schema is now at v${
|
|
292
|
-
`)}var
|
|
290
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{So()}catch{}try{Ao()}catch{}Ho=!0,Go(),console.log(`
|
|
291
|
+
\u2713 Schema is now at v${Ae}
|
|
292
|
+
`)}var ll=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function al(e){let t=e.toLowerCase();return ll.some(o=>o.test(t))}var cl=6e4;function ul(){let e=Date.now(),t=[];for(let o of[ue,qe,Me]){if(!C.existsSync(o))continue;let r;try{r=C.readdirSync(o)}catch{continue}for(let n of r){if(!al(n))continue;let i=P.join(o,n);try{let s=C.statSync(i);if(!s.isFile()||e-s.mtimeMs<cl)continue;t.push({dir:o,file:n,fullPath:i})}catch{}}}return t}function dl({verbose:e=!1}={}){let t=ul();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let r of t)try{C.unlinkSync(r.fullPath),o++,e&&console.log(` Removed orphan: ${P.basename(r.dir)}/${r.file}`)}catch(n){console.warn(` [!] Could not remove orphan ${r.fullPath}: ${n.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function fl(){let e=[];for(let t of[qe,Me]){if(!C.existsSync(t))continue;let o=C.readdirSync(t).filter(r=>{let n=r.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let r of o){let n=P.join(t,r);try{zt(n)}catch(i){e.push({dir:P.basename(t),file:r,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function pl(e){let t=[],o=[];for(let i of[qe,Me]){if(!C.existsSync(i))continue;let s=C.readdirSync(i).filter(a=>a.endsWith(e));for(let a of s){let l=P.join(i,a),c=a.slice(0,-e.length),u=P.join(i,c);try{c.toLowerCase().endsWith(".json")?zt(l):C.accessSync(l,C.constants.R_OK),t.push({backupPath:l,originalPath:u,fileName:a,dir:i})}catch(f){o.push(`${P.basename(i)}/${a}: ${f.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let r=0,n=[];for(let{backupPath:i,originalPath:s,fileName:a,dir:l}of t)try{$r(i,s),r++}catch(c){n.push(`${P.basename(l)}/${a}: ${c.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:r}:{ok:!0,restored:r}}function $r(e,t){let o=t+".tmp";try{C.copyFileSync(e,o),Ar(o)}catch(r){try{C.unlinkSync(o)}catch{}throw r}try{C.renameSync(o,t)}catch(r){try{C.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let n=new Error(`File locked: ${t} (${r.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw n.code=r.code,n}throw r}}import"dotenv/config";import*as ce from"fs";import*as _e from"path";import{fileURLToPath as yl}from"url";import"dotenv/config";function ml(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 hl({scriptName:e,mode:t,status:o,error:r,duration:n}){let i=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),a=n?` ${ml(n)}`:"",l=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",c=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${c} \u2014 ${l} \u2014 ${s}${a}`}async function Tr({scriptName:e,mode:t,status:o,summaryLines:r,error:n,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(r)||r.length===0)return;let l=`**${hl({scriptName:e,mode:t,status:o,error:n,duration:i})}**
|
|
293
293
|
|
|
294
294
|
${r.join(`
|
|
295
|
-
`)}`;try{await Ie.addMessage(s,l)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var fl=dl(import.meta.url),pl=Te.dirname(Te.dirname(fl)),Jo=process.env.DATA_DIR?Te.resolve(process.env.DATA_DIR,"collected-profiles"):Te.join(pl,"collected-profiles"),Ho=Te.join(Jo,"run-log.json");function ml(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ce.writeFileSync(r,o);for(let n=0;n<3;n++)try{ce.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Ar(){try{if(!ce.existsSync(Ho))return{runs:[]};let e=JSON.parse(ce.readFileSync(Ho,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function $r(e){ce.existsSync(Jo)||ce.mkdirSync(Jo,{recursive:!0});try{ml(Ho,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function _r(e,t="default"){let o=Ar();for(let s of o.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let r=new Date,n={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(s=>new Date(s.timestamp).getTime()>i),$r(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Tr(e,t,o=null,r=null){if(!e)return;let n=null;try{let s=Ar(),a=s.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=o,a.error=r,n=a.duration;else{let l=s.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=r,n=l.duration)}$r(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Er({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:r,duration:n??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import de from"fs";import Re from"path";var hl="cookies.json";function Rr(){let e=process.env.ILML_SCOPE_DIR;return e?Re.join(e,"plugins-state","linkedin","cookies.json"):hl}function Kt(){let e=Rr();if(!de.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=de.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}function Ir(){return de.existsSync(Rr())}function yl(){let e=process.env.ILML_SCOPE_DIR;return e?Re.join(e,"plugins-state","linkedin"):"."}function Dr(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function gl(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Dr(t[1]):"default"}function jr(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return de.existsSync(t)||de.mkdirSync(t,{recursive:!0}),Re.resolve(t);let o=Dr(e||gl()),r=Re.join(yl(),"chrome-profile",o);return de.existsSync(r)||de.mkdirSync(r,{recursive:!0}),Re.resolve(r)}var Lr=".ilml-seeded";function Nr(e){return!de.existsSync(Re.join(e,Lr))}function Pr(e){try{de.writeFileSync(Re.join(e,Lr),new Date().toISOString())}catch{}}function Fr(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{de.rmSync(Re.join(e,o),{force:!0}),t++}catch{}return t}import Vo from"fs";import bl from"path";var wl={headless:!1,defaultViewport:null,protocolTimeout:3e5},vt=new Set,Or=!1;async function zt(){let e=[...vt].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});vt.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Sl(){if(Or)return;Or=!0;let e=t=>async()=>{await zt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await zt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await zt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await zt(),process.exit(0))}),process.on("exit",()=>{for(let t of vt)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function Go(e){return bl.join(e,".ilml-browser-session.json")}function Br(e,t={}){try{Vo.writeFileSync(Go(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function kl(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();Br(e,o?{wsEndpoint:o}:{})}catch{}}function vl(e){let t=Jr(e);t&&t.ownerPid===process.pid&&kt(e)}function kt(e){try{Vo.rmSync(Go(e),{force:!0})}catch{}}function Jr(e){try{return JSON.parse(Vo.readFileSync(Go(e),"utf-8"))}catch{return null}}function qr(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Mr(e,t,o){let r,n=new Promise(s=>{r=setTimeout(()=>s(o),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(r),s),s=>{throw clearTimeout(r),s});return Promise.race([i,n])}async function Ur(e,t,{probeTimeoutMs:o=4e3}={}){let r=Jr(t);if(!r)return"free";if(!r.wsEndpoint)return r.ownerPid&&r.ownerPid!==process.pid&&qr(r.ownerPid)?"live":(kt(t),"free");let n=Symbol("timeout"),i=e.connect({browserWSEndpoint:r.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await Mr(i,o,n);if(s===n)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return kt(t),"free";if(qr(r.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Mr(s.close().then(()=>!0).catch(()=>!1),o,!1))return kt(t),"free";try{s.disconnect()}catch{}return"live"}function xl(e,t){e&&(Sl(),vt.add(e),e.on("disconnected",()=>{vt.delete(e),t&&kt(t)}))}async function Wo(e,t={}){let o=jr(),r={...wl,...t,userDataDir:o},n=`Could not open the LinkedIn automation Chrome profile at ${o}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Ur(e,o)==="live")throw new Error(n);Br(o);let i;try{i=await e.launch(r)}catch{if(await Ur(e,o)==="live")throw new Error(n);Fr(o);try{i=await e.launch(r)}catch(a){throw vl(o),new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${a.message})`)}}return xl(i,o),kl(o,i),{browser:i,profileDir:o,needsSeed:Nr(o)}}async function Hr(e,t){if(!t||!t.needsSeed)return!1;if(!Ir())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...Kt()),Pr(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}Ue();async function xt(e,t,o="op"){let r,n=new Promise((i,s)=>{r=setTimeout(()=>s(new Error(`${o} timeout after ${t}ms`)),t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}function nt(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let o=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(o)||/Target closed/i.test(o)||/Session closed/i.test(o)||/Connection closed/i.test(o)||/Most likely the page has been closed/i.test(o)||/Navigating frame was detached/i.test(o)||/Protocol error.*timed out/i.test(o)}async function Vr(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await xt(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function Gr(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await Vr(e,t)?!0:(await w(o),await Vr(e,t))}async function Wr(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await xt(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function Yr(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){try{await xt(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let s=await e.newPage();if(i)try{await i(s)}catch{}if(n)try{let a=n();Array.isArray(a)&&a.length>0&&await s.setCookie(...a)}catch{}if(o){await s.goto(o,{waitUntil:"domcontentloaded",timeout:r});let a=s.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(a))throw new Error(`Session expired after recovery \u2014 landed on ${a}. Run: ilml linkedin login`)}return s}async function Kr(e,{launchFn:t,returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");let s=null;try{s=e.process()}catch{}let a=!1;try{await xt(e.close(),5e3,"oldBrowser.close"),a=!0}catch{}if(!a&&s&&s.pid&&s.exitCode===null){try{s.kill("SIGKILL")}catch{}try{await xt(new Promise(u=>s.once("exit",u)),5e3,"oldBrowser.kill")}catch{}}let l=await t(),c=await l.newPage();if(i)try{await i(c)}catch{}if(n)try{let u=n();Array.isArray(u)&&u.length>0&&await c.setCookie(...u)}catch{}if(o){await c.goto(o,{waitUntil:"domcontentloaded",timeout:r});let u=c.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(u))throw new Error(`Session expired after browser restart \u2014 landed on ${u}. Run: ilml linkedin login`)}return{browser:l,page:c}}await xr();var to=0,Cl=process.env.FUNNEL_CONNECT_RECRUITERS==="true",El=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Al=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),$l=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",Yo=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],Qt=-1;async function _l(){if(Qt===-1){let e=await Je("What is last counter? Answer only number!!");if(console.log(`Lifebot answered about lastIndex:${e}`),!/^\d+$/.test(e.trim()))throw new Error(`Last Counter is not a number, got: "${e}"`);Qt=an(e)+1,console.log(`lastIndex initialized as: ${Qt}`)}return Qt++}var si=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${si}`);var Tl=[{label:"linkedin-session-expired",match:e=>/redirected to login|cookies expired|Session expired after recovery/i.test(e.message),severity:"fatal",instructions:"Run: ilml linkedin login"},{label:"ilml-auth-expired",match:e=>{if(e.code==="PROCESSING_ERROR"||e.constructor?.name==="LifebotProcessingError")return!1;let t=e.message||"";return/Token is invalid or expired/i.test(t)||/\b401\b/.test(t)||/Unauthorized/i.test(t)||/authentication.*(failed|required)/i.test(t)},severity:"fatal",instructions:"Run: ilml login (this is the iLiveMyLife platform login, not the LinkedIn one)"},{label:"lifebot-timeout",match:e=>e.constructor.name==="LifebotTimeoutError",severity:"transient",maxConsecutive:3,cleanup:"popup"},{label:"lifebot-provider-error",match:e=>e.code==="PROCESSING_ERROR"||e.constructor.name==="LifebotProcessingError"||/AI provider returned an unexpected error/i.test(e.message||""),severity:"transient",maxConsecutive:3,cleanup:"popup",cooldownMs:3e3,instructions:"The AI provider had a hiccup. If it keeps failing, switch the provider in your Lifebot node settings."},{label:"stale-context",match:e=>/Execution context was destroyed|Cannot find context/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3}],Ct={};function li(e){let t=e;for(let o=0;t&&o<5;o++){let r=Tl.find(n=>{try{return n.match(t)}catch{return!1}});if(r)return r;t=t.cause}return null}function Rl(e){return Ct[e]=(Ct[e]||0)+1,Ct[e]}function Xr(){for(let e of Object.keys(Ct))Ct[e]=0}var Ko=0;function Il(){return Ko++,Ko>=si?(console.log(`Max run counter reached with ${Ko}`),!1):!0}async function Dl(e){let t=await ar(e)}async function jl(e){return cr(e,{easyApplyOnly:!0})}async function Ll(e){return ur(e)}async function Xo(e,t){return jo(e,t)}var zo=3,Nl=2;async function Zt(e,t){let{searchUrl:o,launchFn:r,setupPage:n,cookiesProvider:i}=e.recoveryCtx,s=await Wr(e.browser);if(!s||e._pageRecoveryStreak>=zo){if(k.browserRestarts>=Nl)throw new Error(`CDP unrecoverable: ${k.browserRestarts} browser restart${k.browserRestarts===1?"":"s"} and ${k.cdpRecoveries} page recover${k.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let l=s?`${zo} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${l}). Reason: ${t}`);let c=await Kr(e.browser,{launchFn:r,setupPage:n,cookiesProvider:i,returnUrl:o});e.browser=c.browser,e.page=c.page,e._pageRecoveryStreak=0,k.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${k.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${zo}). Reason: ${t}`),e.page=await Yr(e.browser,e.page,{returnUrl:o,cookiesProvider:i,setupPage:n}),e._pageRecoveryStreak+=1,k.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${k.cdpRecoveries}).`)}async function Pl(e){let{searchUrl:t}=e.recoveryCtx,o=3;e._pageRecoveryStreak=e._pageRecoveryStreak||0;for(let r=1;r<=o;r++){if(r>1){console.log(`
|
|
296
|
-
--- Pass ${r}/${o}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(u){if(nt(u))await Zt(e,`pass-${r} navigation: ${u.message?.slice(0,80)}`);else throw u}await w(3e3)}let n=k.submitted,i=k.cdpRecoveries+k.browserRestarts,s=!0,a=!0;for(;s&&a;){if(!await Gr(e.page)){await Zt(e,"liveness probe failed twice");continue}try{await Xo(e.page,t);let f=await Ql(e.page,ci,Dl);a=f.keepGoing;let d=f.jobsDone;if(console.log("keepGoing",a),console.log("pageDone"),console.log(d.length),!a)break;s=await Ll(e.page),e._pageRecoveryStreak=0}catch(f){if(!nt(f))throw f;await Zt(e,`mid-iteration: ${f.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!a)break;let l=k.submitted-n,c=k.cdpRecoveries+k.browserRestarts-i;if(l===0){if(c>0&&r<o){console.log(`No new jobs applied in pass ${r}, but ${c} CDP recover${c===1?"y":"ies"} \u2014 pass ${r+1} will retry.`);continue}console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${l} new jobs in pass ${r}.`)}}async function Zr(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return dr(e,t,o,r)}async function ei(e,t){let o=t?.match(/\d+/)?.[0]||t,r=await e.$(`div[data-job-id="${o}"] button[aria-label^="Dismiss"]`);r?(await r.click(),console.log(` Dismissed job ${o} from list`)):console.log(` Dismiss button not found for ${o}`)}async function Fl(e,t){try{let o=await fr(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},lt("recruiters-from-jobs",o)?(to++,console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F3AF} RECRUITER FOUND \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Name: ${o.name?.substring(0,30).padEnd(30)} \u2502`),console.log(`\u2502 Source: ${o.source.padEnd(28)} \u2502`),console.log(`\u2502 Company: ${t.companyName?.substring(0,27).padEnd(27)} \u2502`),console.log(`\u2502 Total today: ${String(to).padEnd(23)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")):console.log(` \u2139 Recruiter already saved: ${o.name}`),Ce(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){jt(o.profileUrl,n),Ke(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let i=o.fromJob?.companyUrl;i&&Jt(i,{recruiterUrl:o.profileUrl,jobId:n})}return o}else console.log(" \u26AA No recruiter found on this job page");return null}catch(o){return console.error("Error extracting recruiter:",o.message),null}}async function eo(e){return await e.evaluate(()=>{let t=document.body.innerText||"",o=document.querySelector("#interop-outlet")?.shadowRoot?.textContent||"",r=t+" "+o;return r.includes("We limit daily submissions")||r.includes("We limit Easy Apply submissions")||r.includes("Easy Apply limit")||r.includes("reached today")||r.includes("apply tomorrow")})}async function ai(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let n of o){let i=n.querySelectorAll("button");for(let s of i){let a=s.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return s.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return t&&console.log(" Daily limit popup closed"),t}catch{return!1}}async function ti(e){await e.evaluate(()=>{let s=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of s)for(let l of a.querySelectorAll("button")){let c=l.innerText?.trim();if(c==="Continue applying"||c==="Got it"||c==="Dismiss"){l.click();return}}});let t=Date.now(),o=3e3,r=null;for(;!r&&Date.now()-t<o;){if(r=await e.$(".jobs-apply-button"),r||(r=await e.$('button[aria-label*="Easy Apply"]')),r||(r=await e.$('a[aria-label*="Easy Apply"]')),r||(r=await e.$('a[href*="/apply/"]')),!r){let s=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let l of a){let c=l.innerText?.trim();if(c==="Easy Apply"||c==="Apply")return l}return null});r=s?.asElement?.()||null,r||await s.dispose().catch(()=>{})}r||await new Promise(s=>setTimeout(s,300))}let n=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${n>400?` (waited ${n}ms)`:""}`),r){if(await e.evaluate(c=>c.disabled,r))return await eo(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(c=>c.tagName==="A",r)){await e.evaluate(c=>c.click(),r),await w(3e3);try{await e.waitForFunction(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[data-easy-apply-next-button], button[aria-label="Submit application"]'),{timeout:1e4})}catch{await w(2e3)}}else await r.click(),await w(1500);return await eo(e)?(await ai(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await eo(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function Ol(e){return await e.evaluate(async()=>{function t(){let l=document.querySelectorAll(".artdeco-inline-feedback__message");if(l.length>0)return l;let c=document.querySelector("#interop-outlet")?.shadowRoot;return c&&(l=c.querySelectorAll(".artdeco-inline-feedback__message")),l}let o=3e3,r=t();if(r?.length===0&&(await new Promise(l=>setTimeout(l,o)),r=t()),r?.length===0)return null;let n=r[0];console.log("errorMsg"),console.log(n);let i=n?.textContent.trim(),s=n.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=n.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(s),a||s){console.log("parentElement"),console.log(a);let l=a.querySelector(".artdeco-text-input--label")||a.querySelector("legend .fb-dash-form-element__label-title--is-required")||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||a.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),c=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),u=a.querySelectorAll('input[type="radio"]'),f=a.querySelector("select[data-test-text-entity-list-form-select]"),d=n.parentElement.parentElement.querySelector('input[type="file"]'),p=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(d),l&&c)return{type:"input",labelText:l.textContent.trim(),errorMsgText:i};if(l&&u.length){let m=l?l.querySelector("span:nth-of-type(1)")?.textContent.trim():null,h=Array.from(u).map(y=>{let v=(document.querySelector(`label[for="${y.id}"]`)||y.nextElementSibling)?.textContent?.trim();return{value:y.value,label:v||y.value}}),g=h.map(y=>y.label);return{type:"radio",labelText:m,errorMsgText:i,options:g,optionsData:h}}else if(f){let m=a.querySelector('label[for="'+f.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),h=m?m.querySelector("span:nth-of-type(2)")?.textContent.trim():null,g=Array.from(f.options).map(y=>y.value).filter(y=>y!=="Select an option");return{type:"select",labelText:h,errorMsgText:i,options:g}}else if(d){let m=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:i,labelText:m}}else{if(p)return{type:"datePicker",errorMsgText:i};{let m=l?l.querySelector("span:nth-of-type(2)")?.textContent.trim():null,h=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(h.length>0){let g=Array.from(h).map(y=>y.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:m,errorMsgText:i,options:g}}else return null}}}return null})}async function ql(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));l.value=n;let c=new Event("input",{bubbles:!0});if(l.dispatchEvent(c),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let u=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},f=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),f(p),await new Promise(m=>setTimeout(m,100)),u(p)})(l)}}return null},t,o)}async function Ml(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('input[type="radio"]'),c=n;if(r.optionsData){let u=r.optionsData.find(f=>f.label.toLowerCase()===n.toLowerCase());u&&(c=u.value,console.log(`Radio: matched label "${n}" to value "${c}"`))}for(let u of l){let d=(document.querySelector(`label[for="${u.id}"]`)||u.nextElementSibling)?.textContent?.trim()||"";if(u.value.toLowerCase()===c.toLowerCase()||d.toLowerCase()===n.toLowerCase()){u.checked=!0;let p=new Event("change",{bubbles:!0});u.dispatchEvent(p),console.log(`Radio selected: value="${u.value}", label="${d}"`);break}}}return null},t,o)}async function Ul(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector("select[data-test-text-entity-list-form-select]");if(!l)return null;let c=Array.from(l.options),u=c.find(d=>d.text.toLowerCase()===n.toLowerCase())||c.find(d=>d.text.toLowerCase().includes(n.toLowerCase()));u?l.value=u.value:l.value=n;let f=new Event("change",{bubbles:!0});l.dispatchEvent(f)}return null},t,o)}async function Bl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');l.length>0&&l.forEach(c=>{if(c.nextElementSibling.textContent.trim()===n.trim()){c.checked=!0;let u=new Event("change",{bubbles:!0});c.dispatchEvent(u)}})}return null},t,o)}async function Jl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i?.length===0)return null;let s=i[0],a=s.closest(".fb-dash-form-element"),l=s.parentElement.parentElement.querySelector('input[type="file"]');if(a&&l){async function c(u,f,d){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let m=new Blob([new Uint8Array(f)]),h=new File([m],d,{type:"application/pdf"}),g=new DataTransfer;g.items.add(h),u.files=g.files;let y=new Event("change",{bubbles:!0});u.dispatchEvent(y)}await c(l,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function oi(e){let t=await Ol(e);if(t===null)return null;if(t?.type==="input"){let n=await no(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await ql(e,t,n)}else if(t?.type==="radio"){let n=await Et(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[];!i.find(a=>a.toLowerCase()===n?.toLowerCase())&&i.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await Et(t.labelText,t.options),n=n?.trim()||n,i.find(l=>l.toLowerCase()===n?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])),t.answer=n,await Ml(e,t,n)}else if(t?.type==="select"){let n=await it(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[],s=i.find(a=>a.toLowerCase()===n?.toLowerCase());if(s)n=s;else if(i.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await it(t.labelText,t.options),n=n?.trim()||n;let a=i.find(l=>l.toLowerCase()===n?.toLowerCase());a?n=a:(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])}t.answer=n,await Ul(e,t,n)}else if(t?.type==="checkbox"){let n=await it(t.labelText,t.options);t.answer=n,await Bl(e,t,n)}else if(t?.type==="file"){let n=process.env.RESUME_PDF_URL;t.answer=n;let i=await fetch(n);if(!i.ok)throw new Error("Network response was not ok");let s=await i.arrayBuffer();await Jl(e,t,s)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let o=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${o}" \u2192 ${r}`),t}async function Hl(e){return await e.evaluate(async()=>{let t=[],o=document.querySelectorAll(".fb-dash-form-element");if(!o||o.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(o=r.querySelectorAll(".fb-dash-form-element"))}if(!o||o.length===0)return[];for(let r of o){let n=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),s=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),l=r.querySelector("select[data-test-text-entity-list-form-select]"),c=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),u=r.querySelector('input[type="file"]');if(n&&s&&a.length===0){let f=n.textContent.trim();t.push({type:"input",labelText:f,answer:s.value,isRequired:i,wasPreFilled:!!s.value})}else if(n&&a.length){let f=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,d=Array.from(a).map(m=>m.value),p=(Array.from(a).find(m=>m.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:f,options:d,answer:p,isRequired:i,wasPreFilled:!!p})}else if(l){let f=r.querySelector('label[for="'+l.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),d=f?.querySelector("span:nth-of-type(2)")?.textContent.trim()||f?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||f?.querySelector("span")?.textContent.trim()||f?.textContent?.trim()||null,p=Array.from(l.options).map(h=>h.value).filter(h=>h!=="Select an option"),m=l.value!=="Select an option"?l.value:"";t.push({type:"select",labelText:d,options:p,answer:m,isRequired:i,wasPreFilled:!!m})}else if(c.length>0){let f=r.querySelector("legend span")?.textContent?.trim(),d=Array.from(c).map(h=>({label:h.nextElementSibling?.textContent?.trim()||h.value,checked:h.checked})),p=d.some(h=>h.checked),m=d.filter(h=>h.checked).map(h=>h.label).join(", ");t.push({type:"checkbox",labelText:f,options:d.map(h=>h.label),answer:m,isRequired:i,wasPreFilled:p})}else if(u){let f=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:f,answer:u.value?"uploaded":"",isRequired:i,wasPreFilled:!!u.value})}}return t})}async function Zo(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelector(".artdeco-text-input--label")||s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||s.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),l=s.querySelector(".artdeco-text-input--input")||s.querySelector("input");if(a&&l&&r===a.textContent.trim()){l.value=n;let c=new Event("input",{bubbles:!0});if(l.dispatchEvent(c),r==="City"||r==="Location (city)"){let u=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},f=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),f(p),await new Promise(m=>setTimeout(m,100)),u(p)})(l)}return!0}}return!1},t,o)}async function Vl(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelectorAll('input[type="radio"]');if(a.length===0)continue;let l=s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('legend [class*="fb-dash-form-element__label"]')||s.querySelector("legend span");if((l?.querySelector("span:nth-of-type(1)")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let u=(n||"").toLowerCase();for(let f of a){let d=f.getRootNode(),m=(f.id&&d.querySelector(`label[for="${f.id}"]`)||f.nextElementSibling)?.textContent?.trim()||"";if(f.value.toLowerCase()===u||m.toLowerCase()===u)return f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function Gl(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelector("select[data-test-text-entity-list-form-select]");if(!a)continue;let l=s.querySelector(`label[for="${a.id}"]`)||s.querySelector(".fb-dash-form-element__label-title--is-required");if((l?.querySelector("span:nth-of-type(2)")?.textContent.trim()||l?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||l?.querySelector("span")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let u=Array.from(a.options),f=(n||"").toLowerCase(),d=u.find(p=>p.text.toLowerCase()===f)||u.find(p=>p.value.toLowerCase()===f)||u.find(p=>p.text.toLowerCase().includes(f));return d?(a.value=d.value,a.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function Wl(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let a=document.querySelector("#interop-outlet")?.shadowRoot;a&&(i=a.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;let s=(n||"").split(",").map(a=>a.trim().toLowerCase()).filter(Boolean);if(s.length===0)return!1;for(let a of i){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(l.length===0||a.querySelector("legend span")?.textContent?.trim()!==r)continue;let u=!1;for(let f of l){let d=(f.nextElementSibling?.textContent||f.value||"").trim().toLowerCase();s.includes(d)&&!f.checked&&(f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),u=!0)}return u}return!1},t,o)}async function Yl(e,t){for(let o of t){if(!o.labelText||o.isRequired||o.wasPreFilled||o.answer||o.type==="datePicker"||o.type==="file")continue;let r="";try{if(o.type==="input")r=await no(o.labelText,"");else if(o.type==="radio")r=await Et(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await it(o.labelText,o.options||[]);else continue}catch(s){console.log(` \u26A0 Lifebot failed for optional "${o.labelText}": ${s.message?.slice(0,80)}`);continue}if(r=(r||"").trim(),o.wasOptional=!0,!r){o.answer="",console.log(` ? [opt ${o.type}] "${o.labelText.slice(0,55)}" \u2192 (empty)`);continue}let n=!1;try{o.type==="input"?n=await Zo(e,o.labelText,r):o.type==="radio"?n=await Vl(e,o.labelText,r):o.type==="select"?n=await Gl(e,o.labelText,r):o.type==="checkbox"&&(n=await Wl(e,o.labelText,r))}catch(s){console.log(` \u26A0 setter failed for "${o.labelText}": ${s.message?.slice(0,80)}`)}o.answer=r,console.log(` ? [${n?"opt":"opt-noapply"} ${o.type}] "${o.labelText.slice(0,55)}" \u2192 "${r.slice(0,50)}"`)}}async function ni(e,t){let o=[],r=!0,n=0,i=null,s=0;for(;r;){if(n++,await eo(e))return console.log(" Daily limit reached during form navigation"),await ai(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let c=(await Hl(e)).filter(p=>!o.some(m=>m.labelText===p.labelText));o.push(...c);try{let p=o.find(h=>h.labelText==="City"||h.labelText==="Location (city)"),m=o.filter(h=>h.labelText!=null).find(h=>h.labelText!==null&&h.labelText.trim()!==null&&(h.labelText.trim().toLowerCase()==="cv"||h.labelText.trim().toLowerCase()==="curriculum vitae"||h.labelText.trim().toLowerCase()==="cover letter"||h.labelText.trim().toLowerCase()==="cover"));if(p&&!p.answer){let h=process.env.City;await Zo(e,p.labelText,h),p.answer=h}else if(m){let h=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!m.answer||m.answer!==h)&&(await w(1e4),await Zo(e,m.labelText,h),m.answer=h,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await Yl(e,c)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let u=null;try{u=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(u!==null){if(u.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:u};let p=u&&o.find(h=>h.errorMsgText&&h.labelText===u.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(u,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:u};let m=o.findIndex(h=>h.labelText===u.labelText&&!h.answer);m!==-1&&o.splice(m,1),o.push(u)}let f=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of p){let h=m.querySelectorAll("button");for(let g of h){let y=g.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return g.click(),y}}return null});f&&console.log(` Dismissed safety popup (${f})`);let d=await e.evaluate(async()=>{function p(b){let E=document.querySelector(b);if(E)return E;let R=document.querySelector("#interop-outlet")?.shadowRoot;return R?R.querySelector(b):null}function m(b){let E=document.querySelectorAll(b),R=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(b);return[...E||[],...R||[]]}let h=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(b=>b.innerText?.trim()==="Next"),g=m('footer[role="presentation"] button').some(b=>b.innerText.trim()==="Review")||m("button").some(b=>b.innerText.trim()==="Review"&&b.getAttribute("aria-label")?.includes("Review")),y=p('button[aria-label="Submit application"]'),S=async()=>{let b=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(E=>E.innerText?.trim()==="Next");b?b.click():console.log("Next button not found")},v=()=>{let b=m("button").find(E=>E.innerText?.trim()==="Review");b&&b.click()};return h?(await S(),{type:"next"}):g?(await v(),{type:"review"}):y?{type:"submit"}:{type:null}});if(d==null)return{filledFields:o,formPages:n,skip:!0};if(d.type&&console.log(` \u2192 ${d.type}`),d.type===null){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of m){let g=h.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of g){let S=y.innerText||"";if(S.includes("application was sent")||S.includes("resume into a profile")||S.includes("Application submitted")||S.includes("Next best action"))for(let v of y.querySelectorAll("button")){let b=v.innerText?.trim();if(b==="Not now"||b==="Done"||b==="Dismiss"||b==="Got it")return v.click(),b}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await w(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(s===0){let m=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],y=[];for(let S of h){for(let b of S.querySelectorAll("button")){let E=b.innerText?.trim();E&&E.length<60&&g.push(E)}let v=S.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');v&&y.push(v.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(m.buttons)}`),m.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(m.modalText)}`)}}if(d.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(u===null&&d.type===i?s++:s=0,i=d.type,s>=5){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),h=[],g=[];for(let y of m){for(let S of y.querySelectorAll(".artdeco-inline-feedback__message"))h.push(S.textContent?.trim()?.slice(0,60));for(let S of y.querySelectorAll(".fb-dash-form-element")){let v=S.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),b=S.querySelector("input, select, textarea"),E=!!S.querySelector(".artdeco-inline-feedback__message");v&&(E||b&&!b.value)&&g.push({label:v.slice(0,40),hasError:E,value:b?.value?.slice(0,20)||""})}}return{errors:h,emptyRequired:g.slice(0,5)}});return console.error(` \u26A0 Stuck on "${d.type}" for ${s} iterations \u2014 form not progressing.`),p.errors.length&&console.error(` Visible errors: ${JSON.stringify(p.errors)}`),p.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(p.emptyRequired)}`),console.error(" Skipping job."),{filledFields:o,formPages:n,skip:!0,duplicateField:{labelText:`stuck_on_${d.type}`}}}await w(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function ri(e){try{await e.evaluate(()=>{let t=document.getElementById("follow-company-checkbox");t?(t.checked=!1,t.dispatchEvent(new Event("change",{bubbles:!0}))):console.warn("Unfollow checkbox not found.")})}catch(t){console.error("Error in unfollowJobCheckbox:",t)}}async function Kl(e){let t=await e.$('button[aria-label="Submit application"]');if(!t){let o=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Submit application"]')||null);t=o?.asElement?.()||null,t||await o.dispose().catch(()=>{})}t&&await t.click()}async function zl(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of o){for(let i of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(i.innerText?.trim()==="Done")return i.click(),"Done";let n=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let i of n){let s=i.innerText||"";if(s.includes("application was sent")||s.includes("Application sent")||s.includes("resume into a profile")||s.includes("Next best action"))for(let a of i.querySelectorAll("button")){let l=a.innerText?.trim();if(l==="Not now"||l==="Dismiss")return a.click(),l}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await w(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function Xt(e){try{await e.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let t=await e.$('button[aria-label="Dismiss"]');t?(await t.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await w(1e3)):console.log("Popup \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.")}catch{console.log("closeJobApplicationPopup failed to execute: \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D \u0438\u043B\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F.")}}async function Qo(e){try{await e.waitForSelector('button[data-control-name="discard_application_confirm_btn"]',{timeout:3e3});let t=await e.$('button[data-control-name="discard_application_confirm_btn"]');t&&(await t.click(),console.log("Discard confirmed"),await w(500))}catch{console.log("No discard confirmation needed")}}async function ci(e,t){let o=[],r=t._fromQueue;try{k.attempted++,console.log(`
|
|
297
|
-
--- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&
|
|
295
|
+
`)}`;try{await Ie.addMessage(s,l)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var gl=yl(import.meta.url),bl=_e.dirname(_e.dirname(gl)),Wo=process.env.DATA_DIR?_e.resolve(process.env.DATA_DIR,"collected-profiles"):_e.join(bl,"collected-profiles"),Yo=_e.join(Wo,"run-log.json");function wl(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ce.writeFileSync(r,o);for(let n=0;n<3;n++)try{ce.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Rr(){try{if(!ce.existsSync(Yo))return{runs:[]};let e=JSON.parse(ce.readFileSync(Yo,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ir(e){ce.existsSync(Wo)||ce.mkdirSync(Wo,{recursive:!0});try{wl(Yo,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function jr(e,t="default"){let o=Rr();for(let s of o.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let r=new Date,n={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(s=>new Date(s.timestamp).getTime()>i),Ir(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Dr(e,t,o=null,r=null){if(!e)return;let n=null;try{let s=Rr(),a=s.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=o,a.error=r,n=a.duration;else{let l=s.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=r,n=l.duration)}Ir(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Tr({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:r,duration:n??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import de from"fs";import $e from"path";var Sl="cookies.json";function Lr(){let e=process.env.ILML_SCOPE_DIR;return e?$e.join(e,"plugins-state","linkedin","cookies.json"):Sl}function Qt(){let e=Lr();if(!de.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=de.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}function Nr(){return de.existsSync(Lr())}function kl(){let e=process.env.ILML_SCOPE_DIR;return e?$e.join(e,"plugins-state","linkedin"):"."}function Pr(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function vl(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Pr(t[1]):"default"}function Fr(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return de.existsSync(t)||de.mkdirSync(t,{recursive:!0}),$e.resolve(t);let o=Pr(e||vl()),r=$e.join(kl(),"chrome-profile",o);return de.existsSync(r)||de.mkdirSync(r,{recursive:!0}),$e.resolve(r)}var Or=".ilml-seeded";function qr(e){return!de.existsSync($e.join(e,Or))}function Mr(e){try{de.writeFileSync($e.join(e,Or),new Date().toISOString())}catch{}}function Ur(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{de.rmSync($e.join(e,o),{force:!0}),t++}catch{}return t}import Ko from"fs";import xl from"path";var Cl={headless:!1,defaultViewport:null,protocolTimeout:3e5},xt=new Set,Br=!1;async function Xt(){let e=[...xt].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});xt.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function El(){if(Br)return;Br=!0;let e=t=>async()=>{await Xt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Xt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Xt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Xt(),process.exit(0))}),process.on("exit",()=>{for(let t of xt)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function zo(e){return xl.join(e,".ilml-browser-session.json")}function Gr(e,t={}){try{Ko.writeFileSync(zo(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Al(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();Gr(e,o?{wsEndpoint:o}:{})}catch{}}function _l(e){let t=Wr(e);t&&t.ownerPid===process.pid&&vt(e)}function vt(e){try{Ko.rmSync(zo(e),{force:!0})}catch{}}function Wr(e){try{return JSON.parse(Ko.readFileSync(zo(e),"utf-8"))}catch{return null}}function Jr(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Hr(e,t,o){let r,n=new Promise(s=>{r=setTimeout(()=>s(o),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(r),s),s=>{throw clearTimeout(r),s});return Promise.race([i,n])}async function Vr(e,t,{probeTimeoutMs:o=4e3}={}){let r=Wr(t);if(!r)return"free";if(!r.wsEndpoint)return r.ownerPid&&r.ownerPid!==process.pid&&Jr(r.ownerPid)?"live":(vt(t),"free");let n=Symbol("timeout"),i=e.connect({browserWSEndpoint:r.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await Hr(i,o,n);if(s===n)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return vt(t),"free";if(Jr(r.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Hr(s.close().then(()=>!0).catch(()=>!1),o,!1))return vt(t),"free";try{s.disconnect()}catch{}return"live"}function $l(e,t){e&&(El(),xt.add(e),e.on("disconnected",()=>{xt.delete(e),t&&vt(t)}))}async function Qo(e,t={}){let o=Fr(),r={...Cl,...t,userDataDir:o},n=`Could not open the LinkedIn automation Chrome profile at ${o}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Vr(e,o)==="live")throw new Error(n);Gr(o);let i;try{i=await e.launch(r)}catch{if(await Vr(e,o)==="live")throw new Error(n);Ur(o);try{i=await e.launch(r)}catch(a){throw _l(o),new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${a.message})`)}}return $l(i,o),Al(o,i),{browser:i,profileDir:o,needsSeed:qr(o)}}async function Yr(e,t){if(!t||!t.needsSeed)return!1;if(!Nr())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...Qt()),Mr(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}Ue();async function Ct(e,t,o="op"){let r,n=new Promise((i,s)=>{r=setTimeout(()=>s(new Error(`${o} timeout after ${t}ms`)),t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}function nt(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let o=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(o)||/Target closed/i.test(o)||/Session closed/i.test(o)||/Connection closed/i.test(o)||/Most likely the page has been closed/i.test(o)||/Navigating frame was detached/i.test(o)||/Protocol error.*timed out/i.test(o)}async function Kr(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await Ct(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function zr(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await Kr(e,t)?!0:(await w(o),await Kr(e,t))}async function Qr(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await Ct(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function Xr(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){try{await Ct(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let s=await e.newPage();if(i)try{await i(s)}catch{}if(n)try{let a=n();Array.isArray(a)&&a.length>0&&await s.setCookie(...a)}catch{}if(o){await s.goto(o,{waitUntil:"domcontentloaded",timeout:r});let a=s.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(a))throw new Error(`Session expired after recovery \u2014 landed on ${a}. Run: ilml linkedin login`)}return s}async function Zr(e,{launchFn:t,returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");let s=null;try{s=e.process()}catch{}let a=!1;try{await Ct(e.close(),5e3,"oldBrowser.close"),a=!0}catch{}if(!a&&s&&s.pid&&s.exitCode===null){try{s.kill("SIGKILL")}catch{}try{await Ct(new Promise(u=>s.once("exit",u)),5e3,"oldBrowser.kill")}catch{}}let l=await t(),c=await l.newPage();if(i)try{await i(c)}catch{}if(n)try{let u=n();Array.isArray(u)&&u.length>0&&await c.setCookie(...u)}catch{}if(o){await c.goto(o,{waitUntil:"domcontentloaded",timeout:r});let u=c.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(u))throw new Error(`Session expired after browser restart \u2014 landed on ${u}. Run: ilml linkedin login`)}return{browser:l,page:c}}await _r();var no=0,Tl=process.env.FUNNEL_CONNECT_RECRUITERS==="true",Rl=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Il=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),jl=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",Xo=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],Zt=-1;async function Dl(){if(Zt===-1){let e=await Je("What is last counter? Answer only number!!");if(console.log(`Lifebot answered about lastIndex:${e}`),!/^\d+$/.test(e.trim()))throw new Error(`Last Counter is not a number, got: "${e}"`);Zt=fn(e)+1,console.log(`lastIndex initialized as: ${Zt}`)}return Zt++}var ui=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${ui}`);var Ll=[{label:"linkedin-session-expired",match:e=>/redirected to login|cookies expired|Session expired after recovery/i.test(e.message),severity:"fatal",instructions:"Run: ilml linkedin login"},{label:"ilml-auth-expired",match:e=>{if(e.code==="PROCESSING_ERROR"||e.constructor?.name==="LifebotProcessingError")return!1;let t=e.message||"";return/Token is invalid or expired/i.test(t)||/\b401\b/.test(t)||/Unauthorized/i.test(t)||/authentication.*(failed|required)/i.test(t)},severity:"fatal",instructions:"Run: ilml login (this is the iLiveMyLife platform login, not the LinkedIn one)"},{label:"lifebot-timeout",match:e=>e.constructor.name==="LifebotTimeoutError",severity:"transient",maxConsecutive:3,cleanup:"popup"},{label:"lifebot-provider-error",match:e=>e.code==="PROCESSING_ERROR"||e.constructor.name==="LifebotProcessingError"||/AI provider returned an unexpected error/i.test(e.message||""),severity:"transient",maxConsecutive:3,cleanup:"popup",cooldownMs:3e3,instructions:"The AI provider had a hiccup. If it keeps failing, switch the provider in your Lifebot node settings."},{label:"stale-context",match:e=>/Execution context was destroyed|Cannot find context/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3}],Et={};function di(e){let t=e;for(let o=0;t&&o<5;o++){let r=Ll.find(n=>{try{return n.match(t)}catch{return!1}});if(r)return r;t=t.cause}return null}function Nl(e){return Et[e]=(Et[e]||0)+1,Et[e]}function oi(){for(let e of Object.keys(Et))Et[e]=0}var Zo=0;function Pl(){return Zo++,Zo>=ui?(console.log(`Max run counter reached with ${Zo}`),!1):!0}async function Fl(e){let t=await fr(e)}async function Ol(e){return pr(e,{easyApplyOnly:!0})}async function ql(e){return mr(e)}async function on(e,t){return Fo(e,t)}var en=3,Ml=2;async function to(e,t){let{searchUrl:o,launchFn:r,setupPage:n,cookiesProvider:i}=e.recoveryCtx,s=await Qr(e.browser);if(!s||e._pageRecoveryStreak>=en){if(k.browserRestarts>=Ml)throw new Error(`CDP unrecoverable: ${k.browserRestarts} browser restart${k.browserRestarts===1?"":"s"} and ${k.cdpRecoveries} page recover${k.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let l=s?`${en} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${l}). Reason: ${t}`);let c=await Zr(e.browser,{launchFn:r,setupPage:n,cookiesProvider:i,returnUrl:o});e.browser=c.browser,e.page=c.page,e._pageRecoveryStreak=0,k.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${k.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${en}). Reason: ${t}`),e.page=await Xr(e.browser,e.page,{returnUrl:o,cookiesProvider:i,setupPage:n}),e._pageRecoveryStreak+=1,k.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${k.cdpRecoveries}).`)}async function Ul(e){let{searchUrl:t}=e.recoveryCtx,o=3;e._pageRecoveryStreak=e._pageRecoveryStreak||0;for(let r=1;r<=o;r++){if(r>1){console.log(`
|
|
296
|
+
--- Pass ${r}/${o}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(u){if(nt(u))await to(e,`pass-${r} navigation: ${u.message?.slice(0,80)}`);else throw u}await w(3e3)}let n=k.submitted,i=k.cdpRecoveries+k.browserRestarts,s=!0,a=!0;for(;s&&a;){if(!await zr(e.page)){await to(e,"liveness probe failed twice");continue}try{await on(e.page,t);let f=await oa(e.page,pi,Fl);a=f.keepGoing;let d=f.jobsDone;if(console.log("keepGoing",a),console.log("pageDone"),console.log(d.length),!a)break;s=await ql(e.page),e._pageRecoveryStreak=0}catch(f){if(!nt(f))throw f;await to(e,`mid-iteration: ${f.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!a)break;let l=k.submitted-n,c=k.cdpRecoveries+k.browserRestarts-i;if(l===0){if(c>0&&r<o){console.log(`No new jobs applied in pass ${r}, but ${c} CDP recover${c===1?"y":"ies"} \u2014 pass ${r+1} will retry.`);continue}console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${l} new jobs in pass ${r}.`)}}async function ni(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return hr(e,t,o,r)}async function ri(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 Bl(e,t){try{let o=await yr(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},at("recruiters-from-jobs",o)?(no++,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(no).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}`),ve(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){Nt(o.profileUrl,n),Ke(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let i=o.fromJob?.companyUrl;i&&Vt(i,{recruiterUrl:o.profileUrl,jobId:n})}return o}else console.log(" \u26AA No recruiter found on this job page");return null}catch(o){return console.error("Error extracting recruiter:",o.message),null}}async function oo(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 fi(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let n of o){let i=n.querySelectorAll("button");for(let s of i){let a=s.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return s.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return t&&console.log(" Daily limit popup closed"),t}catch{return!1}}async function ii(e){await e.evaluate(()=>{let s=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of s)for(let l of a.querySelectorAll("button")){let c=l.innerText?.trim();if(c==="Continue applying"||c==="Got it"||c==="Dismiss"){l.click();return}}});let t=Date.now(),o=3e3,r=null;for(;!r&&Date.now()-t<o;){if(r=await e.$(".jobs-apply-button"),r||(r=await e.$('button[aria-label*="Easy Apply"]')),r||(r=await e.$('a[aria-label*="Easy Apply"]')),r||(r=await e.$('a[href*="/apply/"]')),!r){let s=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let l of a){let c=l.innerText?.trim();if(c==="Easy Apply"||c==="Apply")return l}return null});r=s?.asElement?.()||null,r||await s.dispose().catch(()=>{})}r||await new Promise(s=>setTimeout(s,300))}let n=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${n>400?` (waited ${n}ms)`:""}`),r){if(await e.evaluate(c=>c.disabled,r))return await oo(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(c=>c.tagName==="A",r)){await e.evaluate(c=>c.click(),r),await w(3e3);try{await e.waitForFunction(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[data-easy-apply-next-button], button[aria-label="Submit application"]'),{timeout:1e4})}catch{await w(2e3)}}else await r.click(),await w(1500);return await oo(e)?(await fi(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await oo(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function Jl(e){return await e.evaluate(async()=>{function t(){let l=document.querySelectorAll(".artdeco-inline-feedback__message");if(l.length>0)return l;let c=document.querySelector("#interop-outlet")?.shadowRoot;return c&&(l=c.querySelectorAll(".artdeco-inline-feedback__message")),l}let o=3e3,r=t();if(r?.length===0&&(await new Promise(l=>setTimeout(l,o)),r=t()),r?.length===0)return null;let n=r[0];console.log("errorMsg"),console.log(n);let i=n?.textContent.trim(),s=n.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=n.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(s),a||s){console.log("parentElement"),console.log(a);let l=a.querySelector(".artdeco-text-input--label")||a.querySelector("legend .fb-dash-form-element__label-title--is-required")||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||a.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),c=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),u=a.querySelectorAll('input[type="radio"]'),f=a.querySelector("select[data-test-text-entity-list-form-select]"),d=n.parentElement.parentElement.querySelector('input[type="file"]'),p=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(d),l&&c)return{type:"input",labelText:l.textContent.trim(),errorMsgText:i};if(l&&u.length){let m=l?l.querySelector("span:nth-of-type(1)")?.textContent.trim():null,h=Array.from(u).map(y=>{let x=(document.querySelector(`label[for="${y.id}"]`)||y.nextElementSibling)?.textContent?.trim();return{value:y.value,label:x||y.value}}),g=h.map(y=>y.label);return{type:"radio",labelText:m,errorMsgText:i,options:g,optionsData:h}}else if(f){let m=a.querySelector('label[for="'+f.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),h=m?m.querySelector("span:nth-of-type(2)")?.textContent.trim():null,g=Array.from(f.options).map(y=>y.value).filter(y=>y!=="Select an option");return{type:"select",labelText:h,errorMsgText:i,options:g}}else if(d){let m=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:i,labelText:m}}else{if(p)return{type:"datePicker",errorMsgText:i};{let m=l?l.querySelector("span:nth-of-type(2)")?.textContent.trim():null,h=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(h.length>0){let g=Array.from(h).map(y=>y.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:m,errorMsgText:i,options:g}}else return null}}}return null})}async function Hl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));l.value=n;let c=new Event("input",{bubbles:!0});if(l.dispatchEvent(c),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let u=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},f=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),f(p),await new Promise(m=>setTimeout(m,100)),u(p)})(l)}}return null},t,o)}async function Vl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('input[type="radio"]'),c=n;if(r.optionsData){let u=r.optionsData.find(f=>f.label.toLowerCase()===n.toLowerCase());u&&(c=u.value,console.log(`Radio: matched label "${n}" to value "${c}"`))}for(let u of l){let d=(document.querySelector(`label[for="${u.id}"]`)||u.nextElementSibling)?.textContent?.trim()||"";if(u.value.toLowerCase()===c.toLowerCase()||d.toLowerCase()===n.toLowerCase()){u.checked=!0;let p=new Event("change",{bubbles:!0});u.dispatchEvent(p),console.log(`Radio selected: value="${u.value}", label="${d}"`);break}}}return null},t,o)}async function Gl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector("select[data-test-text-entity-list-form-select]");if(!l)return null;let c=Array.from(l.options),u=c.find(d=>d.text.toLowerCase()===n.toLowerCase())||c.find(d=>d.text.toLowerCase().includes(n.toLowerCase()));u?l.value=u.value:l.value=n;let f=new Event("change",{bubbles:!0});l.dispatchEvent(f)}return null},t,o)}async function Wl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');l.length>0&&l.forEach(c=>{if(c.nextElementSibling.textContent.trim()===n.trim()){c.checked=!0;let u=new Event("change",{bubbles:!0});c.dispatchEvent(u)}})}return null},t,o)}async function Yl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i?.length===0)return null;let s=i[0],a=s.closest(".fb-dash-form-element"),l=s.parentElement.parentElement.querySelector('input[type="file"]');if(a&&l){async function c(u,f,d){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let m=new Blob([new Uint8Array(f)]),h=new File([m],d,{type:"application/pdf"}),g=new DataTransfer;g.items.add(h),u.files=g.files;let y=new Event("change",{bubbles:!0});u.dispatchEvent(y)}await c(l,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function si(e){let t=await Jl(e);if(t===null)return null;if(t?.type==="input"){let n=await lo(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await Hl(e,t,n)}else if(t?.type==="radio"){let n=await _t(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[];!i.find(a=>a.toLowerCase()===n?.toLowerCase())&&i.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await _t(t.labelText,t.options),n=n?.trim()||n,i.find(l=>l.toLowerCase()===n?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])),t.answer=n,await Vl(e,t,n)}else if(t?.type==="select"){let n=await st(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[],s=i.find(a=>a.toLowerCase()===n?.toLowerCase());if(s)n=s;else if(i.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await st(t.labelText,t.options),n=n?.trim()||n;let a=i.find(l=>l.toLowerCase()===n?.toLowerCase());a?n=a:(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])}t.answer=n,await Gl(e,t,n)}else if(t?.type==="checkbox"){let n=await st(t.labelText,t.options);t.answer=n,await Wl(e,t,n)}else if(t?.type==="file"){let n=process.env.RESUME_PDF_URL;t.answer=n;let i=await fetch(n);if(!i.ok)throw new Error("Network response was not ok");let s=await i.arrayBuffer();await Yl(e,t,s)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let o=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${o}" \u2192 ${r}`),t}async function Kl(e){return await e.evaluate(async()=>{let t=[],o=document.querySelectorAll(".fb-dash-form-element");if(!o||o.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(o=r.querySelectorAll(".fb-dash-form-element"))}if(!o||o.length===0)return[];for(let r of o){let n=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),s=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),l=r.querySelector("select[data-test-text-entity-list-form-select]"),c=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),u=r.querySelector('input[type="file"]');if(n&&s&&a.length===0){let f=n.textContent.trim();t.push({type:"input",labelText:f,answer:s.value,isRequired:i,wasPreFilled:!!s.value})}else if(n&&a.length){let f=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,d=Array.from(a).map(m=>m.value),p=(Array.from(a).find(m=>m.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:f,options:d,answer:p,isRequired:i,wasPreFilled:!!p})}else if(l){let f=r.querySelector('label[for="'+l.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),d=f?.querySelector("span:nth-of-type(2)")?.textContent.trim()||f?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||f?.querySelector("span")?.textContent.trim()||f?.textContent?.trim()||null,p=Array.from(l.options).map(h=>h.value).filter(h=>h!=="Select an option"),m=l.value!=="Select an option"?l.value:"";t.push({type:"select",labelText:d,options:p,answer:m,isRequired:i,wasPreFilled:!!m})}else if(c.length>0){let f=r.querySelector("legend span")?.textContent?.trim(),d=Array.from(c).map(h=>({label:h.nextElementSibling?.textContent?.trim()||h.value,checked:h.checked})),p=d.some(h=>h.checked),m=d.filter(h=>h.checked).map(h=>h.label).join(", ");t.push({type:"checkbox",labelText:f,options:d.map(h=>h.label),answer:m,isRequired:i,wasPreFilled:p})}else if(u){let f=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:f,answer:u.value?"uploaded":"",isRequired:i,wasPreFilled:!!u.value})}}return t})}async function nn(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelector(".artdeco-text-input--label")||s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||s.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),l=s.querySelector(".artdeco-text-input--input")||s.querySelector("input");if(a&&l&&r===a.textContent.trim()){l.value=n;let c=new Event("input",{bubbles:!0});if(l.dispatchEvent(c),r==="City"||r==="Location (city)"){let u=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},f=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),f(p),await new Promise(m=>setTimeout(m,100)),u(p)})(l)}return!0}}return!1},t,o)}async function zl(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelectorAll('input[type="radio"]');if(a.length===0)continue;let l=s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('legend [class*="fb-dash-form-element__label"]')||s.querySelector("legend span");if((l?.querySelector("span:nth-of-type(1)")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let u=(n||"").toLowerCase();for(let f of a){let d=f.getRootNode(),m=(f.id&&d.querySelector(`label[for="${f.id}"]`)||f.nextElementSibling)?.textContent?.trim()||"";if(f.value.toLowerCase()===u||m.toLowerCase()===u)return f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function Ql(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelector("select[data-test-text-entity-list-form-select]");if(!a)continue;let l=s.querySelector(`label[for="${a.id}"]`)||s.querySelector(".fb-dash-form-element__label-title--is-required");if((l?.querySelector("span:nth-of-type(2)")?.textContent.trim()||l?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||l?.querySelector("span")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let u=Array.from(a.options),f=(n||"").toLowerCase(),d=u.find(p=>p.text.toLowerCase()===f)||u.find(p=>p.value.toLowerCase()===f)||u.find(p=>p.text.toLowerCase().includes(f));return d?(a.value=d.value,a.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function Xl(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let a=document.querySelector("#interop-outlet")?.shadowRoot;a&&(i=a.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;let s=(n||"").split(",").map(a=>a.trim().toLowerCase()).filter(Boolean);if(s.length===0)return!1;for(let a of i){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(l.length===0||a.querySelector("legend span")?.textContent?.trim()!==r)continue;let u=!1;for(let f of l){let d=(f.nextElementSibling?.textContent||f.value||"").trim().toLowerCase();s.includes(d)&&!f.checked&&(f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),u=!0)}return u}return!1},t,o)}async function Zl(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 lo(o.labelText,"");else if(o.type==="radio")r=await _t(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await st(o.labelText,o.options||[]);else continue}catch(s){console.log(` \u26A0 Lifebot failed for optional "${o.labelText}": ${s.message?.slice(0,80)}`);continue}if(r=(r||"").trim(),o.wasOptional=!0,!r){o.answer="",console.log(` ? [opt ${o.type}] "${o.labelText.slice(0,55)}" \u2192 (empty)`);continue}let n=!1;try{o.type==="input"?n=await nn(e,o.labelText,r):o.type==="radio"?n=await zl(e,o.labelText,r):o.type==="select"?n=await Ql(e,o.labelText,r):o.type==="checkbox"&&(n=await Xl(e,o.labelText,r))}catch(s){console.log(` \u26A0 setter failed for "${o.labelText}": ${s.message?.slice(0,80)}`)}o.answer=r,console.log(` ? [${n?"opt":"opt-noapply"} ${o.type}] "${o.labelText.slice(0,55)}" \u2192 "${r.slice(0,50)}"`)}}async function li(e,t){let o=[],r=!0,n=0,i=null,s=0;for(;r;){if(n++,await oo(e))return console.log(" Daily limit reached during form navigation"),await fi(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let c=(await Kl(e)).filter(p=>!o.some(m=>m.labelText===p.labelText));o.push(...c);try{let p=o.find(h=>h.labelText==="City"||h.labelText==="Location (city)"),m=o.filter(h=>h.labelText!=null).find(h=>h.labelText!==null&&h.labelText.trim()!==null&&(h.labelText.trim().toLowerCase()==="cv"||h.labelText.trim().toLowerCase()==="curriculum vitae"||h.labelText.trim().toLowerCase()==="cover letter"||h.labelText.trim().toLowerCase()==="cover"));if(p&&!p.answer){let h=process.env.City;await nn(e,p.labelText,h),p.answer=h}else if(m){let h=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!m.answer||m.answer!==h)&&(await w(1e4),await nn(e,m.labelText,h),m.answer=h,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await Zl(e,c)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let u=null;try{u=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(u!==null){if(u.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:u};let p=u&&o.find(h=>h.errorMsgText&&h.labelText===u.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(u,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:u};let m=o.findIndex(h=>h.labelText===u.labelText&&!h.answer);m!==-1&&o.splice(m,1),o.push(u)}let f=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of p){let h=m.querySelectorAll("button");for(let g of h){let y=g.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return g.click(),y}}return null});f&&console.log(` Dismissed safety popup (${f})`);let d=await e.evaluate(async()=>{function p(b){let E=document.querySelector(b);if(E)return E;let R=document.querySelector("#interop-outlet")?.shadowRoot;return R?R.querySelector(b):null}function m(b){let E=document.querySelectorAll(b),R=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(b);return[...E||[],...R||[]]}let h=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(b=>b.innerText?.trim()==="Next"),g=m('footer[role="presentation"] button').some(b=>b.innerText.trim()==="Review")||m("button").some(b=>b.innerText.trim()==="Review"&&b.getAttribute("aria-label")?.includes("Review")),y=p('button[aria-label="Submit application"]'),S=async()=>{let b=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(E=>E.innerText?.trim()==="Next");b?b.click():console.log("Next button not found")},x=()=>{let b=m("button").find(E=>E.innerText?.trim()==="Review");b&&b.click()};return h?(await S(),{type:"next"}):g?(await x(),{type:"review"}):y?{type:"submit"}:{type:null}});if(d==null)return{filledFields:o,formPages:n,skip:!0};if(d.type&&console.log(` \u2192 ${d.type}`),d.type===null){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of m){let g=h.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of g){let S=y.innerText||"";if(S.includes("application was sent")||S.includes("resume into a profile")||S.includes("Application submitted")||S.includes("Next best action"))for(let x of y.querySelectorAll("button")){let b=x.innerText?.trim();if(b==="Not now"||b==="Done"||b==="Dismiss"||b==="Got it")return x.click(),b}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await w(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(s===0){let m=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],y=[];for(let S of h){for(let b of S.querySelectorAll("button")){let E=b.innerText?.trim();E&&E.length<60&&g.push(E)}let x=S.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');x&&y.push(x.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(m.buttons)}`),m.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(m.modalText)}`)}}if(d.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(u===null&&d.type===i?s++:s=0,i=d.type,s>=5){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),h=[],g=[];for(let y of m){for(let S of y.querySelectorAll(".artdeco-inline-feedback__message"))h.push(S.textContent?.trim()?.slice(0,60));for(let S of y.querySelectorAll(".fb-dash-form-element")){let x=S.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),b=S.querySelector("input, select, textarea"),E=!!S.querySelector(".artdeco-inline-feedback__message");x&&(E||b&&!b.value)&&g.push({label:x.slice(0,40),hasError:E,value:b?.value?.slice(0,20)||""})}}return{errors:h,emptyRequired:g.slice(0,5)}});return console.error(` \u26A0 Stuck on "${d.type}" for ${s} iterations \u2014 form not progressing.`),p.errors.length&&console.error(` Visible errors: ${JSON.stringify(p.errors)}`),p.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(p.emptyRequired)}`),console.error(" Skipping job."),{filledFields:o,formPages:n,skip:!0,duplicateField:{labelText:`stuck_on_${d.type}`}}}await w(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function ai(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 ea(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 ta(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of o){for(let i of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(i.innerText?.trim()==="Done")return i.click(),"Done";let n=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let i of n){let s=i.innerText||"";if(s.includes("application was sent")||s.includes("Application sent")||s.includes("resume into a profile")||s.includes("Next best action"))for(let a of i.querySelectorAll("button")){let l=a.innerText?.trim();if(l==="Not now"||l==="Dismiss")return a.click(),l}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await w(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function eo(e){try{await e.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let t=await e.$('button[aria-label="Dismiss"]');t?(await t.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await w(1e3)):console.log("Popup \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.")}catch{console.log("closeJobApplicationPopup failed to execute: \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D \u0438\u043B\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F.")}}async function tn(e){try{await e.waitForSelector('button[data-control-name="discard_application_confirm_btn"]',{timeout:3e3});let t=await e.$('button[data-control-name="discard_application_confirm_btn"]');t&&(await t.click(),console.log("Discard confirmed"),await w(500))}catch{console.log("No discard confirmation needed")}}async function pi(e,t){let o=[],r=t._fromQueue;try{k.attempted++,console.log(`
|
|
297
|
+
--- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&Ro(n)?.status==="applied")return k.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (our DB): ${t.jobTitle} \u2014 skipping`),{keepGoing:!0};let i=null;if(!r){let d=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name")?.innerText?.trim()?.replace(/\s+/g," ")?.toLowerCase()||""),p=(t.companyName||"").replace(/\s+/g," ").toLowerCase().trim(),m=d.split(" ")[0],h=p.split(" ")[0];if(m&&h&&!d.includes(h)&&!p.includes(m))return k.mismatch++,console.log(` \u2298 MISMATCH: expected company "${t.companyName}" but panel shows "${d}"`),console.log(` job title: "${t.jobTitle}"`),{keepGoing:!0};if(await e.evaluate(()=>{let y=document.querySelector(".jobs-details__main-content, .job-details-jobs-unified-top-card");if(!y)return!1;let S=y.innerText;return/Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago/i.test(S)||S.includes("Application submitted")}))return k.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${t.jobTitle} \u2014 skipping`),n&&Fe(n,"applied",{source:"detected"}),{keepGoing:!0};try{i=await gr(e)}catch{}}let s=await ii(e);if(s.dailyLimitReached){console.log(`
|
|
298
298
|
========================================`),console.log("LinkedIn daily application limit reached!"),console.log(`========================================
|
|
299
|
-
`);let d=He("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${d.total}`),console.log(` - This session: ${
|
|
299
|
+
`);let d=He("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${d.total}`),console.log(` - This session: ${no}`),console.log(` - Unprocessed: ${d.unprocessed}`),k.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:d}}if(!s.clicked)return k.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${t.jobTitle} @ ${t.companyName}`),{keepGoing:!0};await ai(e);let a=await Dl();console.log(`Applying for job: ${t.id}`);let l=`### Job Information
|
|
300
300
|
- **Counter:** ${a}
|
|
301
301
|
- **Job Title:** ${t.jobTitle}
|
|
302
302
|
- **Company:** ${t.companyName}
|
|
303
303
|
- **Location:** ${t.location}
|
|
304
304
|
- **Salary:** ${t.salary}
|
|
305
|
-
- **Job URL:** ${t.href}`,c=process.env.NODE_EASY_APPLY_MAIN;await Ie.addMessage(c,l,{lifebot:
|
|
306
|
-
\u{1F4C2} Existing recruiters for today: ${
|
|
307
|
-
`),await w(2e3);let
|
|
308
|
-
\u{1F4CB} Queue mode: ${
|
|
309
|
-
`);for(let
|
|
310
|
-
[${
|
|
311
|
-
Queue complete. ${
|
|
312
|
-
Queue done. Continuing with standard search...`);try{await c.goto(d,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3)}catch(
|
|
313
|
-
\u274C Apply phase ended: CDP channel could not be recovered after ${k.cdpRecoveries} page recoveries and ${k.browserRestarts} browser restarts.`),console.error(` Last error: ${
|
|
314
|
-
\u274C Apply phase ended: ${
|
|
315
|
-
\u26A0 Apply phase crashed: ${
|
|
316
|
-
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SESSION SUMMARY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let
|
|
317
|
-
\u26A0 Skipping recruiter funnel \u2014 ${
|
|
318
|
-
--- Funnel: today's recruiters (${
|
|
319
|
-
--- Funnel: backfill from previous days (${
|
|
320
|
-
\u2705 Funnel done. Connection quota left: ${
|
|
321
|
-
\u274C Apply session ended with error: ${l.message}`),l.stack&&console.error(l.stack)}
|
|
305
|
+
- **Job URL:** ${t.href}`,c=process.env.NODE_EASY_APPLY_MAIN;await Ie.addMessage(c,l,{lifebot:ti.off});let u=await Je("Should I apply for this job? Answer only 'yes' or 'no'!!");if(oi(),console.log(`Should I apply for ${t.jobTitle} ?? `+u),u.toLowerCase()==="no"){k.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await eo(e),await tn(e),await ri(e,t.id);let d=t.id?.match(/\d+/)?.[0];return ze({jobId:d,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),Fe(d,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let f=await li(e,si);if(f.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await ii(e)).clicked?f=await li(e,si):(console.log(" pressApplyButton failed on retry"),f={filledFields:[],formPages:0,skip:!0,duplicateField:{labelText:"stale_popup_retry_failed"}})),console.log(`processNavigation: pages=${f.formPages}, fields=${f.filledFields?.length||0}, skip=${f.skip}${f.dailyLimitReached?", DAILY LIMIT":""}`),f.dailyLimitReached)return console.log(" Daily limit reached \u2014 stopping"),await eo(e),{keepGoing:!1,dailyLimitReached:!0};if(f.skip){if(await eo(e),await tn(e),f.duplicateField){await ri(e,t.id);let d=process.env.NODE_EASY_APPLY_ERRORS;await Ie.addMessage(d,`${t.href} failed at label ${f.duplicateField?.labelText}`,{lifebot:ti.off})}k.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${f.duplicateField?.labelText||"form error"}`),ze({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"failed",formPages:f.formPages,failedField:f.duplicateField?.labelText||null,questions:f.filledFields||[]})}else{o=f.filledFields,o.length,await ai(e),await ea(e),await w(2e3),await ta(e),k.submitted++,console.log(` \u2713 APPLIED: ${t.jobTitle} @ ${t.companyName} (${f.formPages} pages, ${o.length} fields)`);let d=t.id?.match(/\d+/)?.[0];if(d&&(Lt(d,{title:t.jobTitle,company:t.companyName,location:t.location,salary:t.salary,url:t.href,applied:!0}),$o(d,{title:t.jobTitle,company:i?.companyName||t.companyName,companyUrl:i?.companyUrl,location:t.location,salary:t.salary,url:t.href,isEasyApply:!0,applyType:"easy-apply",applied:!0,appliedAt:new Date().toISOString().slice(0,10),description:i?.description,techStack:i?.techStack,jobTags:i?.jobTags,seniority:i?.seniority,employmentType:i?.employmentType,industries:i?.industries,jobFunction:i?.jobFunction,postedTime:i?.postedTime,applicantCount:i?.applicantCount,companySize:i?.companySize,workplaceType:i?.workplaceType,contractType:i?.contractType,aboutCompany:i?.aboutCompany}),Fe(d,"applied",{source:"easy-apply"}),i?.companyUrl&&Vt(i.companyUrl,{name:i.companyName||t.companyName,about:i.aboutCompany,size:i.companySize,industries:i.industries,jobId:d})),await Bl(e,t),ze({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:f.formPages,questions:o}),!Pl())return{keepGoing:!1}}}catch(n){if(nt(n))throw console.log(`\u26A0 CDP dead during "${t.jobTitle}" \u2014 bubbling up for page recovery: ${(n.message||"").slice(0,100)}`),n;let i=di(n);if(!i)return console.log(`\u274C Unknown error \u2014 stopping: ${(n.message||"").slice(0,120)}`),console.log(n),{keepGoing:!1};if(i.severity==="fatal")return console.log(`\u274C [${i.label}] Fatal \u2014 stopping: ${(n.message||"").slice(0,120)}`),i.instructions&&console.log(` \u2192 ${i.instructions}`),i.label==="ilml-auth-expired"?k.fatalAuthExpired="ilml":i.label==="linkedin-session-expired"&&(k.fatalAuthExpired="linkedin"),{keepGoing:!1};let s=Nl(i.label);if(console.log(`\u26A0 [${i.label}] on "${t.jobTitle}" (${s}/${i.maxConsecutive} consecutive): ${(n.message||"").slice(0,120)}`),i.cleanup==="popup"){try{await eo(e)}catch{}try{await tn(e)}catch{}}return s>=i.maxConsecutive?(console.log(`\u274C [${i.label}] ${i.maxConsecutive} consecutive \u2014 stopping.`),i.instructions&&console.log(` \u2192 ${i.instructions}`),{keepGoing:!1}):(i.cooldownMs&&await w(i.cooldownMs),{keepGoing:!0})}return oi(),{keepGoing:!0}}async function oa(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL,n=[],i=0;for(;;){await on(e,r)&&(await oe(e),await w(2e3));try{await e.waitForSelector("li.scaffold-layout__list-item",{timeout:3e4})}catch{}await o(e);let a=await Ol(e);if(a.length===0){if(!e.url().includes("/jobs/")){if(i++,i>3){console.log(" Too many recovery attempts \u2014 LinkedIn keeps redirecting. Stopping.");break}console.log(` No jobs found but not on /jobs/ page \u2014 recovery attempt ${i}/3...`),await on(e,r);continue}let c=await e.evaluate(()=>({totalCards:document.querySelectorAll("li.scaffold-layout__list-item").length,hasListContainer:!!document.querySelector(".jobs-search-results-list, .scaffold-layout__list-container")}));c.totalCards===0?console.log(` \u26A0 No job cards on page (container present: ${c.hasListContainer}). Either the search returned nothing, the page never finished loading, or LinkedIn changed its markup.`):console.log(` ${c.totalCards} job card(s) on page but none are Easy Apply \u2014 nothing to apply to with this search filter.`);break}if(i=0,n.length===0){n=a;let{keepGoing:l}=await ni(e,a,t);if(!l)return{keepGoing:!1,jobsDone:n}}else{let l=a.filter(u=>!n.some(f=>f.id===u.id));if(console.log(` New jobs on page: ${l.length} (page: ${a.length}, total seen: ${n.length})`),l.length===0)break;let{keepGoing:c}=await ni(e,l,t);if(n=[...n,...l],!c)return{keepGoing:!1,jobsDone:n}}}return console.log(` All jobs processed. Total: ${n.length}`),{keepGoing:!0,jobsDone:n}}var k={attempted:0,submitted:0,skippedByLifebot:0,failed:0,mismatch:0,alreadyApplied:0,expired:0,noApplyButton:0,dailyLimitHit:!1,cdpRecoveries:0,browserRestarts:0,fatalAuthExpired:null};(async()=>{let e=process.argv.find(l=>l.startsWith("--job-urls=")),t=jr("apply",e?"queue":"search"),o=null,r=null,n=[],i=async()=>(await Qo(ei,{devtools:!1})).browser,s=async l=>{await l.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},a=()=>Qt();try{let l=await Qo(ei,{devtools:!1});o=l.browser;let c=await o.newPage();await s(c),await Yr(c,l);let u=process.argv.find(_=>_.startsWith("--job-urls=")),f=u?u.split("=").slice(1).join("=").replace(/^@/,""):null,d=process.env.LINKEDIN_SEARCH_URL,p=f?"https://www.linkedin.com/feed/":d;try{await c.goto(p,{waitUntil:"domcontentloaded",timeout:6e4})}catch(_){console.error("\u274C Navigation error:",_.message),console.log("Trying to continue anyway..."),await w(5e3)}try{await it(c,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .jobs-search-results-list, li.scaffold-layout__list-item",label:"search page"})}catch(_){throw _.code==="SESSION_EXPIRED"?new Error("Not logged in (or session expired). Run: ilml linkedin login"):_}console.log("\u2713 Logged in to LinkedIn.");let m=He("recruiters-from-jobs");m.total>0&&console.log(`
|
|
306
|
+
\u{1F4C2} Existing recruiters for today: ${m.total} (${m.unprocessed} unprocessed)
|
|
307
|
+
`),await w(2e3);let h={page:c,browser:o,recoveryCtx:{searchUrl:d,launchFn:i,setupPage:s,cookiesProvider:a}},g=!1;if(f)try{let _=JSON.parse(ci.readFileSync(f,"utf-8"));console.log(`
|
|
308
|
+
\u{1F4CB} Queue mode: ${_.length} jobs from ${f}
|
|
309
|
+
`);for(let M=0;M<_.length;M++){let F=typeof _[M]=="string"?{url:_[M]}:_[M],B=F.url,G=F.title||"Unknown",W=F.company||"";console.log(`
|
|
310
|
+
[${M+1}/${_.length}] ${G} @ ${W}`),console.log(` ${B}`),c=h.page,o=h.browser;try{let v=B.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await c.goto(B,{waitUntil:"domcontentloaded",timeout:6e4}),await w(8e3);let I=await c.evaluate(()=>{let J=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:J.includes("Application submitted"),noLongerAccepting:J.includes("No longer accepting applications")}});if(I.alreadyApplied){console.log(" Already applied \u2014 skipping"),k.alreadyApplied++,Fe(v,"applied",{applyMethod:"detected"});continue}if(I.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),k.expired++,Fe(v,"expired",{reason:"no_longer_accepting"});continue}if(!I.hasApply){console.log(" No Easy Apply button \u2014 skipping"),k.noApplyButton++;continue}let Y={id:`/jobs/view/${v}/`,href:B,jobTitle:G,companyName:W,location:F.location||"",salary:F.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let O=await pi(c,Y);if(console.log(` Result: keepGoing=${O.keepGoing}, reason=${O.dailyLimitReached?"daily_limit":"ok"}`),!O.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),g=!0;break}}catch(v){if(nt(v))try{await to(h,`queue job ${M+1}: ${v.message?.slice(0,80)}`),c=h.page,o=h.browser}catch(I){console.error(`\u274C Queue mode: CDP recovery failed: ${I.message}`),console.error(" Aborting queue, falling back to standard search if possible.");break}else{let I=di(v);if(I?.severity==="fatal"){console.error(`\u274C [${I.label}] Fatal \u2014 stopping queue: ${(v.message||"").slice(0,120)}`),I.instructions&&console.error(` \u2192 ${I.instructions}`),I.label==="ilml-auth-expired"?k.fatalAuthExpired="ilml":I.label==="linkedin-session-expired"&&(k.fatalAuthExpired="linkedin");break}console.error(` Error: ${v.message?.slice(0,80)}`)}}}console.log(`
|
|
311
|
+
Queue complete. ${g?"Daily limit hit.":"Continuing to search..."}`)}catch(_){console.error(`Failed to read job URLs file: ${_.message}`)}if(!g){if(f){console.log(`
|
|
312
|
+
Queue done. Continuing with standard search...`);try{await c.goto(d,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3)}catch(_){console.error(" Navigation to search failed:",_.message)}}h.page=c,h.browser=o;try{await Ul(h)}catch(_){nt(_)||/CDP unrecoverable/.test(_.message||"")?(console.error(`
|
|
313
|
+
\u274C Apply phase ended: CDP channel could not be recovered after ${k.cdpRecoveries} page recoveries and ${k.browserRestarts} browser restarts.`),console.error(` Last error: ${_.message}`)):/Session expired/i.test(_.message||"")?(console.error(`
|
|
314
|
+
\u274C Apply phase ended: ${_.message}`),r=_):console.error(`
|
|
315
|
+
\u26A0 Apply phase crashed: ${_.message}`)}c=h.page,o=h.browser}let y=k.submitted+k.skippedByLifebot+k.failed+k.mismatch+k.alreadyApplied+k.expired+k.noApplyButton,S=k.attempted-y,x=He("recruiters-from-jobs");n.push(`Jobs attempted: ${k.attempted}`),n.push(`Successfully applied: ${k.submitted}`),n.push(`Skipped by Lifebot: ${k.skippedByLifebot}`),n.push(`Failed (form errors): ${k.failed}`),k.mismatch>0&&n.push(`Mismatch (wrong panel): ${k.mismatch}`),k.alreadyApplied>0&&n.push(`Already applied: ${k.alreadyApplied}`),k.expired>0&&n.push(`Expired (closed): ${k.expired}`),k.noApplyButton>0&&n.push(`No Apply button: ${k.noApplyButton}`),S>0&&n.push(`Unaccounted: ${S}`),n.push(`Daily limit reached: ${k.dailyLimitHit?"Yes":"No"}`),k.cdpRecoveries>0&&n.push(`Page recoveries (CDP): ${k.cdpRecoveries}`),k.browserRestarts>0&&n.push(`Browser restarts: ${k.browserRestarts}`),n.push(`Recruiters found: ${no}`),n.push(`Recruiters total: ${x.total} (${x.unprocessed} unprocessed)`),console.log(`
|
|
316
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SESSION SUMMARY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let _ of n)console.log(` ${_}`);console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let b=!!o&&o.isConnected?.()!==!1,E=Tl?b?k.fatalAuthExpired==="linkedin"?"LinkedIn session expired (run: ilml linkedin login)":k.fatalAuthExpired==="ilml"?"iLiveMyLife token expired (run: ilml login)":null:"browser is not in a usable state":"recruiter auto-connect is disabled (FUNNEL_CONNECT_RECRUITERS=false)",R=!E;R||(console.log(`
|
|
317
|
+
\u26A0 Skipping recruiter funnel \u2014 ${E}.`),console.log(` ${x.unprocessed} recruiters saved for next run.`),n.push(`Funnel: skipped (${E})`));let{markProfileProcessed:L}=await Promise.resolve().then(()=>(uo(),gn)),{canSendConnection:A,getQuotaStatus:T}=await Qe().then(()=>Pn),D=()=>({message:jl,useCustomMessage:Rl,maxConnections:Il,excludeLocations:Xo,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async(_,M,F)=>{L("recruiters-from-jobs",_.profileUrl,{status:F.reason,connectionSent:F.connectionSent,withCustomMessage:F.withCustomMessage,message:F.messageSent,method:F.method,reason:F.reason,error:F.error,profileInfo:F.profileInfo},_._fromDate||null)}});if(R&&x.unprocessed>0){console.log(`
|
|
318
|
+
--- Funnel: today's recruiters (${x.unprocessed}) ---`),Xo.length>0&&console.log(` Excluding locations: ${Xo.join(", ")}`);let _=Tt("recruiters-from-jobs");await Po(c,_,D())}let K=A();if(R&&K.allowed){let _=Rt("recruiters-from-jobs"),M=new Date().toISOString().split("T")[0],F=_.filter(B=>B._fromDate!==M);if(F.length>0){let B=T();console.log(`
|
|
319
|
+
--- Funnel: backfill from previous days (${F.length} unprocessed) ---`),console.log(` Quota remaining: ${B.daily.remaining} today, ${B.weekly.remaining} this week`),await Po(c,F,{...D(),maxConnections:B.daily.remaining})}}let U=T();console.log(`
|
|
320
|
+
\u2705 Funnel done. Connection quota left: ${U.daily.remaining} of ${U.daily.max} today, ${U.weekly.remaining} of ${U.weekly.max} this week`),n.push(`Connection quota left: ${U.daily.remaining} of ${U.daily.max} today, ${U.weekly.remaining} of ${U.weekly.max} week`)}catch(l){r=l,console.error(`
|
|
321
|
+
\u274C Apply session ended with error: ${l.message}`),l.stack&&console.error(l.stack)}Dr(t,r?"error":"success",{summaryLines:n,dailyLimitHit:k.dailyLimitHit,attempted:k.attempted,submitted:k.submitted,failed:k.failed,skippedByLifebot:k.skippedByLifebot},r?r.message:null);try{await o?.close()}catch{}r&&process.exit(1)})();
|