ilml-plugin-linkedin 1.20.17 → 1.20.19
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 +9 -0
- package/dist/applyQueue.mjs +18 -20
- package/dist/connect.mjs +72 -74
- package/dist/daily.mjs +27 -29
- package/dist/enrichProfiles.mjs +26 -28
- package/dist/funnelRunner.mjs +41 -42
- package/dist/messageBot.mjs +56 -58
- package/dist/run.mjs +37 -39
- package/dist/scout.mjs +42 -44
- package/dist/syncAll.mjs +74 -76
- package/dist/syncConnections.mjs +30 -32
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +36 -38
- package/dist/visit.mjs +33 -35
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/connect.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
var Lr=Object.defineProperty;var V=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{for(var n in t)Lr(e,n,{get:t[n],enumerable:!0})};function Pr(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function Vn(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let n=new URLSearchParams;n.set("keywords",t);let o=(e.JOB_SEARCH_LOCATION||"").trim();o&&n.set("location",o);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&n.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&n.set("distance",String(s)),Hn(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),Hn(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let i=Pr(e.JOB_SEARCH_COMPANY_IDS);i.length&&n.set("f_C",i.join(","));let c=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();c&&n.set("f_TPR",Fr[c]||c),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let a="https://www.linkedin.com/jobs/search/?"+n.toString(),l=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return l&&(a+="&"+l),a}var Fr,Hn,Wn=V(()=>{Fr={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},Hn=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim())});import{getPluginConfig as Mr}from"@ilivemylife/graph-sdk";var qr,Gn,Se,fe,Vt,Wt,St=V(async()=>{Wn();qr=await Mr();for(let[e,t]of Object.entries(qr))process.env[e]===void 0&&(process.env[e]=t);Gn=Vn(process.env);Gn&&(process.env.LINKEDIN_SEARCH_URL=Gn);Se=process.env.LINKEDIN_NAME,fe=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Vt=Object.freeze(new Set([fe.DRAFT,fe.CONFIRMED,fe.NEEDS_REVIEW])),Wt=Object.freeze(new Set([fe.DRAFT,fe.CONFIRMED,fe.REJECTED,fe.NEEDS_REVIEW]))});import"dotenv/config";import*as q from"fs";import*as B from"path";import{fileURLToPath as Ur}from"url";function Zn(){qe=null,Hr=null,pe=null,Vr=null,Wr=null,Gr=null}function vt(){q.existsSync(me)||q.mkdirSync(me,{recursive:!0})}function et(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";q.writeFileSync(o,n);for(let r=0;r<3;r++)try{q.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function tt(e,t){if(!q.existsSync(e))return null;try{let n=JSON.parse(q.readFileSync(e,"utf-8"));try{q.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${B.resolve(e)}`);let o=e+".backup";if(q.existsSync(o))try{let r=JSON.parse(q.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{q.copyFileSync(o,e)}catch{}return r}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 nt(){return new Date().toISOString().split("T")[0]}function U(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Yn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Ue(e,t,n=null){if(!t||e[t])return t;let o=U(t);if(!o)return t;let r=null;for(let[s,i]of Object.entries(e)){if(U(i.profileUrl||s)===o)return s;!r&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}if(r){let s=Yn(n),i=Yn(e[r].name);if(s&&i&&s===i)return r}return t}function zr(){q.existsSync(Yt)||q.mkdirSync(Yt,{recursive:!0})}function eo(e){let t=U(e);return t?B.join(Yt,`${t}.json`):null}function Qr(e){let t=eo(e);return t?tt(t,`profile-history/${U(e)}.json`)||[]:[]}function Xr(e,t){let n=eo(e);if(!n)return;zr();let o=Qr(e);o.unshift(t);try{et(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${U(e)}: ${r.message}`)}}function Kn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function zn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Zr(e,t){if(!e)return[];let n=[];for(let o of Kr){let r=e[o],s=t[o];Kn(r)||Kn(s)||zn(r)!==zn(s)&&n.push(o)}return n}function ei(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function W(){return qe||(vt(),qe=tt(Gt,"people.json")||{},qe)}function $t(e){vt(),qe=e;try{et(Gt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(Gt)}`)}}function kt(e,t={}){if(!e)return null;let n=W(),o=nt(),r=new Date().toISOString(),s=Ue(n,e,t.name),i=n[s];if(i){let c=Zr(i,t);c.length>0&&(Xr(s,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:c,snapshot:ei(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let a of Yr)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(i[a])&&i[a].length>0)continue;i[a]=t[a]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[s]={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:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return $t(n),n[s]}function to(e,t){if(!e||!t)return;let n=W(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let s={date:nt(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(s.jobId=String(t.jobId)),t.jobTitle&&(s.jobTitle=t.jobTitle),t.jobCompany&&(s.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===s.date&&c.source===s.source&&c.action===s.action&&(c.jobId||"")===(s.jobId||""))&&(o.encounters.push(s),o.lastUpdated=new Date().toISOString(),$t(n))}function no(e){return e&&W()[e]?.connectionStatus||null}function At(e,t,n={}){if(!e)return;if(n.profileInfo)kt(e,n.profileInfo);else{let c=W(),a=Ue(c,e,n.profileInfo?.name);c[a]||kt(e,{})}let o=W(),r=Ue(o,e,n.profileInfo?.name),s=o[r];if(!s)return;let i=nt();s.connectionStatus=t,t==="connected"?s.connectionDate=i:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(s.requestedConnectionAt||(s.requestedConnectionAt=i)),s.connectionMethod=n.method||s.connectionMethod,s.messageSent=n.messageSent||s.messageSent,s.lastUpdated=new Date().toISOString(),$t(o)}function Ct(e,t,n={}){if(n.dryRun||!e||!t)return;let o=U(t);if(!o)return;let r=W(),s=Ue(r,e),i=r[s];if(!i)return;let c=U(i.profileUrl||s);o!==c&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(o)||(i.aliases.push(o),i.lastUpdated=new Date().toISOString(),$t(r)))}function oo(){return pe||(vt(),pe=tt(Qn,"quota.json"),(!pe||!pe.connections)&&(pe={connections:[]}),pe)}function ti(e){vt(),pe=e;try{et(Qn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function ro(e,t="unknown"){let n=oo(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),ti(n)}function io(){let e=oo(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function ot(){let e=io(),t=nt(),n=e.filter(a=>a.date===t).length,o=e.length,r=n>=Xe,s=o>=Ze,i=!r&&!s,c={allowed:i,daily:{sent:n,max:Xe},weekly:{sent:o,max:Ze}};return i||(c.reason=r?`Daily limit reached (${n}/${Xe})`:`Weekly limit reached (${o}/${Ze})`),c}function De(){let e=io(),t=nt(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Xe,remaining:Xe-n},weekly:{sent:o,max:Ze,remaining:Ze-o}}}var Br,Jr,me,Gt,Ua,Qn,Ba,Ja,Ha,Yt,Xn,Xe,Ze,qe,Hr,pe,Vr,Wr,Gr,Yr,Kr,Re=V(async()=>{await St();Br=Ur(import.meta.url),Jr=B.dirname(B.dirname(Br)),me=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Jr,"collected-profiles"),Gt=B.join(me,"people.json"),Ua=B.join(me,"jobs.json"),Qn=B.join(me,"quota.json"),Ba=B.join(me,"conversations.json"),Ja=B.join(me,"sync-state.json"),Ha=B.join(me,"application-questions.json"),Yt=B.join(me,"profile-history"),Xn=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Xe=Xn(process.env.CONNECT_MAX_DAILY,20),Ze=Xn(process.env.CONNECT_MAX_WEEKLY,100),qe=null,Hr=null,pe=null,Vr=null,Wr=null,Gr=null;Yr=["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"],Kr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var So={};z(So,{computeEngagement:()=>Xt,detectCategory:()=>fo,detectCategoryFromTitle:()=>Je,determineAction:()=>wo,determineLastMessageBy:()=>mo,determineSituation:()=>po,enrichConversation:()=>ai,enrichPerson:()=>pi,enrichPersonContext:()=>bo,extractAutoTags:()=>go,generateSummary:()=>ho,normPreview:()=>Qt});function ai(e,t,n){if(!e)return e;let r=(e.messages||[]).filter(a=>!Wt.has(a.status)),s=ci(t,e.profileUrl,n),i=mo(r,t);if(e.lastMessageBy=i,e.conversationStatus=i==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let a=fo(r,t,s);a&&(e.category=a,e.categorySource=e.categorySource||"message_content")}if(e.situation=po(r,i,t),r.length>0){let a=r[r.length-1];e.lastMessageTime=a.time}if(r.length>0&&!e.initiatedBy){let a=r[0];a.sender===Se?e.initiatedBy="us":a.sender!=="Unknown"&&a.sender!==""&&(e.initiatedBy="them")}e.engagement=Xt(r,t),e.personContext=bo(s),e.summary=ho(e,t,s),e.autoTags=go(e,t,s);let c=wo(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=li(e),e}function fo(e,t,n){if(!e||e.length===0)return n?.title?Je(n.title):null;let o=e.filter(r=>r.sender!==Se&&r.sender!=="Unknown"&&r.sender!=="").map(r=>r.text).join(" ");for(let[r,s]of Object.entries(uo))if(s.theirMessages){for(let i of s.theirMessages)if(i.test(o))return r}if(n?.title){let r=Je(n.title);if(r)return r}return null}function Je(e){if(!e)return null;for(let[t,n]of Object.entries(uo))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function po(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return co.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let r=[...e].reverse().find(s=>s.sender!==Se&&s.sender!=="Unknown");return co.test(r?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function mo(e,t){if(!e||e.length===0)return"them";let n=[...e].map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,s)=>s.t-r.t).map(r=>r.m),o=n.length>0?n:[...e].reverse();for(let r of o){let s=r.sender;if(s===Se)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}function ho(e,t,n){let o=e.messages||[];if(o.length===0)return null;let r=[],s=e.category,i=n?.title,c=n?.company,a=n?.location;s==="recruiter"&&c?r.push(`Recruiter from ${c}`):s==="hiring_manager"&&c?r.push(`Hiring manager at ${c}`):s==="founder"&&c?r.push(`Founder of ${c}`):s&&i?r.push(`${Zt(s)}: ${Be(i,40)}`):i?r.push(Be(i,50)):r.push(t.split(" ")[0]);let l=o.filter(g=>g.sender!==Se&&g.sender!=="Unknown").map(g=>g.text).join(" "),u=ui(l),f=di(l),d=fi(l),p=[];return u&&p.push(u),d&&d!==a&&p.push(d),f&&p.push(f),p.length>0&&r.push(p.join(", ")),e.situation==="they_want_to_schedule_call"?r.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?r.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?r.push("needs reply"):e.conversationStatus==="awaiting_reply"&&r.push("waiting on them"),r.join(". ").replace(/\.\./g,".")}function go(e,t,n){let o=[],r=(e.messages||[]).filter(l=>!Wt.has(l.status)),s=r.map(l=>l.text).join(" "),i=r.filter(l=>l.sender!==Se&&l.sender!=="Unknown").map(l=>l.text).join(" "),c=yo(i,n?.location);o.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(s)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(s)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(s)&&o.push("remote"),/\b(hybrid)\b/i.test(s)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(s)&&o.push("onsite"),/\b(java)\b/i.test(s)&&!/javascript/i.test(s)&&o.push("java"),/\b(python)\b/i.test(s)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(s)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(s)&&o.push("backend"),/\b(full.?stack)\b/i.test(s)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(s)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(s)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(s)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(s)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(s)&&o.push("has-salary");let a=e.engagement||Xt(r,t);return a.messageCount>=6&&o.push("active-thread"),a.theirCount===0&&a.ourCount>0&&o.push("no-response"),a.ourCount===0&&a.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(l=>Vt.has(l.status))&&o.push("has-draft"),[...new Set(o)]}function yo(e,t){let n=[],o=["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"],r=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],s=(e+" "+(t||"")).toLowerCase();for(let i of o)s.includes(i)&&n.push(i.replace(/\s+/g,"-"));for(let[i,c]of r)s.includes(i)&&n.push(c);return n}function wo(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&Qt(e.lastMessagePreview)===Qt(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let r=(e.messages||[]).find(s=>Vt.has(s.status));return r?r.status===fe.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="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:`${Zt(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function Xt(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,r=0,s=!1,i=!1,c=e.map(a=>a.text).join(" ");for(let a of e)a.sender===Se?n++:a.sender==="Unknown"||a.sender===""?r++:o++;return s=/\b(job|role|position|opening)\b/i.test(c),i=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:r,hasJob:s,hasSalary:i}}function bo(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function li(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="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 ci(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let r=Ue(n,t,e);if(n[r])return n[r]}if(!e)return null;let o=Object.values(n).filter(r=>r.name===e);return o.length===1?o[0]:null}function Qt(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Zt(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Be(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function ui(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 n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function di(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 fi(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 pi(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=Je(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}mi(e),e.personSummary=hi(e),e.personAutoTags=gi(e);let n=yi(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=wi(e)),e}function mi(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.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 hi(e){let t=[],n=e.category,o=e.title,r=e.company,s=e.location;if(n==="recruiter"&&r?t.push(`Recruiter at ${r}`):n==="hiring_manager"&&r?t.push(`Hiring manager at ${r}`):n==="founder"&&r?t.push(`Founder of ${r}`):o&&r?t.push(`${Be(o,40)} at ${Be(r,30)}`):o?t.push(Be(o,50)):e.name&&t.push(e.name.split(" ")[0]),s&&t.push(s),e.connectionDate){let i=new Date(e.connectionDate);if(!isNaN(i)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[i.getMonth()]} ${i.getDate()}`)}}if(e.jobCount>0){let i=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(i+=` (last: ${Be(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(i+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}i+=")"}t.push(i)}return t.join(". ").replace(/\.\./g,".")||null}function gi(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=yo("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function yi(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:`${Zt(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function wi(e){let t=e.category;if(!t)return null;let n=bi(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function bi(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}var uo,co,en=V(async()=>{await St();await Re();uo={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]}};co=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var Eo={};z(Eo,{BLOCK_MARKERS:()=>Ao,dedupeAndCap:()=>xo,extractSidePanelProfiles:()=>Ji,normalizeFundUrl:()=>It,normalizeProfileUrl:()=>He,scanRelatedBlocks:()=>Co});function He(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 n=t[1].trim();return n?`https://www.linkedin.com/in/${n}/`:null}function It(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function Co(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=l=>(l||"").replace(/\s+/g," ").trim(),r=l=>{let u=String(l||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},s=l=>o(l).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),i=l=>{let u=l,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||l.parentElement},c=[],a=Array.from(n.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let l of a){let u=o(l.textContent).toLowerCase();if(!u)continue;let f=e.find(([h])=>u.includes(h));if(!f)continue;let d=f[1],p=i(l);if(!p)continue;let g=0,m=new Set;for(let h of Array.from(p.querySelectorAll('a[href*="/in/"]'))){let y=h.href||h.getAttribute("href")||"",k=r(y);if(!k)continue;let x=h.querySelector('span[aria-hidden="true"]'),w=o(x?x.textContent:h.getAttribute("aria-label")||h.textContent),S=s(w);if(!S||m.has(k))continue;m.add(k);let C="",b=w.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(b&&(C=o(b[1])),!C){let D=h.closest("li")||h.parentElement;D&&(C=Array.from(D.querySelectorAll("p, span")).map(R=>o(R.textContent)).filter(R=>R&&R!==S&&!/^view\b/i.test(R)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(R)&&/[a-z]/i.test(R)&&R.length>2)[0]||"")}c.push({href:y,name:S,headline:C,block:d,rank:g++})}}return c}function xo(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=He(t.seedUrl||""),r=new Map,s={};for(let i of e||[]){let c=He(i.href);c&&(o&&c===o||(s[i.block]=s[i.block]||0,!(s[i.block]>=n)&&(r.has(c)||(s[i.block]++,r.set(c,{url:c,name:i.name,headline:i.headline||null,block:i.block,rank:i.rank})))))}return Array.from(r.values())}async function Ji(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(o=>setTimeout(o,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(o=>setTimeout(o,1200))}catch{}let n;try{n=await e.evaluate(Co,Ao)}catch{return[]}return xo(n,t)}var Ao,ln=V(()=>{Ao=[["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 No={};z(No,{getJobDecision:()=>Ki,getLastVisit:()=>os,getScoutStats:()=>rs,loadCompanies:()=>mn,loadDiscoveredPeople:()=>je,loadJobDecisions:()=>pn,loadScoutedJobs:()=>fn,loadVisitLog:()=>Tt,recordCompany:()=>es,recordDiscoveredEdge:()=>Xi,recordDiscoveredEdges:()=>Zi,recordVisit:()=>ns,resetCaches:()=>dn,saveCompany:()=>ts,saveDiscoveredPerson:()=>zi,saveScoutedJob:()=>Gi,setJobDecision:()=>Yi});import"dotenv/config";import*as se from"fs";import*as te from"path";import{fileURLToPath as Hi}from"url";function ve(){se.existsSync(Oe)||se.mkdirSync(Oe,{recursive:!0})}function $e(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";se.writeFileSync(o,n);for(let r=0;r<3;r++)try{se.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function ut(e){try{if(se.existsSync(e))return JSON.parse(se.readFileSync(e,"utf-8"))}catch{}return null}function dn(){st=null,at=null,lt=null,ct=null,Ne=null}function fn(){return st||(st=ut(_o)||{},st)}function Gi(e,t){if(!e)return;ve();let n=fn(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[r,s]of Object.entries(t))s!=null&&(n[e][r]=s);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{$e(_o,n)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}function pn(){return at||(at=ut(Do)||{},at)}function Yi(e,t,n={}){if(!e||!t)return;ve();let o=pn(),r=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=r,n.reason&&(o[e].reason=n.reason),n.score!=null&&(o[e].score=n.score),n.source&&(o[e].source=n.source)):o[e]={status:t,decidedAt:r,updatedAt:r,reason:n.reason||null,score:n.score??null,source:n.source||null};try{$e(Do,o)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function Ki(e){return pn()[e]||null}function je(){return lt||(lt=ut(Rt)||{},lt)}function Ve(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Ro(e,t){let n=He(t)||t;if(e[n])return n;let o=Ve(t);if(!o)return n;let r=null;for(let[s,i]of Object.entries(e)){if(Ve(i&&(i.canonicalUrl||i.profileUrl)||s)===o)return s;!r&&i&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}return r||n}function zi(e,t){if(!e)return;ve();let n=je(),o=new Date().toISOString().slice(0,10),r=Ro(n,e),s=Ve(e);if(n[r]){let i=n[r];t.name&&(i.name=t.name),t.title&&(i.title=t.title),t.company&&(i.company=t.company),t.location&&(i.location=t.location),t.role&&(i.role=t.role),t.isConnected!=null&&(i.isConnected=t.isConnected),t.jobId&&(i.jobIds||(i.jobIds=[]),i.jobIds.includes(t.jobId)||i.jobIds.push(t.jobId)),s&&Ve(i.canonicalUrl||i.profileUrl||r)!==s&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(s)||i.aliases.push(s)),i.lastSeen=o,i.seenCount=(i.seenCount||1)+1}else n[r]={canonicalUrl:r,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:o,lastSeen:o,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{$e(Rt,n)}catch(i){console.error(`[!] Failed to save discovered-people.json: ${i.message}`)}}function Qi(e,t){let n=e.kind||"similar-panel";return n==="list-post"?{edge:{kind:n,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:o=>o.kind==="list-post"&&o.postUrl===(e.postUrl||null)&&o.fund===(e.fund||null)}:n==="scout"?{edge:{kind:n,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:o=>o.kind==="scout"&&o.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:o=>o.kind!=="list-post"&&o.kind!=="scout"&&o.seedUrl===(e.seedUrl||null)&&o.block===(e.block||"unknown")}}function To(e,t,n={},o){if(!t)return;let r=Ve(t);t=Ro(e,t);let s=n.seedUrl?{...n,seedUrl:He(n.seedUrl)||n.seedUrl}:n,i=o.slice(0,10),{edge:c,match:a}=Qi(s,o),l=e[t];l||(l=e[t]={canonicalUrl:t,aliases:[],name:n.name||null,headline:n.headline||null,location:n.location||null,company:n.company||null,companyUrl:n.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:c.kind,sources:[],connectionsCount:n.connectionsCount??null,selectivity:n.selectivity||"unknown",connectGate:n.connectGate||"unknown",score:null,fitScore:null,isConnected:n.isConnected||!1,graphRefs:[],note:n.note||"",whyUseful:n.whyUseful||"",extra:{},source:c.kind,role:Array.isArray(n.categories)&&n.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:i,firstSeen:i,lastSeen:i}),n.name&&(l.name=n.name),n.headline&&(!l.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(l.headline))&&(l.headline=n.headline),n.location&&(l.location=l.location||n.location),n.company&&(l.company=n.company),n.companyUrl&&(l.companyUrl=l.companyUrl||n.companyUrl),n.isConnected!=null&&(l.isConnected=n.isConnected),n.connectionsCount!=null&&(l.connectionsCount=n.connectionsCount),n.selectivity&&n.selectivity!=="unknown"&&(l.selectivity=n.selectivity),n.connectGate&&n.connectGate!=="unknown"&&(l.connectGate=n.connectGate),n.note&&!l.note&&(l.note=n.note),n.whyUseful&&!l.whyUseful&&(l.whyUseful=n.whyUseful),n.extra&&typeof n.extra=="object"&&(l.extra={...l.extra||{},...n.extra}),Array.isArray(l.sources)||(l.sources=[]);let u=l.sources.find(a);if(u?(c.rank!=null&&(u.rank==null||c.rank<u.rank)&&(u.rank=c.rank),u.at=c.at):l.sources.push(c),Array.isArray(l.categories)||(l.categories=[]),Array.isArray(l.sectors)||(l.sectors=[]),Array.isArray(l.aliases)||(l.aliases=[]),Array.isArray(l.graphRefs)||(l.graphRefs=[]),cn(l.categories,n.category),Dt(l.categories,n.categories),Dt(l.sectors,n.sectors),Dt(l.aliases,n.aliases),r&&Ve(l.canonicalUrl||t)!==r&&cn(l.aliases,r),Dt(l.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(l.affiliations)||(l.affiliations=[]);for(let f of n.affiliations)!f||!f.companyKey||l.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||l.affiliations.push(f)}l.lastSeen=i,l.seenCount=(l.seenCount||0)+1}function Xi(e,t={}){if(!e)return;ve();let n=je();To(n,e,t,new Date().toISOString());try{$e(Rt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function Zi(e){if(!Array.isArray(e)||e.length===0)return;ve();let t=je(),n=new Date().toISOString(),o=0;for(let r of e)!r||!r.url||(To(t,r.url,r,n),o++);if(o)try{$e(Rt,t)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function es(e={}){if(!e||!e.name)return;ve();let t=e.key||It(e.website)||It(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=mn(),o=new Date().toISOString().slice(0,10),r=(a,l)=>{l&&Array.isArray(a)&&!a.includes(l)&&a.push(l)},s=(a,l)=>{if(Array.isArray(l))for(let u of l)r(a,u)},i=n[t];i||(i=n[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:o,lastSeen:o}),e.name&&(i.name=e.name),e.website&&(i.website=i.website||e.website),e.linkedinUrl&&(i.linkedinUrl=i.linkedinUrl||e.linkedinUrl);for(let a of["size","check","stage","location","industries","about"])e[a]&&!i[a]&&(i[a]=e[a]);e.note&&!i.note&&(i.note=e.note),e.whyUseful&&!i.whyUseful&&(i.whyUseful=e.whyUseful),e.fitScore!=null&&(i.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(i.extra={...i.extra||{},...e.extra});for(let a of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(i[a])||(i[a]=[]),s(i[a],e[a]);Array.isArray(i.people)||(i.people=[]);let c=a=>{if(!a||!a.url)return;let l=i.people.find(u=>u.url===a.url&&(u.role||null)===(a.role||null));l?a.current!=null&&(l.current=a.current):i.people.push({url:a.url,name:a.name||null,role:a.role||null,current:a.current??null,from:a.from??null,to:a.to??null})};(e.people||[]).forEach(c),(e.partners||[]).forEach(a=>c({url:a.url,name:a.name,role:"Partner",current:!0})),Array.isArray(i.portfolio)||(i.portfolio=[]);for(let a of e.portfolio||[]){let l=a&&(a.key||a.name);l&&!i.portfolio.some(u=>(u.key||u.name)===l)&&i.portfolio.push(a)}i.lastSeen=o,i.seenCount=(i.seenCount||0)+1;try{$e(un,n)}catch(a){console.error(`[!] Failed to save companies.json: ${a.message}`)}return t}function mn(){return ct||(ct=ut(un)||{},ct)}function ts(e,t){if(!e)return;ve();let n=mn(),o=new Date().toISOString().slice(0,10);if(n[e]){let r=n[e];t.name&&(r.name=t.name),t.about&&(r.about=t.about),t.size&&(r.size=t.size),t.industries&&(r.industries=t.industries),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),t.recruiterUrl&&(r.recruiterUrls||(r.recruiterUrls=[]),r.recruiterUrls.includes(t.recruiterUrl)||r.recruiterUrls.push(t.recruiterUrl)),r.lastSeen=o,r.jobCount=r.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:o,lastSeen:o,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{$e(un,n)}catch(r){console.error(`[!] Failed to save companies.json: ${r.message}`)}}function Tt(){return Ne||(Ne=ut(Io)||{visits:[]},Array.isArray(Ne.visits)||(Ne.visits=[]),Ne)}function ns(e,t={}){if(!e)return;ve();let n=Tt();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(r=>new Date(r.date).getTime()>o);try{$e(Io,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function os(e){let t=Tt();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function rs(){let e=fn(),t=je(),n=Object.values(e),o=Object.values(t),r={};for(let d of n)d.company&&(r[d.company]=(r[d.company]||0)+1);let s=Object.entries(r).sort((d,p)=>p[1]-d[1]).slice(0,5).map(([d,p])=>`${d} (${p})`),i={};for(let d of n)for(let p of d.techStack||[])i[p]=(i[p]||0)+1;let c=Object.entries(i).sort((d,p)=>p[1]-d[1]).slice(0,8).map(([d,p])=>`${d} (${p})`),a=Tt(),l=new Date().toISOString().slice(0,10),u=a.visits.filter(d=>d.date.startsWith(l)).length,f=new Set(a.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:s,topTech:c,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,p)=>(p.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var Vi,Wi,Oe,_o,Rt,Io,un,Do,st,at,lt,cn,Dt,ct,Ne,Nt=V(()=>{ln();Vi=Hi(import.meta.url),Wi=te.dirname(te.dirname(Vi)),Oe=process.env.DATA_DIR?te.resolve(process.env.DATA_DIR,"market-research"):te.join(Wi,"market-research"),_o=te.join(Oe,"scouted-jobs.json"),Rt=te.join(Oe,"discovered-people.json"),Io=te.join(Oe,"visit-log.json"),un=te.join(Oe,"companies.json"),Do=te.join(Oe,"job-decisions.json");st=null;at=null;lt=null;cn=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Dt=(e,t)=>{if(Array.isArray(t))for(let n of t)cn(e,n)};ct=null;Ne=null});var Bo={};z(Bo,{DEFAULT_PROFILE_INTERESTS:()=>jt,computeFit:()=>wn,detectSectors:()=>$s});function $s(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(vs))r.some(s=>s.test(t))&&n.push(o);return n}function wn(e,t=jt){if(!Array.isArray(e)||e.length===0)return 0;let n=s=>typeof s=="number"&&Number.isFinite(s)?s:0,o=Math.max(1,...Object.values(t||{}).map(n)),r=0;for(let s of e){let i=n(t&&t[s]);i>r&&(r=i)}return Math.min(1,r/o)}var vs,jt,bn=V(()=>{vs={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/]};jt={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});import Z from"fs";import we from"path";function Sn(){let e=process.env.ILML_SCOPE_DIR;return e?we.join(e,"plugins-state","linkedin","cookies.json"):Rs}function Ts(){let e=Sn(),t=we.dirname(e);return t&&t!=="."&&!Z.existsSync(t)&&Z.mkdirSync(t,{recursive:!0}),e}function Vo(e){let t=Ts();return Z.writeFileSync(t,JSON.stringify(e)),t}function Wo(){let e=Sn();if(!Z.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Z.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function Go(){return Z.existsSync(Sn())}function Ns(){let e=process.env.ILML_SCOPE_DIR;return e?we.join(e,"plugins-state","linkedin"):"."}function Yo(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Os(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Yo(t[1]):"default"}function Ko(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return Z.existsSync(t)||Z.mkdirSync(t,{recursive:!0}),we.resolve(t);let n=Yo(e||Os()),o=we.join(Ns(),"chrome-profile",n);return Z.existsSync(o)||Z.mkdirSync(o,{recursive:!0}),we.resolve(o)}function Qo(e){return!Z.existsSync(we.join(e,zo))}function kn(e){try{Z.writeFileSync(we.join(e,zo),new Date().toISOString())}catch{}}function Xo(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{Z.rmSync(we.join(e,n),{force:!0}),t++}catch{}return t}var Rs,zo,vn=V(()=>{Rs="cookies.json";zo=".ilml-seeded"});var rr={};z(rr,{_pidAlive:()=>$n,launchWithProfile:()=>qs,markProfileEstablished:()=>Bs,registerBrowserForCleanup:()=>or,resolveProfileHolder:()=>An,seedCookiesIfNeeded:()=>Us});import Cn from"fs";import js from"path";async function Lt(){let e=[...ft].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});ft.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Fs(){if(Zo)return;Zo=!0;let e=t=>async()=>{await Lt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Lt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Lt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Lt(),process.exit(0))}),process.on("exit",()=>{for(let t of ft)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function xn(e){return js.join(e,".ilml-browser-session.json")}function tr(e,t={}){try{Cn.writeFileSync(xn(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Ps(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();tr(e,n?{wsEndpoint:n}:{})}catch{}}function Ms(e){let t=nr(e);t&&t.ownerPid===process.pid&&dt(e)}function dt(e){try{Cn.rmSync(xn(e),{force:!0})}catch{}}function nr(e){try{return JSON.parse(Cn.readFileSync(xn(e),"utf-8"))}catch{return null}}function $n(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function er(e,t,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(o),i),i=>{throw clearTimeout(o),i});return Promise.race([s,r])}async function An(e,t,{probeTimeoutMs:n=4e3}={}){let o=nr(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&$n(o.ownerPid)?"live":(dt(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await er(s,n,r);if(i===r)return s.then(a=>{if(a)try{a.disconnect()}catch{}}),"live";if(!i)return dt(t),"free";if($n(o.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await er(i.close().then(()=>!0).catch(()=>!1),n,!1))return dt(t),"free";try{i.disconnect()}catch{}return"live"}function or(e,t){e&&(Fs(),ft.add(e),e.on("disconnected",()=>{ft.delete(e),t&&dt(t)}))}async function qs(e,t={}){let n=Ko(),o={...Ls,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. 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 An(e,n)==="live")throw new Error(r);tr(n);let s;try{s=await e.launch(o)}catch{if(await An(e,n)==="live")throw new Error(r);Xo(n);try{s=await e.launch(o)}catch(c){throw Ms(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return or(s,n),Ps(n,s),{browser:s,profileDir:n,needsSeed:Qo(n)}}async function Us(e,t){if(!t||!t.needsSeed)return!1;if(!Go())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(...Wo()),kn(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}function Bs(e){kn(e)}var Ls,ft,Zo,ir=V(()=>{vn();Ls={headless:!1,defaultViewport:null,protocolTimeout:3e5},ft=new Set,Zo=!1});var ar={};z(ar,{AUTHWALL_RE:()=>In,cleanSearchName:()=>Ys,delayed:()=>A,dismissPremiumOverlay:()=>Ce,ensureInboxPage:()=>Ws,gotoWithReauth:()=>Me,isAuthwallUrl:()=>mt,parseLinkedInTime:()=>Vs,recoverFromAuthwall:()=>Ft,safeParseInt:()=>Gs,stripDesignations:()=>Ks,utilityFunction:()=>Js,waitForPageReady:()=>sr,waitPastReauth:()=>_n});function Js(){console.log("Utility function called...")}function pt(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),r=t[3].toUpperCase()==="PM";return r&&n!==12&&(n+=12),!r&&n===12&&(n=0),{hours:n,minutes:o}}function Vs(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let c=pt(n),a=new Date(t);return c?a.setHours(c.hours,c.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let c=Hs[o[1].toLowerCase()],a=pt(o[2]||""),l=new Date(t),f=l.getDay()-c;return f<=0&&(f+=7),l.setDate(l.getDate()-f),a?l.setHours(a.hours,a.minutes,0,0):l.setHours(0,0,0,0),l.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(r){let c=En[r[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(r[2],10),l=parseInt(r[3],10),u=pt(r[4]||"");return new Date(l,c,a,u?.hours||0,u?.minutes||0,0,0).toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(s){let c=En[s[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(s[2],10),l=pt(s[3]||""),u=t.getFullYear(),f=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let c=En[i[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(i[2],10),l=pt(i[3]||""),u=t.getFullYear(),f=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}return null}async function A(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function sr(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let s=Date.now();for(;Date.now()-s<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-s;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(i=>setTimeout(i,o))}return!1}function mt(e){return In.test(e||"")}async function Ft(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),r=o?t:Math.min(t,45e3),s=Date.now(),i=!1;for(;Date.now()-s<r;){let a="wait";try{a=await e.evaluate(l=>!new RegExp(l).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",In.source)}catch{}if(a==="in"){try{let l=await e.cookies();if(Array.isArray(l)&&l.some(f=>f.name==="li_at")){let f=Vo(l);console.log(` \u2713 Session recovered \u2014 re-saved ${l.length} cookies (${f}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(l){console.log(` \u2713 Session recovered (cookie re-save skipped: ${l.message}).`)}return!0}if(a==="creds"){if(!o){let l=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}i||(i=!0,console.log(`
|
|
1
|
+
var Pr=Object.defineProperty;var V=(e,t)=>()=>(e&&(t=e(e=0)),t);var Y=(e,t)=>{for(var n in t)Pr(e,n,{get:t[n],enumerable:!0})};function qr(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function Vn(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let n=new URLSearchParams;n.set("keywords",t);let o=(e.JOB_SEARCH_LOCATION||"").trim();o&&n.set("location",o);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&n.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&n.set("distance",String(s)),Hn(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),Hn(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let i=qr(e.JOB_SEARCH_COMPANY_IDS);i.length&&n.set("f_C",i.join(","));let c=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();c&&n.set("f_TPR",Mr[c]||c),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let a="https://www.linkedin.com/jobs/search/?"+n.toString(),l=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return l&&(a+="&"+l),a}var Mr,Hn,Wn=V(()=>{Mr={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},Hn=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim())});import{getPluginConfig as Ur}from"@ilivemylife/graph-sdk";var Br,Gn,be,de,Vt,Wt,St=V(async()=>{Wn();Br=await Ur();for(let[e,t]of Object.entries(Br))process.env[e]===void 0&&(process.env[e]=t);Gn=Vn(process.env);Gn&&(process.env.LINKEDIN_SEARCH_URL=Gn);be=process.env.LINKEDIN_NAME,de=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Vt=Object.freeze(new Set([de.DRAFT,de.CONFIRMED,de.NEEDS_REVIEW])),Wt=Object.freeze(new Set([de.DRAFT,de.CONFIRMED,de.REJECTED,de.NEEDS_REVIEW]))});import"dotenv/config";import*as P from"fs";import*as U from"path";import{fileURLToPath as Jr}from"url";function Zn(){Pe=null,Wr=null,fe=null,Gr=null,Yr=null,Kr=null}function vt(){P.existsSync(pe)||P.mkdirSync(pe,{recursive:!0})}function Ze(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";P.writeFileSync(o,n);for(let r=0;r<3;r++)try{P.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function et(e,t){if(!P.existsSync(e))return null;try{let n=JSON.parse(P.readFileSync(e,"utf-8"));try{P.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${U.resolve(e)}`);let o=e+".backup";if(P.existsSync(o))try{let r=JSON.parse(P.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{P.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{P.copyFileSync(e,e+".corrupted")}catch{}return null}}function tt(){return new Date().toISOString().split("T")[0]}function q(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Yn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Me(e,t,n=null){if(!t||e[t])return t;let o=q(t);if(!o)return t;let r=null;for(let[s,i]of Object.entries(e)){if(q(i.profileUrl||s)===o)return s;!r&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}if(r){let s=Yn(n),i=Yn(e[r].name);if(s&&i&&s===i)return r}return t}function Xr(){P.existsSync(Yt)||P.mkdirSync(Yt,{recursive:!0})}function eo(e){let t=q(e);return t?U.join(Yt,`${t}.json`):null}function Zr(e){let t=eo(e);return t?et(t,`profile-history/${q(e)}.json`)||[]:[]}function ei(e,t){let n=eo(e);if(!n)return;Xr();let o=Zr(e);o.unshift(t);try{Ze(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${q(e)}: ${r.message}`)}}function Kn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function zn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function ti(e,t){if(!e)return[];let n=[];for(let o of Qr){let r=e[o],s=t[o];Kn(r)||Kn(s)||zn(r)!==zn(s)&&n.push(o)}return n}function ni(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function W(){return Pe||(vt(),Pe=et(Gt,"people.json")||{},Pe)}function $t(e){vt(),Pe=e;try{Ze(Gt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${U.resolve(Gt)}`)}}function kt(e,t={}){if(!e)return null;let n=W(),o=tt(),r=new Date().toISOString(),s=Me(n,e,t.name),i=n[s];if(i){let c=ti(i,t);c.length>0&&(ei(s,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:c,snapshot:ni(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let a of zr)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(i[a])&&i[a].length>0)continue;i[a]=t[a]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[s]={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:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return $t(n),n[s]}function to(e,t){if(!e||!t)return;let n=W(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let s={date:tt(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(s.jobId=String(t.jobId)),t.jobTitle&&(s.jobTitle=t.jobTitle),t.jobCompany&&(s.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===s.date&&c.source===s.source&&c.action===s.action&&(c.jobId||"")===(s.jobId||""))&&(o.encounters.push(s),o.lastUpdated=new Date().toISOString(),$t(n))}function no(e){return e&&W()[e]?.connectionStatus||null}function At(e,t,n={}){if(!e)return;if(n.profileInfo)kt(e,n.profileInfo);else{let c=W(),a=Me(c,e,n.profileInfo?.name);c[a]||kt(e,{})}let o=W(),r=Me(o,e,n.profileInfo?.name),s=o[r];if(!s)return;let i=tt();s.connectionStatus=t,t==="connected"?s.connectionDate=i:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(s.requestedConnectionAt||(s.requestedConnectionAt=i)),s.connectionMethod=n.method||s.connectionMethod,s.messageSent=n.messageSent||s.messageSent,s.lastUpdated=new Date().toISOString(),$t(o)}function Ct(e,t,n={}){if(n.dryRun||!e||!t)return;let o=q(t);if(!o)return;let r=W(),s=Me(r,e),i=r[s];if(!i)return;let c=q(i.profileUrl||s);o!==c&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(o)||(i.aliases.push(o),i.lastUpdated=new Date().toISOString(),$t(r)))}function oo(){return fe||(vt(),fe=et(Qn,"quota.json"),(!fe||!fe.connections)&&(fe={connections:[]}),fe)}function oi(e){vt(),fe=e;try{Ze(Qn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function ro(e,t="unknown"){let n=oo(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),oi(n)}function io(){let e=oo(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function nt(){let e=io(),t=tt(),n=e.filter(a=>a.date===t).length,o=e.length,r=n>=Qe,s=o>=Xe,i=!r&&!s,c={allowed:i,daily:{sent:n,max:Qe},weekly:{sent:o,max:Xe}};return i||(c.reason=r?`Daily limit reached (${n}/${Qe})`:`Weekly limit reached (${o}/${Xe})`),c}function Ee(){let e=io(),t=tt(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Qe,remaining:Qe-n},weekly:{sent:o,max:Xe,remaining:Xe-o}}}var Hr,Vr,pe,Gt,Ha,Qn,Va,Wa,Ga,Yt,Xn,Qe,Xe,Pe,Wr,fe,Gr,Yr,Kr,zr,Qr,Ie=V(async()=>{await St();Hr=Jr(import.meta.url),Vr=U.dirname(U.dirname(Hr)),pe=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"collected-profiles"):U.join(Vr,"collected-profiles"),Gt=U.join(pe,"people.json"),Ha=U.join(pe,"jobs.json"),Qn=U.join(pe,"quota.json"),Va=U.join(pe,"conversations.json"),Wa=U.join(pe,"sync-state.json"),Ga=U.join(pe,"application-questions.json"),Yt=U.join(pe,"profile-history"),Xn=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Qe=Xn(process.env.CONNECT_MAX_DAILY,20),Xe=Xn(process.env.CONNECT_MAX_WEEKLY,100),Pe=null,Wr=null,fe=null,Gr=null,Yr=null,Kr=null;zr=["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"],Qr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var So={};Y(So,{computeEngagement:()=>Xt,detectCategory:()=>fo,detectCategoryFromTitle:()=>Ue,determineAction:()=>wo,determineLastMessageBy:()=>mo,determineSituation:()=>po,enrichConversation:()=>ci,enrichPerson:()=>hi,enrichPersonContext:()=>bo,extractAutoTags:()=>go,generateSummary:()=>ho,normPreview:()=>Qt});function ci(e,t,n){if(!e)return e;let r=(e.messages||[]).filter(a=>!Wt.has(a.status)),s=di(t,e.profileUrl,n),i=mo(r,t);if(e.lastMessageBy=i,e.conversationStatus=i==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let a=fo(r,t,s);a&&(e.category=a,e.categorySource=e.categorySource||"message_content")}if(e.situation=po(r,i,t),r.length>0){let a=r[r.length-1];e.lastMessageTime=a.time}if(r.length>0&&!e.initiatedBy){let a=r[0];a.sender===be?e.initiatedBy="us":a.sender!=="Unknown"&&a.sender!==""&&(e.initiatedBy="them")}e.engagement=Xt(r,t),e.personContext=bo(s),e.summary=ho(e,t,s),e.autoTags=go(e,t,s);let c=wo(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=ui(e),e}function fo(e,t,n){if(!e||e.length===0)return n?.title?Ue(n.title):null;let o=e.filter(r=>r.sender!==be&&r.sender!=="Unknown"&&r.sender!=="").map(r=>r.text).join(" ");for(let[r,s]of Object.entries(uo))if(s.theirMessages){for(let i of s.theirMessages)if(i.test(o))return r}if(n?.title){let r=Ue(n.title);if(r)return r}return null}function Ue(e){if(!e)return null;for(let[t,n]of Object.entries(uo))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function po(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return co.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let r=[...e].reverse().find(s=>s.sender!==be&&s.sender!=="Unknown");return co.test(r?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function mo(e,t){if(!e||e.length===0)return"them";let n=[...e].map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,s)=>s.t-r.t).map(r=>r.m),o=n.length>0?n:[...e].reverse();for(let r of o){let s=r.sender;if(s===be)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}function ho(e,t,n){let o=e.messages||[];if(o.length===0)return null;let r=[],s=e.category,i=n?.title,c=n?.company,a=n?.location;s==="recruiter"&&c?r.push(`Recruiter from ${c}`):s==="hiring_manager"&&c?r.push(`Hiring manager at ${c}`):s==="founder"&&c?r.push(`Founder of ${c}`):s&&i?r.push(`${Zt(s)}: ${qe(i,40)}`):i?r.push(qe(i,50)):r.push(t.split(" ")[0]);let l=o.filter(g=>g.sender!==be&&g.sender!=="Unknown").map(g=>g.text).join(" "),u=fi(l),f=pi(l),d=mi(l),p=[];return u&&p.push(u),d&&d!==a&&p.push(d),f&&p.push(f),p.length>0&&r.push(p.join(", ")),e.situation==="they_want_to_schedule_call"?r.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?r.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?r.push("needs reply"):e.conversationStatus==="awaiting_reply"&&r.push("waiting on them"),r.join(". ").replace(/\.\./g,".")}function go(e,t,n){let o=[],r=(e.messages||[]).filter(l=>!Wt.has(l.status)),s=r.map(l=>l.text).join(" "),i=r.filter(l=>l.sender!==be&&l.sender!=="Unknown").map(l=>l.text).join(" "),c=yo(i,n?.location);o.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(s)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(s)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(s)&&o.push("remote"),/\b(hybrid)\b/i.test(s)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(s)&&o.push("onsite"),/\b(java)\b/i.test(s)&&!/javascript/i.test(s)&&o.push("java"),/\b(python)\b/i.test(s)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(s)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(s)&&o.push("backend"),/\b(full.?stack)\b/i.test(s)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(s)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(s)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(s)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(s)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(s)&&o.push("has-salary");let a=e.engagement||Xt(r,t);return a.messageCount>=6&&o.push("active-thread"),a.theirCount===0&&a.ourCount>0&&o.push("no-response"),a.ourCount===0&&a.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(l=>Vt.has(l.status))&&o.push("has-draft"),[...new Set(o)]}function yo(e,t){let n=[],o=["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"],r=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],s=(e+" "+(t||"")).toLowerCase();for(let i of o)s.includes(i)&&n.push(i.replace(/\s+/g,"-"));for(let[i,c]of r)s.includes(i)&&n.push(c);return n}function wo(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&Qt(e.lastMessagePreview)===Qt(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let r=(e.messages||[]).find(s=>Vt.has(s.status));return r?r.status===de.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="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:`${Zt(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function Xt(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,r=0,s=!1,i=!1,c=e.map(a=>a.text).join(" ");for(let a of e)a.sender===be?n++:a.sender==="Unknown"||a.sender===""?r++:o++;return s=/\b(job|role|position|opening)\b/i.test(c),i=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:r,hasJob:s,hasSalary:i}}function bo(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function ui(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="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 di(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let r=Me(n,t,e);if(n[r])return n[r]}if(!e)return null;let o=Object.values(n).filter(r=>r.name===e);return o.length===1?o[0]:null}function Qt(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Zt(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function qe(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function fi(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 n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function pi(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 mi(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 hi(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=Ue(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}gi(e),e.personSummary=yi(e),e.personAutoTags=wi(e);let n=bi(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=Si(e)),e}function gi(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.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 yi(e){let t=[],n=e.category,o=e.title,r=e.company,s=e.location;if(n==="recruiter"&&r?t.push(`Recruiter at ${r}`):n==="hiring_manager"&&r?t.push(`Hiring manager at ${r}`):n==="founder"&&r?t.push(`Founder of ${r}`):o&&r?t.push(`${qe(o,40)} at ${qe(r,30)}`):o?t.push(qe(o,50)):e.name&&t.push(e.name.split(" ")[0]),s&&t.push(s),e.connectionDate){let i=new Date(e.connectionDate);if(!isNaN(i)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[i.getMonth()]} ${i.getDate()}`)}}if(e.jobCount>0){let i=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(i+=` (last: ${qe(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(i+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}i+=")"}t.push(i)}return t.join(". ").replace(/\.\./g,".")||null}function wi(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=yo("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function bi(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:`${Zt(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function Si(e){let t=e.category;if(!t)return null;let n=ki(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function ki(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}var uo,co,en=V(async()=>{await St();await Ie();uo={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]}};co=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var _o={};Y(_o,{BLOCK_MARKERS:()=>Ao,dedupeAndCap:()=>xo,extractSidePanelProfiles:()=>Vi,normalizeFundUrl:()=>It,normalizeProfileUrl:()=>Be,scanRelatedBlocks:()=>Co});function Be(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 n=t[1].trim();return n?`https://www.linkedin.com/in/${n}/`:null}function It(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function Co(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=l=>(l||"").replace(/\s+/g," ").trim(),r=l=>{let u=String(l||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},s=l=>o(l).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),i=l=>{let u=l,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||l.parentElement},c=[],a=Array.from(n.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let l of a){let u=o(l.textContent).toLowerCase();if(!u)continue;let f=e.find(([h])=>u.includes(h));if(!f)continue;let d=f[1],p=i(l);if(!p)continue;let g=0,m=new Set;for(let h of Array.from(p.querySelectorAll('a[href*="/in/"]'))){let y=h.href||h.getAttribute("href")||"",k=r(y);if(!k)continue;let w=h.querySelector('span[aria-hidden="true"]'),b=o(w?w.textContent:h.getAttribute("aria-label")||h.textContent),S=s(b);if(!S||m.has(k))continue;m.add(k);let C="",_=b.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(_&&(C=o(_[1])),!C){let T=h.closest("li")||h.parentElement;T&&(C=Array.from(T.querySelectorAll("p, span")).map(x=>o(x.textContent)).filter(x=>x&&x!==S&&!/^view\b/i.test(x)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(x)&&/[a-z]/i.test(x)&&x.length>2)[0]||"")}c.push({href:y,name:S,headline:C,block:d,rank:g++})}}return c}function xo(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=Be(t.seedUrl||""),r=new Map,s={};for(let i of e||[]){let c=Be(i.href);c&&(o&&c===o||(s[i.block]=s[i.block]||0,!(s[i.block]>=n)&&(r.has(c)||(s[i.block]++,r.set(c,{url:c,name:i.name,headline:i.headline||null,block:i.block,rank:i.rank})))))}return Array.from(r.values())}async function Vi(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(o=>setTimeout(o,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(o=>setTimeout(o,1200))}catch{}let n;try{n=await e.evaluate(Co,Ao)}catch{return[]}return xo(n,t)}var Ao,ln=V(()=>{Ao=[["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 No={};Y(No,{getJobDecision:()=>Qi,getLastVisit:()=>is,getScoutStats:()=>ss,loadCompanies:()=>mn,loadDiscoveredPeople:()=>Ne,loadJobDecisions:()=>pn,loadScoutedJobs:()=>fn,loadVisitLog:()=>Tt,recordCompany:()=>ns,recordDiscoveredEdge:()=>es,recordDiscoveredEdges:()=>ts,recordVisit:()=>rs,resetCaches:()=>dn,saveCompany:()=>os,saveDiscoveredPerson:()=>Xi,saveScoutedJob:()=>Ki,setJobDecision:()=>zi});import"dotenv/config";import*as re from"fs";import*as X from"path";import{fileURLToPath as Wi}from"url";function ke(){re.existsSync(Te)||re.mkdirSync(Te,{recursive:!0})}function ve(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";re.writeFileSync(o,n);for(let r=0;r<3;r++)try{re.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function ct(e){try{if(re.existsSync(e))return JSON.parse(re.readFileSync(e,"utf-8"))}catch{}return null}function dn(){it=null,st=null,at=null,lt=null,Re=null}function fn(){return it||(it=ct(Eo)||{},it)}function Ki(e,t){if(!e)return;ke();let n=fn(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[r,s]of Object.entries(t))s!=null&&(n[e][r]=s);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{ve(Eo,n)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}function pn(){return st||(st=ct(Do)||{},st)}function zi(e,t,n={}){if(!e||!t)return;ke();let o=pn(),r=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=r,n.reason&&(o[e].reason=n.reason),n.score!=null&&(o[e].score=n.score),n.source&&(o[e].source=n.source)):o[e]={status:t,decidedAt:r,updatedAt:r,reason:n.reason||null,score:n.score??null,source:n.source||null};try{ve(Do,o)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function Qi(e){return pn()[e]||null}function Ne(){return at||(at=ct(Rt)||{},at)}function Je(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Ro(e,t){let n=Be(t)||t;if(e[n])return n;let o=Je(t);if(!o)return n;let r=null;for(let[s,i]of Object.entries(e)){if(Je(i&&(i.canonicalUrl||i.profileUrl)||s)===o)return s;!r&&i&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}return r||n}function Xi(e,t){if(!e)return;ke();let n=Ne(),o=new Date().toISOString().slice(0,10),r=Ro(n,e),s=Je(e);if(n[r]){let i=n[r];t.name&&(i.name=t.name),t.title&&(i.title=t.title),t.company&&(i.company=t.company),t.location&&(i.location=t.location),t.role&&(i.role=t.role),t.isConnected!=null&&(i.isConnected=t.isConnected),t.jobId&&(i.jobIds||(i.jobIds=[]),i.jobIds.includes(t.jobId)||i.jobIds.push(t.jobId)),s&&Je(i.canonicalUrl||i.profileUrl||r)!==s&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(s)||i.aliases.push(s)),i.lastSeen=o,i.seenCount=(i.seenCount||1)+1}else n[r]={canonicalUrl:r,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:o,lastSeen:o,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{ve(Rt,n)}catch(i){console.error(`[!] Failed to save discovered-people.json: ${i.message}`)}}function Zi(e,t){let n=e.kind||"similar-panel";return n==="list-post"?{edge:{kind:n,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:o=>o.kind==="list-post"&&o.postUrl===(e.postUrl||null)&&o.fund===(e.fund||null)}:n==="scout"?{edge:{kind:n,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:o=>o.kind==="scout"&&o.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:o=>o.kind!=="list-post"&&o.kind!=="scout"&&o.seedUrl===(e.seedUrl||null)&&o.block===(e.block||"unknown")}}function To(e,t,n={},o){if(!t)return;let r=Je(t);t=Ro(e,t);let s=n.seedUrl?{...n,seedUrl:Be(n.seedUrl)||n.seedUrl}:n,i=o.slice(0,10),{edge:c,match:a}=Zi(s,o),l=e[t];l||(l=e[t]={canonicalUrl:t,aliases:[],name:n.name||null,headline:n.headline||null,location:n.location||null,company:n.company||null,companyUrl:n.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:c.kind,sources:[],connectionsCount:n.connectionsCount??null,selectivity:n.selectivity||"unknown",connectGate:n.connectGate||"unknown",score:null,fitScore:null,isConnected:n.isConnected||!1,graphRefs:[],note:n.note||"",whyUseful:n.whyUseful||"",extra:{},source:c.kind,role:Array.isArray(n.categories)&&n.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:i,firstSeen:i,lastSeen:i}),n.name&&(l.name=n.name),n.headline&&(!l.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(l.headline))&&(l.headline=n.headline),n.location&&(l.location=l.location||n.location),n.company&&(l.company=n.company),n.companyUrl&&(l.companyUrl=l.companyUrl||n.companyUrl),n.isConnected!=null&&(l.isConnected=n.isConnected),n.connectionsCount!=null&&(l.connectionsCount=n.connectionsCount),n.selectivity&&n.selectivity!=="unknown"&&(l.selectivity=n.selectivity),n.connectGate&&n.connectGate!=="unknown"&&(l.connectGate=n.connectGate),n.note&&!l.note&&(l.note=n.note),n.whyUseful&&!l.whyUseful&&(l.whyUseful=n.whyUseful),n.extra&&typeof n.extra=="object"&&(l.extra={...l.extra||{},...n.extra}),Array.isArray(l.sources)||(l.sources=[]);let u=l.sources.find(a);if(u?(c.rank!=null&&(u.rank==null||c.rank<u.rank)&&(u.rank=c.rank),u.at=c.at):l.sources.push(c),Array.isArray(l.categories)||(l.categories=[]),Array.isArray(l.sectors)||(l.sectors=[]),Array.isArray(l.aliases)||(l.aliases=[]),Array.isArray(l.graphRefs)||(l.graphRefs=[]),cn(l.categories,n.category),Dt(l.categories,n.categories),Dt(l.sectors,n.sectors),Dt(l.aliases,n.aliases),r&&Je(l.canonicalUrl||t)!==r&&cn(l.aliases,r),Dt(l.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(l.affiliations)||(l.affiliations=[]);for(let f of n.affiliations)!f||!f.companyKey||l.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||l.affiliations.push(f)}l.lastSeen=i,l.seenCount=(l.seenCount||0)+1}function es(e,t={}){if(!e)return;ke();let n=Ne();To(n,e,t,new Date().toISOString());try{ve(Rt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function ts(e){if(!Array.isArray(e)||e.length===0)return;ke();let t=Ne(),n=new Date().toISOString(),o=0;for(let r of e)!r||!r.url||(To(t,r.url,r,n),o++);if(o)try{ve(Rt,t)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function ns(e={}){if(!e||!e.name)return;ke();let t=e.key||It(e.website)||It(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=mn(),o=new Date().toISOString().slice(0,10),r=(a,l)=>{l&&Array.isArray(a)&&!a.includes(l)&&a.push(l)},s=(a,l)=>{if(Array.isArray(l))for(let u of l)r(a,u)},i=n[t];i||(i=n[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:o,lastSeen:o}),e.name&&(i.name=e.name),e.website&&(i.website=i.website||e.website),e.linkedinUrl&&(i.linkedinUrl=i.linkedinUrl||e.linkedinUrl);for(let a of["size","check","stage","location","industries","about"])e[a]&&!i[a]&&(i[a]=e[a]);e.note&&!i.note&&(i.note=e.note),e.whyUseful&&!i.whyUseful&&(i.whyUseful=e.whyUseful),e.fitScore!=null&&(i.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(i.extra={...i.extra||{},...e.extra});for(let a of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(i[a])||(i[a]=[]),s(i[a],e[a]);Array.isArray(i.people)||(i.people=[]);let c=a=>{if(!a||!a.url)return;let l=i.people.find(u=>u.url===a.url&&(u.role||null)===(a.role||null));l?a.current!=null&&(l.current=a.current):i.people.push({url:a.url,name:a.name||null,role:a.role||null,current:a.current??null,from:a.from??null,to:a.to??null})};(e.people||[]).forEach(c),(e.partners||[]).forEach(a=>c({url:a.url,name:a.name,role:"Partner",current:!0})),Array.isArray(i.portfolio)||(i.portfolio=[]);for(let a of e.portfolio||[]){let l=a&&(a.key||a.name);l&&!i.portfolio.some(u=>(u.key||u.name)===l)&&i.portfolio.push(a)}i.lastSeen=o,i.seenCount=(i.seenCount||0)+1;try{ve(un,n)}catch(a){console.error(`[!] Failed to save companies.json: ${a.message}`)}return t}function mn(){return lt||(lt=ct(un)||{},lt)}function os(e,t){if(!e)return;ke();let n=mn(),o=new Date().toISOString().slice(0,10);if(n[e]){let r=n[e];t.name&&(r.name=t.name),t.about&&(r.about=t.about),t.size&&(r.size=t.size),t.industries&&(r.industries=t.industries),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),t.recruiterUrl&&(r.recruiterUrls||(r.recruiterUrls=[]),r.recruiterUrls.includes(t.recruiterUrl)||r.recruiterUrls.push(t.recruiterUrl)),r.lastSeen=o,r.jobCount=r.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:o,lastSeen:o,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{ve(un,n)}catch(r){console.error(`[!] Failed to save companies.json: ${r.message}`)}}function Tt(){return Re||(Re=ct(Io)||{visits:[]},Array.isArray(Re.visits)||(Re.visits=[]),Re)}function rs(e,t={}){if(!e)return;ke();let n=Tt();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(r=>new Date(r.date).getTime()>o);try{ve(Io,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function is(e){let t=Tt();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function ss(){let e=fn(),t=Ne(),n=Object.values(e),o=Object.values(t),r={};for(let d of n)d.company&&(r[d.company]=(r[d.company]||0)+1);let s=Object.entries(r).sort((d,p)=>p[1]-d[1]).slice(0,5).map(([d,p])=>`${d} (${p})`),i={};for(let d of n)for(let p of d.techStack||[])i[p]=(i[p]||0)+1;let c=Object.entries(i).sort((d,p)=>p[1]-d[1]).slice(0,8).map(([d,p])=>`${d} (${p})`),a=Tt(),l=new Date().toISOString().slice(0,10),u=a.visits.filter(d=>d.date.startsWith(l)).length,f=new Set(a.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:s,topTech:c,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,p)=>(p.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var Gi,Yi,Te,Eo,Rt,Io,un,Do,it,st,at,cn,Dt,lt,Re,Nt=V(()=>{ln();Gi=Wi(import.meta.url),Yi=X.dirname(X.dirname(Gi)),Te=process.env.DATA_DIR?X.resolve(process.env.DATA_DIR,"market-research"):X.join(Yi,"market-research"),Eo=X.join(Te,"scouted-jobs.json"),Rt=X.join(Te,"discovered-people.json"),Io=X.join(Te,"visit-log.json"),un=X.join(Te,"companies.json"),Do=X.join(Te,"job-decisions.json");it=null;st=null;at=null;cn=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Dt=(e,t)=>{if(Array.isArray(t))for(let n of t)cn(e,n)};lt=null;Re=null});var Bo={};Y(Bo,{DEFAULT_PROFILE_INTERESTS:()=>jt,computeFit:()=>wn,detectSectors:()=>Cs});function Cs(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(As))r.some(s=>s.test(t))&&n.push(o);return n}function wn(e,t=jt){if(!Array.isArray(e)||e.length===0)return 0;let n=s=>typeof s=="number"&&Number.isFinite(s)?s:0,o=Math.max(1,...Object.values(t||{}).map(n)),r=0;for(let s of e){let i=n(t&&t[s]);i>r&&(r=i)}return Math.min(1,r/o)}var As,jt,bn=V(()=>{As={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/]};jt={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});import Q from"fs";import ye from"path";function Sn(){let e=process.env.ILML_SCOPE_DIR;return e?ye.join(e,"plugins-state","linkedin","cookies.json"):Ns}function Os(){let e=Sn(),t=ye.dirname(e);return t&&t!=="."&&!Q.existsSync(t)&&Q.mkdirSync(t,{recursive:!0}),e}function Vo(e){let t=Os();return Q.writeFileSync(t,JSON.stringify(e)),t}function Wo(){let e=Sn();if(!Q.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Q.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function Go(){return Q.existsSync(Sn())}function js(){let e=process.env.ILML_SCOPE_DIR;return e?ye.join(e,"plugins-state","linkedin"):"."}function Yo(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Ls(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Yo(t[1]):"default"}function Ko(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return Q.existsSync(t)||Q.mkdirSync(t,{recursive:!0}),ye.resolve(t);let n=Yo(e||Ls()),o=ye.join(js(),"chrome-profile",n);return Q.existsSync(o)||Q.mkdirSync(o,{recursive:!0}),ye.resolve(o)}function Qo(e){return!Q.existsSync(ye.join(e,zo))}function kn(e){try{Q.writeFileSync(ye.join(e,zo),new Date().toISOString())}catch{}}function Xo(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{Q.rmSync(ye.join(e,n),{force:!0}),t++}catch{}return t}var Ns,zo,vn=V(()=>{Ns="cookies.json";zo=".ilml-seeded"});var rr={};Y(rr,{_pidAlive:()=>$n,launchWithProfile:()=>Bs,markProfileEstablished:()=>Hs,registerBrowserForCleanup:()=>or,resolveProfileHolder:()=>An,seedCookiesIfNeeded:()=>Js});import Cn from"fs";import Fs from"path";async function Lt(){let e=[...dt].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});dt.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Ms(){if(Zo)return;Zo=!0;let e=t=>async()=>{await Lt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Lt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Lt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Lt(),process.exit(0))}),process.on("exit",()=>{for(let t of dt)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function xn(e){return Fs.join(e,".ilml-browser-session.json")}function tr(e,t={}){try{Cn.writeFileSync(xn(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function qs(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();tr(e,n?{wsEndpoint:n}:{})}catch{}}function Us(e){let t=nr(e);t&&t.ownerPid===process.pid&&ut(e)}function ut(e){try{Cn.rmSync(xn(e),{force:!0})}catch{}}function nr(e){try{return JSON.parse(Cn.readFileSync(xn(e),"utf-8"))}catch{return null}}function $n(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function er(e,t,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(o),i),i=>{throw clearTimeout(o),i});return Promise.race([s,r])}async function An(e,t,{probeTimeoutMs:n=4e3}={}){let o=nr(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&$n(o.ownerPid)?"live":(ut(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await er(s,n,r);if(i===r)return s.then(a=>{if(a)try{a.disconnect()}catch{}}),"live";if(!i)return ut(t),"free";if($n(o.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await er(i.close().then(()=>!0).catch(()=>!1),n,!1))return ut(t),"free";try{i.disconnect()}catch{}return"live"}function or(e,t){e&&(Ms(),dt.add(e),e.on("disconnected",()=>{dt.delete(e),t&&ut(t)}))}async function Bs(e,t={}){let n=Ko(),o={...Ps,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. 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 An(e,n)==="live")throw new Error(r);tr(n);let s;try{s=await e.launch(o)}catch{if(await An(e,n)==="live")throw new Error(r);Xo(n);try{s=await e.launch(o)}catch(c){throw Us(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return or(s,n),qs(n,s),{browser:s,profileDir:n,needsSeed:Qo(n)}}async function Js(e,t){if(!t||!t.needsSeed)return!1;if(!Go())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(...Wo()),kn(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}function Hs(e){kn(e)}var Ps,dt,Zo,ir=V(()=>{vn();Ps={headless:!1,defaultViewport:null,protocolTimeout:3e5},dt=new Set,Zo=!1});var ar={};Y(ar,{AUTHWALL_RE:()=>In,cleanSearchName:()=>zs,delayed:()=>A,dismissPremiumOverlay:()=>Ae,ensureInboxPage:()=>Ys,gotoWithReauth:()=>Fe,isAuthwallUrl:()=>pt,parseLinkedInTime:()=>Gs,recoverFromAuthwall:()=>Ft,safeParseInt:()=>Ks,stripDesignations:()=>Qs,utilityFunction:()=>Vs,waitForPageReady:()=>sr,waitPastReauth:()=>En});function Vs(){console.log("Utility function called...")}function ft(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),r=t[3].toUpperCase()==="PM";return r&&n!==12&&(n+=12),!r&&n===12&&(n=0),{hours:n,minutes:o}}function Gs(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let c=ft(n),a=new Date(t);return c?a.setHours(c.hours,c.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let c=Ws[o[1].toLowerCase()],a=ft(o[2]||""),l=new Date(t),f=l.getDay()-c;return f<=0&&(f+=7),l.setDate(l.getDate()-f),a?l.setHours(a.hours,a.minutes,0,0):l.setHours(0,0,0,0),l.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(r){let c=_n[r[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(r[2],10),l=parseInt(r[3],10),u=ft(r[4]||"");return new Date(l,c,a,u?.hours||0,u?.minutes||0,0,0).toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(s){let c=_n[s[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(s[2],10),l=ft(s[3]||""),u=t.getFullYear(),f=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let c=_n[i[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(i[2],10),l=ft(i[3]||""),u=t.getFullYear(),f=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}return null}async function A(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function sr(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let s=Date.now();for(;Date.now()-s<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-s;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(i=>setTimeout(i,o))}return!1}function pt(e){return In.test(e||"")}async function Ft(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),r=o?t:Math.min(t,45e3),s=Date.now(),i=!1;for(;Date.now()-s<r;){let a="wait";try{a=await e.evaluate(l=>!new RegExp(l).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",In.source)}catch{}if(a==="in"){try{let l=await e.cookies();if(Array.isArray(l)&&l.some(f=>f.name==="li_at")){let f=Vo(l);console.log(` \u2713 Session recovered \u2014 re-saved ${l.length} cookies (${f}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(l){console.log(` \u2713 Session recovered (cookie re-save skipped: ${l.message}).`)}return!0}if(a==="creds"){if(!o){let l=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}i||(i=!0,console.log(`
|
|
2
2
|
\u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
|
|
3
|
-
`))}await new Promise(l=>setTimeout(l,2500))}let c=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}async function
|
|
3
|
+
`))}await new Promise(l=>setTimeout(l,2500))}let c=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}async function En(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await sr(e,t,{timeout:o,label:n});if(!r&&pt(e.url())){let s=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw s.code="SESSION_EXPIRED",s}return r}async function Fe(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:s=6e4,autoRecover:i=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:s});try{return await En(e,{readySelector:n,label:o,timeout:r})}catch(c){if(i&&c.code==="SESSION_EXPIRED"){await Ft(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:s})}catch{}return await En(e,{readySelector:n,label:o,timeout:r})}throw c}}async function Ys(e){let t=e.url();if(t.includes("/messaging"))return!1;if(pt(t)?await Ft(e,{label:"inbox"}):console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3),pt(e.url())&&(await Ft(e,{label:"inbox"}),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(3e3),pt(e.url())))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}function Ks(e){return parseInt(e,10)||0}async function Ae(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",s=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),i=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),c=r.includes("Get hired faster")||r.includes("Get hired 2x");if(s||i||c){let a=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(a)return a.click(),{dismissed:!0,matched:r.substring(0,80)};let l=o.querySelectorAll("button");for(let u of l){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:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}function zs(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function Qs(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}var _n,Ws,In,Pt=V(()=>{vn();_n={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Ws={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};In=/\/authwall|\/login|\/checkpoint|\/uas\/login/});var lr={};Y(lr,{extractCertificationsFromDetails:()=>na,extractEducationFromDetails:()=>ea,extractExperienceFromDetails:()=>Xs,extractFeaturedFromDetails:()=>Zs,extractRecommendationsFromDetails:()=>oa,extractSkillsFromDetails:()=>ta});async function Xs(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await Fe(e,n,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await A(1e3);let o=e.url();if(!o.toLowerCase().includes("/details/experience/"))throw new Error(`Section /details/experience/ not available on profile (landed on ${o})`);for(let s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await A(900);await A(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 A(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await A(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function i(u){let f=[];for(let d of u.querySelectorAll("div")){let p=Array.from(d.children).filter(m=>m.tagName==="DIV");if(p.length<3)continue;let g=p.filter(m=>(m.textContent||"").trim().length>50);g.length<3||(d.textContent||"").length<500||f.push({el:d,count:g.length,totalText:(d.textContent||"").length})}return f.sort((d,p)=>p.count-d.count||d.totalText-p.totalText),f[0]?.el}let c=i(s);if(!c)return[];let a=Array.from(c.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function l(u){let f=u[0]||null,d=null,p=null;if(u[1]){let v=u[1].split("\xB7").map(x=>x.trim());d=v[0]||null,v[1]&&(p=v[1])}let g=u.findIndex(v=>/(\d{4}|present)/i.test(v)&&/(-|–|—)/i.test(v)&&v.length<80),m=null,h=null;if(g>=0){let v=u[g].split("\xB7").map(x=>x.trim());m=v[0]||null,v[1]&&(h=v[1])}let y=null,k=-1;if(g>=0&&u[g+1]){let v=u[g+1],x=/^[>*\-•]|^>/.test(v),B=/https?:\/\//.test(v),I=/\d{4}/.test(v),O=/,/.test(v)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(v);!x&&!B&&!I&&v.length<100&&O&&(y=v,k=g+1)}let w=null,b=-1,S=u[u.length-1];if(S&&/and\s+\+\d+\s+skills?$/i.test(S)){b=u.length-1;let v=S.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);v&&(w={listed:v[1].split(",").map(x=>x.trim()),additional:parseInt(v[2],10)})}let C=new Set([0,1,g,k,b].filter(v=>v>=0)),_=u.filter((v,x)=>!C.has(x)),T=_.length>0?_.join(`
|
|
4
4
|
|
|
5
|
-
`):null;return{title:f,company:d,employmentType:p,dates:m,duration:h,location:y,description:
|
|
6
|
-
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return l(d)}).filter(u=>u.title)})}catch(o){if(o.code==="SESSION_EXPIRED"||/^session expired/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function
|
|
7
|
-
${
|
|
5
|
+
`):null;return{title:f,company:d,employmentType:p,dates:m,duration:h,location:y,description:T,skills:w,_raw:u}}return a.map(u=>{let d=(u.innerText||"").trim().split(`
|
|
6
|
+
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return l(d)}).filter(u=>u.title)})}catch(o){if(o.code==="SESSION_EXPIRED"||/^session expired/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function mt(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await Fe(e,o,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:`details/${n}`}),await A(1e3);let r=e.url();if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let i=0;i<4;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await A(700);await A(800);let s=0;for(;s<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)s++,await A(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await A(600)}async function gt(e,t,n,o){try{return await o()}catch(r){let s=r.message||"";if(r.code==="SESSION_EXPIRED"||/^session expired/i.test(s))throw r;return/not available on profile/i.test(s)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${s.slice(0,120)}`),[])}}async function Zs(e,t){return gt(t,"featured","extractFeaturedFromDetails",async()=>(await mt(e,t,"featured"),await e.evaluate(`(() => {
|
|
7
|
+
${ht}
|
|
8
8
|
|
|
9
9
|
const main = document.querySelector('main');
|
|
10
10
|
if (!main) return [];
|
|
@@ -44,8 +44,8 @@ var Lr=Object.defineProperty;var V=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{fo
|
|
|
44
44
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
45
45
|
return true;
|
|
46
46
|
});
|
|
47
|
-
})()`)))}async function
|
|
48
|
-
${
|
|
47
|
+
})()`)))}async function ea(e,t){return gt(t,"education","extractEducationFromDetails",async()=>(await mt(e,t,"education"),await e.evaluate(`(() => {
|
|
48
|
+
${ht}
|
|
49
49
|
|
|
50
50
|
const main = document.querySelector('main');
|
|
51
51
|
if (!main) return [];
|
|
@@ -81,8 +81,8 @@ var Lr=Object.defineProperty;var V=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{fo
|
|
|
81
81
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
82
82
|
return true;
|
|
83
83
|
});
|
|
84
|
-
})()`)))}async function
|
|
85
|
-
${
|
|
84
|
+
})()`)))}async function ta(e,t){return gt(t,"skills","extractSkillsFromDetails",async()=>(await mt(e,t,"skills"),await e.evaluate(`(() => {
|
|
85
|
+
${ht}
|
|
86
86
|
|
|
87
87
|
const main = document.querySelector('main');
|
|
88
88
|
if (!main) return [];
|
|
@@ -113,8 +113,8 @@ var Lr=Object.defineProperty;var V=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{fo
|
|
|
113
113
|
skills.push({ name, endorsements, _raw: lines });
|
|
114
114
|
}
|
|
115
115
|
return skills;
|
|
116
|
-
})()`)))}async function
|
|
117
|
-
${
|
|
116
|
+
})()`)))}async function na(e,t){return gt(t,"certifications","extractCertificationsFromDetails",async()=>(await mt(e,t,"certifications"),await e.evaluate(`(() => {
|
|
117
|
+
${ht}
|
|
118
118
|
|
|
119
119
|
const main = document.querySelector('main');
|
|
120
120
|
if (!main) return [];
|
|
@@ -138,8 +138,8 @@ var Lr=Object.defineProperty;var V=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{fo
|
|
|
138
138
|
|
|
139
139
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
140
140
|
}).filter(e => e.name);
|
|
141
|
-
})()`)))}async function
|
|
142
|
-
${
|
|
141
|
+
})()`)))}async function oa(e,t){return gt(t,"recommendations","extractRecommendationsFromDetails",async()=>(await mt(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
142
|
+
${ht}
|
|
143
143
|
|
|
144
144
|
const main = document.querySelector('main');
|
|
145
145
|
if (!main) return [];
|
|
@@ -174,7 +174,7 @@ var Lr=Object.defineProperty;var V=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{fo
|
|
|
174
174
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
175
175
|
return true;
|
|
176
176
|
});
|
|
177
|
-
})()`)))}var
|
|
177
|
+
})()`)))}var ht,cr=V(()=>{Pt();ht=`
|
|
178
178
|
function findEntryContainer(root) {
|
|
179
179
|
const candidates = [];
|
|
180
180
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -237,91 +237,89 @@ function findEntryContainer(root) {
|
|
|
237
237
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
238
238
|
return candidates[0]?.el;
|
|
239
239
|
}
|
|
240
|
-
`});var fr={};z(fr,{clickConnectButton:()=>Rn,default:()=>ra,detectConnectionStatus:()=>xe,findConnectButton:()=>wt,runFunnel:()=>dr,sendConnectionRequest:()=>Tn,shouldExcludeLocation:()=>Mt,viewProfile:()=>Dn});async function ur(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await A(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Mt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Dn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:i=!1,extractRecommendations:c=!1,extractCertifications:a=!1}=n;try{await Me(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await A(1500),await Ce(e)&&(console.log(" Dismissed Premium overlay"),await A(1500),await ur(e,t));let u=0;for(let w=0;w<2;w++){let S=await e.evaluate(()=>document.body.scrollHeight);for(let b=1;b<=6;b++)await e.evaluate(D=>window.scrollTo(0,D),S*b/6),await A(900);let C=await e.evaluate(()=>document.body.scrollHeight);if(C===u)break;u=C}await A(800);let f=null;try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(f=w.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let w=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"]),S=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"]),C=E=>{let I=(E||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(I)},b={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:[]},D=document.querySelector("main");if(!D)return b;let $=[...Array.from(D.querySelectorAll("h1")),...Array.from(D.querySelectorAll("h2"))],R=Array.from(D.querySelectorAll("h2")),Y=$.find(E=>{let I=E.textContent&&E.textContent.trim(),N=(I||"").replace(/\s*\(\d+\)$/,"").trim();return I&&I.length>1&&I.length<100&&!w.has(N)&&!S.has(N)}),J=Y?Y.textContent.trim():null,P=Y?Y.parentElement:null;for(;P&&P!==D&&!Array.from(P.children).filter(I=>I.tagName==="P").some(I=>{let N=I.textContent&&I.textContent.trim();return N&&N.length>5&&!C(N)});)P=P.parentElement;let j=null,ee=null,T=null,K=null;if(P&&P!==D){let E=Array.from(P.children).filter(N=>N.tagName==="P").filter(N=>{let be=N.textContent&&N.textContent.trim();return be&&be.length>5&&!C(be)});if(E[0]&&(j=E[0].textContent.trim()),E[1]){let N=E[1].textContent.trim().split(/\s*[·•]\s*/);ee=N[0]||null,N.length>1&&(T=N.slice(1).join(" \xB7 "))}let I=Array.from(P.children).filter(N=>N.tagName==="DIV");for(let N=I.length-1;N>=0;N--){let be=I[N].textContent&&I[N].textContent.trim();if(be&&!(J&&be.startsWith(J))&&(K=be.split(/[·•]/)[0].trim(),K))break}}let Ie=null;if(P){let E=P.querySelectorAll("p, span, div");for(let I of E){let N=(I.textContent||"").trim().replace(/^[·•]\s*/,"");if(N==="1st"||N==="2nd"||N==="3rd"){Ie=N;break}}}let _=!!D.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),L=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),H=L&&L.src||null,M=D.textContent||"",le=null,Ln=M.match(/(\d+\+?)\s+connections\b/i);Ln&&(le=Ln[1]+" connections");let bt=null,Fn=M.match(/(\d+)\s+mutual connection/i),Pn=M.match(/and\s+(\d+)\s+other mutual/i),Rr=M.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Fn?bt=parseInt(Fn[1],10):Pn?bt=2+parseInt(Pn[1],10):Rr&&(bt=2);let Mn=null,qn=null,Un=R.find(E=>E.textContent&&E.textContent.trim()==="About");if(Un){let E=Un.parentElement;for(;E&&E.tagName!=="SECTION";)E=E.parentElement;if(E){let I=(E.textContent||"").trim();I=I.replace(/^About\s*/,"").trim();let N=I.match(/Top skills\s*(.+?)$/i);if(N){let Ht=N[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(jr=>jr.trim()).filter(Boolean);Ht.length>0&&Ht.length<10&&(qn=Ht)}I=I.split(/\n?…\s*more/i)[0].trim(),I=I.split(/\n?\.\.\.\s*more/i)[0].trim(),I=I.split(/\bTop skills\b/i)[0].trim(),I=I.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Mn=I||null}}let Bn=null,Jn=R.find(E=>E.textContent&&E.textContent.trim()==="Activity");if(Jn){let E=Jn.parentElement;for(;E&&E.tagName!=="SECTION";)E=E.parentElement;if(E){let I=(E.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);I&&(Bn=parseInt(I[1].replace(/,/g,""),10))}}let Tr=[...new Set(R.map(E=>(E.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(E=>E&&E.length>1&&E.length<60&&E!==J).filter(E=>w.has(E)))],Qe=document.body.textContent||"",Nr=/#OpenToWork\b/i.test(Qe)||/\bOpen to work\b/.test(Qe),Or=/#Hiring\b/i.test(Qe)||/\bI'?m hiring\b/i.test(Qe)||/\bWe are hiring\b/i.test(Qe);return{name:J,title:j,location:K,currentCompany:ee,currentSchool:T,connectionDegree:Ie,hasVerifiedBadge:_,photoUrl:H,connectionsLevel:le,mutualConnectionsCount:bt,followers:Bn,openToWork:Nr,hiring:Or,about:Mn,topSkills:qn,availableSections:Tr}});console.log(`Viewed: ${d.name} - ${d.title}`);let p=null,g=null,m=null,h=null,y=null,k=null;if(o||r||s||i||c||a){let w=await Promise.resolve().then(()=>(cr(),lr));o&&(p=await w.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),r&&(g=await w.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${g.length} entries`)),s&&(m=await w.extractEducationFromDetails(e,t),console.log(` + Education: ${m.length} entries`)),i&&(h=await w.extractSkillsFromDetails(e,t),console.log(` + Skills: ${h.length} entries`)),c&&(y=await w.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),a&&(k=await w.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${k.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...p!==null&&{experience:p},...g!==null&&{featured:g},...m!==null&&{education:m},...h!==null&&{skillsFull:h},...y!==null&&{recommendations:y},...k!==null&&{certifications:k}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await A(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(l.message||""))throw l;return null}}async function xe(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let r='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',s=f=>f&&!f.closest(r),i=f=>Array.from(document.querySelectorAll(f)).filter(s),c=i('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=i('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,l=i('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:c.length,pendingLabels:c.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!a,hasConnectBtn:!!l};return c.length>0?{status:"pending",debug:u}:a&&!l?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await A(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function wt(e){let t=null,n=await e.evaluate(()=>{let l=document.querySelector("h1")?.textContent?.trim();if(l&&!l.includes("notification"))return l;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(l=u.textContent?.trim(),l&&!l.includes("notification")))return l;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: "${n}"`),n){let l=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))}});l.count>0&&console.log(` S0: ${l.count} custom-invite links: ${JSON.stringify(l.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),p=f.toLowerCase().split(" ")[0],g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let m of d){let h=m.getBoundingClientRect();if(h.width===0||h.height===0||m.closest(g))continue;if((m.getAttribute("aria-label")||"").toLowerCase().includes(p))return m}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let l=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${l}"`);let u=await e.evaluate(d=>{let p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),g=document.querySelectorAll("button[aria-label]");return Array.from(g).filter(h=>{let y=h.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&p.test(y)}).map(h=>h.getAttribute("aria-label")?.slice(0,50))},l);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let p=document.querySelectorAll("button[aria-label]"),g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of p){if(h.closest(g))continue;let y=h.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&m.test(y))return h}return null},l);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&&n){let l=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();l.includes("invite")&&!l.includes(u)&&(console.log(` Skipping primary button: wrong person (${l})`),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 o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",s=null;for(let l of o){let u=await e.evaluate((f,d)=>{let p=f.className.includes("muted"),g=f.className.includes("sticky-header")||f.className.includes("sticky"),m=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,h=(f.getAttribute("aria-label")||"").toLowerCase(),y=h.includes("invite"),k=d?h.includes(d):!0;return{isMuted:p,isStickyHeader:g,inRecommendations:m,hasInvite:y,matchesName:k,ariaLabel:h}},l,r);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}s=l;break}}for(let l of o)l!==s&&await l.dispose().catch(()=>{});if(s)return console.log(" Found: secondary button"),{button:s,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let i=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let l of c){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),p=d.width>0&&d.height>0,g=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:g,top:d.top}},l);if(u.isVisible&&!u.isInStickyHeader){i=l,console.log(" Found More button by ID pattern (main)");break}}for(let l of c)l!==i&&await l.dispose().catch(()=>{});if(!i&&c.length>0&&(i=c[c.length-1],console.log(" Found More button by ID pattern (last)")),i||(i=await e.$('button[aria-label="More actions"]'),i&&console.log(" Found More button by aria-label")),!i){let l=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(p=>{let g=p.innerText?.trim(),m=p.getAttribute("aria-label")||"",h=p.getBoundingClientRect();return h.top<100||h.top>600||h.width===0?!1:g==="Follow"||g==="Message"||g==="Connect"||m.includes("Follow")||m.includes("Message")||m.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let p=0;p<8&&d;p++){for(let g of d.querySelectorAll("button"))if(g.innerText?.trim()==="More"&&g!==f)return g;d=d.parentElement}return null});i=l?.asElement?.()||null,i||await l?.dispose?.().catch(()=>{}),i&&console.log(" Found More button by text (near profile actions)")}if(i)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),i),await A(500),await e.evaluate(d=>d.click(),i),await A(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 g of p){let m=g.querySelector('a[href*="custom-invite"]');if(m)return m;for(let h of g.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}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 g of d)for(let m of g.querySelectorAll('[role="menuitem"], a, div')){let h=m.innerText?.trim();h&&h.length<40&&p.push(h)}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(l){console.log(" More dropdown click failed:",l.message),await e.keyboard.press("Escape")}let a=await e.evaluateHandle(l=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(l||"").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 g=d.getBoundingClientRect();if(!(g.width===0||g.height===0)){if(p.includes("invite")){if(f&&p.includes(f))return d;continue}if(p==="connect")return d}}return null},n||"");return t=a?.asElement?.()||null,t||await a?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Rn(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await A(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),s=n.tag==="DIV",i=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(i))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(i.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&&!i.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(r){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 A(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 A(2e3),"premium_redirect"}else s?(await e.evaluate(u=>u.click(),t),await A(3e3)):(await e.evaluate(u=>u.click(),t),await A(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),l=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${l}`:` \u26A0 No modal after connect click \u2014 ${l}`),"success"}async function na(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 A(1500);let n=await wt(e);if(n){await e.evaluate(r=>r.click(),n),await A(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await We(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function We(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(i=>{let c=a=>!!(a&&a.querySelector(i));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),r=()=>e.evaluate(()=>{for(let i of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(i.innerText||""))return!0;return!1}),s=async()=>{let i=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(i)return i;let c=await e.evaluateHandle(a=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(a)||null,n);return i=c?.asElement?.()||null,i||await c?.dispose?.().catch(()=>{}),i};for(let i=0;i<2;i++){try{await t.evaluate(c=>c.click())}catch{}if(await A(3e3),await r())return!1;if(await o())return!0;if(i===0){let c=await s();if(!c)return await o();t=c,await A(600)}}return await o()}async function Tn(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:s=!1}=n;if(!r){let c=ot();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let i=await oa(e,t,n);return i.connectionSent&&!s&&ro(t,o),i}async function oa(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:s=!0,skipIfConnected:i=!0,excludeLocations:c=[]}=n,a={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let l=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
241
|
-
--- Connecting: ${l} ---`),c.length>0){let y=W()[t]?.location;if(Mt(y,c))return console.log(` \u26A0 Excluded location (stored): ${y}`),a.reason="excluded_location",a.profileInfo={location:y},a}try{await Me(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"),a.reason="session_expired",a.fatal=!0,a;throw y}if(await A(2e3),await Ce(e)&&(console.log(" Dismissed Premium overlay"),await A(2e3),await ur(e,t),await A(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:k}=await Promise.resolve().then(()=>(ln(),Eo)),{recordDiscoveredEdges:x}=await Promise.resolve().then(()=>(Nt(),No)),{detectCategoryFromTitle:w}=await en().then(()=>So),{detectSectors:S}=await Promise.resolve().then(()=>(bn(),Bo)),C=k(t)||t,b=await y(e,{seedUrl:C}),D=b.map($=>{let R=$.headline?w($.headline):null;return{url:$.url,seedUrl:C,block:$.block,rank:$.rank,name:$.name,headline:$.headline,categories:R?[R]:[],sectors:S($.headline||"")}});x(D),b.length&&console.log(` \xB7 discovery: harvested ${b.length} related profiles`)}catch(y){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${y.message}`)}a.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),k=_=>{let L=(_||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(L)},x={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},w=document.querySelector("main");if(!w)return x;let S=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],C=Array.from(w.querySelectorAll("h2")),b=S.find(_=>{let L=_.textContent&&_.textContent.trim();return L&&L.length>1&&L.length<100&&!y.has(L)&&L!=="0 notifications"}),D=b?b.textContent.trim():null,$=b?b.parentElement:null;for(;$&&$!==w&&!Array.from($.children).filter(H=>H.tagName==="P").some(H=>{let M=H.textContent&&H.textContent.trim();return M&&M.length>5&&!k(M)});)$=$.parentElement;let R=null,Y=null,J=null;if($&&$!==w){let _=Array.from($.children),L=_.filter(M=>M.tagName==="P").filter(M=>{let le=M.textContent&&M.textContent.trim();return le&&le.length>5&&!k(le)});L[0]&&(R=L[0].textContent.trim()),L[1]&&(Y=L[1].textContent.trim());let H=_.filter(M=>M.tagName==="DIV");for(let M=H.length-1;M>=0;M--){let le=H[M].textContent&&H[M].textContent.trim();if(le&&!(D&&le.startsWith(D))&&(J=le.split(/[·•]/)[0].trim(),J))break}}let P=null;if($){let _=$.querySelectorAll("p, span, div");for(let L of _){let H=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(H==="1st"||H==="2nd"||H==="3rd"){P=H;break}}}let j=null,ee=C.find(_=>_.textContent&&_.textContent.trim()==="About");if(ee){let _=ee.parentElement;for(;_&&_.tagName!=="SECTION";)_=_.parentElement;_&&(j=(_.textContent||"").trim().replace(/^About\s*/,"").trim()||null,j&&(j=j.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let T=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),K=T&&T.src||null,Ie=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:D,title:R,location:J,about:j,company:Y,connectionDegree:P,connectionsCount:null,mutualConnections:null,photoUrl:K,hasVerifiedBadge:Ie}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(a.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let y=a.profileInfo?.location,k=W()[t]?.location,x=y||k;if(Mt(x,c))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${x}`),a.reason="excluded_location",a;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await xe(e,{detail:!0})).status==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),a.reason="pending",a;await Ce(e);let d=await wt(e);if(d||await Ce(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await A(2e3),d=await wt(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),a.reason="connected",a;if(!d){let y=await xe(e,{detail:!0});return i&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),a.reason="connected",a):(console.log(" \u2717 Connect not found"),a.reason="button_not_found",a)}a.method=d.method;let p=await Rn(e,d.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),a.reason="wrong_target",a;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let y=await xe(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await Ce(e),await A(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),k),await A(500),await k.click().catch(()=>e.evaluate(w=>w.click(),k)),await A(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(C=>C.click(),x),await A(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await A(3e3),a.reason="premium_required",a;if(await xe(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.method="more_dropdown",a.withCustomMessage=!1,a;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await A(500),a.reason="premium_required",a}catch(x){return console.log(" More dropdown failed:",x.message),await e.keyboard.press("Escape").catch(()=>{}),a.reason="premium_required",a}else return console.log(" \u2717 No More button found \u2014 Premium required"),a.reason="premium_required",a}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let k of y){let x=k.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!x)continue;let w=(x.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(w)||x.querySelector('input[type="email"], input[name="email"]'))return!0;let S=x.querySelector('button[aria-label="Send without a note"]');if(S&&(S.disabled||S.getAttribute("aria-disabled")==="true"||(S.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 A(500),a.reason="email_required",a}let m=await e.$('button[aria-label="Add a note"]'),h=await e.$('button[aria-label="Send without a note"]');if(!m&&!h){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let x=k.querySelector('button[aria-label="Add a note"]'),w=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!x,sendWithout:!!w}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=k?.asElement?.()||null,m||await k.dispose().catch(()=>{})}if(y.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));h=k?.asElement?.()||null,h||await k.dispose().catch(()=>{})}}if(r)if(m&&o){if(console.log(" Adding personalized note..."),await m.click(),await A(1500),await e.$("div.modal-upsell")){let x=await na(e);return a.success=x,a.connectionSent=x,a.reason=x?"sent_without_note_upsell":"upsell_failed",a.withCustomMessage=!1,a}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let x=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=o.replace("{name}",x);await k.type(w,{delay:20}),await A(500);let S=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(S)return await We(e,S)?(console.log(" \u2713 Connection sent (with note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_with_note",a.withCustomMessage=!0,a.messageSent=w,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{if(h)return console.log(" Sending without note..."),await We(e,h)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a);if(m&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await We(e,y)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{console.log(" Sending without note (custom messages disabled)...");let y=h;if(y)return await We(e,y)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}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 A(4e3)),await Ce(e),await A(500);let k=await e.$$('button[id*="profile-overflow-action"]'),x=null;for(let w of k){let S=await e.evaluate(C=>{let b=C.getBoundingClientRect();return{visible:b.width>0&&b.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},w);if(S.visible&&!S.inSticky){x=w;break}}!x&&k.length>0&&(x=k[k.length-1]);for(let w of k)w!==x&&await w.dispose().catch(()=>{});if(x)try{await e.evaluate(S=>S.scrollIntoView({behavior:"smooth",block:"center"}),x),await A(500),await x.click().catch(()=>e.evaluate(S=>S.click(),x)),await A(2e3);let w=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(w){console.log(" Found Connect in More dropdown, clicking..."),a.method="more_dropdown",await e.evaluate(D=>D.click(),w),await A(3e3);let S=e.url();if(S.includes("/premium/")||S.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await A(3e3),await xe(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(a.reason="premium_required",a);if(await xe(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a;let b=await e.$('button[aria-label="Send without a note"]');if(b)return console.log(" Modal appeared via More dropdown, sending without note..."),await We(e,b)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),a.reason="modal_failed",a);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),a.reason="modal_failed",a}catch(l){console.error(` \u2717 Error: ${l.message}`),a.reason="error",a.error=l.message;let u=l.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return a.fatal=!0,a;try{await e.goto("about:blank",{timeout:1e4}),await A(1e3)}catch{a.fatal=!0}return a}}async function dr(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:s=20,viewOnly:i=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:a=null,excludeLocations:l=[],source:u="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
242
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${i?"View Only":`Connect (max ${s})`}`),i||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),l.length>0&&console.log(`Excluding locations: ${l.join(", ")}`),!i){let p=
|
|
240
|
+
`});var fr={};Y(fr,{clickConnectButton:()=>Rn,default:()=>sa,detectConnectionStatus:()=>Ce,findConnectButton:()=>yt,runFunnel:()=>dr,sendConnectionRequest:()=>Tn,shouldExcludeLocation:()=>Mt,viewProfile:()=>Dn});async function ur(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await A(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Mt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Dn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:i=!1,extractRecommendations:c=!1,extractCertifications:a=!1}=n;try{await Fe(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await A(1500),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await A(1500),await ur(e,t));let u=0;for(let b=0;b<2;b++){let S=await e.evaluate(()=>document.body.scrollHeight);for(let _=1;_<=6;_++)await e.evaluate(T=>window.scrollTo(0,T),S*_/6),await A(900);let C=await e.evaluate(()=>document.body.scrollHeight);if(C===u)break;u=C}await A(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"]),S=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"]),C=E=>{let D=(E||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(D)},_={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:[]},T=document.querySelector("main");if(!T)return _;let v=[...Array.from(T.querySelectorAll("h1")),...Array.from(T.querySelectorAll("h2"))],x=Array.from(T.querySelectorAll("h2")),B=v.find(E=>{let D=E.textContent&&E.textContent.trim(),R=(D||"").replace(/\s*\(\d+\)$/,"").trim();return D&&D.length>1&&D.length<100&&!b.has(R)&&!S.has(R)}),I=B?B.textContent.trim():null,O=B?B.parentElement:null;for(;O&&O!==T&&!Array.from(O.children).filter(D=>D.tagName==="P").some(D=>{let R=D.textContent&&D.textContent.trim();return R&&R.length>5&&!C(R)});)O=O.parentElement;let Z=null,J=null,se=null,Ke=null;if(O&&O!==T){let E=Array.from(O.children).filter(R=>R.tagName==="P").filter(R=>{let we=R.textContent&&R.textContent.trim();return we&&we.length>5&&!C(we)});if(E[0]&&(Z=E[0].textContent.trim()),E[1]){let R=E[1].textContent.trim().split(/\s*[·•]\s*/);J=R[0]||null,R.length>1&&(se=R.slice(1).join(" \xB7 "))}let D=Array.from(O.children).filter(R=>R.tagName==="DIV");for(let R=D.length-1;R>=0;R--){let we=D[R].textContent&&D[R].textContent.trim();if(we&&!(I&&we.startsWith(I))&&(Ke=we.split(/[·•]/)[0].trim(),Ke))break}}let wt=null;if(O){let E=O.querySelectorAll("p, span, div");for(let D of E){let R=(D.textContent||"").trim().replace(/^[·•]\s*/,"");if(R==="1st"||R==="2nd"||R==="3rd"){wt=R;break}}}let j=!!T.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),M=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),H=M&&M.src||null,F=T.textContent||"",ae=null,Ln=F.match(/(\d+\+?)\s+connections\b/i);Ln&&(ae=Ln[1]+" connections");let bt=null,Fn=F.match(/(\d+)\s+mutual connection/i),Pn=F.match(/and\s+(\d+)\s+other mutual/i),Nr=F.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Fn?bt=parseInt(Fn[1],10):Pn?bt=2+parseInt(Pn[1],10):Nr&&(bt=2);let Mn=null,qn=null,Un=x.find(E=>E.textContent&&E.textContent.trim()==="About");if(Un){let E=Un.parentElement;for(;E&&E.tagName!=="SECTION";)E=E.parentElement;if(E){let D=(E.textContent||"").trim();D=D.replace(/^About\s*/,"").trim();let R=D.match(/Top skills\s*(.+?)$/i);if(R){let Ht=R[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Fr=>Fr.trim()).filter(Boolean);Ht.length>0&&Ht.length<10&&(qn=Ht)}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(),Mn=D||null}}let Bn=null,Jn=x.find(E=>E.textContent&&E.textContent.trim()==="Activity");if(Jn){let E=Jn.parentElement;for(;E&&E.tagName!=="SECTION";)E=E.parentElement;if(E){let D=(E.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);D&&(Bn=parseInt(D[1].replace(/,/g,""),10))}}let Or=[...new Set(x.map(E=>(E.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(E=>E&&E.length>1&&E.length<60&&E!==I).filter(E=>b.has(E)))],ze=document.body.textContent||"",jr=/#OpenToWork\b/i.test(ze)||/\bOpen to work\b/.test(ze),Lr=/#Hiring\b/i.test(ze)||/\bI'?m hiring\b/i.test(ze)||/\bWe are hiring\b/i.test(ze);return{name:I,title:Z,location:Ke,currentCompany:J,currentSchool:se,connectionDegree:wt,hasVerifiedBadge:j,photoUrl:H,connectionsLevel:ae,mutualConnectionsCount:bt,followers:Bn,openToWork:jr,hiring:Lr,about:Mn,topSkills:qn,availableSections:Or}});console.log(`Viewed: ${d.name} - ${d.title}`);let p=null,g=null,m=null,h=null,y=null,k=null;if(o||r||s||i||c||a){let b=await Promise.resolve().then(()=>(cr(),lr));o&&(p=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),r&&(g=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${g.length} entries`)),s&&(m=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${m.length} entries`)),i&&(h=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${h.length} entries`)),c&&(y=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),a&&(k=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${k.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...p!==null&&{experience:p},...g!==null&&{featured:g},...m!==null&&{education:m},...h!==null&&{skillsFull:h},...y!==null&&{recommendations:y},...k!==null&&{certifications:k}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await A(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(l.message||""))throw l;return null}}async function Ce(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let r='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',s=f=>f&&!f.closest(r),i=f=>Array.from(document.querySelectorAll(f)).filter(s),c=i('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=i('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,l=i('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:c.length,pendingLabels:c.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!a,hasConnectBtn:!!l};return c.length>0?{status:"pending",debug:u}:a&&!l?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await A(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function yt(e){let t=null,n=await e.evaluate(()=>{let l=document.querySelector("h1")?.textContent?.trim();if(l&&!l.includes("notification"))return l;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(l=u.textContent?.trim(),l&&!l.includes("notification")))return l;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: "${n}"`),n){let l=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))}});l.count>0&&console.log(` S0: ${l.count} custom-invite links: ${JSON.stringify(l.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),p=f.toLowerCase().split(" ")[0],g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let m of d){let h=m.getBoundingClientRect();if(h.width===0||h.height===0||m.closest(g))continue;if((m.getAttribute("aria-label")||"").toLowerCase().includes(p))return m}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let l=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${l}"`);let u=await e.evaluate(d=>{let p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),g=document.querySelectorAll("button[aria-label]");return Array.from(g).filter(h=>{let y=h.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&p.test(y)}).map(h=>h.getAttribute("aria-label")?.slice(0,50))},l);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let p=document.querySelectorAll("button[aria-label]"),g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of p){if(h.closest(g))continue;let y=h.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&m.test(y))return h}return null},l);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&&n){let l=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();l.includes("invite")&&!l.includes(u)&&(console.log(` Skipping primary button: wrong person (${l})`),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 o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",s=null;for(let l of o){let u=await e.evaluate((f,d)=>{let p=f.className.includes("muted"),g=f.className.includes("sticky-header")||f.className.includes("sticky"),m=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,h=(f.getAttribute("aria-label")||"").toLowerCase(),y=h.includes("invite"),k=d?h.includes(d):!0;return{isMuted:p,isStickyHeader:g,inRecommendations:m,hasInvite:y,matchesName:k,ariaLabel:h}},l,r);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}s=l;break}}for(let l of o)l!==s&&await l.dispose().catch(()=>{});if(s)return console.log(" Found: secondary button"),{button:s,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let i=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let l of c){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),p=d.width>0&&d.height>0,g=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:g,top:d.top}},l);if(u.isVisible&&!u.isInStickyHeader){i=l,console.log(" Found More button by ID pattern (main)");break}}for(let l of c)l!==i&&await l.dispose().catch(()=>{});if(!i&&c.length>0&&(i=c[c.length-1],console.log(" Found More button by ID pattern (last)")),i||(i=await e.$('button[aria-label="More actions"]'),i&&console.log(" Found More button by aria-label")),!i){let l=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(p=>{let g=p.innerText?.trim(),m=p.getAttribute("aria-label")||"",h=p.getBoundingClientRect();return h.top<100||h.top>600||h.width===0?!1:g==="Follow"||g==="Message"||g==="Connect"||m.includes("Follow")||m.includes("Message")||m.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let p=0;p<8&&d;p++){for(let g of d.querySelectorAll("button"))if(g.innerText?.trim()==="More"&&g!==f)return g;d=d.parentElement}return null});i=l?.asElement?.()||null,i||await l?.dispose?.().catch(()=>{}),i&&console.log(" Found More button by text (near profile actions)")}if(i)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),i),await A(500),await e.evaluate(d=>d.click(),i),await A(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 g of p){let m=g.querySelector('a[href*="custom-invite"]');if(m)return m;for(let h of g.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}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 g of d)for(let m of g.querySelectorAll('[role="menuitem"], a, div')){let h=m.innerText?.trim();h&&h.length<40&&p.push(h)}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(l){console.log(" More dropdown click failed:",l.message),await e.keyboard.press("Escape")}let a=await e.evaluateHandle(l=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(l||"").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 g=d.getBoundingClientRect();if(!(g.width===0||g.height===0)){if(p.includes("invite")){if(f&&p.includes(f))return d;continue}if(p==="connect")return d}}return null},n||"");return t=a?.asElement?.()||null,t||await a?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Rn(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await A(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),s=n.tag==="DIV",i=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(i))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(i.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&&!i.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(r){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 A(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 A(2e3),"premium_redirect"}else s?(await e.evaluate(u=>u.click(),t),await A(3e3)):(await e.evaluate(u=>u.click(),t),await A(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),l=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${l}`:` \u26A0 No modal after connect click \u2014 ${l}`),"success"}async function ra(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 A(1500);let n=await yt(e);if(n){await e.evaluate(r=>r.click(),n),await A(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await He(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function He(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(i=>{let c=a=>!!(a&&a.querySelector(i));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),r=()=>e.evaluate(()=>{for(let i of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(i.innerText||""))return!0;return!1}),s=async()=>{let i=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(i)return i;let c=await e.evaluateHandle(a=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(a)||null,n);return i=c?.asElement?.()||null,i||await c?.dispose?.().catch(()=>{}),i};for(let i=0;i<2;i++){try{await t.evaluate(c=>c.click())}catch{}if(await A(3e3),await r())return!1;if(await o())return!0;if(i===0){let c=await s();if(!c)return await o();t=c,await A(600)}}return await o()}async function Tn(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:s=!1}=n;if(!r){let c=nt();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let i=await ia(e,t,n);return i.connectionSent&&!s&&ro(t,o),i}async function ia(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:s=!0,skipIfConnected:i=!0,excludeLocations:c=[]}=n,a={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let l=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
241
|
+
--- Connecting: ${l} ---`),c.length>0){let y=W()[t]?.location;if(Mt(y,c))return console.log(` \u26A0 Excluded location (stored): ${y}`),a.reason="excluded_location",a.profileInfo={location:y},a}try{await Fe(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"),a.reason="session_expired",a.fatal=!0,a;throw y}if(await A(2e3),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await A(2e3),await ur(e,t),await A(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:k}=await Promise.resolve().then(()=>(ln(),_o)),{recordDiscoveredEdges:w}=await Promise.resolve().then(()=>(Nt(),No)),{detectCategoryFromTitle:b}=await en().then(()=>So),{detectSectors:S}=await Promise.resolve().then(()=>(bn(),Bo)),C=k(t)||t,_=await y(e,{seedUrl:C}),T=_.map(v=>{let x=v.headline?b(v.headline):null;return{url:v.url,seedUrl:C,block:v.block,rank:v.rank,name:v.name,headline:v.headline,categories:x?[x]:[],sectors:S(v.headline||"")}});w(T),_.length&&console.log(` \xB7 discovery: harvested ${_.length} related profiles`)}catch(y){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${y.message}`)}a.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),k=j=>{let M=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(M)},w={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 w;let S=[...Array.from(b.querySelectorAll("h1")),...Array.from(b.querySelectorAll("h2"))],C=Array.from(b.querySelectorAll("h2")),_=S.find(j=>{let M=j.textContent&&j.textContent.trim();return M&&M.length>1&&M.length<100&&!y.has(M)&&M!=="0 notifications"}),T=_?_.textContent.trim():null,v=_?_.parentElement:null;for(;v&&v!==b&&!Array.from(v.children).filter(H=>H.tagName==="P").some(H=>{let F=H.textContent&&H.textContent.trim();return F&&F.length>5&&!k(F)});)v=v.parentElement;let x=null,B=null,I=null;if(v&&v!==b){let j=Array.from(v.children),M=j.filter(F=>F.tagName==="P").filter(F=>{let ae=F.textContent&&F.textContent.trim();return ae&&ae.length>5&&!k(ae)});M[0]&&(x=M[0].textContent.trim()),M[1]&&(B=M[1].textContent.trim());let H=j.filter(F=>F.tagName==="DIV");for(let F=H.length-1;F>=0;F--){let ae=H[F].textContent&&H[F].textContent.trim();if(ae&&!(T&&ae.startsWith(T))&&(I=ae.split(/[·•]/)[0].trim(),I))break}}let O=null;if(v){let j=v.querySelectorAll("p, span, div");for(let M of j){let H=(M.textContent||"").trim().replace(/^[·•]\s*/,"");if(H==="1st"||H==="2nd"||H==="3rd"){O=H;break}}}let Z=null,J=C.find(j=>j.textContent&&j.textContent.trim()==="About");if(J){let j=J.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(Z=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,Z&&(Z=Z.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let se=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ke=se&&se.src||null,wt=!!b.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:T,title:x,location:I,about:Z,company:B,connectionDegree:O,connectionsCount:null,mutualConnections:null,photoUrl:Ke,hasVerifiedBadge:wt}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(a.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let y=a.profileInfo?.location,k=W()[t]?.location,w=y||k;if(Mt(w,c))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${w}`),a.reason="excluded_location",a;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await Ce(e,{detail:!0})).status==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),a.reason="pending",a;await Ae(e);let d=await yt(e);if(d||await Ae(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await A(2e3),d=await yt(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),a.reason="connected",a;if(!d){let y=await Ce(e,{detail:!0});return i&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),a.reason="connected",a):(console.log(" \u2717 Connect not found"),a.reason="button_not_found",a)}a.method=d.method;let p=await Rn(e,d.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),a.reason="wrong_target",a;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let y=await Ce(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await Ae(e),await A(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(b=>b.scrollIntoView({behavior:"smooth",block:"center"}),k),await A(500),await k.click().catch(()=>e.evaluate(b=>b.click(),k)),await A(2e3);let w=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(w){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),w),await A(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 A(3e3),a.reason="premium_required",a;if(await Ce(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.method="more_dropdown",a.withCustomMessage=!1,a;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await A(500),a.reason="premium_required",a}catch(w){return console.log(" More dropdown failed:",w.message),await e.keyboard.press("Escape").catch(()=>{}),a.reason="premium_required",a}else return console.log(" \u2717 No More button found \u2014 Premium required"),a.reason="premium_required",a}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let k of y){let w=k.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!w)continue;let b=(w.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(b)||w.querySelector('input[type="email"], input[name="email"]'))return!0;let S=w.querySelector('button[aria-label="Send without a note"]');if(S&&(S.disabled||S.getAttribute("aria-disabled")==="true"||(S.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 A(500),a.reason="email_required",a}let m=await e.$('button[aria-label="Add a note"]'),h=await e.$('button[aria-label="Send without a note"]');if(!m&&!h){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let w=k.querySelector('button[aria-label="Add a note"]'),b=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!w,sendWithout:!!b}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=k?.asElement?.()||null,m||await k.dispose().catch(()=>{})}if(y.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));h=k?.asElement?.()||null,h||await k.dispose().catch(()=>{})}}if(r)if(m&&o){if(console.log(" Adding personalized note..."),await m.click(),await A(1500),await e.$("div.modal-upsell")){let w=await ra(e);return a.success=w,a.connectionSent=w,a.reason=w?"sent_without_note_upsell":"upsell_failed",a.withCustomMessage=!1,a}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let w=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),b=o.replace("{name}",w);await k.type(b,{delay:20}),await A(500);let S=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(S)return await He(e,S)?(console.log(" \u2713 Connection sent (with note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_with_note",a.withCustomMessage=!0,a.messageSent=b,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{if(h)return console.log(" Sending without note..."),await He(e,h)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a);if(m&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await He(e,y)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{console.log(" Sending without note (custom messages disabled)...");let y=h;if(y)return await He(e,y)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}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 A(4e3)),await Ae(e),await A(500);let k=await e.$$('button[id*="profile-overflow-action"]'),w=null;for(let b of k){let S=await e.evaluate(C=>{let _=C.getBoundingClientRect();return{visible:_.width>0&&_.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},b);if(S.visible&&!S.inSticky){w=b;break}}!w&&k.length>0&&(w=k[k.length-1]);for(let b of k)b!==w&&await b.dispose().catch(()=>{});if(w)try{await e.evaluate(S=>S.scrollIntoView({behavior:"smooth",block:"center"}),w),await A(500),await w.click().catch(()=>e.evaluate(S=>S.click(),w)),await A(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..."),a.method="more_dropdown",await e.evaluate(T=>T.click(),b),await A(3e3);let S=e.url();if(S.includes("/premium/")||S.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await A(3e3),await Ce(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(a.reason="premium_required",a);if(await Ce(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a;let _=await e.$('button[aria-label="Send without a note"]');if(_)return console.log(" Modal appeared via More dropdown, sending without note..."),await He(e,_)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),a.reason="modal_failed",a);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"),a.reason="modal_failed",a}catch(l){console.error(` \u2717 Error: ${l.message}`),a.reason="error",a.error=l.message;let u=l.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return a.fatal=!0,a;try{await e.goto("about:blank",{timeout:1e4}),await A(1e3)}catch{a.fatal=!0}return a}}async function dr(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:s=20,viewOnly:i=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:a=null,excludeLocations:l=[],source:u="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
242
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${i?"View Only":`Connect (max ${s})`}`),i||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),l.length>0&&console.log(`Excluding locations: ${l.join(", ")}`),!i){let p=Ee();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 g=t[p];try{if(e.isClosed()){console.log(`
|
|
243
243
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
244
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=no(g.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${g.name||g.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,a&&await a(g,f,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${g.name||g.profileUrl}`);let h=null;if(i){let y=await Dn(e,g.profileUrl);y?(kt(g.profileUrl,{...y,source:u}),f.viewed++,h={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(f.errors++,h={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=s){console.log(` Max connections per session (${s}) reached`);break}let y=
|
|
244
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=no(g.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${g.name||g.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,a&&await a(g,f,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${g.name||g.profileUrl}`);let h=null;if(i){let y=await Dn(e,g.profileUrl);y?(kt(g.profileUrl,{...y,source:u}),f.viewed++,h={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(f.errors++,h={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=s){console.log(` Max connections per session (${s}) reached`);break}let y=nt();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(h=await Tn(e,g.profileUrl,{message:o,useCustomMessage:r,excludeLocations:l,source:u,skipQuotaGate:!0}),h.success)f.connectionsSent++;else switch(h.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(h?.fatal){console.log(`
|
|
245
245
|
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(h?.reason==="error"){if(d++,d>=3){console.log(`
|
|
246
246
|
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(h&&h.reason&&(At(g.profileUrl,h.reason,{method:h.method,messageSent:h.messageSent,profileInfo:h.profileInfo}),h.resolvedUrl&&Ct(g.profileUrl,h.resolvedUrl),to(g.profileUrl,{source:u||"funnel",jobId:g.jobId||g.fromJob?.jobId||null,jobTitle:g.fromJob?.title||null,jobCompany:g.fromJob?.company||null,action:h.reason})),a&&await a(g,f,h),p<t.length-1){let y=c+Math.random()*2e3;await A(y)}}if(console.log(`
|
|
247
|
-
=== 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}`),!i){let p=
|
|
247
|
+
=== 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}`),!i){let p=Ee();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return f}var sa,pr=V(async()=>{Pt();await Ie();sa={viewProfile:Dn,detectConnectionStatus:Ce,findConnectButton:yt,clickConnectButton:Rn,sendConnectionRequest:Tn,runFunnel:dr,shouldExcludeLocation:Mt}});import{createGraphClient as aa,resolveToken as la}from"@ilivemylife/graph-sdk";import{config as ca}from"dotenv";var mr,hr,gr=V(()=>{ca();mr=la()||process.env.TOKEN;mr||(console.error(`
|
|
248
248
|
[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.
|
|
249
249
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
250
250
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
251
|
-
`),process.exit(1));hr=
|
|
252
|
-
|
|
253
|
-
${o.join(`
|
|
254
|
-
`)}`;try{await hr.addMessage(i,a)}catch(l){console.error(`[runReport] Failed to post end-of-session message: ${l.message}`)}}var wr=V(()=>{gr()});var vr={};z(vr,{endRun:()=>ha,formatScriptStatus:()=>wa,getLastRun:()=>ya,getRunHistory:()=>ga,getTodayRunSummary:()=>Sr,startRun:()=>ma,timeAgo:()=>kr});import"dotenv/config";import*as ae from"fs";import*as Ee from"path";import{fileURLToPath as ua}from"url";function pa(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";ae.writeFileSync(o,n);for(let r=0;r<3;r++)try{ae.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ge(){try{if(!ae.existsSync(On))return{runs:[]};let e=JSON.parse(ae.readFileSync(On,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function br(e){ae.existsSync(Nn)||ae.mkdirSync(Nn,{recursive:!0});try{pa(On,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function ma(e,t="default"){let n=Ge();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>s),br(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function ha(e,t,n=null,o=null){if(!e)return;let r=null;try{let i=Ge(),c=i.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let a=i.runs.find(l=>l.script===e.script&&l.status==="running"&&l.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,r=a.duration)}br(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";yr({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}function ga(e=7){let t=Ge(),n=Date.now()-e*24*60*60*1e3;return t.runs.filter(o=>new Date(o.timestamp).getTime()>n).sort((o,r)=>r.timestamp.localeCompare(o.timestamp))}function ya(e=null){let t=Ge(),n=e?t.runs.filter(o=>o.script===e):t.runs;return n[n.length-1]||null}function Sr(){let e=new Date().toISOString().slice(0,10),t=Ge(),n={};for(let o of t.runs){if(!o.timestamp.startsWith(e))continue;n[o.script]||(n[o.script]={total:0,success:0,error:0,interrupted:0,partial:0,running:0,lastRun:null});let r=n[o.script];r.total++,o.status==="success"?r.success++:o.status==="error"?r.error++:o.status==="interrupted"?r.interrupted++:o.status==="partial"?r.partial++:o.status==="running"&&r.running++,r.lastRun=o}return n}function kr(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),r=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:r===1?"yesterday":`${r} days ago`}function wa(){let e=["sync-all","messages","funnel","sync","apply"],t=Ge(),n=Sr(),o=[];o.push("\u2550\u2550\u2550 SCRIPT STATUS \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let s of e){let i=t.runs.filter(m=>m.script===s),c=[...i].reverse().find(m=>m.status==="success"),a=i[i.length-1],l=c||a,u=l?kr(l.timestamp):"never",d=(l?Math.floor((Date.now()-new Date(l.timestamp).getTime())/864e5):1/0)>1?" \u26A0":l?.status==="error"?" \u2717":" \u2713",p="";if(l?.stats){let m=l.stats,h=Object.entries(m).filter(([,y])=>typeof y=="number"&&y>0).slice(0,3).map(([y,k])=>`${k} ${y}`);h.length&&(p=` (${h.join(", ")})`)}let g=l?.duration?` ${Math.round(l.duration/1e3)}s`:"";o.push(` ${s.padEnd(14)} ${u.padEnd(16)}${g}${p}${d}`)}let r=Object.entries(n);if(r.length>0){o.push("");for(let[s,i]of r){let c=[];i.success&&c.push(`${i.success} success`),i.error&&c.push(`${i.error} error`),i.interrupted&&c.push(`${i.interrupted} interrupted`),i.running&&c.push(`${i.running} running`),o.push(` Today: ${s} \xD7${i.total} (${c.join(", ")})`)}}return o.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),o.join(`
|
|
255
|
-
`)}var da,fa,Nn,On,$r=V(()=>{wr();da=ua(import.meta.url),fa=Ee.dirname(Ee.dirname(da)),Nn=process.env.DATA_DIR?Ee.resolve(process.env.DATA_DIR,"collected-profiles"):Ee.join(fa,"collected-profiles"),On=Ee.join(Nn,"run-log.json")});import*as Bt from"fs";import*as Ye from"path";await St();await Re();import"dotenv/config";import*as xt from"fs";import*as ke from"path";import{fileURLToPath as ni}from"url";var oi=ni(import.meta.url),ri=ke.dirname(ke.dirname(oi)),Kt=process.env.DATA_DIR?ke.resolve(process.env.DATA_DIR,"collected-profiles"):ke.join(ri,"collected-profiles"),ao=ke.join(Kt,"connect-queue.json"),ii=1,Te=300,Et=["queued","approved","sent","skipped","failed"],ce=["high","normal","low"],so={high:0,normal:1,low:2};function si(){xt.existsSync(Kt)||xt.mkdirSync(Kt,{recursive:!0})}function zt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=Te?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:ce.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:Et.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function Q(){let e=tt(ao,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(zt).filter(n=>n.url):[]}function ue(e){si(),et(ao,{version:ii,entries:e.map(zt)})}function he(e){return U(e)||(e||"").trim().toLowerCase()}function rt(e,t){let n=he(t);return e.find(o=>he(o.url)===n)||null}function it(e,t,n={}){let{tag:o="untagged",priority:r="normal",alreadyEngaged:s=()=>!1,nowIso:i}=n,c={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},a=new Set(e.map(l=>he(l.url)));for(let l of t){let u=l?.url;if(!u){c.skippedNoUrl++;continue}let f=he(u);if(a.has(f)){c.skippedDup++;continue}if(s(u)){c.skippedEngaged++;continue}let d=typeof l.note=="string"?l.note.trim():"";d.length>Te&&c.notesTooLong++;let p=d.length>0&&d.length<=Te;e.push(zt({url:u,tag:l.tag||o,priority:l.priority||r,withNote:p,note:p?d:null,status:"queued",addedAt:i||null})),a.add(f),c.added++}return c}function lo(e){return[...e].sort((t,n)=>{let o=(so[t.priority]??1)-(so[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function ge(e,t){return e.filter(n=>n.status===t)}await Re();await en();import"dotenv/config";import*as v from"fs";import*as gn from"os";import*as O from"path";import{fileURLToPath as is}from"url";var on={};z(on,{NAME:()=>ki,VERSION:()=>Si,up:()=>Ai});import*as ne from"fs";import*as _t from"path";var Si=1,ki="normalize-jobs-and-questions",vi=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],$i=50;function tn(e){return ne.existsSync(e)?JSON.parse(ne.readFileSync(e,"utf-8")):null}function nn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ne.writeFileSync(o,n)}catch(r){try{ne.unlinkSync(o)}catch{}throw r}try{ne.renameSync(o,e)}catch(r){try{ne.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Ai(e,t){let n=_t.join(e,"jobs.json"),o=_t.join(t,"scouted-jobs.json"),r=_t.join(e,"application-questions.json"),s=tn(n)||{},i=tn(o)||{},c=0,a=[];for(let u of Object.keys(s)){if(!i[u])continue;let f=i[u],d=s[u];for(let p of vi)f[p]!=null&&d[p]==null&&(d[p]=f[p]);a.push(u),c++}c>0?(nn(n,s),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=tn(r);if(l&&Array.isArray(l.applications)){let u={},f=0;for(let d of l.applications){let p=d.jobId||"unknown";u[p]||(u[p]={applications:[]});let g=(d.questions||[]).map(m=>{let h={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=$i?h.options=m.options:(h.optionsOmitted=!0,f++)),m.page&&(h.page=m.page),m.wasPreFilled&&(h.wasPreFilled=!0),m.wasRetry&&(h.wasRetry=!0),h});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||g.length,questions:g})}nn(r,u),console.log(` Phase 2: Rekeyed ${l.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else l&&!l.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(a.length>0){for(let u of a)delete i[u];nn(o,i),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var rn={};z(rn,{NAME:()=>xi,VERSION:()=>Ci,up:()=>Ii});import*as oe from"fs";import*as ko from"path";var Ci=2,xi="reset-unread-flags";function Ei(e){return oe.existsSync(e)?JSON.parse(oe.readFileSync(e,"utf-8")):null}function _i(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{oe.writeFileSync(o,n)}catch(r){try{oe.unlinkSync(o)}catch{}throw r}try{oe.renameSync(o,e)}catch(r){try{oe.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Ii(e){let t=ko.join(e,"conversations.json"),n=Ei(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}_i(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var sn={};z(sn,{NAME:()=>Ri,VERSION:()=>Di,up:()=>Li});import*as re from"fs";import*as vo from"path";var Di=3,Ri="recompute-last-message-by",Ti=new Set(["draft","confirmed","rejected","needs_review"]);function Ni(e){return re.existsSync(e)?JSON.parse(re.readFileSync(e,"utf-8")):null}function Oi(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{re.writeFileSync(o,n)}catch(r){try{re.unlinkSync(o)}catch{}throw r}try{re.renameSync(o,e)}catch(r){try{re.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function ji(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!Ti.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Li(e){let t=vo.join(e,"conversations.json"),n=Ni(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.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 r=0,s=0,i=0;for(let c of Object.keys(n)){let a=n[c];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,s++);let l=Array.isArray(a.messages)?a.messages:[],u=ji(l,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==u&&i++,a.lastMessageBy=u,a.conversationStatus=f,r++}if(r===0){console.log(" No conversations to recompute.");return}Oi(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var an={};z(an,{NAME:()=>Pi,VERSION:()=>Fi,up:()=>Bi});import*as ie from"fs";import*as $o from"path";var Fi=4,Pi="split-connection-timestamps",Mi=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function qi(e){if(!ie.existsSync(e))return null;let t=ie.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Ui(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ie.writeFileSync(o,n)}catch(r){try{ie.unlinkSync(o)}catch{}throw r}try{ie.renameSync(o,e)}catch(r){try{ie.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Bi(e){let t=$o.join(e,"people.json"),n=qi(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let i=n[s];!i||typeof i!="object"||(r++,Mi.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ui(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Re();Nt();var ss=is(import.meta.url),as=O.dirname(ss),ls=O.dirname(O.dirname(as));function cs(e){return e&&(e==="~"?gn.homedir():e.startsWith("~/")||e.startsWith("~\\")?O.join(gn.homedir(),e.slice(2)):e)}var de=process.env.DATA_DIR?O.resolve(cs(process.env.DATA_DIR)):ls,Fe=O.join(de,"collected-profiles"),Pe=O.join(de,"market-research"),X=O.join(de,".schema-version"),Oo=[O.join(Fe,".schema-version"),O.join(Pe,".schema-version")],Ae=4,ye=[{version:1,module:on},{version:2,module:rn},{version:3,module:sn},{version:4,module:an}];(function(){ye.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ye){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ye.length?ye[ye.length-1].version:0;if(n!==Ae)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${Ae}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ye.length;o++){let r=o+1;if(ye[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ye[o].version}`)}})();function Po(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
251
|
+
`),process.exit(1));hr=aa({token:mr})});import"dotenv/config";function ua(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function fa(e){let t=String(e||"").toLowerCase();return/authwall|session expired|not logged in|re-?auth|logged out|sign ?in/.test(t)?"LinkedIn asked to sign in again. Run `ilml linkedin login`, then run this again.":/protocoltimeout|callfunctionon|target closed|session closed|detached|execution context|browser.*disconnected|connection closed/.test(t)?"The browser stopped responding partway through. This is usually temporary \u2014 just run it again.":/err_aborted|err_network|err_connection|err_name_not_resolved|net::/.test(t)?"A page failed to load (network hiccup). Try running it again in a moment.":/navigation timeout|timeout.*exceeded|waiting for selector|waiting for/.test(t)?"A page took too long to load. Try again in a moment.":/invite limit|weekly.*limit|too many|rate.?limit|quota/.test(t)?"You've reached a LinkedIn sending limit for now. Wait a while, then try again.":"Something went wrong partway through. It is safe to run the command again."}function pa({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",c=n==="error"?"stopped early":n==="quota-reached"?"daily limit reached":"done",a=da[e]||e,l=t&&t!=="default"?` \xB7 ${t}`:"",u=new Date().toISOString().slice(0,16).replace("T"," "),f=s?` \xB7 ${ua(s)}`:"",d=[];d.push(`## ${i} ${a} \u2014 ${c}`),d.push(`_${u}${l}${f}_`),d.push("");for(let p of o)d.push(`- ${p}`);if(n==="error"){d.push(""),d.push(`**What happened:** ${fa(r)}`);let p=String(r||"").replace(/\s+/g," ").trim();p&&d.push(`_Technical detail: ${p.slice(0,140)}_`)}return d.join(`
|
|
252
|
+
`)}async function yr({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let c=pa({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s});try{await hr.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var da,wr=V(()=>{gr();da={apply:"Job apply","apply-queue":"Job apply (queue)",scout:"Job scout",connect:"Connect run",funnel:"Recruiter funnel",messages:"Messages",sync:"Connections sync","sync-all":"Inbox sync",visit:"Profile visits",viewers:"Profile viewers",daily:"Daily run"}});var Ar={};Y(Ar,{endRun:()=>kr,formatScriptStatus:()=>ka,getLastRun:()=>Sa,getRunHistory:()=>ba,getTodayRunSummary:()=>vr,startRun:()=>Sr,timeAgo:()=>$r,withRunReport:()=>wa});import"dotenv/config";import*as ie from"fs";import*as xe from"path";import{fileURLToPath as ma}from"url";function ya(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";ie.writeFileSync(o,n);for(let r=0;r<3;r++)try{ie.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ve(){try{if(!ie.existsSync(On))return{runs:[]};let e=JSON.parse(ie.readFileSync(On,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function br(e){ie.existsSync(Nn)||ie.mkdirSync(Nn,{recursive:!0});try{ya(On,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Sr(e,t="default"){let n=Ve();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>s),br(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function kr(e,t,n=null,o=null){if(!e)return;let r=null;try{let i=Ve(),c=i.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let a=i.runs.find(l=>l.script===e.script&&l.status==="running"&&l.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,r=a.duration)}br(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";yr({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}async function wa(e,t,n,o,r={}){let{rethrow:s=!0}=r,i=Sr(e,t),c={},a=null;try{await n(c)}catch(u){a=u}let l=[];try{let u=o?o(c):[];l=(Array.isArray(u)?u:[]).filter(f=>typeof f=="string"&&f.trim())}catch(u){console.error(`[runLog] summarize threw (report still sent): ${u.message}`)}if(l.length===0&&a&&(l=["(crashed before any progress was recorded)"]),a){let u=t&&t!=="default"?` (${t})`:"";console.error(`
|
|
253
|
+
\u2717 ${e}${u} failed: ${a.message||a}`)}try{kr(i,a?"error":"success",{...c,summaryLines:l},a?a.message||String(a):null)}catch(u){console.error(`[runLog] endRun failed: ${u.message}`)}if(a&&s)throw a;return c}function ba(e=7){let t=Ve(),n=Date.now()-e*24*60*60*1e3;return t.runs.filter(o=>new Date(o.timestamp).getTime()>n).sort((o,r)=>r.timestamp.localeCompare(o.timestamp))}function Sa(e=null){let t=Ve(),n=e?t.runs.filter(o=>o.script===e):t.runs;return n[n.length-1]||null}function vr(){let e=new Date().toISOString().slice(0,10),t=Ve(),n={};for(let o of t.runs){if(!o.timestamp.startsWith(e))continue;n[o.script]||(n[o.script]={total:0,success:0,error:0,interrupted:0,partial:0,running:0,lastRun:null});let r=n[o.script];r.total++,o.status==="success"?r.success++:o.status==="error"?r.error++:o.status==="interrupted"?r.interrupted++:o.status==="partial"?r.partial++:o.status==="running"&&r.running++,r.lastRun=o}return n}function $r(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),r=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:r===1?"yesterday":`${r} days ago`}function ka(){let e=["sync-all","messages","funnel","sync","apply"],t=Ve(),n=vr(),o=[];o.push("\u2550\u2550\u2550 SCRIPT STATUS \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let s of e){let i=t.runs.filter(m=>m.script===s),c=[...i].reverse().find(m=>m.status==="success"),a=i[i.length-1],l=c||a,u=l?$r(l.timestamp):"never",d=(l?Math.floor((Date.now()-new Date(l.timestamp).getTime())/864e5):1/0)>1?" \u26A0":l?.status==="error"?" \u2717":" \u2713",p="";if(l?.stats){let m=l.stats,h=Object.entries(m).filter(([,y])=>typeof y=="number"&&y>0).slice(0,3).map(([y,k])=>`${k} ${y}`);h.length&&(p=` (${h.join(", ")})`)}let g=l?.duration?` ${Math.round(l.duration/1e3)}s`:"";o.push(` ${s.padEnd(14)} ${u.padEnd(16)}${g}${p}${d}`)}let r=Object.entries(n);if(r.length>0){o.push("");for(let[s,i]of r){let c=[];i.success&&c.push(`${i.success} success`),i.error&&c.push(`${i.error} error`),i.interrupted&&c.push(`${i.interrupted} interrupted`),i.running&&c.push(`${i.running} running`),o.push(` Today: ${s} \xD7${i.total} (${c.join(", ")})`)}}return o.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),o.join(`
|
|
254
|
+
`)}var ha,ga,Nn,On,Cr=V(()=>{wr();ha=ma(import.meta.url),ga=xe.dirname(xe.dirname(ha)),Nn=process.env.DATA_DIR?xe.resolve(process.env.DATA_DIR,"collected-profiles"):xe.join(ga,"collected-profiles"),On=xe.join(Nn,"run-log.json")});import*as Bt from"fs";import*as We from"path";await St();await Ie();import"dotenv/config";import*as xt from"fs";import*as Se from"path";import{fileURLToPath as ri}from"url";var ii=ri(import.meta.url),si=Se.dirname(Se.dirname(ii)),Kt=process.env.DATA_DIR?Se.resolve(process.env.DATA_DIR,"collected-profiles"):Se.join(si,"collected-profiles"),ao=Se.join(Kt,"connect-queue.json"),ai=1,De=300,_t=["queued","approved","sent","skipped","failed"],le=["high","normal","low"],so={high:0,normal:1,low:2};function li(){xt.existsSync(Kt)||xt.mkdirSync(Kt,{recursive:!0})}function zt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=De?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:le.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:_t.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function K(){let e=et(ao,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(zt).filter(n=>n.url):[]}function ce(e){li(),Ze(ao,{version:ai,entries:e.map(zt)})}function me(e){return q(e)||(e||"").trim().toLowerCase()}function ot(e,t){let n=me(t);return e.find(o=>me(o.url)===n)||null}function rt(e,t,n={}){let{tag:o="untagged",priority:r="normal",alreadyEngaged:s=()=>!1,nowIso:i}=n,c={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},a=new Set(e.map(l=>me(l.url)));for(let l of t){let u=l?.url;if(!u){c.skippedNoUrl++;continue}let f=me(u);if(a.has(f)){c.skippedDup++;continue}if(s(u)){c.skippedEngaged++;continue}let d=typeof l.note=="string"?l.note.trim():"";d.length>De&&c.notesTooLong++;let p=d.length>0&&d.length<=De;e.push(zt({url:u,tag:l.tag||o,priority:l.priority||r,withNote:p,note:p?d:null,status:"queued",addedAt:i||null})),a.add(f),c.added++}return c}function lo(e){return[...e].sort((t,n)=>{let o=(so[t.priority]??1)-(so[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function he(e,t){return e.filter(n=>n.status===t)}await Ie();await en();import"dotenv/config";import*as $ from"fs";import*as gn from"os";import*as N from"path";import{fileURLToPath as as}from"url";var on={};Y(on,{NAME:()=>$i,VERSION:()=>vi,up:()=>xi});import*as ee from"fs";import*as Et from"path";var vi=1,$i="normalize-jobs-and-questions",Ai=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Ci=50;function tn(e){return ee.existsSync(e)?JSON.parse(ee.readFileSync(e,"utf-8")):null}function nn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ee.writeFileSync(o,n)}catch(r){try{ee.unlinkSync(o)}catch{}throw r}try{ee.renameSync(o,e)}catch(r){try{ee.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function xi(e,t){let n=Et.join(e,"jobs.json"),o=Et.join(t,"scouted-jobs.json"),r=Et.join(e,"application-questions.json"),s=tn(n)||{},i=tn(o)||{},c=0,a=[];for(let u of Object.keys(s)){if(!i[u])continue;let f=i[u],d=s[u];for(let p of Ai)f[p]!=null&&d[p]==null&&(d[p]=f[p]);a.push(u),c++}c>0?(nn(n,s),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=tn(r);if(l&&Array.isArray(l.applications)){let u={},f=0;for(let d of l.applications){let p=d.jobId||"unknown";u[p]||(u[p]={applications:[]});let g=(d.questions||[]).map(m=>{let h={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=Ci?h.options=m.options:(h.optionsOmitted=!0,f++)),m.page&&(h.page=m.page),m.wasPreFilled&&(h.wasPreFilled=!0),m.wasRetry&&(h.wasRetry=!0),h});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||g.length,questions:g})}nn(r,u),console.log(` Phase 2: Rekeyed ${l.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else l&&!l.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(a.length>0){for(let u of a)delete i[u];nn(o,i),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var rn={};Y(rn,{NAME:()=>Ei,VERSION:()=>_i,up:()=>Ri});import*as te from"fs";import*as ko from"path";var _i=2,Ei="reset-unread-flags";function Ii(e){return te.existsSync(e)?JSON.parse(te.readFileSync(e,"utf-8")):null}function Di(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{te.writeFileSync(o,n)}catch(r){try{te.unlinkSync(o)}catch{}throw r}try{te.renameSync(o,e)}catch(r){try{te.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Ri(e){let t=ko.join(e,"conversations.json"),n=Ii(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Di(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var sn={};Y(sn,{NAME:()=>Ni,VERSION:()=>Ti,up:()=>Pi});import*as ne from"fs";import*as vo from"path";var Ti=3,Ni="recompute-last-message-by",Oi=new Set(["draft","confirmed","rejected","needs_review"]);function ji(e){return ne.existsSync(e)?JSON.parse(ne.readFileSync(e,"utf-8")):null}function Li(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ne.writeFileSync(o,n)}catch(r){try{ne.unlinkSync(o)}catch{}throw r}try{ne.renameSync(o,e)}catch(r){try{ne.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function Fi(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!Oi.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Pi(e){let t=vo.join(e,"conversations.json"),n=ji(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.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 r=0,s=0,i=0;for(let c of Object.keys(n)){let a=n[c];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,s++);let l=Array.isArray(a.messages)?a.messages:[],u=Fi(l,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==u&&i++,a.lastMessageBy=u,a.conversationStatus=f,r++}if(r===0){console.log(" No conversations to recompute.");return}Li(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var an={};Y(an,{NAME:()=>qi,VERSION:()=>Mi,up:()=>Hi});import*as oe from"fs";import*as $o from"path";var Mi=4,qi="split-connection-timestamps",Ui=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Bi(e){if(!oe.existsSync(e))return null;let t=oe.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Ji(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{oe.writeFileSync(o,n)}catch(r){try{oe.unlinkSync(o)}catch{}throw r}try{oe.renameSync(o,e)}catch(r){try{oe.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Hi(e){let t=$o.join(e,"people.json"),n=Bi(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let i=n[s];!i||typeof i!="object"||(r++,Ui.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ji(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Ie();Nt();var ls=as(import.meta.url),cs=N.dirname(ls),us=N.dirname(N.dirname(cs));function ds(e){return e&&(e==="~"?gn.homedir():e.startsWith("~/")||e.startsWith("~\\")?N.join(gn.homedir(),e.slice(2)):e)}var ue=process.env.DATA_DIR?N.resolve(ds(process.env.DATA_DIR)):us,je=N.join(ue,"collected-profiles"),Le=N.join(ue,"market-research"),z=N.join(ue,".schema-version"),Oo=[N.join(je,".schema-version"),N.join(Le,".schema-version")],$e=4,ge=[{version:1,module:on},{version:2,module:rn},{version:3,module:sn},{version:4,module:an}];(function(){ge.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ge){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ge.length?ge[ge.length-1].version:0;if(n!==$e)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${$e}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ge.length;o++){let r=o+1;if(ge[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ge[o].version}`)}})();function Po(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
256
255
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
257
|
-
`),process.exit(1));try{
|
|
258
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
259
|
-
`),process.exit(1))}let e;try{e
|
|
260
|
-
[FATAL] DATA_DIR (${
|
|
256
|
+
`),process.exit(1));try{$.mkdirSync(ue,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
257
|
+
[FATAL] Cannot create DATA_DIR (${ue}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
258
|
+
`),process.exit(1))}let e;try{e=$.statSync(ue)}catch(t){console.error(`
|
|
259
|
+
[FATAL] DATA_DIR (${ue}) is not accessible: ${t.message}
|
|
261
260
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
262
|
-
[FATAL] DATA_DIR (${
|
|
263
|
-
`),process.exit(1));for(let t of[
|
|
261
|
+
[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.
|
|
262
|
+
`),process.exit(1));for(let t of[je,Le]){let n;try{n=$.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
|
|
264
263
|
[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.
|
|
265
|
-
`),process.exit(1))}}var
|
|
266
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${
|
|
264
|
+
`),process.exit(1))}}var Oe=N.join(ue,".migration-lock");function fs(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return $.writeFileSync(Oe,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse($.readFileSync(Oe,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(i){i.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,s=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(s=Date.now()-i)}o&&s<r&&(console.error(`
|
|
265
|
+
[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}
|
|
267
266
|
`),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.
|
|
268
|
-
`),process.exit(1)),o&&s>=r&&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 n=
|
|
267
|
+
`),process.exit(1)),o&&s>=r&&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 n=Oe+".tmp";try{return $.writeFileSync(n,e),$.renameSync(n,Oe),!0}catch(o){try{$.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function yn(){try{if(JSON.parse($.readFileSync(Oe,"utf-8")).pid!==process.pid)return;$.unlinkSync(Oe)}catch{}}var jo=!1;function ps(){if(jo)return;jo=!0;let e=()=>{try{yn()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function ms(){if($.existsSync(z))return;let e=[],t=[];for(let s of Oo)if($.existsSync(s))try{e.push({file:s,schema:Ot(s)})}catch(i){t.push({file:s,err:i.message})}if(t.length>0){console.error(`
|
|
269
268
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of t)console.error(` ${s.file}: ${s.err}`);console.error(`
|
|
270
269
|
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.
|
|
271
270
|
`),process.exit(1)}if(e.length===0)return;let n=e.map(s=>s.schema.version);if(new Set(n).size>1){console.error(`
|
|
272
271
|
[FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
273
|
-
`),process.exit(1)}let o=e[0].schema,r=
|
|
274
|
-
[FATAL] ${
|
|
275
|
-
`),process.exit(1)}let t=
|
|
276
|
-
[FATAL] ${
|
|
277
|
-
`),process.exit(1)),t}function Mo(e){try{
|
|
278
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
279
|
-
`),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${
|
|
272
|
+
`),process.exit(1)}let o=e[0].schema,r=z+".tmp";try{$.writeFileSync(r,JSON.stringify(o,null,2)),$.renameSync(r,z)}catch(s){try{$.unlinkSync(r)}catch{}throw s}for(let s of Oo)if($.existsSync(s))try{$.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${z}`)}function hs(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 Ot(e){let t=$.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Lo(){if(ms(),!$.existsSync(z))return{version:0,migrations:[]};let e;try{e=Ot(z)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
273
|
+
[FATAL] ${z} is not valid JSON: ${n.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.
|
|
274
|
+
`),process.exit(1)}let t=hs(e);return t===null&&(console.error(`
|
|
275
|
+
[FATAL] ${z} 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.
|
|
276
|
+
`),process.exit(1)),t}function Mo(e){try{$.chmodSync(e,384)}catch{}}function gs(e){if(Po(),$.existsSync(z))try{if($.lstatSync(z).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${z}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=z+".tmp";try{$.writeFileSync(t,JSON.stringify(e,null,2)),Mo(t),$.renameSync(t,z)}catch(n){try{$.unlinkSync(t)}catch{}throw n}}function Fo(e,t){if(!$.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=$.readdirSync(e).filter(c=>{let a=c.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return $.statSync(N.join(e,c)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let c of o){let a=N.join(e,c),l=N.join(e,c+n);if($.existsSync(l)){s++;continue}try{Uo(a,l),r++}catch(u){i.push({file:c,err:u.message})}}if(i.length>0){let c=new Error(`Failed to back up ${i.length} file(s) in ${N.basename(e)}/: `+i.map(a=>`${a.file} (${a.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||s>0){let c=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${N.basename(e)}/ (${n})${c}`)}}var hn=!1;async function qo(){if(hn)return;Po(),ks();let t=Lo().version;if(t===$e){hn=!0;return}ps(),fs(),process.on("exit",yn),t>$e&&(console.error(`
|
|
277
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${$e}.`),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.
|
|
278
|
+
`),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${$e}.
|
|
280
279
|
`),process.exit(1)),console.log(`
|
|
281
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
280
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${$e}`);let n=vs();if(!n.ok){console.error(`
|
|
282
281
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
|
|
283
282
|
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'.
|
|
284
|
-
`),process.exit(1)}let o=
|
|
285
|
-
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{Fo(
|
|
283
|
+
`),process.exit(1)}let o=ge.filter(r=>r.version>t);for(let r of o){console.log(`
|
|
284
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{Fo(je,r.version),Fo(Le,r.version)}catch(a){console.error(`
|
|
286
285
|
[FATAL] Pre-migration backup failed for ${s}: ${a.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
287
|
-
`),process.exit(1)}let c=r.module;try{await c.up(
|
|
288
|
-
[FATAL] Migration ${s} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let l
|
|
286
|
+
`),process.exit(1)}let c=r.module;try{await c.up(je,Le)}catch(a){console.error(`
|
|
287
|
+
[FATAL] Migration ${s} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let l=$s(i);l.ok?(console.error(` \u2713 Auto-rollback restored ${l.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
289
288
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${l.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
290
289
|
`))}catch(l){console.error(` [!] Auto-rollback CRASHED while restoring: ${l.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
291
|
-
`)}process.exit(1)}try{let a=new Date().toISOString(),l={version:r.version,name:c.NAME||s,appliedAt:a},u=Lo();u.version=r.version,u.migratedAt=a,u.migrations=u.migrations||[],u.migrations.push(l),
|
|
290
|
+
`)}process.exit(1)}try{let a=new Date().toISOString(),l={version:r.version,name:c.NAME||s,appliedAt:a},u=Lo();u.version=r.version,u.migratedAt=a,u.migrations=u.migrations||[],u.migrations.push(l),gs(u)}catch(a){console.error(`
|
|
292
291
|
[FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${a.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
293
292
|
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{Zn()}catch{}try{dn()}catch{}hn=!0,yn(),console.log(`
|
|
294
|
-
\u2713 Schema is now at v${
|
|
295
|
-
`)}var
|
|
296
|
-
`);let i=new Date().toISOString().replace(/[:.]/g,"-");try{await e.screenshot({path:
|
|
297
|
-
Added ${c.added} to queue (tag=${n}, priority=${r}).`),c.skippedDup&&console.log(` ${c.skippedDup} already in queue \u2014 skipped.`),c.skippedEngaged&&console.log(` ${c.skippedEngaged} already connected/pending \u2014 skipped.`),c.skippedNoUrl&&console.log(` ${c.skippedNoUrl} had no url \u2014 skipped.`),c.notesTooLong&&console.log(` ${c.notesTooLong} had notes over ${
|
|
298
|
-
Queue now: ${
|
|
299
|
-
${f?"[dry-run] ":""}Fill from discovered pool \u2014 ${d.candidates} ranked candidates.`),f){console.log(`Would add ${d.selected.length} (top by rank\xD7fit):`);for(let g of d.selected.slice(0,30))console.log(` rank ${g.rank.toFixed(2)} \xB7 fit ${g.fit.toFixed(2)} \xB7 ${g.name||g.url} [${(g.sectors||[]).join(",")}]`);return}console.log(`Added ${d.added} to queue (tag=${a}, priority=${u}).`),d.skippedDup&&console.log(` ${d.skippedDup} already in queue \u2014 skipped.`),d.skippedEngaged&&console.log(` ${d.skippedEngaged} already connected/pending \u2014 skipped.`);let p=
|
|
300
|
-
Queue now: ${
|
|
301
|
-
(shortcut: --valuable = ${
|
|
302
|
-
Filled ${
|
|
303
|
-
Queue now: ${
|
|
293
|
+
\u2713 Schema is now at v${$e}
|
|
294
|
+
`)}var ys=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function ws(e){let t=e.toLowerCase();return ys.some(n=>n.test(t))}var bs=6e4;function Ss(){let e=Date.now(),t=[];for(let n of[ue,je,Le]){if(!$.existsSync(n))continue;let o;try{o=$.readdirSync(n)}catch{continue}for(let r of o){if(!ws(r))continue;let s=N.join(n,r);try{let i=$.statSync(s);if(!i.isFile()||e-i.mtimeMs<bs)continue;t.push({dir:n,file:r,fullPath:s})}catch{}}}return t}function ks({verbose:e=!1}={}){let t=Ss();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{$.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${N.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function vs(){let e=[];for(let t of[je,Le]){if(!$.existsSync(t))continue;let n=$.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=N.join(t,o);try{Ot(r)}catch(s){e.push({dir:N.basename(t),file:o,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function $s(e){let t=[],n=[];for(let s of[je,Le]){if(!$.existsSync(s))continue;let i=$.readdirSync(s).filter(c=>c.endsWith(e));for(let c of i){let a=N.join(s,c),l=c.slice(0,-e.length),u=N.join(s,l);try{l.toLowerCase().endsWith(".json")?Ot(a):$.accessSync(a,$.constants.R_OK),t.push({backupPath:a,originalPath:u,fileName:c,dir:s})}catch(f){n.push(`${N.basename(s)}/${c}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:s,originalPath:i,fileName:c,dir:a}of t)try{Uo(s,i),o++}catch(l){r.push(`${N.basename(a)}/${c}: ${l.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function Uo(e,t){let n=t+".tmp";try{$.copyFileSync(e,n),Mo(n)}catch(o){try{$.unlinkSync(n)}catch{}throw o}try{$.renameSync(n,t)}catch(o){try{$.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.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 r.code=o.code,r}throw o}}Nt();bn();var xs={people_also_viewed:1,similar_profiles:1,more_profiles_for_you:.7,viewers_also_viewed:.6,people_you_may_know:.5,other_profiles:.4,unknown:.3};function _s(e){return 1/(1+(Number.isFinite(e)?Math.max(0,e):3))}function Es(e,t={}){let n=t.seedWeights||{},o=t.blockWeights||xs,r=Number.isInteger(t.iterations)?t.iterations:3,s=typeof t.damping=="number"?t.damping:.6,i=d=>typeof d=="number"&&Number.isFinite(d)?d:0,c=d=>Array.isArray(d&&d.sources)?d.sources.filter(p=>p&&p.seedUrl):[],a=Object.keys(e||{}),l={};for(let d of a)l[d]=i(n[d]);for(let d of a)for(let p of c(e[d]))p.seedUrl in l||(l[p.seedUrl]=i(n[p.seedUrl]));let u={...l},f=(d,p)=>d in n?i(n[d]):i(p[d]);for(let d=0;d<r;d++){let p={...l};for(let m of a){let h=0;for(let y of c(e[m])){let k=i(o[y.block]??o.unknown??.3);h+=f(y.seedUrl,u)*k*_s(y.rank)}p[m]+=s*h}let g=1e-9;for(let m of Object.keys(p)){let h=i(p[m]);h>g&&(g=h)}for(let m of Object.keys(p))p[m]=i(p[m])/g;u=p}return a.map(d=>{let p=c(e[d]),g=[...new Set(p.map(m=>m.seedUrl).filter(Boolean))].sort((m,h)=>f(h,u)-f(m,u)).slice(0,3);return{url:d,score:u[d]||0,categories:e[d]?.categories||[],edges:p.length,topSeeds:g}}).sort((d,p)=>p.score-d.score)}function Jo(e,t={}){let n=t.interests||jt,o=typeof t.fitWeight=="number"?t.fitWeight:1;return Es(e,t).map(s=>{let i=e[s.url]?.sectors||[],c=wn(i,n),a=s.score*(1+o*c);return{...s,sectors:i,fit:c,rank:a}}).sort((s,i)=>i.rank-s.rank)}await Ie();var Is=new Set(["connected"]),Ds=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Rs(e=W()){let t=new Map;for(let[n,o]of Object.entries(e)){let r=q(o.profileUrl||n);r&&!t.has(r)&&t.set(r,o);for(let s of o.aliases||[])s&&!t.has(s)&&t.set(s,o)}return n=>{let o=t.get(q(n));return!!o&&(Is.has(o.connectionStatus)||Ds.has(o.connectionStatus))}}function Ts(e,t={}){let n=Number.isInteger(t.max)?t.max:20,o=t.minRank??0,r=t.minFit??0,s=new Set(t.categories||[]),i=new Set(t.sectors||[]),c=typeof t.isEngaged=="function"?t.isEngaged:()=>!1,a=(t.excludeLocations||[]).map(m=>String(m).toLowerCase()).filter(Boolean),l=m=>!!m&&a.some(h=>String(m).toLowerCase().includes(h)),u=m=>{let h=e[m]||{};return Date.parse(h.discoveredAt||h.lastSeen||"")||0},f=t.now&&Date.parse(t.now)||0,d=f&&Number.isFinite(t.maxAgeDays)&&t.maxAgeDays>0?t.maxAgeDays*864e5:0,p=Jo(e||{},{interests:t.interests,seedWeights:t.seedWeights,fitWeight:t.fitWeight});p.sort((m,h)=>h.rank-m.rank||u(h.url)-u(m.url));let g=[];for(let m of p){if(g.length>=n)break;let h=e[m.url]||{};h.isConnected||c(m.url)||m.rank<o||m.fit<r||d&&f-u(m.url)>d||l(h.location)||s.size&&!(h.categories||[]).some(y=>s.has(y))||i.size&&!(h.sectors||[]).some(y=>i.has(y))||g.push({url:m.url,name:h.name||null,rank:m.rank,fit:m.fit,score:m.score,categories:h.categories||[],sectors:h.sectors||[]})}return{candidates:p.length,selected:g}}function Ho(e={}){let t=e.tag||"discovered",n=e.priority||"normal",o=Ne(),r=e.isEngaged||Rs(),s=e.excludeLocations||(process.env.FUNNEL_EXCLUDE_LOCATIONS||"").split(",").map(p=>p.trim()).filter(Boolean),i=e.now||new Date().toISOString(),c=e.maxAgeDays===null?void 0:Number.isFinite(e.maxAgeDays)?e.maxAgeDays:45,{candidates:a,selected:l}=Ts(o,{...e,isEngaged:r,excludeLocations:s,now:i,maxAgeDays:c});if(e.dryRun)return{candidates:a,selected:l,added:0,skippedDup:0,skippedEngaged:0,dryRun:!0};let u=K(),f=l.map(p=>({url:p.url,tag:t,priority:n})),d=rt(u,f,{tag:t,priority:n,nowIso:new Date().toISOString(),alreadyEngaged:r});return ce(u),{candidates:a,selected:l,...d,dryRun:!1}}var Er=new Set(["connected"]),Ir=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]),xr=new Set(["pending","connected","excluded_location","email_required","premium_required","wrong_target"]),va=3,qt=process.env.DATA_DIR?We.resolve(process.env.DATA_DIR,"collected-profiles","connect-diagnostics"):We.resolve("collected-profiles","connect-diagnostics");async function $a(e,t,n){try{let o=e.url(),r=await e.evaluate(()=>({modal:(l=>Array.from(document.querySelectorAll(l)).map(u=>(u.innerText||"").trim()).filter(Boolean).join(" | "))('[role="alertdialog"], [role="dialog"], .artdeco-modal, .artdeco-toast-item, .ip-fuse-limit-alert, .artdeco-inline-feedback').slice(0,1e3),body:(document.body.innerText||"").slice(0,1500)}));Bt.mkdirSync(qt,{recursive:!0});let s={at:new Date().toISOString(),target:t.url,reason:n||null,pageUrl:o,modalText:r.modal,bodySnippet:r.body};Bt.appendFileSync(We.join(qt,"connect-failures.jsonl"),JSON.stringify(s)+`
|
|
295
|
+
`);let i=new Date().toISOString().replace(/[:.]/g,"-");try{await e.screenshot({path:We.join(qt,`fail-${i}.png`)})}catch{}return r.modal||""}catch{return""}}var Ge=process.argv.slice(2),Dr=Ge[0],Ye=Ge.filter(e=>!e.startsWith("--")),_e=e=>Ge.some(t=>t===`--${e}`||t.startsWith(`--${e}=`)),G=e=>{let t=Ge.find(o=>o===`--${e}`||o.startsWith(`--${e}=`));if(t===void 0)return;let n=t.indexOf("=");return n===-1&&L(`--${e} needs a value \u2014 write --${e}=value (no space).`),t.slice(n+1)},jn=()=>new Date().toISOString();function Jt(){let e=W(),t=new Map;for(let[n,o]of Object.entries(e)){let r=q(o.profileUrl||n);r&&!t.has(r)&&t.set(r,o)}for(let n of Object.values(e))for(let o of n.aliases||[])o&&!t.has(o)&&t.set(o,n);return t}function Rr(e,t){let n=e.get(q(t));return n?Er.has(n.connectionStatus)||Ir.has(n.connectionStatus):!1}async function Aa(){let e=Ye[1];if(!e)return L("Usage: connect add <file.json> [--tag=X] [--priority=high]");let t;try{t=JSON.parse((await import("fs")).readFileSync(e,"utf-8"))}catch(l){return L(`Could not read/parse ${e}: ${l.message}`)}if(!Array.isArray(t))return L("File must be a JSON array of { url, note?, name? }.");let n=G("tag")||"untagged",o=G("priority");if(o&&!le.includes(o))return L(`--priority must be one of: ${le.join(", ")}`);let r=o||"normal",s=K(),i=Jt(),c=rt(s,t,{tag:n,priority:r,nowIso:jn(),alreadyEngaged:l=>Rr(i,l)});ce(s),console.log(`
|
|
296
|
+
Added ${c.added} to queue (tag=${n}, priority=${r}).`),c.skippedDup&&console.log(` ${c.skippedDup} already in queue \u2014 skipped.`),c.skippedEngaged&&console.log(` ${c.skippedEngaged} already connected/pending \u2014 skipped.`),c.skippedNoUrl&&console.log(` ${c.skippedNoUrl} had no url \u2014 skipped.`),c.notesTooLong&&console.log(` ${c.notesTooLong} had notes over ${De} chars \u2014 added WITHOUT a note (LinkedIn's limit); set a shorter one with \`connect note\`.`);let a=s.filter(l=>l.status==="queued"&&l.withNote).length;console.log(`
|
|
297
|
+
Queue now: ${he(s,"queued").length} queued, ${he(s,"approved").length} approved.`),a&&console.log(` ${a} queued entries have a note saved \u2014 sent only with \`connect run --with-notes\`.`),console.log(`Next: review with \`connect list\`, approve with \`connect approve --tag=${n}\`, send with \`connect run\`.`)}var _r=["founder","investor","hiring_manager","peer"];function Ca(){let e=g=>{let m=G(g);if(m===void 0)return;let h=parseFloat(m);return Number.isFinite(h)?h:L(`--${g} must be a number.`)},t=G("max"),n=20;if(t!==void 0&&(n=parseInt(t,10),!Number.isInteger(n)||n<=0))return L("--max must be a positive integer.");let o=e("min-fit")??0,r=e("min-rank")??0,s=g=>{let m=G(g);return m?m.split(",").map(h=>h.trim()).filter(Boolean):void 0},i=s("category"),c=s("sector"),a=G("tag")||"discovered",l=G("priority");if(l&&!le.includes(l))return L(`--priority must be one of: ${le.join(", ")}`);let u=l||"normal",f=_e("dry-run"),d=Ho({max:n,minFit:o,minRank:r,categories:i,sectors:c,tag:a,priority:u,dryRun:f});if(console.log(`
|
|
298
|
+
${f?"[dry-run] ":""}Fill from discovered pool \u2014 ${d.candidates} ranked candidates.`),f){console.log(`Would add ${d.selected.length} (top by rank\xD7fit):`);for(let g of d.selected.slice(0,30))console.log(` rank ${g.rank.toFixed(2)} \xB7 fit ${g.fit.toFixed(2)} \xB7 ${g.name||g.url} [${(g.sectors||[]).join(",")}]`);return}console.log(`Added ${d.added} to queue (tag=${a}, priority=${u}).`),d.skippedDup&&console.log(` ${d.skippedDup} already in queue \u2014 skipped.`),d.skippedEngaged&&console.log(` ${d.skippedEngaged} already connected/pending \u2014 skipped.`);let p=K();console.log(`
|
|
299
|
+
Queue now: ${he(p,"queued").length} queued, ${he(p,"approved").length} approved.`),console.log(`Next: review \`connect list\`, approve \`connect approve --tag=${a}\`, send \`connect run\`.`)}function xa(){if(_e("from-discovered"))return Ca();let e=G("category");if(e===void 0&&_e("valuable")&&(e=_r.join(",")),!e)return L(`Usage: connect fill --category=founder,investor,hiring_manager[,peer,recruiter] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
|
|
300
|
+
(shortcut: --valuable = ${_r.join(",")})`);let t=e.split(",").map(S=>S.trim()).filter(Boolean),n=S=>{let C=G(S);if(C===void 0)return;let _=parseInt(C,10);return!Number.isInteger(_)||_<0?L(`--${S} must be a non-negative integer.`):_},o=n("min-posts")??0,r=n("max"),s=G("priority");if(s&&!le.includes(s))return L(`--priority must be one of: ${le.join(", ")}`);let i=G("tag"),c=!_e("no-validate"),a=new Set(["recruiter","hiring_manager","founder","investor","coach","sales"]),l=(process.env.FUNNEL_EXCLUDE_LOCATIONS||"").split(",").map(S=>S.trim().toLowerCase()).filter(Boolean),u=S=>{if(!S)return!1;let C=String(S).toLowerCase();return l.some(_=>C.includes(_))},f=W(),d=[],p=0,g=0,m=0;for(let[S,C]of Object.entries(f))if(t.includes(C.category)&&!(Er.has(C.connectionStatus)||Ir.has(C.connectionStatus))&&C.connectionDegree!=="1st"&&!((C.jobIds?.length||0)<o)){if(u(C.location)){p++;continue}if(c&&a.has(C.category)){let _=(typeof C.title=="string"?C.title:"").trim();if(!_){g++;continue}if(Ue(_)!==C.category){m++;continue}}d.push({url:C.profileUrl||S,p:C})}let h={high:0,medium:1,low:2};d.sort((S,C)=>(h[S.p.personPriority]??1)-(h[C.p.personPriority]??1)||(C.p.mutualConnections||0)-(S.p.mutualConnections||0)||(C.p.jobIds?.length||0)-(S.p.jobIds?.length||0)),r!==void 0&&(d=d.slice(0,r));let y=d.map(S=>({url:S.url,tag:i||S.p.category,priority:s||(S.p.personPriority==="high"?"high":"normal")})),k=K(),w=Jt(),b=rt(k,y,{alreadyEngaged:S=>Rr(w,S),nowIso:jn()});ce(k),console.log(`
|
|
301
|
+
Filled ${b.added} from [${t.join(", ")}]${o?` (\u2265${o} job-posts)`:""}${c?"":" (--no-validate)"}.`),b.skippedDup&&console.log(` ${b.skippedDup} already in queue \u2014 skipped.`),b.skippedEngaged&&console.log(` ${b.skippedEngaged} already connected/pending \u2014 skipped.`),p&&console.log(` ${p} in excluded locations \u2014 skipped.`),m&&console.log(` ${m} filtered \u2014 title doesn't confirm the category (likely mis-tagged by enrichment).`),g&&console.log(` ${g} skipped \u2014 no title stored to validate (held; not visited, to avoid ban risk).`),console.log(`
|
|
302
|
+
Queue now: ${he(k,"queued").length} queued, ${he(k,"approved").length} approved.`),console.log("Next: review with `connect list`, approve with `connect approve --all`, send with `connect run`.")}function _a(){let e=K();if(!e.length)return console.log("\nQueue is empty. Add people with `connect add <file.json>`.");let t=G("status"),n=Jt(),o=Ee();console.log(`
|
|
304
303
|
=== Connect Queue === (quota left: ${o.daily.remaining}/${o.daily.max} today, ${o.weekly.remaining}/${o.weekly.max} week)
|
|
305
304
|
`);let r={};for(let l of e)r[l.status]=(r[l.status]||0)+1;console.log("Status: "+Object.entries(r).map(([l,u])=>`${l}=${u}`).join(" ")+`
|
|
306
|
-
`),t&&!
|
|
307
|
-
`);let s=t?e.filter(l=>l.status===t):e,i={approved:0,queued:1,failed:2,skipped:3,sent:4},c=[...s].sort((l,u)=>(i[l.status]??9)-(i[u.status]??9));for(let l of c){let u=n.get(
|
|
308
|
-
${a} pending entries have a saved note \u2014 sent only with \`connect run --with-notes\` (LinkedIn caps personal notes per month).`),console.log("")}function Ut(e,t,n,o){let r=
|
|
309
|
-
${o}: ${s} entr${s===1?"y":"ies"} \u2192 ${n}.`),s}function
|
|
310
|
-
Note saved (${n.length} chars). It's sent ONLY when you run \`connect run --with-notes\` (that spends one of your few monthly LinkedIn notes) \u2014 otherwise this person gets a plain request.`)}function
|
|
311
|
-
Note reminder cleared.`)}function
|
|
312
|
-
Priority set to ${t}.`)}async function
|
|
313
|
-
Nothing approved to send.`),
|
|
305
|
+
`),t&&!_t.includes(t)&&console.log(`(unknown status "${t}" \u2014 valid: ${_t.join(", ")})
|
|
306
|
+
`);let s=t?e.filter(l=>l.status===t):e,i={approved:0,queued:1,failed:2,skipped:3,sent:4},c=[...s].sort((l,u)=>(i[l.status]??9)-(i[u.status]??9));for(let l of c){let u=n.get(q(l.url)),f=u&&u.name||"",d=u&&u.title?` \xB7 ${u.title.slice(0,40)}`:"",p=u&&u.mutualConnections?` \xB7 ${u.mutualConnections} mutual`:"",g=l.withNote?"\u{1F4DD}":" ",m=l.priority==="high"?"\u2B06high ":l.priority==="low"?"\u2B07low ":"normal";console.log(` [${l.status.padEnd(8)}] ${m} ${g} ${f}${d}${p}`),console.log(` ${l.url} (tag=${l.tag})`)}let a=e.filter(l=>(l.status==="queued"||l.status==="approved")&&l.withNote).length;a&&console.log(`
|
|
307
|
+
${a} pending entries have a saved note \u2014 sent only with \`connect run --with-notes\` (LinkedIn caps personal notes per month).`),console.log("")}function Ut(e,t,n,o){let r=K(),s=0;for(let i of r)e(i)&&t.includes(i.status)&&(i.status=n,s++);return ce(r),console.log(`
|
|
308
|
+
${o}: ${s} entr${s===1?"y":"ies"} \u2192 ${n}.`),s}function Ea(){let e=["queued","failed"];if(_e("all"))return Ut(()=>!0,e,"approved","Approved");let t=G("tag");if(t)return Ut(r=>r.tag===t,e,"approved",`Approved tag=${t}`);let n=Ye[1];if(!n)return L("Usage: connect approve <url> | --all | --tag=X");let o=me(n);return Ut(r=>me(r.url)===o,["queued","failed","skipped"],"approved","Approved")}function Ia(){let e=Ye[1];if(!e)return L("Usage: connect skip <url>");let t=me(e);return Ut(n=>me(n.url)===t,["queued","approved"],"skipped","Skipped")}function Da(){let e=Ge[1],t=Ge[2];if(!e||t===void 0)return L('Usage: connect note <url> "custom note text"');let n=t.trim();if(!n)return L("Note is empty \u2014 use `connect no-note <url>` to remove a note.");if(n.length>De)return L(`Note is ${n.length} chars \u2014 LinkedIn caps connection-request notes at ${De}. Shorten it.`);let o=K(),r=ot(o,e);if(!r)return L("Not in queue.");r.note=n,r.withNote=!0,ce(o),console.log(`
|
|
309
|
+
Note saved (${n.length} chars). It's sent ONLY when you run \`connect run --with-notes\` (that spends one of your few monthly LinkedIn notes) \u2014 otherwise this person gets a plain request.`)}function Ra(){let e=Ye[1];if(!e)return L("Usage: connect no-note <url>");let t=K(),n=ot(t,e);if(!n)return L("Not in queue.");n.note=null,n.withNote=!1,ce(t),console.log(`
|
|
310
|
+
Note reminder cleared.`)}function Ta(){let e=Ye[1],t=Ye[2];if(!e||!le.includes(t))return L(`Usage: connect priority <url> <${le.join("|")}>`);let n=K(),o=ot(n,e);if(!o)return L("Not in queue.");o.priority=t,ce(n),console.log(`
|
|
311
|
+
Priority set to ${t}.`)}async function Na(){let e=_e("dry-run"),t=_e("yes"),n=_e("with-notes"),o=G("max"),r=1/0;if(o!==void 0){let w=parseInt(o,10);if(!Number.isInteger(w)||w<0)return L("--max must be a non-negative integer.");r=w}let s=Ee(),i=Math.min(s.daily.remaining,s.weekly.remaining),c=K(),a=lo(he(c,"approved"));if(!a.length){let w=he(c,"queued").length;console.log(`
|
|
312
|
+
Nothing approved to send.`),w&&console.log(` ${w} queued \u2014 approve them first: \`connect approve --all\` (or --tag=X).`);return}if(i<=0){console.log(`
|
|
314
313
|
Connection quota is used up (${s.daily.remaining}/${s.daily.max} today, ${s.weekly.remaining}/${s.weekly.max} week). Try again later.`);return}let l=a.slice(0,Math.min(r,i));if(!l.length){console.log(`
|
|
315
|
-
Nothing to send (--max=${r===1/0?"\u221E":r}).`);return}let u=l.filter(
|
|
316
|
-
=== Connect run ===`),console.log(` Approved: ${a.length} \xB7 quota left: ${i} \xB7 sending: ${l.length}${n?` (${u} WITH a note)`:" (without notes)"}`),!n&&u&&console.log(` ${u} have a saved note \u2014 add --with-notes to send it (spends your scarce monthly notes).`);let f=Jt();if(l.forEach((b
|
|
314
|
+
Nothing to send (--max=${r===1/0?"\u221E":r}).`);return}let u=l.filter(w=>w.withNote).length;console.log(`
|
|
315
|
+
=== Connect run ===`),console.log(` Approved: ${a.length} \xB7 quota left: ${i} \xB7 sending: ${l.length}${n?` (${u} WITH a note)`:" (without notes)"}`),!n&&u&&console.log(` ${u} have a saved note \u2014 add --with-notes to send it (spends your scarce monthly notes).`);let f=Jt();if(l.forEach((w,b)=>{let S=f.get(q(w.url));console.log(` ${b+1}. ${w.withNote?"\u{1F4DD}":" "} ${S?.name||w.url} (${w.priority}, tag=${w.tag})`)}),e){console.log(`
|
|
317
316
|
[dry-run] Nothing sent. Drop --dry-run to send.`);return}t||(console.log(`
|
|
318
|
-
Press Enter to send, or Ctrl+C to cancel...`),await new Promise(
|
|
319
|
-
[!] ${
|
|
320
|
-
`);try{
|
|
321
|
-
\u26A0 Browser/page died mid-run \u2014 aborting (remaining entries left approved).`);break}let
|
|
322
|
-
\u26A0 ${
|
|
323
|
-
=== Done: ${
|
|
324
|
-
[!] Run aborted: ${b.message}`);try{k(x,"error",null,b.message)}catch{}C=1}finally{try{await w.close()}catch{}}process.exit(C)}function F(e){console.error(e),process.exit(1)}function Ra(){console.log(`connect \u2014 connect queue
|
|
317
|
+
Press Enter to send, or Ctrl+C to cancel...`),await new Promise(w=>process.stdin.once("data",()=>w())));let d=(await import("puppeteer")).default,{launchWithProfile:p,seedCookiesIfNeeded:g}=await Promise.resolve().then(()=>(ir(),rr)),{sendConnectionRequest:m}=await pr().then(()=>fr),{delayed:h}=await Promise.resolve().then(()=>(Pt(),ar)),{withRunReport:y}=await Promise.resolve().then(()=>(Cr(),Ar)),k=0;try{await y("connect","run",async w=>{w.sent=0,w.skipped=0,w.failed=0;let b,S;try{let C=await p(d);b=C.browser,S=await b.newPage(),await g(S,C)}catch(C){console.error(`
|
|
318
|
+
[!] ${C.message}
|
|
319
|
+
`);try{b&&await b.close()}catch{}throw C}try{let C=W(),_=new Map;for(let[x,B]of Object.entries(C)){let I=q(B.profileUrl||x);I&&!_.has(I)&&_.set(I,x)}for(let[x,B]of Object.entries(C))for(let I of B.aliases||[])I&&!_.has(I)&&_.set(I,x);let T=0;for(let x of l){if(!nt().allowed){console.log(" Quota reached mid-run \u2014 stopping.");break}let B=n&&x.withNote,I=await m(S,x.url,{message:B?x.note:null,useCustomMessage:B,source:x.tag,skipQuotaGate:!0});if(I.fatal){I.reason==="session_expired"?console.log("\n\u26A0 Session expired (LinkedIn re-auth / logout) \u2014 run: `ilml linkedin login`, then retry. Remaining entries left approved."):console.log(`
|
|
320
|
+
\u26A0 Browser/page died mid-run \u2014 aborting (remaining entries left approved).`);break}let O;if(I.connectionSent?(O="sent",w.sent++):xr.has(I.reason)?(O="skipped",w.skipped++):(O="failed",w.failed++),O==="failed"){T++;let J=await $a(S,x,I.reason);console.log(` \u2717 ${x.url.slice(-32)} \u2014 ${I.reason||"failed"}${J?` \xB7 LinkedIn: "${J.slice(0,120)}"`:""}`)}else T=0;let Z=_.get(q(x.url));if(I.connectionSent||xr.has(I.reason)&&Z){let J=Z||x.url;try{At(J,I.reason,{method:I.method,messageSent:I.messageSent,profileInfo:I.profileInfo})}catch{}if(I.resolvedUrl)try{Ct(J,I.resolvedUrl)}catch{}}try{let J=K(),se=ot(J,x.url);se&&(se.status=O,O==="sent"&&(se.sentAt=jn()),se.result=I.reason||I.error||O,ce(J))}catch(J){console.error(` \u26A0 Could not persist queue update for ${x.url}: ${J.message}`)}if(T>=va){console.log(`
|
|
321
|
+
\u26A0 ${T} sends failed in a row \u2014 stopping to protect your account (this is often LinkedIn's invite limit).`),console.log(` What LinkedIn showed on each failure is saved to: ${qt}`),console.log(" Try again later; if it persists you've likely hit LinkedIn's weekly invite limit.");break}await h(3e3+Math.random()*2e3)}let v=Ee();w.quotaDaily=`${v.daily.remaining}/${v.daily.max}`,w.quotaWeek=`${v.weekly.remaining}/${v.weekly.max}`,console.log(`
|
|
322
|
+
=== Done: ${w.sent} sent, ${w.skipped} skipped, ${w.failed} failed ===`),console.log(`Connection quota left: ${v.daily.remaining}/${v.daily.max} today, ${v.weekly.remaining}/${v.weekly.max} week.`)}finally{try{b&&await b.close()}catch{}}},w=>[`${w.sent||0} sent, ${w.skipped||0} skipped, ${w.failed||0} failed`,w.quotaDaily?`Quota left: ${w.quotaDaily} today, ${w.quotaWeek} week`:null])}catch{k=1}process.exit(k)}function L(e){console.error(e),process.exit(1)}function Oa(){console.log(`connect \u2014 connect queue
|
|
325
323
|
|
|
326
324
|
connect add <file.json> [--tag=X] [--priority=high|normal|low]
|
|
327
325
|
connect fill --category=founder,investor,... [--valuable] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
|
|
@@ -329,4 +327,4 @@ Press Enter to send, or Ctrl+C to cancel...`),await new Promise(b=>process.stdin
|
|
|
329
327
|
connect approve <url> | --all | --tag=X
|
|
330
328
|
connect note <url> "custom note" connect no-note <url>
|
|
331
329
|
connect skip <url> connect priority <url> <high|normal|low>
|
|
332
|
-
connect run [--max=N] [--with-notes] [--dry-run] [--yes]`)}var
|
|
330
|
+
connect run [--max=N] [--with-notes] [--dry-run] [--yes]`)}var ja={add:Aa,fill:xa,list:_a,approve:Ea,skip:Ia,note:Da,"no-note":Ra,priority:Ta,run:Na},Tr=ja[Dr];Tr||(Oa(),process.exit(Dr?1:0));await qo();await Tr();
|