ilml-plugin-linkedin 1.20.7 → 1.20.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/connect.mjs +59 -57
- package/dist/enrichProfile.mjs +17 -15
- package/dist/enrichProfiles.mjs +41 -39
- package/dist/funnelRunner.mjs +45 -43
- package/dist/messageBot.mjs +74 -72
- package/dist/readPost.mjs +8 -8
- package/dist/run.mjs +54 -52
- package/dist/scout.mjs +11 -11
- package/dist/syncAll.mjs +98 -96
- package/dist/syncConnections.mjs +34 -32
- package/dist/verifyAbout.mjs +20 -18
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +44 -42
- package/dist/visit.mjs +40 -38
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/syncAll.mjs
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
var Hs=Object.defineProperty;var fe=(e,t)=>()=>(e&&(t=e(e=0)),t);var le=(e,t)=>{for(var n in t)Hs(e,n,{get:t[n],enumerable:!0})};function et(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),s=t[3].toUpperCase()==="PM";return s&&n!==12&&(n+=12),!s&&n===12&&(n=0),{hours:n,minutes:o}}function Yt(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=et(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=Js[o[1].toLowerCase()],a=et(o[2]||""),l=new Date(t),d=l.getDay()-c;return d<=0&&(d+=7),l.setDate(l.getDate()-d),a?l.setHours(a.hours,a.minutes,0,0):l.setHours(0,0,0,0),l.toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let c=Wt[s[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(s[2],10),l=parseInt(s[3],10),u=et(s[4]||"");return new Date(l,c,a,u?.hours||0,u?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let c=Wt[i[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(i[2],10),l=et(i[3]||""),u=t.getFullYear(),d=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return d>t&&d.setFullYear(u-1),d.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(r){let c=Wt[r[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(r[2],10),l=et(r[3]||""),u=t.getFullYear(),d=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return d>t&&d.setFullYear(u-1),d.toISOString()}return null}async function k(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function Vs(e,t,{timeout:n=45e3,poll:o=1e3,label:s="page"}={}){let i=Date.now();for(;Date.now()-i<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-i;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${s})`),!0}}catch{}await new Promise(r=>setTimeout(r,o))}return!1}function Ys(e){return Ws.test(e||"")}async function Gt(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let s=await Vs(e,t,{timeout:o,label:n});if(!s&&Ys(e.url())){let i=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw i.code="SESSION_EXPIRED",i}return s}async function tt(e,t,{readySelector:n,label:o="page",timeout:s=45e3,gotoTimeout:i=6e4}={}){return await e.goto(t,{waitUntil:"domcontentloaded",timeout:i}),Gt(e,{readySelector:n,label:o,timeout:s})}async function Gn(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");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 k(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}async function Ae(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),r=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),c=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||r||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:s.substring(0,80)};let l=o.querySelectorAll("button");for(let u of l){let d=u.innerText?.trim().toLowerCase()||"",f=u.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return u.click(),{dismissed:!0,matched:s.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 zn(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 Kn(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 Wt,Js,Ws,Le=fe(()=>{Wt={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Js={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};Ws=/\/authwall|\/login|\/checkpoint|\/uas\/login/});import{getPluginConfig as Gs}from"@ilivemylife/graph-sdk";var zs,z,V,nt,Fe,ot=fe(async()=>{zs=await Gs();for(let[e,t]of Object.entries(zs))process.env[e]===void 0&&(process.env[e]=t);z=process.env.LINKEDIN_NAME,V=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),nt=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.NEEDS_REVIEW])),Fe=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.REJECTED,V.NEEDS_REVIEW]))});import"dotenv/config";import*as F from"fs";import*as B from"path";import{fileURLToPath as Ks}from"url";import{execSync as zt}from"child_process";function so(){Ue=null,Zs=null,de=null,Ee=null,qe=null,xe=null}function me(){F.existsSync(X)||F.mkdirSync(X,{recursive:!0})}function He(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";F.writeFileSync(o,n);for(let s=0;s<3;s++)try{F.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function it(e,t){if(!F.existsSync(e))return null;try{let n=JSON.parse(F.readFileSync(e,"utf-8"));try{F.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(F.existsSync(o))try{let s=JSON.parse(F.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{F.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{F.copyFileSync(e,e+".corrupted")}catch{}return null}}function at(){return new Date().toISOString().split("T")[0]}function _e(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Xn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Be(e,t,n=null){if(!t||e[t])return t;let o=_e(t);if(!o)return t;let s=null;for(let[i,r]of Object.entries(e)){if(_e(r.profileUrl||i)===o)return i;!s&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}if(s){let i=Xn(n),r=Xn(e[s].name);if(i&&r&&i===r)return s}return t}function nr(){F.existsSync(Qt)||F.mkdirSync(Qt,{recursive:!0})}function ro(e){let t=_e(e);return t?B.join(Qt,`${t}.json`):null}function or(e){let t=ro(e);return t?it(t,`profile-history/${_e(e)}.json`)||[]:[]}function sr(e,t){let n=ro(e);if(!n)return;nr();let o=or(e);o.unshift(t);try{He(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${_e(e)}: ${s.message}`)}}function Zn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function eo(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function rr(e,t){if(!e)return[];let n=[];for(let o of tr){let s=e[o],i=t[o];Zn(s)||Zn(i)||eo(s)!==eo(i)&&n.push(o)}return n}function ir(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function J(){return Ue||(me(),Ue=it(Kt,"people.json")||{},Ue)}function Re(e){me(),Ue=e;try{He(Kt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(Kt)}`)}}function lt(){return Ee||(me(),Ee=it(Et,"conversations.json")||{},ar(Ee),Ee)}function ar(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(i=>i.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{He(Et,e)}catch{}}}function ye(e){me(),Ee=e;try{He(Et,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${B.resolve(Et)}`)}}function Te(e,t={}){if(!e)return null;let n=J(),o=at(),s=new Date().toISOString(),i=Be(n,e,t.name),r=n[i];if(r){let c=rr(r,t);c.length>0&&(sr(i,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:c,snapshot:ir(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=o,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let a of er)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(r[a])&&r[a].length>0)continue;r[a]=t[a]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else n[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Re(n),n[i]}function io(e,t){if(!e||!t)return;let n=J(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:at(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),Re(n))}function ao(e){return e&&J()[e]?.connectionStatus||null}function lo(e,t,n={}){if(!e)return;if(n.profileInfo)Te(e,n.profileInfo);else{let c=J(),a=Be(c,e,n.profileInfo?.name);c[a]||Te(e,{})}let o=J(),s=Be(o,e,n.profileInfo?.name),i=o[s];if(!i)return;let r=at();i.connectionStatus=t,t==="connected"?i.connectionDate=r:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=r)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),Re(o)}function _t(e,t,n={}){if(n.dryRun||!e||!t)return;let o=_e(t);if(!o)return;let s=J(),i=Be(s,e),r=s[i];if(!r)return;let c=_e(r.profileUrl||i);o!==c&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(o)||(r.aliases.push(o),r.lastUpdated=new Date().toISOString(),Re(s)))}function co(){return de||(me(),de=it(to,"quota.json"),(!de||!de.connections)&&(de={connections:[]}),de)}function lr(e){me(),de=e;try{He(to,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function uo(e,t="unknown"){let n=co(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),lr(n)}function fo(){let e=co(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Xt(){let e=fo(),t=at(),n=e.filter(a=>a.date===t).length,o=e.length,s=n>=st,i=o>=rt,r=!s&&!i,c={allowed:r,daily:{sent:n,max:st},weekly:{sent:o,max:rt}};return r||(c.reason=s?`Daily limit reached (${n}/${st})`:`Weekly limit reached (${o}/${rt})`),c}function ct(){let e=fo(),t=at(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:st,remaining:st-n},weekly:{sent:o,max:rt,remaining:rt-o}}}function Zt(){return qe||(me(),qe=it(no,"sync-state.json")||{},qe)}function mo(e){me(),qe=e;try{He(no,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function cr(){if(xe)return xe;me();try{F.existsSync(Qn)&&(xe=JSON.parse(F.readFileSync(Qn,"utf-8")))}catch{}return xe||(xe={}),xe}function ur(e){return Array.isArray(e.applications)}function fr(){let e=cr();if(ur(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function po(){let e=fr(),t=new Map;for(let i of e)for(let r of i.questions||[]){let c=r.question.toLowerCase().trim();if(!c)continue;t.has(c)||t.set(c,{question:r.question,count:0,answers:new Map});let a=t.get(c);a.count++;let l=(r.answer||"").trim();a.answers.set(l,(a.answers.get(l)||0)+1)}let n=[...t.values()].sort((i,r)=>r.count-i.count),o=n.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((r,c)=>c[1]-r[1])[0]?.[0]||""})),s=n.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((r,c)=>c[1]-r[1]).map(([r,c])=>`${r} (${c}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:o,inconsistent:s}}function en(e){if(F.existsSync(B.join(X,".git")))try{let t={cwd:X,stdio:"pipe",timeout:1e4};zt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{zt("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');zt(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Qs,Xs,X,Kt,Ja,to,Et,no,Qn,Qt,oo,st,rt,Ue,Zs,de,Ee,qe,xe,er,tr,Je=fe(async()=>{await ot();Qs=Ks(import.meta.url),Xs=B.dirname(B.dirname(Qs)),X=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Xs,"collected-profiles"),Kt=B.join(X,"people.json"),Ja=B.join(X,"jobs.json"),to=B.join(X,"quota.json"),Et=B.join(X,"conversations.json"),no=B.join(X,"sync-state.json"),Qn=B.join(X,"application-questions.json"),Qt=B.join(X,"profile-history"),oo=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},st=oo(process.env.CONNECT_MAX_DAILY,20),rt=oo(process.env.CONNECT_MAX_WEEKLY,100),Ue=null,Zs=null,de=null,Ee=null,qe=null,xe=null;er=["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"],tr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var wo={};le(wo,{BLOCK_MARKERS:()=>go,dedupeAndCap:()=>yo,extractSidePanelProfiles:()=>dr,normalizeFundUrl:()=>Tt,normalizeProfileUrl:()=>Ve,scanRelatedBlocks:()=>ho});function Ve(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 Tt(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function ho(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=l=>(l||"").replace(/\s+/g," ").trim(),s=l=>{let u=String(l||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},i=l=>o(l).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),r=l=>{let u=l,d=null;for(let f=0;f<6&&u.parentElement;f++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){d||(d=u);let m=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(m))return u}return d||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 d=e.find(([b])=>u.includes(b));if(!d)continue;let f=d[1],m=r(l);if(!m)continue;let w=0,g=new Set;for(let b of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let y=b.href||b.getAttribute("href")||"",S=s(y);if(!S)continue;let h=b.querySelector('span[aria-hidden="true"]'),p=o(h?h.textContent:b.getAttribute("aria-label")||b.textContent),v=i(p);if(!v||g.has(S))continue;g.add(S);let C="",_=p.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(_&&(C=o(_[1])),!C){let A=b.closest("li")||b.parentElement;A&&(C=Array.from(A.querySelectorAll("p, span")).map(P=>o(P.textContent)).filter(P=>P&&P!==v&&!/^view\b/i.test(P)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(P)&&/[a-z]/i.test(P)&&P.length>2)[0]||"")}c.push({href:y,name:v,headline:C,block:f,rank:w++})}}return c}function yo(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=Ve(t.seedUrl||""),s=new Map,i={};for(let r of e||[]){let c=Ve(r.href);c&&(o&&c===o||(i[r.block]=i[r.block]||0,!(i[r.block]>=n)&&(s.has(c)||(i[r.block]++,s.set(c,{url:c,name:r.name,headline:r.headline||null,block:r.block,rank:r.rank})))))}return Array.from(s.values())}async function dr(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(ho,go)}catch{return[]}return yo(n,t)}var go,tn=fe(()=>{go=[["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 Co={};le(Co,{getJobDecision:()=>wr,getLastVisit:()=>xr,getScoutStats:()=>an,loadCompanies:()=>rn,loadDiscoveredPeople:()=>yt,loadJobDecisions:()=>ht,loadScoutedJobs:()=>gt,loadVisitLog:()=>Dt,recordCompany:()=>$r,recordDiscoveredEdge:()=>vr,recordDiscoveredEdges:()=>kr,recordVisit:()=>Ar,resetCaches:()=>sn,saveCompany:()=>Cr,saveDiscoveredPerson:()=>br,saveScoutedJob:()=>hr,setJobDecision:()=>yr});import"dotenv/config";import*as Z from"fs";import*as K from"path";import{fileURLToPath as mr}from"url";function we(){Z.existsSync(De)||Z.mkdirSync(De,{recursive:!0})}function be(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";Z.writeFileSync(o,n);for(let s=0;s<3;s++)try{Z.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function pt(e){try{if(Z.existsSync(e))return JSON.parse(Z.readFileSync(e,"utf-8"))}catch{}return null}function sn(){ut=null,ft=null,dt=null,mt=null,Ie=null}function gt(){return ut||(ut=pt(bo)||{},ut)}function hr(e,t){if(!e)return;we();let n=gt(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[s,i]of Object.entries(t))i!=null&&(n[e][s]=i);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{be(bo,n)}catch(s){console.error(`[!] Failed to save scouted-jobs.json: ${s.message}`)}}function ht(){return ft||(ft=pt(vo)||{},ft)}function yr(e,t,n={}){if(!e||!t)return;we();let o=ht(),s=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=s,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:s,updatedAt:s,reason:n.reason||null,score:n.score??null,source:n.source||null};try{be(vo,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function wr(e){return ht()[e]||null}function yt(){return dt||(dt=pt(It)||{},dt)}function We(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function ko(e,t){let n=Ve(t)||t;if(e[n])return n;let o=We(t);if(!o)return n;let s=null;for(let[i,r]of Object.entries(e)){if(We(r&&(r.canonicalUrl||r.profileUrl)||i)===o)return i;!s&&r&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}return s||n}function br(e,t){if(!e)return;we();let n=yt(),o=new Date().toISOString().slice(0,10),s=ko(n,e),i=We(e);if(n[s]){let r=n[s];t.name&&(r.name=t.name),t.title&&(r.title=t.title),t.company&&(r.company=t.company),t.location&&(r.location=t.location),t.role&&(r.role=t.role),t.isConnected!=null&&(r.isConnected=t.isConnected),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),i&&We(r.canonicalUrl||r.profileUrl||s)!==i&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(i)||r.aliases.push(i)),r.lastSeen=o,r.seenCount=(r.seenCount||1)+1}else n[s]={canonicalUrl:s,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{be(It,n)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function Sr(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 $o(e,t,n={},o){if(!t)return;let s=We(t);t=ko(e,t);let i=n.seedUrl?{...n,seedUrl:Ve(n.seedUrl)||n.seedUrl}:n,r=o.slice(0,10),{edge:c,match:a}=Sr(i,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:r,firstSeen:r,lastSeen:r}),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=[]),nn(l.categories,n.category),Rt(l.categories,n.categories),Rt(l.sectors,n.sectors),Rt(l.aliases,n.aliases),s&&We(l.canonicalUrl||t)!==s&&nn(l.aliases,s),Rt(l.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(l.affiliations)||(l.affiliations=[]);for(let d of n.affiliations)!d||!d.companyKey||l.affiliations.some(f=>f.companyKey===d.companyKey&&f.role===d.role)||l.affiliations.push(d)}l.lastSeen=r,l.seenCount=(l.seenCount||0)+1}function vr(e,t={}){if(!e)return;we();let n=yt();$o(n,e,t,new Date().toISOString());try{be(It,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function kr(e){if(!Array.isArray(e)||e.length===0)return;we();let t=yt(),n=new Date().toISOString(),o=0;for(let s of e)!s||!s.url||($o(t,s.url,s,n),o++);if(o)try{be(It,t)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function $r(e={}){if(!e||!e.name)return;we();let t=e.key||Tt(e.website)||Tt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=rn(),o=new Date().toISOString().slice(0,10),s=(a,l)=>{l&&Array.isArray(a)&&!a.includes(l)&&a.push(l)},i=(a,l)=>{if(Array.isArray(l))for(let u of l)s(a,u)},r=n[t];r||(r=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&&(r.name=e.name),e.website&&(r.website=r.website||e.website),e.linkedinUrl&&(r.linkedinUrl=r.linkedinUrl||e.linkedinUrl);for(let a of["size","check","stage","location","industries","about"])e[a]&&!r[a]&&(r[a]=e[a]);e.note&&!r.note&&(r.note=e.note),e.whyUseful&&!r.whyUseful&&(r.whyUseful=e.whyUseful),e.fitScore!=null&&(r.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(r.extra={...r.extra||{},...e.extra});for(let a of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(r[a])||(r[a]=[]),i(r[a],e[a]);Array.isArray(r.people)||(r.people=[]);let c=a=>{if(!a||!a.url)return;let l=r.people.find(u=>u.url===a.url&&(u.role||null)===(a.role||null));l?a.current!=null&&(l.current=a.current):r.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(r.portfolio)||(r.portfolio=[]);for(let a of e.portfolio||[]){let l=a&&(a.key||a.name);l&&!r.portfolio.some(u=>(u.key||u.name)===l)&&r.portfolio.push(a)}r.lastSeen=o,r.seenCount=(r.seenCount||0)+1;try{be(on,n)}catch(a){console.error(`[!] Failed to save companies.json: ${a.message}`)}return t}function rn(){return mt||(mt=pt(on)||{},mt)}function Cr(e,t){if(!e)return;we();let n=rn(),o=new Date().toISOString().slice(0,10);if(n[e]){let s=n[e];t.name&&(s.name=t.name),t.about&&(s.about=t.about),t.size&&(s.size=t.size),t.industries&&(s.industries=t.industries),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),t.recruiterUrl&&(s.recruiterUrls||(s.recruiterUrls=[]),s.recruiterUrls.includes(t.recruiterUrl)||s.recruiterUrls.push(t.recruiterUrl)),s.lastSeen=o,s.jobCount=s.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{be(on,n)}catch(s){console.error(`[!] Failed to save companies.json: ${s.message}`)}}function Dt(){return Ie||(Ie=pt(So)||{visits:[]},Array.isArray(Ie.visits)||(Ie.visits=[]),Ie)}function Ar(e,t={}){if(!e)return;we();let n=Dt();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(s=>new Date(s.date).getTime()>o);try{be(So,n)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function xr(e){let t=Dt();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function an(){let e=gt(),t=yt(),n=Object.values(e),o=Object.values(t),s={};for(let f of n)f.company&&(s[f.company]=(s[f.company]||0)+1);let i=Object.entries(s).sort((f,m)=>m[1]-f[1]).slice(0,5).map(([f,m])=>`${f} (${m})`),r={};for(let f of n)for(let m of f.techStack||[])r[m]=(r[m]||0)+1;let c=Object.entries(r).sort((f,m)=>m[1]-f[1]).slice(0,8).map(([f,m])=>`${f} (${m})`),a=Dt(),l=new Date().toISOString().slice(0,10),u=a.visits.filter(f=>f.date.startsWith(l)).length,d=new Set(a.visits.map(f=>f.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:c,totalVisited:d,todayVisited:u,lastScoutDate:n.length>0?n.sort((f,m)=>(m.scoutedAt||"").localeCompare(f.scoutedAt||""))[0]?.scoutedAt:null}}var pr,gr,De,bo,It,So,on,vo,ut,ft,dt,nn,Rt,mt,Ie,wt=fe(()=>{tn();pr=mr(import.meta.url),gr=K.dirname(K.dirname(pr)),De=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"market-research"):K.join(gr,"market-research"),bo=K.join(De,"scouted-jobs.json"),It=K.join(De,"discovered-people.json"),So=K.join(De,"visit-log.json"),on=K.join(De,"companies.json"),vo=K.join(De,"job-decisions.json");ut=null;ft=null;dt=null;nn=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Rt=(e,t)=>{if(Array.isArray(t))for(let n of t)nn(e,n)};mt=null;Ie=null});var ss={};le(ss,{computeEngagement:()=>yn,detectCategory:()=>Qo,detectCategoryFromTitle:()=>Pt,determineAction:()=>ns,determineLastMessageBy:()=>Lt,determineSituation:()=>Xo,enrichConversation:()=>jt,enrichPerson:()=>bn,enrichPersonContext:()=>os,extractAutoTags:()=>es,generateSummary:()=>Zo,normPreview:()=>ze});function jt(e,t,n){if(!e)return e;let s=(e.messages||[]).filter(a=>!Fe.has(a.status)),i=zr(t,e.profileUrl,n),r=Lt(s,t);if(e.lastMessageBy=r,e.conversationStatus=r==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let a=Qo(s,t,i);a&&(e.category=a,e.categorySource=e.categorySource||"message_content")}if(e.situation=Xo(s,r,t),s.length>0){let a=s[s.length-1];e.lastMessageTime=a.time}if(s.length>0&&!e.initiatedBy){let a=s[0];a.sender===z?e.initiatedBy="us":a.sender!=="Unknown"&&a.sender!==""&&(e.initiatedBy="them")}e.engagement=yn(s,t),e.personContext=os(i),e.summary=Zo(e,t,i),e.autoTags=es(e,t,i);let c=ns(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=Gr(e),e}function Qo(e,t,n){if(!e||e.length===0)return n?.title?Pt(n.title):null;let o=e.filter(s=>s.sender!==z&&s.sender!=="Unknown"&&s.sender!=="").map(s=>s.text).join(" ");for(let[s,i]of Object.entries(Ko))if(i.theirMessages){for(let r of i.theirMessages)if(r.test(o))return s}if(n?.title){let s=Pt(n.title);if(s)return s}return null}function Pt(e){if(!e)return null;for(let[t,n]of Object.entries(Ko))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function Xo(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 zo.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let s=[...e].reverse().find(i=>i.sender!==z&&i.sender!=="Unknown");return zo.test(s?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Lt(e,t){if(!e||e.length===0)return"them";let n=[...e].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),o=n.length>0?n:[...e].reverse();for(let s of o){let i=s.sender;if(i===z)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function Zo(e,t,n){let o=e.messages||[];if(o.length===0)return null;let s=[],i=e.category,r=n?.title,c=n?.company,a=n?.location;i==="recruiter"&&c?s.push(`Recruiter from ${c}`):i==="hiring_manager"&&c?s.push(`Hiring manager at ${c}`):i==="founder"&&c?s.push(`Founder of ${c}`):i&&r?s.push(`${wn(i)}: ${Ge(r,40)}`):r?s.push(Ge(r,50)):s.push(t.split(" ")[0]);let l=o.filter(w=>w.sender!==z&&w.sender!=="Unknown").map(w=>w.text).join(" "),u=Kr(l),d=Qr(l),f=Xr(l),m=[];return u&&m.push(u),f&&f!==a&&m.push(f),d&&m.push(d),m.length>0&&s.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?s.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?s.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?s.push("needs reply"):e.conversationStatus==="awaiting_reply"&&s.push("waiting on them"),s.join(". ").replace(/\.\./g,".")}function es(e,t,n){let o=[],s=(e.messages||[]).filter(l=>!Fe.has(l.status)),i=s.map(l=>l.text).join(" "),r=s.filter(l=>l.sender!==z&&l.sender!=="Unknown").map(l=>l.text).join(" "),c=ts(r,n?.location);o.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&o.push("remote"),/\b(hybrid)\b/i.test(i)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&o.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&o.push("java"),/\b(python)\b/i.test(i)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&o.push("backend"),/\b(full.?stack)\b/i.test(i)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&o.push("has-salary");let a=e.engagement||yn(s,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=>nt.has(l.status))&&o.push("has-draft"),[...new Set(o)]}function ts(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"],s=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let r of o)i.includes(r)&&n.push(r.replace(/\s+/g,"-"));for(let[r,c]of s)i.includes(r)&&n.push(c);return n}function ns(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&ze(e.lastMessagePreview)===ze(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let s=(e.messages||[]).find(i=>nt.has(i.status));return s?s.status===V.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:`${wn(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 yn(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,s=0,i=!1,r=!1,c=e.map(a=>a.text).join(" ");for(let a of e)a.sender===z?n++:a.sender==="Unknown"||a.sender===""?s++:o++;return i=/\b(job|role|position|opening)\b/i.test(c),r=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:s,hasJob:i,hasSalary:r}}function os(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Gr(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 zr(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let s=Be(n,t,e);if(n[s])return n[s]}if(!e)return null;let o=Object.values(n).filter(s=>s.name===e);return o.length===1?o[0]:null}function ze(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function wn(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Ge(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Kr(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 Qr(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 Xr(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 bn(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=Pt(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Zr(e),e.personSummary=ei(e),e.personAutoTags=ti(e);let n=ni(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=oi(e)),e}function Zr(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 ei(e){let t=[],n=e.category,o=e.title,s=e.company,i=e.location;if(n==="recruiter"&&s?t.push(`Recruiter at ${s}`):n==="hiring_manager"&&s?t.push(`Hiring manager at ${s}`):n==="founder"&&s?t.push(`Founder of ${s}`):o&&s?t.push(`${Ge(o,40)} at ${Ge(s,30)}`):o?t.push(Ge(o,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let r=new Date(e.connectionDate);if(!isNaN(r)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[r.getMonth()]} ${r.getDate()}`)}}if(e.jobCount>0){let r=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(r+=` (last: ${Ge(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(r+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}r+=")"}t.push(r)}return t.join(". ").replace(/\.\./g,".")||null}function ti(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=ts("",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 ni(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:`${wn(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function oi(e){let t=e.category;if(!t)return null;let n=si(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 si(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 Ko,zo,Sn=fe(async()=>{await ot();await Je();Ko={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]}};zo=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var ks={};le(ks,{extractCertificationsFromDetails:()=>aa,extractEducationFromDetails:()=>ra,extractExperienceFromDetails:()=>oa,extractFeaturedFromDetails:()=>sa,extractRecommendationsFromDetails:()=>la,extractSkillsFromDetails:()=>ia});async function oa(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await Gt(e,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await k(1e3);for(let s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(900);await k(1e3);let o=0;for(;o<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});)o++,await k(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function i(l){let u=[];for(let d of l.querySelectorAll("div")){let f=Array.from(d.children).filter(w=>w.tagName==="DIV");if(f.length<3)continue;let m=f.filter(w=>(w.textContent||"").trim().length>50);m.length<3||(d.textContent||"").length<500||u.push({el:d,count:m.length,totalText:(d.textContent||"").length})}return u.sort((d,f)=>f.count-d.count||d.totalText-f.totalText),u[0]?.el}let r=i(s);if(!r)return[];let c=Array.from(r.children).filter(l=>l.tagName==="DIV").filter(l=>(l.textContent||"").trim().length>50);function a(l){let u=l[0]||null,d=null,f=null;if(l[1]){let A=l[1].split("\xB7").map(I=>I.trim());d=A[0]||null,A[1]&&(f=A[1])}let m=l.findIndex(A=>/(\d{4}|present)/i.test(A)&&/(-|–|—)/i.test(A)&&A.length<80),w=null,g=null;if(m>=0){let A=l[m].split("\xB7").map(I=>I.trim());w=A[0]||null,A[1]&&(g=A[1])}let b=null,y=-1;if(m>=0&&l[m+1]){let A=l[m+1],I=/^[>*\-•]|^>/.test(A),P=/https?:\/\//.test(A),G=/\d{4}/.test(A),$=/,/.test(A)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(A);!I&&!P&&!G&&A.length<100&&$&&(b=A,y=m+1)}let S=null,h=-1,p=l[l.length-1];if(p&&/and\s+\+\d+\s+skills?$/i.test(p)){h=l.length-1;let A=p.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);A&&(S={listed:A[1].split(",").map(I=>I.trim()),additional:parseInt(A[2],10)})}let v=new Set([0,1,m,y,h].filter(A=>A>=0)),C=l.filter((A,I)=>!v.has(I)),_=C.length>0?C.join(`
|
|
1
|
+
var Gs=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{for(var n in t)Gs(e,n,{get:t[n],enumerable:!0})};import Y from"fs";import fe from"path";function zt(){let e=process.env.ILML_SCOPE_DIR;return e?fe.join(e,"plugins-state","linkedin","cookies.json"):zs}function Ks(){let e=zt(),t=fe.dirname(e);return t&&t!=="."&&!Y.existsSync(t)&&Y.mkdirSync(t,{recursive:!0}),e}function Xn(e){let t=Ks();return Y.writeFileSync(t,JSON.stringify(e)),t}function _t(){let e=zt();if(!Y.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Y.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 Zn(){return Y.existsSync(zt())}function Qs(){let e=process.env.ILML_SCOPE_DIR;return e?fe.join(e,"plugins-state","linkedin"):"."}function eo(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Xs(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?eo(t[1]):"default"}function to(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return Y.existsSync(t)||Y.mkdirSync(t,{recursive:!0}),fe.resolve(t);let n=eo(e||Xs()),o=fe.join(Qs(),"chrome-profile",n);return Y.existsSync(o)||Y.mkdirSync(o,{recursive:!0}),fe.resolve(o)}function oo(e){return!Y.existsSync(fe.join(e,no))}function so(e){try{Y.writeFileSync(fe.join(e,no),new Date().toISOString())}catch{}}function ro(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{Y.rmSync(fe.join(e,n),{force:!0}),t++}catch{}return t}var zs,no,et=ce(()=>{zs="cookies.json";no=".ilml-seeded"});function tt(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),s=t[3].toUpperCase()==="PM";return s&&n!==12&&(n+=12),!s&&n===12&&(n=0),{hours:n,minutes:o}}function Xt(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=tt(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=Zs[o[1].toLowerCase()],a=tt(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 s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let c=Kt[s[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(s[2],10),l=parseInt(s[3],10),u=tt(s[4]||"");return new Date(l,c,a,u?.hours||0,u?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let c=Kt[i[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(i[2],10),l=tt(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()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(r){let c=Kt[r[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(r[2],10),l=tt(r[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 k(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function er(e,t,{timeout:n=45e3,poll:o=1e3,label:s="page"}={}){let i=Date.now();for(;Date.now()-i<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-i;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${s})`),!0}}catch{}await new Promise(r=>setTimeout(r,o))}return!1}function Tt(e){return io.test(e||"")}async function Qt(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),s=o?t:Math.min(t,45e3),i=Date.now(),r=!1;for(;Date.now()-i<s;){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",io.source)}catch{}if(a==="in"){try{let l=await e.cookies();if(Array.isArray(l)&&l.some(f=>f.name==="li_at")){let f=Xn(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}r||(r=!0,console.log(`
|
|
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 Rt(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let s=await er(e,t,{timeout:o,label:n});if(!s&&Tt(e.url())){let i=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw i.code="SESSION_EXPIRED",i}return s}async function nt(e,t,{readySelector:n,label:o="page",timeout:s=45e3,gotoTimeout:i=6e4,autoRecover:r=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:i});try{return await Rt(e,{readySelector:n,label:o,timeout:s})}catch(c){if(r&&c.code==="SESSION_EXPIRED"){await Qt(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:i})}catch{}return await Rt(e,{readySelector:n,label:o,timeout:s})}throw c}}async function ao(e){let t=e.url();if(t.includes("/messaging"))return!1;if(Tt(t)?await Qt(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 k(4e3),Tt(e.url())&&(await Qt(e,{label:"inbox"}),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),Tt(e.url())))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}async function Ae(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),r=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),c=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||r||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:s.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:s.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 lo(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 co(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 Kt,Zs,io,Le=ce(()=>{et();Kt={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Zs={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};io=/\/authwall|\/login|\/checkpoint|\/uas\/login/});import{getPluginConfig as tr}from"@ilivemylife/graph-sdk";var nr,K,V,ot,Fe,st=ce(async()=>{nr=await tr();for(let[e,t]of Object.entries(nr))process.env[e]===void 0&&(process.env[e]=t);K=process.env.LINKEDIN_NAME,V=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ot=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.NEEDS_REVIEW])),Fe=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.REJECTED,V.NEEDS_REVIEW]))});import"dotenv/config";import*as F from"fs";import*as B from"path";import{fileURLToPath as or}from"url";import{execSync as Zt}from"child_process";function wo(){Ue=null,ir=null,me=null,xe=null,qe=null,Ee=null}function pe(){F.existsSync(Z)||F.mkdirSync(Z,{recursive:!0})}function He(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";F.writeFileSync(o,n);for(let s=0;s<3;s++)try{F.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function at(e,t){if(!F.existsSync(e))return null;try{let n=JSON.parse(F.readFileSync(e,"utf-8"));try{F.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(F.existsSync(o))try{let s=JSON.parse(F.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{F.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{F.copyFileSync(e,e+".corrupted")}catch{}return null}}function lt(){return new Date().toISOString().split("T")[0]}function _e(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function fo(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Be(e,t,n=null){if(!t||e[t])return t;let o=_e(t);if(!o)return t;let s=null;for(let[i,r]of Object.entries(e)){if(_e(r.profileUrl||i)===o)return i;!s&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}if(s){let i=fo(n),r=fo(e[s].name);if(i&&r&&i===r)return s}return t}function cr(){F.existsSync(tn)||F.mkdirSync(tn,{recursive:!0})}function bo(e){let t=_e(e);return t?B.join(tn,`${t}.json`):null}function ur(e){let t=bo(e);return t?at(t,`profile-history/${_e(e)}.json`)||[]:[]}function dr(e,t){let n=bo(e);if(!n)return;cr();let o=ur(e);o.unshift(t);try{He(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${_e(e)}: ${s.message}`)}}function mo(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function po(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function fr(e,t){if(!e)return[];let n=[];for(let o of lr){let s=e[o],i=t[o];mo(s)||mo(i)||po(s)!==po(i)&&n.push(o)}return n}function mr(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function J(){return Ue||(pe(),Ue=at(en,"people.json")||{},Ue)}function Re(e){pe(),Ue=e;try{He(en,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(en)}`)}}function ct(){return xe||(pe(),xe=at(It,"conversations.json")||{},pr(xe),xe)}function pr(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(i=>i.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{He(It,e)}catch{}}}function we(e){pe(),xe=e;try{He(It,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${B.resolve(It)}`)}}function Te(e,t={}){if(!e)return null;let n=J(),o=lt(),s=new Date().toISOString(),i=Be(n,e,t.name),r=n[i];if(r){let c=fr(r,t);c.length>0&&(dr(i,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:c,snapshot:mr(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=o,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let a of ar)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(r[a])&&r[a].length>0)continue;r[a]=t[a]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else n[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Re(n),n[i]}function So(e,t){if(!e||!t)return;let n=J(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:lt(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),Re(n))}function vo(e){return e&&J()[e]?.connectionStatus||null}function ko(e,t,n={}){if(!e)return;if(n.profileInfo)Te(e,n.profileInfo);else{let c=J(),a=Be(c,e,n.profileInfo?.name);c[a]||Te(e,{})}let o=J(),s=Be(o,e,n.profileInfo?.name),i=o[s];if(!i)return;let r=lt();i.connectionStatus=t,t==="connected"?i.connectionDate=r:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=r)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),Re(o)}function Dt(e,t,n={}){if(n.dryRun||!e||!t)return;let o=_e(t);if(!o)return;let s=J(),i=Be(s,e),r=s[i];if(!r)return;let c=_e(r.profileUrl||i);o!==c&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(o)||(r.aliases.push(o),r.lastUpdated=new Date().toISOString(),Re(s)))}function $o(){return me||(pe(),me=at(ho,"quota.json"),(!me||!me.connections)&&(me={connections:[]}),me)}function hr(e){pe(),me=e;try{He(ho,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Co(e,t="unknown"){let n=$o(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),hr(n)}function Ao(){let e=$o(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function nn(){let e=Ao(),t=lt(),n=e.filter(a=>a.date===t).length,o=e.length,s=n>=rt,i=o>=it,r=!s&&!i,c={allowed:r,daily:{sent:n,max:rt},weekly:{sent:o,max:it}};return r||(c.reason=s?`Daily limit reached (${n}/${rt})`:`Weekly limit reached (${o}/${it})`),c}function ut(){let e=Ao(),t=lt(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:rt,remaining:rt-n},weekly:{sent:o,max:it,remaining:it-o}}}function on(){return qe||(pe(),qe=at(go,"sync-state.json")||{},qe)}function Eo(e){pe(),qe=e;try{He(go,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function gr(){if(Ee)return Ee;pe();try{F.existsSync(uo)&&(Ee=JSON.parse(F.readFileSync(uo,"utf-8")))}catch{}return Ee||(Ee={}),Ee}function yr(e){return Array.isArray(e.applications)}function wr(){let e=gr();if(yr(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function xo(){let e=wr(),t=new Map;for(let i of e)for(let r of i.questions||[]){let c=r.question.toLowerCase().trim();if(!c)continue;t.has(c)||t.set(c,{question:r.question,count:0,answers:new Map});let a=t.get(c);a.count++;let l=(r.answer||"").trim();a.answers.set(l,(a.answers.get(l)||0)+1)}let n=[...t.values()].sort((i,r)=>r.count-i.count),o=n.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((r,c)=>c[1]-r[1])[0]?.[0]||""})),s=n.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((r,c)=>c[1]-r[1]).map(([r,c])=>`${r} (${c}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:o,inconsistent:s}}function sn(e){if(F.existsSync(B.join(Z,".git")))try{let t={cwd:Z,stdio:"pipe",timeout:1e4};Zt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{Zt("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');Zt(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var sr,rr,Z,en,Xa,ho,It,go,uo,tn,yo,rt,it,Ue,ir,me,xe,qe,Ee,ar,lr,Je=ce(async()=>{await st();sr=or(import.meta.url),rr=B.dirname(B.dirname(sr)),Z=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(rr,"collected-profiles"),en=B.join(Z,"people.json"),Xa=B.join(Z,"jobs.json"),ho=B.join(Z,"quota.json"),It=B.join(Z,"conversations.json"),go=B.join(Z,"sync-state.json"),uo=B.join(Z,"application-questions.json"),tn=B.join(Z,"profile-history"),yo=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},rt=yo(process.env.CONNECT_MAX_DAILY,20),it=yo(process.env.CONNECT_MAX_WEEKLY,100),Ue=null,ir=null,me=null,xe=null,qe=null,Ee=null;ar=["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"],lr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var Io={};ue(Io,{BLOCK_MARKERS:()=>_o,dedupeAndCap:()=>Ro,extractSidePanelProfiles:()=>br,normalizeFundUrl:()=>Ot,normalizeProfileUrl:()=>Ve,scanRelatedBlocks:()=>To});function Ve(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 Ot(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function To(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=l=>(l||"").replace(/\s+/g," ").trim(),s=l=>{let u=String(l||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},i=l=>o(l).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),r=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 m=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(m))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(([b])=>u.includes(b));if(!f)continue;let d=f[1],m=r(l);if(!m)continue;let w=0,h=new Set;for(let b of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let y=b.href||b.getAttribute("href")||"",S=s(y);if(!S)continue;let g=b.querySelector('span[aria-hidden="true"]'),p=o(g?g.textContent:b.getAttribute("aria-label")||b.textContent),v=i(p);if(!v||h.has(S))continue;h.add(S);let C="",_=p.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(_&&(C=o(_[1])),!C){let A=b.closest("li")||b.parentElement;A&&(C=Array.from(A.querySelectorAll("p, span")).map(P=>o(P.textContent)).filter(P=>P&&P!==v&&!/^view\b/i.test(P)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(P)&&/[a-z]/i.test(P)&&P.length>2)[0]||"")}c.push({href:y,name:v,headline:C,block:d,rank:w++})}}return c}function Ro(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=Ve(t.seedUrl||""),s=new Map,i={};for(let r of e||[]){let c=Ve(r.href);c&&(o&&c===o||(i[r.block]=i[r.block]||0,!(i[r.block]>=n)&&(s.has(c)||(i[r.block]++,s.set(c,{url:c,name:r.name,headline:r.headline||null,block:r.block,rank:r.rank})))))}return Array.from(s.values())}async function br(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(To,_o)}catch{return[]}return Ro(n,t)}var _o,rn=ce(()=>{_o=[["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 jo={};ue(jo,{getJobDecision:()=>Ar,getLastVisit:()=>Or,getScoutStats:()=>dn,loadCompanies:()=>un,loadDiscoveredPeople:()=>wt,loadJobDecisions:()=>yt,loadScoutedJobs:()=>gt,loadVisitLog:()=>Pt,recordCompany:()=>Rr,recordDiscoveredEdge:()=>_r,recordDiscoveredEdges:()=>Tr,recordVisit:()=>Dr,resetCaches:()=>cn,saveCompany:()=>Ir,saveDiscoveredPerson:()=>Er,saveScoutedJob:()=>$r,setJobDecision:()=>Cr});import"dotenv/config";import*as ee from"fs";import*as Q from"path";import{fileURLToPath as Sr}from"url";function be(){ee.existsSync(De)||ee.mkdirSync(De,{recursive:!0})}function Se(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";ee.writeFileSync(o,n);for(let s=0;s<3;s++)try{ee.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function ht(e){try{if(ee.existsSync(e))return JSON.parse(ee.readFileSync(e,"utf-8"))}catch{}return null}function cn(){dt=null,ft=null,mt=null,pt=null,Ie=null}function gt(){return dt||(dt=ht(Do)||{},dt)}function $r(e,t){if(!e)return;be();let n=gt(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[s,i]of Object.entries(t))i!=null&&(n[e][s]=i);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{Se(Do,n)}catch(s){console.error(`[!] Failed to save scouted-jobs.json: ${s.message}`)}}function yt(){return ft||(ft=ht(No)||{},ft)}function Cr(e,t,n={}){if(!e||!t)return;be();let o=yt(),s=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=s,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:s,updatedAt:s,reason:n.reason||null,score:n.score??null,source:n.source||null};try{Se(No,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function Ar(e){return yt()[e]||null}function wt(){return mt||(mt=ht(Mt)||{},mt)}function We(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Mo(e,t){let n=Ve(t)||t;if(e[n])return n;let o=We(t);if(!o)return n;let s=null;for(let[i,r]of Object.entries(e)){if(We(r&&(r.canonicalUrl||r.profileUrl)||i)===o)return i;!s&&r&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}return s||n}function Er(e,t){if(!e)return;be();let n=wt(),o=new Date().toISOString().slice(0,10),s=Mo(n,e),i=We(e);if(n[s]){let r=n[s];t.name&&(r.name=t.name),t.title&&(r.title=t.title),t.company&&(r.company=t.company),t.location&&(r.location=t.location),t.role&&(r.role=t.role),t.isConnected!=null&&(r.isConnected=t.isConnected),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),i&&We(r.canonicalUrl||r.profileUrl||s)!==i&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(i)||r.aliases.push(i)),r.lastSeen=o,r.seenCount=(r.seenCount||1)+1}else n[s]={canonicalUrl:s,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{Se(Mt,n)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function xr(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 Po(e,t,n={},o){if(!t)return;let s=We(t);t=Mo(e,t);let i=n.seedUrl?{...n,seedUrl:Ve(n.seedUrl)||n.seedUrl}:n,r=o.slice(0,10),{edge:c,match:a}=xr(i,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:r,firstSeen:r,lastSeen:r}),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=[]),an(l.categories,n.category),Nt(l.categories,n.categories),Nt(l.sectors,n.sectors),Nt(l.aliases,n.aliases),s&&We(l.canonicalUrl||t)!==s&&an(l.aliases,s),Nt(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=r,l.seenCount=(l.seenCount||0)+1}function _r(e,t={}){if(!e)return;be();let n=wt();Po(n,e,t,new Date().toISOString());try{Se(Mt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function Tr(e){if(!Array.isArray(e)||e.length===0)return;be();let t=wt(),n=new Date().toISOString(),o=0;for(let s of e)!s||!s.url||(Po(t,s.url,s,n),o++);if(o)try{Se(Mt,t)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function Rr(e={}){if(!e||!e.name)return;be();let t=e.key||Ot(e.website)||Ot(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=un(),o=new Date().toISOString().slice(0,10),s=(a,l)=>{l&&Array.isArray(a)&&!a.includes(l)&&a.push(l)},i=(a,l)=>{if(Array.isArray(l))for(let u of l)s(a,u)},r=n[t];r||(r=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&&(r.name=e.name),e.website&&(r.website=r.website||e.website),e.linkedinUrl&&(r.linkedinUrl=r.linkedinUrl||e.linkedinUrl);for(let a of["size","check","stage","location","industries","about"])e[a]&&!r[a]&&(r[a]=e[a]);e.note&&!r.note&&(r.note=e.note),e.whyUseful&&!r.whyUseful&&(r.whyUseful=e.whyUseful),e.fitScore!=null&&(r.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(r.extra={...r.extra||{},...e.extra});for(let a of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(r[a])||(r[a]=[]),i(r[a],e[a]);Array.isArray(r.people)||(r.people=[]);let c=a=>{if(!a||!a.url)return;let l=r.people.find(u=>u.url===a.url&&(u.role||null)===(a.role||null));l?a.current!=null&&(l.current=a.current):r.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(r.portfolio)||(r.portfolio=[]);for(let a of e.portfolio||[]){let l=a&&(a.key||a.name);l&&!r.portfolio.some(u=>(u.key||u.name)===l)&&r.portfolio.push(a)}r.lastSeen=o,r.seenCount=(r.seenCount||0)+1;try{Se(ln,n)}catch(a){console.error(`[!] Failed to save companies.json: ${a.message}`)}return t}function un(){return pt||(pt=ht(ln)||{},pt)}function Ir(e,t){if(!e)return;be();let n=un(),o=new Date().toISOString().slice(0,10);if(n[e]){let s=n[e];t.name&&(s.name=t.name),t.about&&(s.about=t.about),t.size&&(s.size=t.size),t.industries&&(s.industries=t.industries),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),t.recruiterUrl&&(s.recruiterUrls||(s.recruiterUrls=[]),s.recruiterUrls.includes(t.recruiterUrl)||s.recruiterUrls.push(t.recruiterUrl)),s.lastSeen=o,s.jobCount=s.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{Se(ln,n)}catch(s){console.error(`[!] Failed to save companies.json: ${s.message}`)}}function Pt(){return Ie||(Ie=ht(Oo)||{visits:[]},Array.isArray(Ie.visits)||(Ie.visits=[]),Ie)}function Dr(e,t={}){if(!e)return;be();let n=Pt();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(s=>new Date(s.date).getTime()>o);try{Se(Oo,n)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function Or(e){let t=Pt();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function dn(){let e=gt(),t=wt(),n=Object.values(e),o=Object.values(t),s={};for(let d of n)d.company&&(s[d.company]=(s[d.company]||0)+1);let i=Object.entries(s).sort((d,m)=>m[1]-d[1]).slice(0,5).map(([d,m])=>`${d} (${m})`),r={};for(let d of n)for(let m of d.techStack||[])r[m]=(r[m]||0)+1;let c=Object.entries(r).sort((d,m)=>m[1]-d[1]).slice(0,8).map(([d,m])=>`${d} (${m})`),a=Pt(),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:i,topTech:c,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var vr,kr,De,Do,Mt,Oo,ln,No,dt,ft,mt,an,Nt,pt,Ie,bt=ce(()=>{rn();vr=Sr(import.meta.url),kr=Q.dirname(Q.dirname(vr)),De=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"market-research"):Q.join(kr,"market-research"),Do=Q.join(De,"scouted-jobs.json"),Mt=Q.join(De,"discovered-people.json"),Oo=Q.join(De,"visit-log.json"),ln=Q.join(De,"companies.json"),No=Q.join(De,"job-decisions.json");dt=null;ft=null;mt=null;an=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Nt=(e,t)=>{if(Array.isArray(t))for(let n of t)an(e,n)};pt=null;Ie=null});var cs={};ue(cs,{computeEngagement:()=>vn,detectCategory:()=>ns,detectCategoryFromTitle:()=>Ft,determineAction:()=>as,determineLastMessageBy:()=>qt,determineSituation:()=>os,enrichConversation:()=>Ut,enrichPerson:()=>$n,enrichPersonContext:()=>ls,extractAutoTags:()=>rs,generateSummary:()=>ss,normPreview:()=>ze});function Ut(e,t,n){if(!e)return e;let s=(e.messages||[]).filter(a=>!Fe.has(a.status)),i=Zr(t,e.profileUrl,n),r=qt(s,t);if(e.lastMessageBy=r,e.conversationStatus=r==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let a=ns(s,t,i);a&&(e.category=a,e.categorySource=e.categorySource||"message_content")}if(e.situation=os(s,r,t),s.length>0){let a=s[s.length-1];e.lastMessageTime=a.time}if(s.length>0&&!e.initiatedBy){let a=s[0];a.sender===K?e.initiatedBy="us":a.sender!=="Unknown"&&a.sender!==""&&(e.initiatedBy="them")}e.engagement=vn(s,t),e.personContext=ls(i),e.summary=ss(e,t,i),e.autoTags=rs(e,t,i);let c=as(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=Xr(e),e}function ns(e,t,n){if(!e||e.length===0)return n?.title?Ft(n.title):null;let o=e.filter(s=>s.sender!==K&&s.sender!=="Unknown"&&s.sender!=="").map(s=>s.text).join(" ");for(let[s,i]of Object.entries(ts))if(i.theirMessages){for(let r of i.theirMessages)if(r.test(o))return s}if(n?.title){let s=Ft(n.title);if(s)return s}return null}function Ft(e){if(!e)return null;for(let[t,n]of Object.entries(ts))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function os(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 es.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let s=[...e].reverse().find(i=>i.sender!==K&&i.sender!=="Unknown");return es.test(s?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function qt(e,t){if(!e||e.length===0)return"them";let n=[...e].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),o=n.length>0?n:[...e].reverse();for(let s of o){let i=s.sender;if(i===K)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function ss(e,t,n){let o=e.messages||[];if(o.length===0)return null;let s=[],i=e.category,r=n?.title,c=n?.company,a=n?.location;i==="recruiter"&&c?s.push(`Recruiter from ${c}`):i==="hiring_manager"&&c?s.push(`Hiring manager at ${c}`):i==="founder"&&c?s.push(`Founder of ${c}`):i&&r?s.push(`${kn(i)}: ${Ge(r,40)}`):r?s.push(Ge(r,50)):s.push(t.split(" ")[0]);let l=o.filter(w=>w.sender!==K&&w.sender!=="Unknown").map(w=>w.text).join(" "),u=ei(l),f=ti(l),d=ni(l),m=[];return u&&m.push(u),d&&d!==a&&m.push(d),f&&m.push(f),m.length>0&&s.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?s.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?s.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?s.push("needs reply"):e.conversationStatus==="awaiting_reply"&&s.push("waiting on them"),s.join(". ").replace(/\.\./g,".")}function rs(e,t,n){let o=[],s=(e.messages||[]).filter(l=>!Fe.has(l.status)),i=s.map(l=>l.text).join(" "),r=s.filter(l=>l.sender!==K&&l.sender!=="Unknown").map(l=>l.text).join(" "),c=is(r,n?.location);o.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&o.push("remote"),/\b(hybrid)\b/i.test(i)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&o.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&o.push("java"),/\b(python)\b/i.test(i)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&o.push("backend"),/\b(full.?stack)\b/i.test(i)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&o.push("has-salary");let a=e.engagement||vn(s,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=>ot.has(l.status))&&o.push("has-draft"),[...new Set(o)]}function is(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"],s=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let r of o)i.includes(r)&&n.push(r.replace(/\s+/g,"-"));for(let[r,c]of s)i.includes(r)&&n.push(c);return n}function as(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&ze(e.lastMessagePreview)===ze(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let s=(e.messages||[]).find(i=>ot.has(i.status));return s?s.status===V.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:`${kn(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 vn(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,s=0,i=!1,r=!1,c=e.map(a=>a.text).join(" ");for(let a of e)a.sender===K?n++:a.sender==="Unknown"||a.sender===""?s++:o++;return i=/\b(job|role|position|opening)\b/i.test(c),r=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:s,hasJob:i,hasSalary:r}}function ls(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Xr(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 Zr(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let s=Be(n,t,e);if(n[s])return n[s]}if(!e)return null;let o=Object.values(n).filter(s=>s.name===e);return o.length===1?o[0]:null}function ze(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function kn(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Ge(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function ei(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 ti(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 ni(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 $n(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=Ft(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}oi(e),e.personSummary=si(e),e.personAutoTags=ri(e);let n=ii(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=ai(e)),e}function oi(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 si(e){let t=[],n=e.category,o=e.title,s=e.company,i=e.location;if(n==="recruiter"&&s?t.push(`Recruiter at ${s}`):n==="hiring_manager"&&s?t.push(`Hiring manager at ${s}`):n==="founder"&&s?t.push(`Founder of ${s}`):o&&s?t.push(`${Ge(o,40)} at ${Ge(s,30)}`):o?t.push(Ge(o,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let r=new Date(e.connectionDate);if(!isNaN(r)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[r.getMonth()]} ${r.getDate()}`)}}if(e.jobCount>0){let r=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(r+=` (last: ${Ge(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(r+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}r+=")"}t.push(r)}return t.join(". ").replace(/\.\./g,".")||null}function ri(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=is("",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 ii(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:`${kn(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function ai(e){let t=e.category;if(!t)return null;let n=li(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 li(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 ts,es,Cn=ce(async()=>{await st();await Je();ts={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]}};es=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var xs={};ue(xs,{extractCertificationsFromDetails:()=>da,extractEducationFromDetails:()=>ca,extractExperienceFromDetails:()=>aa,extractFeaturedFromDetails:()=>la,extractRecommendationsFromDetails:()=>fa,extractSkillsFromDetails:()=>ua});async function aa(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await Rt(e,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await k(1e3);for(let s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(900);await k(1e3);let o=0;for(;o<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});)o++,await k(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function i(l){let u=[];for(let f of l.querySelectorAll("div")){let d=Array.from(f.children).filter(w=>w.tagName==="DIV");if(d.length<3)continue;let m=d.filter(w=>(w.textContent||"").trim().length>50);m.length<3||(f.textContent||"").length<500||u.push({el:f,count:m.length,totalText:(f.textContent||"").length})}return u.sort((f,d)=>d.count-f.count||f.totalText-d.totalText),u[0]?.el}let r=i(s);if(!r)return[];let c=Array.from(r.children).filter(l=>l.tagName==="DIV").filter(l=>(l.textContent||"").trim().length>50);function a(l){let u=l[0]||null,f=null,d=null;if(l[1]){let A=l[1].split("\xB7").map(I=>I.trim());f=A[0]||null,A[1]&&(d=A[1])}let m=l.findIndex(A=>/(\d{4}|present)/i.test(A)&&/(-|–|—)/i.test(A)&&A.length<80),w=null,h=null;if(m>=0){let A=l[m].split("\xB7").map(I=>I.trim());w=A[0]||null,A[1]&&(h=A[1])}let b=null,y=-1;if(m>=0&&l[m+1]){let A=l[m+1],I=/^[>*\-•]|^>/.test(A),P=/https?:\/\//.test(A),z=/\d{4}/.test(A),$=/,/.test(A)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(A);!I&&!P&&!z&&A.length<100&&$&&(b=A,y=m+1)}let S=null,g=-1,p=l[l.length-1];if(p&&/and\s+\+\d+\s+skills?$/i.test(p)){g=l.length-1;let A=p.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);A&&(S={listed:A[1].split(",").map(I=>I.trim()),additional:parseInt(A[2],10)})}let v=new Set([0,1,m,y,g].filter(A=>A>=0)),C=l.filter((A,I)=>!v.has(I)),_=C.length>0?C.join(`
|
|
2
4
|
|
|
3
|
-
`):null;return{title:u,company:
|
|
4
|
-
`).map(
|
|
5
|
-
${
|
|
5
|
+
`):null;return{title:u,company:f,employmentType:d,dates:w,duration:h,location:b,description:_,skills:S,_raw:l}}return c.map(l=>{let f=(l.innerText||"").trim().split(`
|
|
6
|
+
`).map(d=>d.trim()).filter(d=>d&&d.length<5e3);return a(f)}).filter(l=>l.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function kt(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let s=e.url();if(/\/(login|authwall|checkpoint)/i.test(s))throw new Error(`Session expired \u2014 bounced to ${s} when fetching /details/${n}/`);if(!s.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${s})`);for(let r=0;r<4;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);await k(800);let i=0;for(;i<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});)i++,await k(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(600)}async function Ct(e,t,n,o){try{return await o()}catch(s){let i=s.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw s;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${i.slice(0,120)}`),[])}}async function la(e,t){return Ct(t,"featured","extractFeaturedFromDetails",async()=>(await kt(e,t,"featured"),await e.evaluate(`(() => {
|
|
7
|
+
${$t}
|
|
6
8
|
|
|
7
9
|
const main = document.querySelector('main');
|
|
8
10
|
if (!main) return [];
|
|
@@ -42,8 +44,8 @@ var Hs=Object.defineProperty;var fe=(e,t)=>()=>(e&&(t=e(e=0)),t);var le=(e,t)=>{
|
|
|
42
44
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
43
45
|
return true;
|
|
44
46
|
});
|
|
45
|
-
})()`)))}async function
|
|
46
|
-
${
|
|
47
|
+
})()`)))}async function ca(e,t){return Ct(t,"education","extractEducationFromDetails",async()=>(await kt(e,t,"education"),await e.evaluate(`(() => {
|
|
48
|
+
${$t}
|
|
47
49
|
|
|
48
50
|
const main = document.querySelector('main');
|
|
49
51
|
if (!main) return [];
|
|
@@ -79,8 +81,8 @@ var Hs=Object.defineProperty;var fe=(e,t)=>()=>(e&&(t=e(e=0)),t);var le=(e,t)=>{
|
|
|
79
81
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
80
82
|
return true;
|
|
81
83
|
});
|
|
82
|
-
})()`)))}async function
|
|
83
|
-
${
|
|
84
|
+
})()`)))}async function ua(e,t){return Ct(t,"skills","extractSkillsFromDetails",async()=>(await kt(e,t,"skills"),await e.evaluate(`(() => {
|
|
85
|
+
${$t}
|
|
84
86
|
|
|
85
87
|
const main = document.querySelector('main');
|
|
86
88
|
if (!main) return [];
|
|
@@ -111,8 +113,8 @@ var Hs=Object.defineProperty;var fe=(e,t)=>()=>(e&&(t=e(e=0)),t);var le=(e,t)=>{
|
|
|
111
113
|
skills.push({ name, endorsements, _raw: lines });
|
|
112
114
|
}
|
|
113
115
|
return skills;
|
|
114
|
-
})()`)))}async function
|
|
115
|
-
${
|
|
116
|
+
})()`)))}async function da(e,t){return Ct(t,"certifications","extractCertificationsFromDetails",async()=>(await kt(e,t,"certifications"),await e.evaluate(`(() => {
|
|
117
|
+
${$t}
|
|
116
118
|
|
|
117
119
|
const main = document.querySelector('main');
|
|
118
120
|
if (!main) return [];
|
|
@@ -136,8 +138,8 @@ var Hs=Object.defineProperty;var fe=(e,t)=>()=>(e&&(t=e(e=0)),t);var le=(e,t)=>{
|
|
|
136
138
|
|
|
137
139
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
138
140
|
}).filter(e => e.name);
|
|
139
|
-
})()`)))}async function
|
|
140
|
-
${
|
|
141
|
+
})()`)))}async function fa(e,t){return Ct(t,"recommendations","extractRecommendationsFromDetails",async()=>(await kt(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
142
|
+
${$t}
|
|
141
143
|
|
|
142
144
|
const main = document.querySelector('main');
|
|
143
145
|
if (!main) return [];
|
|
@@ -172,7 +174,7 @@ var Hs=Object.defineProperty;var fe=(e,t)=>()=>(e&&(t=e(e=0)),t);var le=(e,t)=>{
|
|
|
172
174
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
173
175
|
return true;
|
|
174
176
|
});
|
|
175
|
-
})()`)))}var
|
|
177
|
+
})()`)))}var $t,_s=ce(()=>{Le();$t=`
|
|
176
178
|
function findEntryContainer(root) {
|
|
177
179
|
const candidates = [];
|
|
178
180
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -235,129 +237,129 @@ function findEntryContainer(root) {
|
|
|
235
237
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
236
238
|
return candidates[0]?.el;
|
|
237
239
|
}
|
|
238
|
-
`});var As={};le(As,{DEFAULT_PROFILE_INTERESTS:()=>Cs,computeFit:()=>fa,detectSectors:()=>ua});function ua(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,s]of Object.entries(ca))s.some(i=>i.test(t))&&n.push(o);return n}function fa(e,t=Cs){if(!Array.isArray(e)||e.length===0)return 0;let n=i=>typeof i=="number"&&Number.isFinite(i)?i:0,o=Math.max(1,...Object.values(t||{}).map(n)),s=0;for(let i of e){let r=n(t&&t[i]);r>s&&(s=r)}return Math.min(1,s/o)}var ca,Cs,xs=fe(()=>{ca={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/]};Cs={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});var Ts={};le(Ts,{clickConnectButton:()=>On,default:()=>pa,detectConnectionStatus:()=>Ce,findConnectButton:()=>Ct,runFunnel:()=>_s,sendConnectionRequest:()=>Nn,shouldExcludeLocation:()=>Ht,viewProfile:()=>Dn});async function Es(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 k(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Ht(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:s=!1,extractEducation:i=!1,extractSkills:r=!1,extractRecommendations:c=!1,extractCertifications:a=!1}=n;try{await tt(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await k(1500),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await k(1500),await Es(e,t));let u=0;for(let p=0;p<2;p++){let v=await e.evaluate(()=>document.body.scrollHeight);for(let _=1;_<=6;_++)await e.evaluate(A=>window.scrollTo(0,A),v*_/6),await k(900);let C=await e.evaluate(()=>document.body.scrollHeight);if(C===u)break;u=C}await k(800);let d=null;try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(d=p.split("?")[0].replace(/\/+$/,""))}catch{}let f=await e.evaluate(()=>{let p=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"]),v=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=R=>{let D=(R||"").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:[]},A=document.querySelector("main");if(!A)return _;let I=[...Array.from(A.querySelectorAll("h1")),...Array.from(A.querySelectorAll("h2"))],P=Array.from(A.querySelectorAll("h2")),G=I.find(R=>{let D=R.textContent&&R.textContent.trim(),N=(D||"").replace(/\s*\(\d+\)$/,"").trim();return D&&D.length>1&&D.length<100&&!p.has(N)&&!v.has(N)}),$=G?G.textContent.trim():null,x=G?G.parentElement:null;for(;x&&x!==A&&!Array.from(x.children).filter(D=>D.tagName==="P").some(D=>{let N=D.textContent&&D.textContent.trim();return N&&N.length>5&&!C(N)});)x=x.parentElement;let T=null,O=null,H=null,re=null;if(x&&x!==A){let R=Array.from(x.children).filter(N=>N.tagName==="P").filter(N=>{let he=N.textContent&&N.textContent.trim();return he&&he.length>5&&!C(he)});if(R[0]&&(T=R[0].textContent.trim()),R[1]){let N=R[1].textContent.trim().split(/\s*[·•]\s*/);O=N[0]||null,N.length>1&&(H=N.slice(1).join(" \xB7 "))}let D=Array.from(x.children).filter(N=>N.tagName==="DIV");for(let N=D.length-1;N>=0;N--){let he=D[N].textContent&&D[N].textContent.trim();if(he&&!($&&he.startsWith($))&&(re=he.split(/[·•]/)[0].trim(),re))break}}let ie=null;if(x){let R=x.querySelectorAll("p, span, div");for(let D of R){let N=(D.textContent||"").trim().replace(/^[·•]\s*/,"");if(N==="1st"||N==="2nd"||N==="3rd"){ie=N;break}}}let j=!!A.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),L=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),U=L&&L.src||null,q=A.textContent||"",ae=null,Un=q.match(/(\d+\+?)\s+connections\b/i);Un&&(ae=Un[1]+" connections");let xt=null,qn=q.match(/(\d+)\s+mutual connection/i),Bn=q.match(/and\s+(\d+)\s+other mutual/i),Ls=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);qn?xt=parseInt(qn[1],10):Bn?xt=2+parseInt(Bn[1],10):Ls&&(xt=2);let Hn=null,Jn=null,Vn=P.find(R=>R.textContent&&R.textContent.trim()==="About");if(Vn){let R=Vn.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").trim();D=D.replace(/^About\s*/,"").trim();let N=D.match(/Top skills\s*(.+?)$/i);if(N){let Vt=N[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Bs=>Bs.trim()).filter(Boolean);Vt.length>0&&Vt.length<10&&(Jn=Vt)}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(),Hn=D||null}}let Wn=null,Yn=P.find(R=>R.textContent&&R.textContent.trim()==="Activity");if(Yn){let R=Yn.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);D&&(Wn=parseInt(D[1].replace(/,/g,""),10))}}let Fs=[...new Set(P.map(R=>(R.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(R=>R&&R.length>1&&R.length<60&&R!==$).filter(R=>p.has(R)))],Ze=document.body.textContent||"",Us=/#OpenToWork\b/i.test(Ze)||/\bOpen to work\b/.test(Ze),qs=/#Hiring\b/i.test(Ze)||/\bI'?m hiring\b/i.test(Ze)||/\bWe are hiring\b/i.test(Ze);return{name:$,title:T,location:re,currentCompany:O,currentSchool:H,connectionDegree:ie,hasVerifiedBadge:j,photoUrl:U,connectionsLevel:ae,mutualConnectionsCount:xt,followers:Wn,openToWork:Us,hiring:qs,about:Hn,topSkills:Jn,availableSections:Fs}});console.log(`Viewed: ${f.name} - ${f.title}`);let m=null,w=null,g=null,b=null,y=null,S=null;if(o||s||i||r||c||a){let p=await Promise.resolve().then(()=>($s(),ks));o&&(m=await p.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),s&&(w=await p.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${w.length} entries`)),i&&(g=await p.extractEducationFromDetails(e,t),console.log(` + Education: ${g.length} entries`)),r&&(b=await p.extractSkillsFromDetails(e,t),console.log(` + Skills: ${b.length} entries`)),c&&(y=await p.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),a&&(S=await p.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...f,profileUrl:t,resolvedUrl:d,...m!==null&&{experience:m},...w!==null&&{featured:w},...g!==null&&{education:g},...b!==null&&{skillsFull:b},...y!==null&&{recommendations:y},...S!==null&&{certifications:S}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await k(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 s='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=d=>d&&!d.closest(s),r=d=>Array.from(document.querySelectorAll(d)).filter(i),c=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,l=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:c.length,pendingLabels:c.map(d=>d.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 k(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function Ct(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 d=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(d)return d.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let l=await e.evaluate(()=>{let d=document.querySelectorAll('a[href*="custom-invite"]');return{count:d.length,labels:Array.from(d).map(f=>f.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(d=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),m=d.toLowerCase().split(" ")[0],w='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let g of f){let b=g.getBoundingClientRect();if(b.width===0||b.height===0||g.closest(w))continue;if((g.getAttribute("aria-label")||"").toLowerCase().includes(m))return g}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(f=>{let m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),w=document.querySelectorAll("button[aria-label]");return Array.from(w).filter(b=>{let y=b.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&m.test(y)}).map(b=>b.getAttribute("aria-label")?.slice(0,50))},l);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(f=>{let m=document.querySelectorAll("button[aria-label]"),w='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',g=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let b of m){if(b.closest(w))continue;let y=b.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&g.test(y))return b}return null},l);let d=t?.asElement?.()||null;if(d||await t?.dispose?.().catch(()=>{}),d)return console.log(" Found: button matching profile name"),{button:d,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(d=>(d.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 s=n?n.split(" ")[0].toLowerCase():"",i=null;for(let l of o){let u=await e.evaluate((d,f)=>{let m=d.className.includes("muted"),w=d.className.includes("sticky-header")||d.className.includes("sticky"),g=d.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,b=(d.getAttribute("aria-label")||"").toLowerCase(),y=b.includes("invite"),S=f?b.includes(f):!0;return{isMuted:m,isStickyHeader:w,inRecommendations:g,hasInvite:y,matchesName:S,ariaLabel:b}},l,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=l;break}}for(let l of o)l!==i&&await l.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let r=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let l of c){let u=await e.evaluate(d=>{let f=d.getBoundingClientRect(),m=f.width>0&&f.height>0,w=d.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:w,top:f.top}},l);if(u.isVisible&&!u.isInStickyHeader){r=l,console.log(" Found More button by ID pattern (main)");break}}for(let l of c)l!==r&&await l.dispose().catch(()=>{});if(!r&&c.length>0&&(r=c[c.length-1],console.log(" Found More button by ID pattern (last)")),r||(r=await e.$('button[aria-label="More actions"]'),r&&console.log(" Found More button by aria-label")),!r){let l=await e.evaluateHandle(()=>{let d=Array.from(document.querySelectorAll("button, a")).find(m=>{let w=m.innerText?.trim(),g=m.getAttribute("aria-label")||"",b=m.getBoundingClientRect();return b.top<100||b.top>600||b.width===0?!1:w==="Follow"||w==="Message"||w==="Connect"||g.includes("Follow")||g.includes("Message")||g.includes("Invite")});if(!d)return null;let f=d.parentElement;for(let m=0;m<8&&f;m++){for(let w of f.querySelectorAll("button"))if(w.innerText?.trim()==="More"&&w!==d)return w;f=f.parentElement}return null});r=l?.asElement?.()||null,r||await l?.dispose?.().catch(()=>{}),r&&console.log(" Found More button by text (near profile actions)")}if(r)try{if(await e.evaluate(f=>f.scrollIntoView({behavior:"smooth",block:"center"}),r),await k(500),await e.evaluate(f=>f.click(),r),await k(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 f=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let w of m){let g=w.querySelector('a[href*="custom-invite"]');if(g)return g;for(let b of w.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(b.innerText?.trim()==="Connect")return b}return null});u=f?.asElement?.()||null,u||await f?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let d=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let w of f)for(let g of w.querySelectorAll('[role="menuitem"], a, div')){let b=g.innerText?.trim();b&&b.length<40&&m.push(b)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(d)}`),await e.keyboard.press("Escape"),d.some(f=>/remove (your )?connection/i.test(f)))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',d=(l||"").split(" ")[0].toLowerCase();for(let f of document.querySelectorAll("button[aria-label]")){if(f.closest(u))continue;let m=(f.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let w=f.getBoundingClientRect();if(!(w.width===0||w.height===0)){if(m.includes("invite")){if(d&&m.includes(d))return f;continue}if(m==="connect")return f}}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 On(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await k(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",r=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(r))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(r.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&&!r.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await k(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 k(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await k(3e3)):(await e.evaluate(u=>u.click(),t),await k(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 da(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 k(1500);let n=await Ct(e);if(n){await e.evaluate(s=>s.click(),n),await k(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await Qe(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Qe(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(r=>{let c=a=>!!(a&&a.querySelector(r));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),s=()=>e.evaluate(()=>{for(let r of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(r.innerText||""))return!0;return!1}),i=async()=>{let r=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(r)return r;let c=await e.evaluateHandle(a=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(a)||null,n);return r=c?.asElement?.()||null,r||await c?.dispose?.().catch(()=>{}),r};for(let r=0;r<2;r++){try{await t.evaluate(c=>c.click())}catch{}if(await k(3e3),await s())return!1;if(await o())return!0;if(r===0){let c=await i();if(!c)return await o();t=c,await k(600)}}return await o()}async function Nn(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:i=!1}=n;if(!s){let c=Xt();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 r=await ma(e,t,n);return r.connectionSent&&!i&&uo(t,o),r}async function ma(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:r=!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(`
|
|
239
|
-
--- Connecting: ${l} ---`),c.length>0){let y=J()[t]?.location;if(Ht(y,c))return console.log(` \u26A0 Excluded location (stored): ${y}`),a.reason="excluded_location",a.profileInfo={location:y},a}try{await tt(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 k(2e3),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await k(2e3),await Es(e,t),await k(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(tn(),wo)),{recordDiscoveredEdges:h}=await Promise.resolve().then(()=>(wt(),Co)),{detectCategoryFromTitle:p}=await Sn().then(()=>ss),{detectSectors:v}=await Promise.resolve().then(()=>(xs(),As)),C=S(t)||t,_=await y(e,{seedUrl:C}),A=_.map(I=>{let P=I.headline?p(I.headline):null;return{url:I.url,seedUrl:C,block:I.block,rank:I.rank,name:I.name,headline:I.headline,categories:P?[P]:[],sectors:v(I.headline||"")}});h(A),_.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"]),S=j=>{let L=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(L)},h={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},p=document.querySelector("main");if(!p)return h;let v=[...Array.from(p.querySelectorAll("h1")),...Array.from(p.querySelectorAll("h2"))],C=Array.from(p.querySelectorAll("h2")),_=v.find(j=>{let L=j.textContent&&j.textContent.trim();return L&&L.length>1&&L.length<100&&!y.has(L)&&L!=="0 notifications"}),A=_?_.textContent.trim():null,I=_?_.parentElement:null;for(;I&&I!==p&&!Array.from(I.children).filter(U=>U.tagName==="P").some(U=>{let q=U.textContent&&U.textContent.trim();return q&&q.length>5&&!S(q)});)I=I.parentElement;let P=null,G=null,$=null;if(I&&I!==p){let j=Array.from(I.children),L=j.filter(q=>q.tagName==="P").filter(q=>{let ae=q.textContent&&q.textContent.trim();return ae&&ae.length>5&&!S(ae)});L[0]&&(P=L[0].textContent.trim()),L[1]&&(G=L[1].textContent.trim());let U=j.filter(q=>q.tagName==="DIV");for(let q=U.length-1;q>=0;q--){let ae=U[q].textContent&&U[q].textContent.trim();if(ae&&!(A&&ae.startsWith(A))&&($=ae.split(/[·•]/)[0].trim(),$))break}}let x=null;if(I){let j=I.querySelectorAll("p, span, div");for(let L of j){let U=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(U==="1st"||U==="2nd"||U==="3rd"){x=U;break}}}let T=null,O=C.find(j=>j.textContent&&j.textContent.trim()==="About");if(O){let j=O.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(T=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,T&&(T=T.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let H=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),re=H&&H.src||null,ie=!!p.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:A,title:P,location:$,about:T,company:G,connectionDegree:x,connectionsCount:null,mutualConnections:null,photoUrl:re,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,S=J()[t]?.location,h=y||S;if(Ht(h,c))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${h}`),a.reason="excluded_location",a;!y&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await Ce(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),a.reason="pending",a;await Ae(e);let f=await Ct(e);if(f||await Ae(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await k(2e3),f=await Ct(e)),f&&f.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),a.reason="connected",a;if(!f){let y=await Ce(e,{detail:!0});return r&&(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=f.method;let m=await On(e,f.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),a.reason="wrong_target",a;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(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 k(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(p=>p.scrollIntoView({behavior:"smooth",block:"center"}),S),await k(500),await S.click().catch(()=>e.evaluate(p=>p.click(),S)),await k(2e3);let h=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(h){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),h),await k(3e3);let p=e.url();if(p.includes("/premium/")||p.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(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 k(500),a.reason="premium_required",a}catch(h){return console.log(" More dropdown failed:",h.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 S of y){let h=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!h)continue;let p=(h.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(p)||h.querySelector('input[type="email"], input[name="email"]'))return!0;let v=h.querySelector('button[aria-label="Send without a note"]');if(v&&(v.disabled||v.getAttribute("aria-disabled")==="true"||(v.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 k(500),a.reason="email_required",a}let g=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!g&&!b){let y=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let h=S.querySelector('button[aria-label="Add a note"]'),p=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!h,sendWithout:!!p}});if(y.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));g=S?.asElement?.()||null,g||await S.dispose().catch(()=>{})}if(y.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=S?.asElement?.()||null,b||await S.dispose().catch(()=>{})}}if(s)if(g&&o){if(console.log(" Adding personalized note..."),await g.click(),await k(1500),await e.$("div.modal-upsell")){let h=await da(e);return a.success=h,a.connectionSent=h,a.reason=h?"sent_without_note_upsell":"upsell_failed",a.withCustomMessage=!1,a}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let h=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),p=o.replace("{name}",h);await S.type(p,{delay:20}),await k(500);let v=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(v)return await Qe(e,v)?(console.log(" \u2713 Connection sent (with note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_with_note",a.withCustomMessage=!0,a.messageSent=p,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{if(b)return console.log(" Sending without note..."),await Qe(e,b)?(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(g&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await Qe(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=b;if(y)return await Qe(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(f.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(4e3)),await Ae(e),await k(500);let S=await e.$$('button[id*="profile-overflow-action"]'),h=null;for(let p of S){let v=await e.evaluate(C=>{let _=C.getBoundingClientRect();return{visible:_.width>0&&_.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},p);if(v.visible&&!v.inSticky){h=p;break}}!h&&S.length>0&&(h=S[S.length-1]);for(let p of S)p!==h&&await p.dispose().catch(()=>{});if(h)try{await e.evaluate(v=>v.scrollIntoView({behavior:"smooth",block:"center"}),h),await k(500),await h.click().catch(()=>e.evaluate(v=>v.click(),h)),await k(2e3);let p=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(p){console.log(" Found Connect in More dropdown, clicking..."),a.method="more_dropdown",await e.evaluate(A=>A.click(),p),await k(3e3);let v=e.url();if(v.includes("/premium/")||v.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(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 Qe(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(p){console.log(" More dropdown fallback failed:",p.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 k(1e3)}catch{a.fatal=!0}return a}}async function _s(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:r=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:a=null,excludeLocations:l=[],source:u="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
240
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${r?"View Only":`Connect (max ${i})`}`),r||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),l.length>0&&console.log(`Excluding locations: ${l.join(", ")}`),!r){let m=
|
|
240
|
+
`});var Rs={};ue(Rs,{DEFAULT_PROFILE_INTERESTS:()=>Ts,computeFit:()=>ha,detectSectors:()=>pa});function pa(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,s]of Object.entries(ma))s.some(i=>i.test(t))&&n.push(o);return n}function ha(e,t=Ts){if(!Array.isArray(e)||e.length===0)return 0;let n=i=>typeof i=="number"&&Number.isFinite(i)?i:0,o=Math.max(1,...Object.values(t||{}).map(n)),s=0;for(let i of e){let r=n(t&&t[i]);r>s&&(s=r)}return Math.min(1,s/o)}var ma,Ts,Is=ce(()=>{ma={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/]};Ts={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});var Ns={};ue(Ns,{clickConnectButton:()=>jn,default:()=>wa,detectConnectionStatus:()=>Ce,findConnectButton:()=>At,runFunnel:()=>Os,sendConnectionRequest:()=>Ln,shouldExcludeLocation:()=>Wt,viewProfile:()=>Pn});async function Ds(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 k(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Wt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Pn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:i=!1,extractSkills:r=!1,extractRecommendations:c=!1,extractCertifications:a=!1}=n;try{await nt(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await k(1500),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await k(1500),await Ds(e,t));let u=0;for(let p=0;p<2;p++){let v=await e.evaluate(()=>document.body.scrollHeight);for(let _=1;_<=6;_++)await e.evaluate(A=>window.scrollTo(0,A),v*_/6),await k(900);let C=await e.evaluate(()=>document.body.scrollHeight);if(C===u)break;u=C}await k(800);let f=null;try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(f=p.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let p=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"]),v=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=R=>{let D=(R||"").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:[]},A=document.querySelector("main");if(!A)return _;let I=[...Array.from(A.querySelectorAll("h1")),...Array.from(A.querySelectorAll("h2"))],P=Array.from(A.querySelectorAll("h2")),z=I.find(R=>{let D=R.textContent&&R.textContent.trim(),N=(D||"").replace(/\s*\(\d+\)$/,"").trim();return D&&D.length>1&&D.length<100&&!p.has(N)&&!v.has(N)}),$=z?z.textContent.trim():null,E=z?z.parentElement:null;for(;E&&E!==A&&!Array.from(E.children).filter(D=>D.tagName==="P").some(D=>{let N=D.textContent&&D.textContent.trim();return N&&N.length>5&&!C(N)});)E=E.parentElement;let T=null,O=null,H=null,ie=null;if(E&&E!==A){let R=Array.from(E.children).filter(N=>N.tagName==="P").filter(N=>{let ye=N.textContent&&N.textContent.trim();return ye&&ye.length>5&&!C(ye)});if(R[0]&&(T=R[0].textContent.trim()),R[1]){let N=R[1].textContent.trim().split(/\s*[·•]\s*/);O=N[0]||null,N.length>1&&(H=N.slice(1).join(" \xB7 "))}let D=Array.from(E.children).filter(N=>N.tagName==="DIV");for(let N=D.length-1;N>=0;N--){let ye=D[N].textContent&&D[N].textContent.trim();if(ye&&!($&&ye.startsWith($))&&(ie=ye.split(/[·•]/)[0].trim(),ie))break}}let ae=null;if(E){let R=E.querySelectorAll("p, span, div");for(let D of R){let N=(D.textContent||"").trim().replace(/^[·•]\s*/,"");if(N==="1st"||N==="2nd"||N==="3rd"){ae=N;break}}}let j=!!A.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),L=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),U=L&&L.src||null,q=A.textContent||"",le=null,Jn=q.match(/(\d+\+?)\s+connections\b/i);Jn&&(le=Jn[1]+" connections");let xt=null,Vn=q.match(/(\d+)\s+mutual connection/i),Wn=q.match(/and\s+(\d+)\s+other mutual/i),Hs=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Vn?xt=parseInt(Vn[1],10):Wn?xt=2+parseInt(Wn[1],10):Hs&&(xt=2);let Yn=null,Gn=null,zn=P.find(R=>R.textContent&&R.textContent.trim()==="About");if(zn){let R=zn.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").trim();D=D.replace(/^About\s*/,"").trim();let N=D.match(/Top skills\s*(.+?)$/i);if(N){let Gt=N[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Ys=>Ys.trim()).filter(Boolean);Gt.length>0&&Gt.length<10&&(Gn=Gt)}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(),Yn=D||null}}let Kn=null,Qn=P.find(R=>R.textContent&&R.textContent.trim()==="Activity");if(Qn){let R=Qn.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);D&&(Kn=parseInt(D[1].replace(/,/g,""),10))}}let Js=[...new Set(P.map(R=>(R.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(R=>R&&R.length>1&&R.length<60&&R!==$).filter(R=>p.has(R)))],Ze=document.body.textContent||"",Vs=/#OpenToWork\b/i.test(Ze)||/\bOpen to work\b/.test(Ze),Ws=/#Hiring\b/i.test(Ze)||/\bI'?m hiring\b/i.test(Ze)||/\bWe are hiring\b/i.test(Ze);return{name:$,title:T,location:ie,currentCompany:O,currentSchool:H,connectionDegree:ae,hasVerifiedBadge:j,photoUrl:U,connectionsLevel:le,mutualConnectionsCount:xt,followers:Kn,openToWork:Vs,hiring:Ws,about:Yn,topSkills:Gn,availableSections:Js}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,w=null,h=null,b=null,y=null,S=null;if(o||s||i||r||c||a){let p=await Promise.resolve().then(()=>(_s(),xs));o&&(m=await p.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),s&&(w=await p.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${w.length} entries`)),i&&(h=await p.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),r&&(b=await p.extractSkillsFromDetails(e,t),console.log(` + Skills: ${b.length} entries`)),c&&(y=await p.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),a&&(S=await p.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...m!==null&&{experience:m},...w!==null&&{featured:w},...h!==null&&{education:h},...b!==null&&{skillsFull:b},...y!==null&&{recommendations:y},...S!==null&&{certifications:S}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await k(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 s='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=f=>f&&!f.closest(s),r=f=>Array.from(document.querySelectorAll(f)).filter(i),c=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,l=r('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 k(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function At(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"]'),m=f.toLowerCase().split(" ")[0],w='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let b=h.getBoundingClientRect();if(b.width===0||b.height===0||h.closest(w))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(m))return h}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 m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),w=document.querySelectorAll("button[aria-label]");return Array.from(w).filter(b=>{let y=b.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&m.test(y)}).map(b=>b.getAttribute("aria-label")?.slice(0,50))},l);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let m=document.querySelectorAll("button[aria-label]"),w='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',h=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let b of m){if(b.closest(w))continue;let y=b.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&h.test(y))return b}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 s=n?n.split(" ")[0].toLowerCase():"",i=null;for(let l of o){let u=await e.evaluate((f,d)=>{let m=f.className.includes("muted"),w=f.className.includes("sticky-header")||f.className.includes("sticky"),h=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,b=(f.getAttribute("aria-label")||"").toLowerCase(),y=b.includes("invite"),S=d?b.includes(d):!0;return{isMuted:m,isStickyHeader:w,inRecommendations:h,hasInvite:y,matchesName:S,ariaLabel:b}},l,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=l;break}}for(let l of o)l!==i&&await l.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let r=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let l of c){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),m=d.width>0&&d.height>0,w=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:w,top:d.top}},l);if(u.isVisible&&!u.isInStickyHeader){r=l,console.log(" Found More button by ID pattern (main)");break}}for(let l of c)l!==r&&await l.dispose().catch(()=>{});if(!r&&c.length>0&&(r=c[c.length-1],console.log(" Found More button by ID pattern (last)")),r||(r=await e.$('button[aria-label="More actions"]'),r&&console.log(" Found More button by aria-label")),!r){let l=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(m=>{let w=m.innerText?.trim(),h=m.getAttribute("aria-label")||"",b=m.getBoundingClientRect();return b.top<100||b.top>600||b.width===0?!1:w==="Follow"||w==="Message"||w==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let m=0;m<8&&d;m++){for(let w of d.querySelectorAll("button"))if(w.innerText?.trim()==="More"&&w!==f)return w;d=d.parentElement}return null});r=l?.asElement?.()||null,r||await l?.dispose?.().catch(()=>{}),r&&console.log(" Found More button by text (near profile actions)")}if(r)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),r),await k(500),await e.evaluate(d=>d.click(),r),await k(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 m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let w of m){let h=w.querySelector('a[href*="custom-invite"]');if(h)return h;for(let b of w.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(b.innerText?.trim()==="Connect")return b}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'),m=[];for(let w of d)for(let h of w.querySelectorAll('[role="menuitem"], a, div')){let b=h.innerText?.trim();b&&b.length<40&&m.push(b)}return[...new Set(m)].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 m=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let w=d.getBoundingClientRect();if(!(w.width===0||w.height===0)){if(m.includes("invite")){if(f&&m.includes(f))return d;continue}if(m==="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 jn(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await k(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",r=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(r))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(r.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&&!r.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(s){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 k(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 k(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await k(3e3)):(await e.evaluate(u=>u.click(),t),await k(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 ga(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 k(1500);let n=await At(e);if(n){await e.evaluate(s=>s.click(),n),await k(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await Qe(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Qe(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(r=>{let c=a=>!!(a&&a.querySelector(r));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),s=()=>e.evaluate(()=>{for(let r of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(r.innerText||""))return!0;return!1}),i=async()=>{let r=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(r)return r;let c=await e.evaluateHandle(a=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(a)||null,n);return r=c?.asElement?.()||null,r||await c?.dispose?.().catch(()=>{}),r};for(let r=0;r<2;r++){try{await t.evaluate(c=>c.click())}catch{}if(await k(3e3),await s())return!1;if(await o())return!0;if(r===0){let c=await i();if(!c)return await o();t=c,await k(600)}}return await o()}async function Ln(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:i=!1}=n;if(!s){let c=nn();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 r=await ya(e,t,n);return r.connectionSent&&!i&&Co(t,o),r}async function ya(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:r=!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=J()[t]?.location;if(Wt(y,c))return console.log(` \u26A0 Excluded location (stored): ${y}`),a.reason="excluded_location",a.profileInfo={location:y},a}try{await nt(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 k(2e3),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await k(2e3),await Ds(e,t),await k(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(rn(),Io)),{recordDiscoveredEdges:g}=await Promise.resolve().then(()=>(bt(),jo)),{detectCategoryFromTitle:p}=await Cn().then(()=>cs),{detectSectors:v}=await Promise.resolve().then(()=>(Is(),Rs)),C=S(t)||t,_=await y(e,{seedUrl:C}),A=_.map(I=>{let P=I.headline?p(I.headline):null;return{url:I.url,seedUrl:C,block:I.block,rank:I.rank,name:I.name,headline:I.headline,categories:P?[P]:[],sectors:v(I.headline||"")}});g(A),_.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"]),S=j=>{let L=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(L)},g={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},p=document.querySelector("main");if(!p)return g;let v=[...Array.from(p.querySelectorAll("h1")),...Array.from(p.querySelectorAll("h2"))],C=Array.from(p.querySelectorAll("h2")),_=v.find(j=>{let L=j.textContent&&j.textContent.trim();return L&&L.length>1&&L.length<100&&!y.has(L)&&L!=="0 notifications"}),A=_?_.textContent.trim():null,I=_?_.parentElement:null;for(;I&&I!==p&&!Array.from(I.children).filter(U=>U.tagName==="P").some(U=>{let q=U.textContent&&U.textContent.trim();return q&&q.length>5&&!S(q)});)I=I.parentElement;let P=null,z=null,$=null;if(I&&I!==p){let j=Array.from(I.children),L=j.filter(q=>q.tagName==="P").filter(q=>{let le=q.textContent&&q.textContent.trim();return le&&le.length>5&&!S(le)});L[0]&&(P=L[0].textContent.trim()),L[1]&&(z=L[1].textContent.trim());let U=j.filter(q=>q.tagName==="DIV");for(let q=U.length-1;q>=0;q--){let le=U[q].textContent&&U[q].textContent.trim();if(le&&!(A&&le.startsWith(A))&&($=le.split(/[·•]/)[0].trim(),$))break}}let E=null;if(I){let j=I.querySelectorAll("p, span, div");for(let L of j){let U=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(U==="1st"||U==="2nd"||U==="3rd"){E=U;break}}}let T=null,O=C.find(j=>j.textContent&&j.textContent.trim()==="About");if(O){let j=O.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(T=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,T&&(T=T.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let H=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),ie=H&&H.src||null,ae=!!p.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:A,title:P,location:$,about:T,company:z,connectionDegree:E,connectionsCount:null,mutualConnections:null,photoUrl:ie,hasVerifiedBadge:ae}});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,S=J()[t]?.location,g=y||S;if(Wt(g,c))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${g}`),a.reason="excluded_location",a;!y&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await Ce(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),a.reason="pending",a;await Ae(e);let d=await At(e);if(d||await Ae(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await k(2e3),d=await At(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 r&&(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 m=await jn(e,d.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),a.reason="wrong_target",a;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(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 k(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(p=>p.scrollIntoView({behavior:"smooth",block:"center"}),S),await k(500),await S.click().catch(()=>e.evaluate(p=>p.click(),S)),await k(2e3);let g=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(g){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),g),await k(3e3);let p=e.url();if(p.includes("/premium/")||p.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(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 k(500),a.reason="premium_required",a}catch(g){return console.log(" More dropdown failed:",g.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 S of y){let g=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!g)continue;let p=(g.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(p)||g.querySelector('input[type="email"], input[name="email"]'))return!0;let v=g.querySelector('button[aria-label="Send without a note"]');if(v&&(v.disabled||v.getAttribute("aria-disabled")==="true"||(v.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 k(500),a.reason="email_required",a}let h=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!h&&!b){let y=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let g=S.querySelector('button[aria-label="Add a note"]'),p=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!g,sendWithout:!!p}});if(y.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=S?.asElement?.()||null,h||await S.dispose().catch(()=>{})}if(y.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=S?.asElement?.()||null,b||await S.dispose().catch(()=>{})}}if(s)if(h&&o){if(console.log(" Adding personalized note..."),await h.click(),await k(1500),await e.$("div.modal-upsell")){let g=await ga(e);return a.success=g,a.connectionSent=g,a.reason=g?"sent_without_note_upsell":"upsell_failed",a.withCustomMessage=!1,a}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let g=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),p=o.replace("{name}",g);await S.type(p,{delay:20}),await k(500);let v=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(v)return await Qe(e,v)?(console.log(" \u2713 Connection sent (with note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_with_note",a.withCustomMessage=!0,a.messageSent=p,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{if(b)return console.log(" Sending without note..."),await Qe(e,b)?(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(h&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await Qe(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=b;if(y)return await Qe(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 k(4e3)),await Ae(e),await k(500);let S=await e.$$('button[id*="profile-overflow-action"]'),g=null;for(let p of S){let v=await e.evaluate(C=>{let _=C.getBoundingClientRect();return{visible:_.width>0&&_.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},p);if(v.visible&&!v.inSticky){g=p;break}}!g&&S.length>0&&(g=S[S.length-1]);for(let p of S)p!==g&&await p.dispose().catch(()=>{});if(g)try{await e.evaluate(v=>v.scrollIntoView({behavior:"smooth",block:"center"}),g),await k(500),await g.click().catch(()=>e.evaluate(v=>v.click(),g)),await k(2e3);let p=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(p){console.log(" Found Connect in More dropdown, clicking..."),a.method="more_dropdown",await e.evaluate(A=>A.click(),p),await k(3e3);let v=e.url();if(v.includes("/premium/")||v.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(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 Qe(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(p){console.log(" More dropdown fallback failed:",p.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 k(1e3)}catch{a.fatal=!0}return a}}async function Os(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:r=!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: ${r?"View Only":`Connect (max ${i})`}`),r||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),l.length>0&&console.log(`Excluding locations: ${l.join(", ")}`),!r){let m=ut();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let d=0;for(let m=0;m<t.length;m++){let w=t[m];try{if(e.isClosed()){console.log(`
|
|
241
243
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
242
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!w.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let
|
|
243
|
-
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),
|
|
244
|
-
\u26A0 ${
|
|
245
|
-
=== Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!r){let m=ct();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return d}var pa,Rs=fe(async()=>{Le();await Je();pa={viewProfile:Dn,detectConnectionStatus:Ce,findConnectButton:Ct,clickConnectButton:On,sendConnectionRequest:Nn,runFunnel:_s,shouldExcludeLocation:Ht}});Le();await Je();wt();await Je();wt();var Er=new Set(["java","c#",".net","scala","python","typescript","javascript","react","node.js","aws","azure","docker","kubernetes","microservices","graphql","rest","sql","postgresql","mongodb","kafka","redis","ci/cd","terraform","spring"]),_r=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Ao=["vancouver","british columbia"],Tr=["canada","montreal","quebec","alberta","calgary","ottawa"],Rr=["toronto","ontario"],Ir=["india","pakistan","nigeria","philippines"];function Dr(e,t={}){let n=0,o=(e.techStack||[]).map(u=>u.toLowerCase()),s=0,i=0;for(let u of o)Er.has(u)&&s++,_r.has(u)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let u=Or(e.salary);u&&(u>=15e4?n+=20:u>=12e4?n+=15:u>=1e5?n+=10:u>=8e4?n+=5:u>=100&&u<1e3?n+=15:u>=70&&u<1e3&&(n+=10))}let r=(e.location||"").toLowerCase(),c=/remote/i.test(r)||e.workplaceType==="remote";Ir.some(u=>r.includes(u))?n-=30:c&&/united states|usa|\bus\b/i.test(r)?n+=25:c&&Ao.some(u=>r.includes(u))?n+=22:c?n+=20:Ao.some(u=>r.includes(u))?n+=18:Tr.some(u=>r.includes(u))?n+=10:Rr.some(u=>r.includes(u))&&(n+=5),e.isEasyApply&&(n+=5);let a=(e.seniority||"").toLowerCase();a.includes("senior")||a.includes("lead")||a.includes("staff")?n+=10:a.includes("mid")?n+=5:(a.includes("entry")||a.includes("intern"))&&(n-=10),e.recruiterUrl&&(t.conversationRecruiters?.has(e.recruiterUrl)?n+=20:t.connectedRecruiters?.has(e.recruiterUrl)?n+=15:n+=3);let l=new Set(e.jobTags||[]);return l.has("managerial")?n+=8:l.has("senior-ic")&&(n+=5),l.has("junior")&&(n-=15),l.has("consultant")&&(n-=3),Math.max(0,Math.min(100,n))}function xo(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=gt(),s=J(),i=new Set,r=new Set;for(let[d,f]of Object.entries(s))f.connectionStatus==="connected"&&i.add(d);let c={connectedRecruiters:i,conversationRecruiters:r},a=ht(),l=new Set(["applied","skipped","expired","archived"]);return Object.entries(o).filter(([d,f])=>{if(typeof f!="object"||n&&!f.isEasyApply||f.applied)return!1;let m=a[d];return!(m&&l.has(m.status))}).map(([d,f])=>({jobId:d,score:Dr(f,c),job:f})).sort((d,f)=>{if(f.score!==d.score)return f.score-d.score;let m=d.job.scoutedAt||d.job.postedTime||"";return(f.job.scoutedAt||f.job.postedTime||"").localeCompare(m)}).slice(0,e)}function Or(e){if(!e)return null;let t=e.match(/[\$£€CAD\s]*([\d,]+(?:\.\d+)?)\s*[kK]?/g);if(!t||t.length===0)return null;let n=t.map(o=>{let s=parseFloat(o.replace(/[^\d.]/g,""));return o.toLowerCase().includes("k")&&(s*=1e3),s}).filter(o=>o>0);return n.length>=2?(n[0]+n[1])/2:n.length===1?n[0]:null}await ot();import Hr from"puppeteer";import{addExtra as Jr}from"puppeteer-extra";import Vr from"puppeteer-extra-plugin-stealth";Le();await ot();import ce from"fs";import Se from"path";var Nr="cookies.json";function Eo(){let e=process.env.ILML_SCOPE_DIR;return e?Se.join(e,"plugins-state","linkedin","cookies.json"):Nr}function Ot(){let e=Eo();if(!ce.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=ce.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 _o(){return ce.existsSync(Eo())}function Mr(){let e=process.env.ILML_SCOPE_DIR;return e?Se.join(e,"plugins-state","linkedin"):"."}function To(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Pr(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?To(t[1]):"default"}function Ro(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return ce.existsSync(t)||ce.mkdirSync(t,{recursive:!0}),Se.resolve(t);let n=To(e||Pr()),o=Se.join(Mr(),"chrome-profile",n);return ce.existsSync(o)||ce.mkdirSync(o,{recursive:!0}),Se.resolve(o)}var Io=".ilml-seeded";function Do(e){return!ce.existsSync(Se.join(e,Io))}function Oo(e){try{ce.writeFileSync(Se.join(e,Io),new Date().toISOString())}catch{}}function No(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{ce.rmSync(Se.join(e,n),{force:!0}),t++}catch{}return t}import ln from"fs";import jr from"path";var Lr={headless:!1,defaultViewport:null,protocolTimeout:3e5},St=new Set,Mo=!1;async function Nt(){let e=[...St].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});St.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Fr(){if(Mo)return;Mo=!0;let e=t=>async()=>{await Nt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Nt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Nt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Nt(),process.exit(0))}),process.on("exit",()=>{for(let t of St)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function cn(e){return jr.join(e,".ilml-browser-session.json")}function Fo(e,t={}){try{ln.writeFileSync(cn(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Ur(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Fo(e,n?{wsEndpoint:n}:{})}catch{}}function qr(e){let t=Uo(e);t&&t.ownerPid===process.pid&&bt(e)}function bt(e){try{ln.rmSync(cn(e),{force:!0})}catch{}}function Uo(e){try{return JSON.parse(ln.readFileSync(cn(e),"utf-8"))}catch{return null}}function Po(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function jo(e,t,n){let o,s=new Promise(r=>{o=setTimeout(()=>r(n),t)}),i=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([i,s])}async function Lo(e,t,{probeTimeoutMs:n=4e3}={}){let o=Uo(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Po(o.ownerPid)?"live":(bt(t),"free");let s=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await jo(i,n,s);if(r===s)return i.then(a=>{if(a)try{a.disconnect()}catch{}}),"live";if(!r)return bt(t),"free";if(Po(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await jo(r.close().then(()=>!0).catch(()=>!1),n,!1))return bt(t),"free";try{r.disconnect()}catch{}return"live"}function Br(e,t){e&&(Fr(),St.add(e),e.on("disconnected",()=>{St.delete(e),t&&bt(t)}))}async function qo(e,t={}){let n=Ro(),o={...Lr,...t,userDataDir:n},s=`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 Lo(e,n)==="live")throw new Error(s);Fo(n);let i;try{i=await e.launch(o)}catch{if(await Lo(e,n)==="live")throw new Error(s);No(n);try{i=await e.launch(o)}catch(c){throw qr(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 Br(i,n),Ur(n,i),{browser:i,profileDir:n,needsSeed:Do(n)}}async function Bo(e,t){if(!t||!t.needsSeed)return!1;if(!_o())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(...Ot()),Oo(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Vo=Jr(Hr);Vo.use(Vr());async function Wo(){let{browser:e,profileDir:t,needsSeed:n}=await qo(Vo),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Bo(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}async function un(e){await tt(e,"https://www.linkedin.com/messaging/",{readySelector:".msg-conversations-container__conversations-list, .msg-conversation-listitem",label:"inbox"})||(console.warn(" Inbox container not found via known selectors, proceeding..."),await k(3e3)),console.log(" Inbox loaded.")}async function Yo(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let r=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!r)continue;let a=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(a)||/^\s*Promoted\b/i.test(a))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",d=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,f,m;if(a.startsWith("You:"))f="me",m=a.slice(4).trim();else{let g=r.split(" ")[0];if(a.startsWith(r+":")||a.startsWith(g+":")){f="them";let b=a.indexOf(":");m=a.slice(b+1).trim()}else f="them",m=a}let w=s.getBoundingClientRect();o.push({name:r,lastMessagePreview:m,lastMessageTime:u,unread:d,lastMessageBy:f,x:w.x+w.width/2,y:w.y+w.height/2})}return o});for(let n of t)n.lastMessageTime=Yt(n.lastMessageTime)||n.lastMessageTime;return t}async function fn(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function Wr(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of n){let i=document.querySelector(s);if(i){let r=i.textContent?.trim()?.replace(/\s+/g," ");if(r&&r.length>1&&r.length<100&&!t.test(r))return r}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let i=s.textContent?.trim();if(i&&i.length>1&&i.length<100&&!/conversation/i.test(i)&&!t.test(i))return i}return null})}async function dn(e){return e.evaluate(()=>{let t=[".msg-thread__link-to-profile",'.msg-entity-lockup__entity-title a[href*="/in/"]','.msg-s-message-list-container a[href*="/in/"]','.msg-thread a[href*="/in/"]','.msg-conversations-container__title-row a[href*="/in/"]','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header a[href*="/in/"]','.msg-overlay-conversation-bubble a[href*="/in/"]'];for(let n of t){let o=document.querySelector(n);if(o){let s=o.getAttribute("href")||"";if(s&&s.includes("/in/"))return s.startsWith("/")&&(s="https://www.linkedin.com"+s),s=s.replace(/\/$/,"").split("?")[0],s}}return null})}async function Ho(e,t){let n=await Wr(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(c=>c.length>1),i=n.toLowerCase();return{match:i.includes(o)||s.some(c=>i.includes(c)),headerName:n}}async function Mt(e,t){let n=t.split(" ")[0],o=8e3,s=500,i=0;for(;i<o;){let{match:a,headerName:l}=await Ho(e,t);if(a)return await k(500),{verified:!0,headerName:l};let u=await e.evaluate(()=>{let d=document.querySelectorAll(".msg-s-message-group__name"),f=Array.from(d).map(w=>w.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:f,msgCount:m}});if(u.msgCount>0&&u.allSenders.some(f=>f.toLowerCase().includes(n.toLowerCase())))return await k(300),{verified:!0,headerName:n};await k(s),i+=s}let{match:r,headerName:c}=await Ho(e,t);return r?{verified:!0,headerName:c}:{verified:!1,headerName:c}}async function Yr(e){let n=0,o=0;for(let s=0;s<50;s++){let i=await e.evaluate(()=>{let r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let l=document.querySelector(".msg-overlay-conversation-bubble");l&&(r=l.querySelector(".msg-s-message-list-container")||l.querySelector(".msg-s-message-list"))}if(!r)return{found:!1};let c=r.querySelectorAll("li.msg-s-message-list__event").length;return r.scrollTop<=1?{found:!0,atTop:!0,msgCount:c}:(r.scrollTop=0,{found:!0,atTop:!1,msgCount:c})});if(!i.found||i.atTop)break;if(await k(800),i.msgCount===n){if(o++,o>=3)break}else o=0;n=i.msgCount}}async function mn(e,{scrollUp:t=!0}={}){t&&await Yr(e);let n=await e.evaluate(()=>{let o=[],s="",i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(i=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!i)return o;let r=i.querySelectorAll("li.msg-s-message-list__event");if(r.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(r=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function c(u){let d=u.getAttribute("data-event-urn");if(!d)return null;let f=d.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!f)return null;try{let w=atob(f[1]).match(/^(\d{13})/);if(!w)return null;let g=Number(w[1]);if(g>14200704e5&&g<20512224e5)return g}catch{}return null}let a="";function l(u,d,f){let m=c(u),g=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",b=u.querySelector(".msg-s-event-listitem__message-bubble");if(!b)return null;let y=b.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!y)return null;let S=m?new Date(m).toISOString():f?`${f} ${g}`.trim():g;return{sender:d,text:y,time:S}}for(let u of r){let d=u.querySelector("time.msg-s-message-list__time-heading");d&&(a=d.textContent?.trim()||a);let f=u.querySelectorAll(".msg-s-message-group");if(f.length>0)for(let m of f){let w=m.querySelector(".msg-s-message-group__name");w&&(s=w.textContent?.trim()||s);let g=s||"Unknown",b=m.querySelectorAll(".msg-s-event-listitem");for(let y of b){let S=l(y,g,a);S&&o.push(S)}}else{let m=u.querySelectorAll(".msg-s-event-listitem");for(let w of m){let g=w.querySelector(".msg-s-message-group__name");g&&(s=g.textContent?.trim()||s);let y=l(w,s||"Unknown",a);y&&o.push(y)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let d of u){let f=d.textContent?.trim();f&&o.push({sender:"",text:f,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=Yt(o.time)||o.time);return n}function pn(e,t,n){if(e.length===0)return!0;let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),i=[...new Set(e.map(l=>l.sender).filter(l=>l&&l!=="Unknown"))],r=i.some(l=>{let u=l.toLowerCase();return u.includes(o)||s.some(d=>u.includes(d))}),c=z.toLowerCase().split(/\s+/),a=i.every(l=>{let u=l.toLowerCase();return c.some(d=>u.includes(d))});if(r)return!0;if(a){for(let l of e){let d=(l.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(d){let f=d[1].toLowerCase();if(f!=="there"&&f!=="all"&&!(s.some(w=>w===f)||f===o))return console.log(` STALE DATA: message says "Hi ${d[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let l=n.map(d=>d.toLowerCase());if(i.some(d=>{let f=d.toLowerCase();return l.some(m=>f.includes(m.split(" ")[0]))}))return console.log(` STALE DATA: messages belong to previous conversation (senders: ${i.join(", ")})`),!1}return console.log(` Sender warning: no match for "${t}" (found: ${i.join(", ")})`),!1}function Ye(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function gn(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=f=>Ye(f.sender)+"||"+Ye(f.text),o=new Set(t.map(n)),s=new Set(e.map(n)),i=e.filter(f=>Fe.has(f.status)?!1:!o.has(n(f))),r=t.filter(f=>!s.has(n(f))),c=t.filter(f=>s.has(n(f))),a=e.filter(f=>Fe.has(f.status)),l=[...i,...c,...r],u=[];for(let f of l){let m=Ye(f.text),w=Ye(f.sender),g=!1;for(let b=0;b<u.length;b++){let y=u[b];if(Ye(y.sender)!==w)continue;let S=Ye(y.text);if(m.length>S.length&&m.endsWith(S)){g=!0;break}if(S.length>m.length&&S.endsWith(m)){u[b]=f,g=!0;break}}g||u.push(f)}return[...u,...a]}async function Go(e,t){await un(e),await k(2500),await e.evaluate(()=>{let c=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let a of c){let l=document.querySelector(a);if(l){l.scrollTop=0;return}}}),await k(500);async function n(){return e.evaluate(c=>{let a=document.querySelectorAll(".msg-conversation-listitem");for(let l of a)if(l.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===c){let f=l.getBoundingClientRect();if(f.height>0)return{x:f.x+f.width/2,y:f.y+f.height/2}}return null},t)}let o=await n(),s=50,i=-1,r=0;for(let c=0;c<s&&!o;c++){let a=await fn(e);if(!a)break;if(a.scrollTop===i){if(r++,r>=2)break}else r=0,i=a.scrollTop;await k(600),o=await n()}return o?(await e.mouse.click(o.x,o.y),await k(3e3),Mt(e,t)):{verified:!1,headerName:null}}async function hn(e,t){let n=await e.evaluate(r=>{let c=document.querySelectorAll(".msg-conversation-listitem");for(let a of c)if(a.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===r){let d=a.getBoundingClientRect();if(d.height>0)return{x:d.x+d.width/2,y:d.y+d.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await k(3e3);let r=await Mt(e,t);if(r.verified)return r}let o=zn(t),s=o!==t?[t,o]:[t];for(let r of s)if(await Jo(e,r,t)){let a=await Mt(e,t);if(a.verified)return a}let i=Kn(o);if(i!==o&&i.length>0&&await Jo(e,i,t,{requireUnique:!0})){let c=await Mt(e,t);if(c.verified)return c}return{verified:!1,headerName:null}}async function Jo(e,t,n,o={}){let{requireUnique:s=!1}=o,i=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!i)return!1;await i.click(),await k(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await k(300),await i.type(t,{delay:30}),await k(500),await e.keyboard.press("Enter"),await k(3500);let r=await e.evaluate((c,a)=>{let l=c.split(" ")[0].toLowerCase(),u=c.toLowerCase(),d=document.querySelectorAll(".msg-conversation-listitem"),f=[],m=[];for(let g of d){let y=g.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=y.toLowerCase();if(S.includes(l)){let h=g.getBoundingClientRect();if(h.height>0){let p=y.includes(",")||/\d+ other/.test(y),v=S===u?3:S.includes(u)?2:1,C={text:y,isGroup:p,score:v,x:h.x+h.width/2,y:h.y+h.height/2};p?m.push(C):f.push(C)}}}f.sort((g,b)=>b.score-g.score);let w=[...f,...m];return a&&w.length!==1?null:f[0]||m[0]||null},n,s);return r?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(r.x,r.y),!0):!1}async function ve(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await k(200),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await e.keyboard.press("Escape"),await k(1e3))}await Sn();import"dotenv/config";import*as ee from"fs";import*as ke from"path";import{fileURLToPath as ui}from"url";import"dotenv/config";import{createGraphClient as ri,resolveToken as ii}from"@ilivemylife/graph-sdk";import{config as ai}from"dotenv";ai();var rs=ii()||process.env.TOKEN;rs||(console.error(`
|
|
244
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!w.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let h=vo(w.profileUrl);if(h==="pending"||h==="connected"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${w.name||w.profileUrl} \u2014 skipped (db: ${h})`),h==="pending"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,a&&await a(w,f,{success:!1,reason:h,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${w.name||w.profileUrl}`);let b=null;if(r){let y=await Pn(e,w.profileUrl);y?(Te(w.profileUrl,{...y,source:u}),f.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(f.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let y=nn();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(b=await Ln(e,w.profileUrl,{message:o,useCustomMessage:s,excludeLocations:l,source:u,skipQuotaGate:!0}),b.success)f.connectionsSent++;else switch(b.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(b?.fatal){console.log(`
|
|
245
|
+
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(b?.reason==="error"){if(d++,d>=3){console.log(`
|
|
246
|
+
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(b&&b.reason&&(ko(w.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),b.resolvedUrl&&Dt(w.profileUrl,b.resolvedUrl),So(w.profileUrl,{source:u||"funnel",jobId:w.jobId||w.fromJob?.jobId||null,jobTitle:w.fromJob?.title||null,jobCompany:w.fromJob?.company||null,action:b.reason})),a&&await a(w,f,b),m<t.length-1){let y=c+Math.random()*2e3;await k(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}`),!r){let m=ut();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return f}var wa,Ms=ce(async()=>{Le();await Je();wa={viewProfile:Pn,detectConnectionStatus:Ce,findConnectButton:At,clickConnectButton:jn,sendConnectionRequest:Ln,runFunnel:Os,shouldExcludeLocation:Wt}});Le();await Je();bt();await Je();bt();var Nr=new Set(["java","c#",".net","scala","python","typescript","javascript","react","node.js","aws","azure","docker","kubernetes","microservices","graphql","rest","sql","postgresql","mongodb","kafka","redis","ci/cd","terraform","spring"]),Mr=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Lo=["vancouver","british columbia"],Pr=["canada","montreal","quebec","alberta","calgary","ottawa"],jr=["toronto","ontario"],Lr=["india","pakistan","nigeria","philippines"];function Fr(e,t={}){let n=0,o=(e.techStack||[]).map(u=>u.toLowerCase()),s=0,i=0;for(let u of o)Nr.has(u)&&s++,Mr.has(u)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let u=Ur(e.salary);u&&(u>=15e4?n+=20:u>=12e4?n+=15:u>=1e5?n+=10:u>=8e4?n+=5:u>=100&&u<1e3?n+=15:u>=70&&u<1e3&&(n+=10))}let r=(e.location||"").toLowerCase(),c=/remote/i.test(r)||e.workplaceType==="remote";Lr.some(u=>r.includes(u))?n-=30:c&&/united states|usa|\bus\b/i.test(r)?n+=25:c&&Lo.some(u=>r.includes(u))?n+=22:c?n+=20:Lo.some(u=>r.includes(u))?n+=18:Pr.some(u=>r.includes(u))?n+=10:jr.some(u=>r.includes(u))&&(n+=5),e.isEasyApply&&(n+=5);let a=(e.seniority||"").toLowerCase();a.includes("senior")||a.includes("lead")||a.includes("staff")?n+=10:a.includes("mid")?n+=5:(a.includes("entry")||a.includes("intern"))&&(n-=10),e.recruiterUrl&&(t.conversationRecruiters?.has(e.recruiterUrl)?n+=20:t.connectedRecruiters?.has(e.recruiterUrl)?n+=15:n+=3);let l=new Set(e.jobTags||[]);return l.has("managerial")?n+=8:l.has("senior-ic")&&(n+=5),l.has("junior")&&(n-=15),l.has("consultant")&&(n-=3),Math.max(0,Math.min(100,n))}function Fo(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=gt(),s=J(),i=new Set,r=new Set;for(let[f,d]of Object.entries(s))d.connectionStatus==="connected"&&i.add(f);let c={connectedRecruiters:i,conversationRecruiters:r},a=yt(),l=new Set(["applied","skipped","expired","archived"]);return Object.entries(o).filter(([f,d])=>{if(typeof d!="object"||n&&!d.isEasyApply||d.applied)return!1;let m=a[f];return!(m&&l.has(m.status))}).map(([f,d])=>({jobId:f,score:Fr(d,c),job:d})).sort((f,d)=>{if(d.score!==f.score)return d.score-f.score;let m=f.job.scoutedAt||f.job.postedTime||"";return(d.job.scoutedAt||d.job.postedTime||"").localeCompare(m)}).slice(0,e)}function Ur(e){if(!e)return null;let t=e.match(/[\$£€CAD\s]*([\d,]+(?:\.\d+)?)\s*[kK]?/g);if(!t||t.length===0)return null;let n=t.map(o=>{let s=parseFloat(o.replace(/[^\d.]/g,""));return o.toLowerCase().includes("k")&&(s*=1e3),s}).filter(o=>o>0);return n.length>=2?(n[0]+n[1])/2:n.length===1?n[0]:null}await st();import Yr from"puppeteer";import{addExtra as Gr}from"puppeteer-extra";import zr from"puppeteer-extra-plugin-stealth";Le();await st();et();et();import fn from"fs";import qr from"path";var Br={headless:!1,defaultViewport:null,protocolTimeout:3e5},vt=new Set,Uo=!1;async function jt(){let e=[...vt].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});vt.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Hr(){if(Uo)return;Uo=!0;let e=t=>async()=>{await jt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await jt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await jt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await jt(),process.exit(0))}),process.on("exit",()=>{for(let t of vt)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function mn(e){return qr.join(e,".ilml-browser-session.json")}function Jo(e,t={}){try{fn.writeFileSync(mn(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Jr(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Jo(e,n?{wsEndpoint:n}:{})}catch{}}function Vr(e){let t=Vo(e);t&&t.ownerPid===process.pid&&St(e)}function St(e){try{fn.rmSync(mn(e),{force:!0})}catch{}}function Vo(e){try{return JSON.parse(fn.readFileSync(mn(e),"utf-8"))}catch{return null}}function qo(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Bo(e,t,n){let o,s=new Promise(r=>{o=setTimeout(()=>r(n),t)}),i=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([i,s])}async function Ho(e,t,{probeTimeoutMs:n=4e3}={}){let o=Vo(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&qo(o.ownerPid)?"live":(St(t),"free");let s=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await Bo(i,n,s);if(r===s)return i.then(a=>{if(a)try{a.disconnect()}catch{}}),"live";if(!r)return St(t),"free";if(qo(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Bo(r.close().then(()=>!0).catch(()=>!1),n,!1))return St(t),"free";try{r.disconnect()}catch{}return"live"}function Wr(e,t){e&&(Hr(),vt.add(e),e.on("disconnected",()=>{vt.delete(e),t&&St(t)}))}async function Wo(e,t={}){let n=to(),o={...Br,...t,userDataDir:n},s=`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 Ho(e,n)==="live")throw new Error(s);Jo(n);let i;try{i=await e.launch(o)}catch{if(await Ho(e,n)==="live")throw new Error(s);ro(n);try{i=await e.launch(o)}catch(c){throw Vr(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 Wr(i,n),Jr(n,i),{browser:i,profileDir:n,needsSeed:oo(n)}}async function Yo(e,t){if(!t||!t.needsSeed)return!1;if(!Zn())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(..._t()),so(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Ko=Gr(Yr);Ko.use(zr());async function Qo(){let{browser:e,profileDir:t,needsSeed:n}=await Wo(Ko),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Yo(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}async function pn(e){await nt(e,"https://www.linkedin.com/messaging/",{readySelector:".msg-conversations-container__conversations-list, .msg-conversation-listitem",label:"inbox"})||(console.warn(" Inbox container not found via known selectors, proceeding..."),await k(3e3)),console.log(" Inbox loaded.")}async function Xo(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let r=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!r)continue;let a=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(a)||/^\s*Promoted\b/i.test(a))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",f=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,d,m;if(a.startsWith("You:"))d="me",m=a.slice(4).trim();else{let h=r.split(" ")[0];if(a.startsWith(r+":")||a.startsWith(h+":")){d="them";let b=a.indexOf(":");m=a.slice(b+1).trim()}else d="them",m=a}let w=s.getBoundingClientRect();o.push({name:r,lastMessagePreview:m,lastMessageTime:u,unread:f,lastMessageBy:d,x:w.x+w.width/2,y:w.y+w.height/2})}return o});for(let n of t)n.lastMessageTime=Xt(n.lastMessageTime)||n.lastMessageTime;return t}async function hn(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function Kr(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of n){let i=document.querySelector(s);if(i){let r=i.textContent?.trim()?.replace(/\s+/g," ");if(r&&r.length>1&&r.length<100&&!t.test(r))return r}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let i=s.textContent?.trim();if(i&&i.length>1&&i.length<100&&!/conversation/i.test(i)&&!t.test(i))return i}return null})}async function gn(e){return e.evaluate(()=>{let t=[".msg-thread__link-to-profile",'.msg-entity-lockup__entity-title a[href*="/in/"]','.msg-s-message-list-container a[href*="/in/"]','.msg-thread a[href*="/in/"]','.msg-conversations-container__title-row a[href*="/in/"]','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header a[href*="/in/"]','.msg-overlay-conversation-bubble a[href*="/in/"]'];for(let n of t){let o=document.querySelector(n);if(o){let s=o.getAttribute("href")||"";if(s&&s.includes("/in/"))return s.startsWith("/")&&(s="https://www.linkedin.com"+s),s=s.replace(/\/$/,"").split("?")[0],s}}return null})}async function Go(e,t){let n=await Kr(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(c=>c.length>1),i=n.toLowerCase();return{match:i.includes(o)||s.some(c=>i.includes(c)),headerName:n}}async function Lt(e,t){let n=t.split(" ")[0],o=8e3,s=500,i=0;for(;i<o;){let{match:a,headerName:l}=await Go(e,t);if(a)return await k(500),{verified:!0,headerName:l};let u=await e.evaluate(()=>{let f=document.querySelectorAll(".msg-s-message-group__name"),d=Array.from(f).map(w=>w.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:d,msgCount:m}});if(u.msgCount>0&&u.allSenders.some(d=>d.toLowerCase().includes(n.toLowerCase())))return await k(300),{verified:!0,headerName:n};await k(s),i+=s}let{match:r,headerName:c}=await Go(e,t);return r?{verified:!0,headerName:c}:{verified:!1,headerName:c}}async function Qr(e){let n=0,o=0;for(let s=0;s<50;s++){let i=await e.evaluate(()=>{let r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let l=document.querySelector(".msg-overlay-conversation-bubble");l&&(r=l.querySelector(".msg-s-message-list-container")||l.querySelector(".msg-s-message-list"))}if(!r)return{found:!1};let c=r.querySelectorAll("li.msg-s-message-list__event").length;return r.scrollTop<=1?{found:!0,atTop:!0,msgCount:c}:(r.scrollTop=0,{found:!0,atTop:!1,msgCount:c})});if(!i.found||i.atTop)break;if(await k(800),i.msgCount===n){if(o++,o>=3)break}else o=0;n=i.msgCount}}async function yn(e,{scrollUp:t=!0}={}){t&&await Qr(e);let n=await e.evaluate(()=>{let o=[],s="",i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(i=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!i)return o;let r=i.querySelectorAll("li.msg-s-message-list__event");if(r.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(r=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function c(u){let f=u.getAttribute("data-event-urn");if(!f)return null;let d=f.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!d)return null;try{let w=atob(d[1]).match(/^(\d{13})/);if(!w)return null;let h=Number(w[1]);if(h>14200704e5&&h<20512224e5)return h}catch{}return null}let a="";function l(u,f,d){let m=c(u),h=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",b=u.querySelector(".msg-s-event-listitem__message-bubble");if(!b)return null;let y=b.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!y)return null;let S=m?new Date(m).toISOString():d?`${d} ${h}`.trim():h;return{sender:f,text:y,time:S}}for(let u of r){let f=u.querySelector("time.msg-s-message-list__time-heading");f&&(a=f.textContent?.trim()||a);let d=u.querySelectorAll(".msg-s-message-group");if(d.length>0)for(let m of d){let w=m.querySelector(".msg-s-message-group__name");w&&(s=w.textContent?.trim()||s);let h=s||"Unknown",b=m.querySelectorAll(".msg-s-event-listitem");for(let y of b){let S=l(y,h,a);S&&o.push(S)}}else{let m=u.querySelectorAll(".msg-s-event-listitem");for(let w of m){let h=w.querySelector(".msg-s-message-group__name");h&&(s=h.textContent?.trim()||s);let y=l(w,s||"Unknown",a);y&&o.push(y)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let f of u){let d=f.textContent?.trim();d&&o.push({sender:"",text:d,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=Xt(o.time)||o.time);return n}function wn(e,t,n){if(e.length===0)return!0;let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),i=[...new Set(e.map(l=>l.sender).filter(l=>l&&l!=="Unknown"))],r=i.some(l=>{let u=l.toLowerCase();return u.includes(o)||s.some(f=>u.includes(f))}),c=K.toLowerCase().split(/\s+/),a=i.every(l=>{let u=l.toLowerCase();return c.some(f=>u.includes(f))});if(r)return!0;if(a){for(let l of e){let f=(l.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(f){let d=f[1].toLowerCase();if(d!=="there"&&d!=="all"&&!(s.some(w=>w===d)||d===o))return console.log(` STALE DATA: message says "Hi ${f[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let l=n.map(f=>f.toLowerCase());if(i.some(f=>{let d=f.toLowerCase();return l.some(m=>d.includes(m.split(" ")[0]))}))return console.log(` STALE DATA: messages belong to previous conversation (senders: ${i.join(", ")})`),!1}return console.log(` Sender warning: no match for "${t}" (found: ${i.join(", ")})`),!1}function Ye(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function bn(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=d=>Ye(d.sender)+"||"+Ye(d.text).replace(/\s+/g,""),o=new Set(t.map(n)),s=new Set(e.map(n)),i=e.filter(d=>Fe.has(d.status)?!1:!o.has(n(d))),r=t.filter(d=>!s.has(n(d))),c=t.filter(d=>s.has(n(d))),a=e.filter(d=>Fe.has(d.status)),l=[...i,...c,...r],u=[];for(let d of l){let m=Ye(d.text),w=Ye(d.sender),h=!1;for(let b=0;b<u.length;b++){let y=u[b];if(Ye(y.sender)!==w)continue;let S=Ye(y.text);if(m.length>S.length&&m.endsWith(S)){h=!0;break}if(S.length>m.length&&S.endsWith(m)){u[b]=d,h=!0;break}}h||u.push(d)}return[...u,...a]}async function Zo(e,t){await pn(e),await k(2500),await e.evaluate(()=>{let c=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let a of c){let l=document.querySelector(a);if(l){l.scrollTop=0;return}}}),await k(500);async function n(){return e.evaluate(c=>{let a=document.querySelectorAll(".msg-conversation-listitem");for(let l of a)if(l.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===c){let d=l.getBoundingClientRect();if(d.height>0)return{x:d.x+d.width/2,y:d.y+d.height/2}}return null},t)}let o=await n(),s=50,i=-1,r=0;for(let c=0;c<s&&!o;c++){let a=await hn(e);if(!a)break;if(a.scrollTop===i){if(r++,r>=2)break}else r=0,i=a.scrollTop;await k(600),o=await n()}return o?(await e.mouse.click(o.x,o.y),await k(3e3),Lt(e,t)):{verified:!1,headerName:null}}async function Sn(e,t){let n=await e.evaluate(r=>{let c=document.querySelectorAll(".msg-conversation-listitem");for(let a of c)if(a.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===r){let f=a.getBoundingClientRect();if(f.height>0)return{x:f.x+f.width/2,y:f.y+f.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await k(3e3);let r=await Lt(e,t);if(r.verified)return r}let o=lo(t),s=o!==t?[t,o]:[t];for(let r of s)if(await zo(e,r,t)){let a=await Lt(e,t);if(a.verified)return a}let i=co(o);if(i!==o&&i.length>0&&await zo(e,i,t,{requireUnique:!0})){let c=await Lt(e,t);if(c.verified)return c}return{verified:!1,headerName:null}}async function zo(e,t,n,o={}){let{requireUnique:s=!1}=o,i=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!i)return!1;await i.click(),await k(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await k(300),await i.type(t,{delay:30}),await k(500),await e.keyboard.press("Enter"),await k(3500);let r=await e.evaluate((c,a)=>{let l=c.split(" ")[0].toLowerCase(),u=c.toLowerCase(),f=document.querySelectorAll(".msg-conversation-listitem"),d=[],m=[];for(let h of f){let y=h.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=y.toLowerCase();if(S.includes(l)){let g=h.getBoundingClientRect();if(g.height>0){let p=y.includes(",")||/\d+ other/.test(y),v=S===u?3:S.includes(u)?2:1,C={text:y,isGroup:p,score:v,x:g.x+g.width/2,y:g.y+g.height/2};p?m.push(C):d.push(C)}}}d.sort((h,b)=>b.score-h.score);let w=[...d,...m];return a&&w.length!==1?null:d[0]||m[0]||null},n,s);return r?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(r.x,r.y),!0):!1}async function ve(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await k(200),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await e.keyboard.press("Escape"),await k(1e3))}await Cn();import"dotenv/config";import*as te from"fs";import*as ke from"path";import{fileURLToPath as pi}from"url";import"dotenv/config";import{createGraphClient as ci,resolveToken as ui}from"@ilivemylife/graph-sdk";import{config as di}from"dotenv";di();var us=ui()||process.env.TOKEN;us||(console.error(`
|
|
246
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.
|
|
247
249
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
248
250
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
249
|
-
`),process.exit(1));var
|
|
251
|
+
`),process.exit(1));var ds=ci({token:us});function fi(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 mi({scriptName:e,mode:t,status:n,error:o,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",r=new Date().toISOString().slice(0,16).replace("T"," "),c=s?` ${fi(s)}`:"",a=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",l=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${l} \u2014 ${a} \u2014 ${r}${c}`}async function fs({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:i}){let r=process.env.NODE_RUN_REPORTS;if(!r||!Array.isArray(o)||o.length===0)return;let a=`**${mi({scriptName:e,mode:t,status:n,error:s,duration:i})}**
|
|
250
252
|
|
|
251
253
|
${o.join(`
|
|
252
|
-
`)}`;try{await
|
|
253
|
-
`)}import"dotenv/config";import*as
|
|
254
|
+
`)}`;try{await ds.addMessage(r,a)}catch(l){console.error(`[runReport] Failed to post end-of-session message: ${l.message}`)}}var hi=pi(import.meta.url),gi=ke.dirname(ke.dirname(hi)),An=process.env.DATA_DIR?ke.resolve(process.env.DATA_DIR,"collected-profiles"):ke.join(gi,"collected-profiles"),En=ke.join(An,"run-log.json");function yi(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";te.writeFileSync(o,n);for(let s=0;s<3;s++)try{te.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function Bt(){try{if(!te.existsSync(En))return{runs:[]};let e=JSON.parse(te.readFileSync(En,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ms(e){te.existsSync(An)||te.mkdirSync(An,{recursive:!0});try{yi(En,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ht(e,t="default"){let n=Bt();for(let r of n.runs)r.status==="running"&&(r.status="interrupted",r.result="interrupted",r.timestamp&&(r.duration=Date.now()-new Date(r.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(r=>new Date(r.timestamp).getTime()>i),ms(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Ke(e,t,n=null,o=null){if(!e)return;let s=null;try{let r=Bt(),c=r.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,s=c.duration;else{let a=r.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,s=a.duration)}ms(r)}catch(r){console.error(`[runLog] Failed to end run: ${r.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let r=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";fs({scriptName:e.script,mode:e.mode,status:r,summaryLines:i,error:o,duration:s??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}function wi(){let e=new Date().toISOString().slice(0,10),t=Bt(),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 s=n[o.script];s.total++,o.status==="success"?s.success++:o.status==="error"?s.error++:o.status==="interrupted"?s.interrupted++:o.status==="partial"?s.partial++:o.status==="running"&&s.running++,s.lastRun=o}return n}function bi(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),s=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:s===1?"yesterday":`${s} days ago`}function ps(){let e=["sync-all","messages","funnel","sync","apply"],t=Bt(),n=wi(),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 i of e){let r=t.runs.filter(h=>h.script===i),c=[...r].reverse().find(h=>h.status==="success"),a=r[r.length-1],l=c||a,u=l?bi(l.timestamp):"never",d=(l?Math.floor((Date.now()-new Date(l.timestamp).getTime())/864e5):1/0)>1?" \u26A0":l?.status==="error"?" \u2717":" \u2713",m="";if(l?.stats){let h=l.stats,b=Object.entries(h).filter(([,y])=>typeof y=="number"&&y>0).slice(0,3).map(([y,S])=>`${S} ${y}`);b.length&&(m=` (${b.join(", ")})`)}let w=l?.duration?` ${Math.round(l.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${u.padEnd(16)}${w}${m}${d}`)}let s=Object.entries(n);if(s.length>0){o.push("");for(let[i,r]of s){let c=[];r.success&&c.push(`${r.success} success`),r.error&&c.push(`${r.error} error`),r.interrupted&&c.push(`${r.interrupted} interrupted`),r.running&&c.push(`${r.running} running`),o.push(` Today: ${i} \xD7${r.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
|
+
`)}import"dotenv/config";import*as x from"fs";import*as Nn from"os";import*as M from"path";import{fileURLToPath as Hi}from"url";var Tn={};ue(Tn,{NAME:()=>vi,VERSION:()=>Si,up:()=>Ci});import*as ne from"fs";import*as Jt from"path";var Si=1,vi="normalize-jobs-and-questions",ki=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],$i=50;function xn(e){return ne.existsSync(e)?JSON.parse(ne.readFileSync(e,"utf-8")):null}function _n(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ne.writeFileSync(o,n)}catch(s){try{ne.unlinkSync(o)}catch{}throw s}try{ne.renameSync(o,e)}catch(s){try{ne.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Ci(e,t){let n=Jt.join(e,"jobs.json"),o=Jt.join(t,"scouted-jobs.json"),s=Jt.join(e,"application-questions.json"),i=xn(n)||{},r=xn(o)||{},c=0,a=[];for(let u of Object.keys(i)){if(!r[u])continue;let f=r[u],d=i[u];for(let m of ki)f[m]!=null&&d[m]==null&&(d[m]=f[m]);a.push(u),c++}c>0?(_n(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=xn(s);if(l&&Array.isArray(l.applications)){let u={},f=0;for(let d of l.applications){let m=d.jobId||"unknown";u[m]||(u[m]={applications:[]});let w=(d.questions||[]).map(h=>{let b={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=$i?b.options=h.options:(b.optionsOmitted=!0,f++)),h.page&&(b.page=h.page),h.wasPreFilled&&(b.wasPreFilled=!0),h.wasRetry&&(b.wasRetry=!0),b});u[m].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||w.length,questions:w})}_n(s,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 r[u];_n(o,r),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(r).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Rn={};ue(Rn,{NAME:()=>Ei,VERSION:()=>Ai,up:()=>Ti});import*as oe from"fs";import*as hs from"path";var Ai=2,Ei="reset-unread-flags";function xi(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(s){try{oe.unlinkSync(o)}catch{}throw s}try{oe.renameSync(o,e)}catch(s){try{oe.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Ti(e){let t=hs.join(e,"conversations.json"),n=xi(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].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 In={};ue(In,{NAME:()=>Ii,VERSION:()=>Ri,up:()=>Pi});import*as se from"fs";import*as gs from"path";var Ri=3,Ii="recompute-last-message-by",Di=new Set(["draft","confirmed","rejected","needs_review"]);function Oi(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function Ni(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{se.writeFileSync(o,n)}catch(s){try{se.unlinkSync(o)}catch{}throw s}try{se.renameSync(o,e)}catch(s){try{se.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}function Mi(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Di.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,r)=>r.t-i.t).map(i=>i.m),s=o.length>0?o:[...n].reverse();for(let i of s){let r=i.sender;if(r===t)return"me";if(r!=="Unknown"&&r!=="")return"them"}return"them"}async function Pi(e){let t=gs.join(e,"conversations.json"),n=Oi(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 s=0,i=0,r=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,i++);let l=Array.isArray(a.messages)?a.messages:[],u=Mi(l,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==u&&r++,a.lastMessageBy=u,a.conversationStatus=f,s++}if(s===0){console.log(" No conversations to recompute.");return}Ni(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${r} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Dn={};ue(Dn,{NAME:()=>Li,VERSION:()=>ji,up:()=>Bi});import*as re from"fs";import*as ys from"path";var ji=4,Li="split-connection-timestamps",Fi=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ui(e){if(!re.existsSync(e))return null;let t=re.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function qi(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{re.writeFileSync(o,n)}catch(s){try{re.unlinkSync(o)}catch{}throw s}try{re.renameSync(o,e)}catch(s){try{re.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Bi(e){let t=ys.join(e,"people.json"),n=Ui(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,s=0;for(let i of Object.keys(n)){let r=n[i];!r||typeof r!="object"||(s++,Fi.has(r.connectionStatus)&&r.connectionDate&&!r.requestedConnectionAt&&(r.requestedConnectionAt=r.connectionDate,r.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}qi(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Je();bt();var Ji=Hi(import.meta.url),Vi=M.dirname(Ji),Wi=M.dirname(M.dirname(Vi));function Yi(e){return e&&(e==="~"?Nn.homedir():e.startsWith("~/")||e.startsWith("~\\")?M.join(Nn.homedir(),e.slice(2)):e)}var de=process.env.DATA_DIR?M.resolve(Yi(process.env.DATA_DIR)):Wi,Ne=M.join(de,"collected-profiles"),Me=M.join(de,"market-research"),G=M.join(de,".schema-version"),ws=[M.join(Ne,".schema-version"),M.join(Me,".schema-version")],$e=4,he=[{version:1,module:Tn},{version:2,module:Rn},{version:3,module:In},{version:4,module:Dn}];(function(){he.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of he){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 s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=he.length?he[he.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<he.length;o++){let s=o+1;if(he[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${he[o].version}`)}})();function ks(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
254
256
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
255
|
-
`),process.exit(1));try{
|
|
256
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
257
|
-
`),process.exit(1))}let e;try{e=
|
|
258
|
-
[FATAL] DATA_DIR (${
|
|
257
|
+
`),process.exit(1));try{x.mkdirSync(de,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
258
|
+
[FATAL] Cannot create DATA_DIR (${de}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
259
|
+
`),process.exit(1))}let e;try{e=x.statSync(de)}catch(t){console.error(`
|
|
260
|
+
[FATAL] DATA_DIR (${de}) is not accessible: ${t.message}
|
|
259
261
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
260
|
-
[FATAL] DATA_DIR (${
|
|
261
|
-
`),process.exit(1));for(let t of[Ne,Me]){let n;try{n=
|
|
262
|
+
[FATAL] DATA_DIR (${de}) 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.
|
|
263
|
+
`),process.exit(1));for(let t of[Ne,Me]){let n;try{n=x.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
|
|
262
264
|
[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.
|
|
263
|
-
`),process.exit(1))}}var Oe=M.join(
|
|
265
|
+
`),process.exit(1))}}var Oe=M.join(de,".migration-lock");function Gi(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return x.writeFileSync(Oe,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(x.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(r){r.code==="EPERM"&&(o=!0)}let s=24*60*60*1e3,i=1/0;if(t.startedAt){let r=Date.parse(t.startedAt);Number.isNaN(r)||(i=Date.now()-r)}o&&i<s&&(console.error(`
|
|
264
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: ${Oe}
|
|
265
267
|
`),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.
|
|
266
|
-
`),process.exit(1)),o&&i>=s&&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
|
|
268
|
+
`),process.exit(1)),o&&i>=s&&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 x.writeFileSync(n,e),x.renameSync(n,Oe),!0}catch(o){try{x.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Mn(){try{if(JSON.parse(x.readFileSync(Oe,"utf-8")).pid!==process.pid)return;x.unlinkSync(Oe)}catch{}}var bs=!1;function zi(){if(bs)return;bs=!0;let e=()=>{try{Mn()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Ki(){if(x.existsSync(G))return;let e=[],t=[];for(let i of ws)if(x.existsSync(i))try{e.push({file:i,schema:Vt(i)})}catch(r){t.push({file:i,err:r.message})}if(t.length>0){console.error(`
|
|
267
269
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
|
|
268
270
|
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.
|
|
269
271
|
`),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
|
|
270
272
|
[FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
271
|
-
`),process.exit(1)}let o=e[0].schema,s=
|
|
272
|
-
[FATAL] ${
|
|
273
|
-
`),process.exit(1)}let t=
|
|
274
|
-
[FATAL] ${
|
|
275
|
-
`),process.exit(1)),t}function
|
|
273
|
+
`),process.exit(1)}let o=e[0].schema,s=G+".tmp";try{x.writeFileSync(s,JSON.stringify(o,null,2)),x.renameSync(s,G)}catch(i){try{x.unlinkSync(s)}catch{}throw i}for(let i of ws)if(x.existsSync(i))try{x.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${G}`)}function Qi(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 Vt(e){let t=x.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Ss(){if(Ki(),!x.existsSync(G))return{version:0,migrations:[]};let e;try{e=Vt(G)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
274
|
+
[FATAL] ${G} 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.
|
|
275
|
+
`),process.exit(1)}let t=Qi(e);return t===null&&(console.error(`
|
|
276
|
+
[FATAL] ${G} 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.
|
|
277
|
+
`),process.exit(1)),t}function $s(e){try{x.chmodSync(e,384)}catch{}}function Xi(e){if(ks(),x.existsSync(G))try{if(x.lstatSync(G).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${G}. 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=G+".tmp";try{x.writeFileSync(t,JSON.stringify(e,null,2)),$s(t),x.renameSync(t,G)}catch(n){try{x.unlinkSync(t)}catch{}throw n}}function vs(e,t){if(!x.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=x.readdirSync(e).filter(c=>{let a=c.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return x.statSync(M.join(e,c)).isFile()}catch{return!1}}),s=0,i=0,r=[];for(let c of o){let a=M.join(e,c),l=M.join(e,c+n);if(x.existsSync(l)){i++;continue}try{As(a,l),s++}catch(u){r.push({file:c,err:u.message})}}if(r.length>0){let c=new Error(`Failed to back up ${r.length} file(s) in ${M.basename(e)}/: `+r.map(a=>`${a.file} (${a.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(s>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${M.basename(e)}/ (${n})${c}`)}}var On=!1;async function Cs(){if(On)return;ks(),oa();let t=Ss().version;if(t===$e){On=!0;return}zi(),Gi(),process.on("exit",Mn),t>$e&&(console.error(`
|
|
276
278
|
[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.
|
|
277
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${$e}.
|
|
278
280
|
`),process.exit(1)),console.log(`
|
|
279
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${$e}`);let n=
|
|
281
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${$e}`);let n=sa();if(!n.ok){console.error(`
|
|
280
282
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of n.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
|
|
281
283
|
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'.
|
|
282
|
-
`),process.exit(1)}let o=
|
|
283
|
-
Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,r=`.pre-${i}.backup`;try{
|
|
284
|
+
`),process.exit(1)}let o=he.filter(s=>s.version>t);for(let s of o){console.log(`
|
|
285
|
+
Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,r=`.pre-${i}.backup`;try{vs(Ne,s.version),vs(Me,s.version)}catch(a){console.error(`
|
|
284
286
|
[FATAL] Pre-migration backup failed for ${i}: ${a.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
285
287
|
`),process.exit(1)}let c=s.module;try{await c.up(Ne,Me)}catch(a){console.error(`
|
|
286
|
-
[FATAL] Migration ${i} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${r} files...`);try{let l=
|
|
288
|
+
[FATAL] Migration ${i} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${r} files...`);try{let l=ra(r);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.
|
|
287
289
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${l.error}`),console.error(` Manual recovery: copy *${r} files back over the originals.
|
|
288
290
|
`))}catch(l){console.error(` [!] Auto-rollback CRASHED while restoring: ${l.message}`),console.error(` Manual recovery: copy *${r} files back over the originals.
|
|
289
|
-
`)}process.exit(1)}try{let a=new Date().toISOString(),l={version:s.version,name:c.NAME||i,appliedAt:a},u=
|
|
291
|
+
`)}process.exit(1)}try{let a=new Date().toISOString(),l={version:s.version,name:c.NAME||i,appliedAt:a},u=Ss();u.version=s.version,u.migratedAt=a,u.migrations=u.migrations||[],u.migrations.push(l),Xi(u)}catch(a){console.error(`
|
|
290
292
|
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${a.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
291
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{
|
|
293
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{wo()}catch{}try{cn()}catch{}On=!0,Mn(),console.log(`
|
|
292
294
|
\u2713 Schema is now at v${$e}
|
|
293
|
-
`)}var
|
|
294
|
-
\u{1F504} CDP dead \u2014 recovering page (#${je.pageRecoveries+1}). Reason: ${t}`),e.page=await
|
|
295
|
-
`)}function Xe(e){return(e.messages||[]).find(t=>
|
|
295
|
+
`)}var Zi=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function ea(e){let t=e.toLowerCase();return Zi.some(n=>n.test(t))}var ta=6e4;function na(){let e=Date.now(),t=[];for(let n of[de,Ne,Me]){if(!x.existsSync(n))continue;let o;try{o=x.readdirSync(n)}catch{continue}for(let s of o){if(!ea(s))continue;let i=M.join(n,s);try{let r=x.statSync(i);if(!r.isFile()||e-r.mtimeMs<ta)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function oa({verbose:e=!1}={}){let t=na();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{x.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${M.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function sa(){let e=[];for(let t of[Ne,Me]){if(!x.existsSync(t))continue;let n=x.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=M.join(t,o);try{Vt(s)}catch(i){e.push({dir:M.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function ra(e){let t=[],n=[];for(let i of[Ne,Me]){if(!x.existsSync(i))continue;let r=x.readdirSync(i).filter(c=>c.endsWith(e));for(let c of r){let a=M.join(i,c),l=c.slice(0,-e.length),u=M.join(i,l);try{l.toLowerCase().endsWith(".json")?Vt(a):x.accessSync(a,x.constants.R_OK),t.push({backupPath:a,originalPath:u,fileName:c,dir:i})}catch(f){n.push(`${M.basename(i)}/${c}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:i,originalPath:r,fileName:c,dir:a}of t)try{As(i,r),o++}catch(l){s.push(`${M.basename(a)}/${c}: ${l.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function As(e,t){let n=t+".tmp";try{x.copyFileSync(e,n),$s(n)}catch(o){try{x.unlinkSync(n)}catch{}throw o}try{x.renameSync(n,t)}catch(o){try{x.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=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 s.code=o.code,s}throw o}}et();Le();async function ia(e,t,n="op"){let o,s=new Promise((i,r)=>{o=setTimeout(()=>r(new Error(`${n} timeout after ${t}ms`)),t)});try{return await Promise.race([e,s])}finally{clearTimeout(o)}}function Pe(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let n=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(n)||/Target closed/i.test(n)||/Session closed/i.test(n)||/Connection closed/i.test(n)||/Most likely the page has been closed/i.test(n)||/Navigating frame was detached/i.test(n)||/Protocol error.*timed out/i.test(n)}async function Es(e,t,{returnUrl:n,gotoTimeoutMs:o=6e4,cookiesProvider:s=null,setupPage:i=null}={}){try{await ia(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let r=await e.newPage();if(i)try{await i(r)}catch{}if(s)try{let c=s();Array.isArray(c)&&c.length>0&&await r.setCookie(...c)}catch{}if(n){await r.goto(n,{waitUntil:"domcontentloaded",timeout:o});let c=r.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(c))throw new Error(`Session expired after recovery \u2014 landed on ${c}. Run: ilml linkedin login`)}return r}await Cs();var qs="https://www.linkedin.com/messaging/",ba=10,Fn=3,Sa=async e=>{await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},va=()=>_t(),je={pageRecoveries:0};async function Yt(e,t){if(je.pageRecoveries>=ba)throw new Error(`CDP unrecoverable: ${je.pageRecoveries} page recoveries already attempted. Last: ${t}`);console.log(`
|
|
296
|
+
\u{1F504} CDP dead \u2014 recovering page (#${je.pageRecoveries+1}). Reason: ${t}`),e.page=await Es(e.browser,e.page,{returnUrl:qs,cookiesProvider:va,setupPage:Sa}),je.pageRecoveries++,await k(3e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}console.log(`\u2713 Page recovered (total: ${je.pageRecoveries}).
|
|
297
|
+
`)}function Xe(e){return(e.messages||[]).find(t=>ot.has(t.status))?.status}var X=process.argv.slice(2),Un=X.includes("--full"),W=X.includes("--dry-run"),Ps=X.includes("--report"),qn=X.includes("--verbose"),js=X.includes("--backfill"),Ls=X.includes("--enrich"),Fs=X.includes("--today"),Bn=X.includes("--read-unread"),Et=parseInt(X.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),ka=X.includes("--auto-enrich-replies"),Us=parseInt(X.find(e=>e.startsWith("--auto-enrich-max="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_MAX||"3"),$a=parseInt(X.find(e=>e.startsWith("--auto-enrich-stale-days="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_STALE_DAYS||"30");function Ca(e,t){if(!t)return"new";if(e.unread)return"unread";if(!t.profileUrl&&(t.messages?.length||t.lastMessagePreview))return"missing_url";let n=(t.lastMessagePreview||"").substring(0,50),o=(e.lastMessagePreview||"").substring(0,50);if(o&&n&&o!==n)return"preview_changed";if(e.lastMessageBy==="me"&&t.lastMessageBy!=="me")return"sender_changed";if(t.lastSynced&&e.lastMessageTime){let s=new Date(e.lastMessageTime).getTime(),i=new Date(t.lastSynced).getTime();if(Number.isFinite(s)&&Number.isFinite(i)&&s>i)return"activity_after_last_read"}return null}async function Aa(e,t){console.log(`
|
|
296
298
|
\u2550\u2550 PHASE 1: Inbox Scan \u2550\u2550
|
|
297
|
-
`);let n=
|
|
298
|
-
3 rounds with no new items \u2014 end of visible list.`);break}}else
|
|
299
|
-
Caught up \u2014 3 screens with no new threads to read.`);break}}else l=0;u=i.size}let
|
|
300
|
-
Scroll stalled \u2014 reached end of inbox.`);break}}else m=0;
|
|
301
|
-
`);let w=new Date().toISOString(),
|
|
302
|
-
Inbox scan complete:`),console.log(` Total conversations seen: ${s.size}`),console.log(` New conversations: ${
|
|
299
|
+
`);let n=on(),o=n.lastIncrementalSync?new Date(n.lastIncrementalSync):null,s=new Map,i=new Map,r=new Map,c=0,a=0,l=0,u=0,f=0,d=-1,m=0;for(;;){a++;let y=await Xo(e),S=0;for(let p of y){if(!p.name||s.has(p.name))continue;s.set(p.name,p),S++,p.unread&&r.set(p.name,p);let v=t[p.name],C=Ca(p,v);C&&(!Bn&&p.unread?c++:i.set(p.name,{card:p,reason:C})),v&&(C||(v.lastMessageBy=p.lastMessageBy,v.lastMessagePreview=p.lastMessagePreview||v.lastMessagePreview,v.lastMessageTime=p.lastMessageTime||v.lastMessageTime),v.unread=p.unread,p.lastMessageBy==="them"&&p.unread&&(v.conversationStatus="unanswered_by_us"))}if(qn?console.log(` Round #${a}: +${S} new | Total: ${s.size} | Need reading: ${i.size}`):process.stdout.write(`\r Scanned: ${s.size} conversations (page #${a}, ${i.size} need reading)`),S===0){if(f++,f>=3){console.log(`
|
|
300
|
+
3 rounds with no new items \u2014 end of visible list.`);break}}else f=0;if(!Un){if(i.size===u){if(l++,l>=3){console.log(`
|
|
301
|
+
Caught up \u2014 3 screens with no new threads to read.`);break}}else l=0;u=i.size}let g=await hn(e);if(g){if(g.scrollTop===d){if(m++,m>=3){console.log(`
|
|
302
|
+
Scroll stalled \u2014 reached end of inbox.`);break}}else m=0;d=g.scrollTop}else{let p=await e.$(".msg-conversation-listitem");if(p){let v=await p.boundingBox();v&&(await e.mouse.move(v.x+v.width/2,v.y+v.height/2),await e.mouse.wheel({deltaY:600}))}}await k(2e3)}qn||process.stdout.write(`
|
|
303
|
+
`);let w=new Date().toISOString(),h=0;for(let[y,{card:S}]of i)t[y]||(t[y]={profileUrl:null,lastSynced:w,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:S.unread||!1,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},h++);let b=0;for(let[y,S]of r)t[y]||(t[y]={profileUrl:null,lastSynced:w,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:!0,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},b++);if(console.log(`
|
|
304
|
+
Inbox scan complete:`),console.log(` Total conversations seen: ${s.size}`),console.log(` New conversations: ${h}`),console.log(` Need reading/re-reading: ${i.size}`),!Bn&&c>0&&console.log(` Preserved unread (default): ${c} \u2014 kept bold in LinkedIn UI; pass --read-unread to vacuum them into the DB`),b>0&&console.log(` New unread stubs: ${b} \u2014 saved to DB so 'today' / 'report' can show them offline`),i.size>0){let y={};for(let{reason:S}of i.values())y[S]=(y[S]||0)+1;for(let[S,g]of Object.entries(y))console.log(` ${S}: ${g}`)}if(!W){let y=on();y.lastIncrementalSync=new Date().toISOString(),Un&&(y.lastFullSync=y.lastIncrementalSync),Eo(y),we(t)}return{allCards:s,toReRead:i,unreadCards:r}}async function Ea(e,t,n,o){console.log(`
|
|
303
305
|
\u2550\u2550 PHASE 2: Read Changed Threads \u2550\u2550
|
|
304
|
-
`);let s=Array.from(t.entries()),i=Math.min(s.length,
|
|
305
|
-
`);let c=[],a=[],l=0,u=0;for(let
|
|
306
|
-
Phase 2 complete: ${c.length} read, ${l} failed${u?`, ${u} skipped on CDP recovery`:""}`),s.length>i&&console.log(` ${s.length-i} more threads pending (run again or increase --max)`),c}async function
|
|
306
|
+
`);let s=Array.from(t.entries()),i=Math.min(s.length,Et);if(i===0)return console.log(" No threads to read \u2014 all up to date."),[];console.log(" Resetting inbox view...");try{await e.page.goto(qs,{waitUntil:"domcontentloaded",timeout:6e4})}catch(f){if(!Pe(f))throw f;await Yt(e,"Phase 2 inbox reset")}await k(4e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}let r={unread:0,preview_changed:1,sender_changed:2,no_messages:3,new:4};s.sort((f,d)=>(r[f[1].reason]??5)-(r[d[1].reason]??5)),console.log(` Reading ${i} of ${s.length} threads (--max=${Et})
|
|
307
|
+
`);let c=[],a=[],l=0,u=0;for(let f=0;f<i;f++){let[d,{card:m,reason:w}]=s[f];console.log(` [${f+1}/${i}] ${d} (${w})`);let h=e.page;try{let b={verified:!1,headerName:null};try{b=await Sn(h,d)}catch(S){if(Pe(S))throw S;console.log(` searchAndOpenThread threw: ${(S.message||"").substring(0,80)}`)}if(!b.verified){console.log(" Sidebar fallback (scroll-to-find)...");try{b=await Zo(e.page,d)}catch(S){if(Pe(S))throw S;console.log(` Fallback threw: ${(S.message||"").substring(0,80)}`)}}if(!b.verified){console.log(" Could not open thread."),l++;try{await ve(e.page)}catch{}continue}let y=await yn(h);if(y&&y.length>0){if(!wn(y,d,a)){console.log(" Skipped \u2014 stale data."),l++,await ve(h);continue}let g=await gn(h),p=n[d]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]},v=p.messages?.length||0;p.messages=bn(p.messages,y),p.lastSynced=new Date().toISOString(),g&&!p.profileUrl&&(p.profileUrl=g);let C=p.messages.filter(A=>!["draft","confirmed","rejected","needs_review"].includes(A.status));p.lastMessageBy=qt(C,d),p.lastMessagePreview=m.lastMessagePreview||p.lastMessagePreview,p.lastMessageTime=m.lastMessageTime||p.lastMessageTime,p.unread=!1,n[d]=p,W||we(n);let _=p.messages.length-v;console.log(` ${p.messages.length} msgs (${_>=0?"+"+_:_} new)${g&&!p.profileUrl?" +url":""}`),c.push({name:d}),a=[...new Set(y.map(A=>A.sender).filter(A=>A&&A!=="Unknown"))]}else console.log(" No messages extracted."),l++;await ve(h),await k(500)}catch(b){if(!Pe(b))throw b;u++,o&&o.add(d),await Yt(e,`Phase 2 thread ${f+1}/${i} (${d})`)}}return console.log(`
|
|
308
|
+
Phase 2 complete: ${c.length} read, ${l} failed${u?`, ${u} skipped on CDP recovery`:""}`),s.length>i&&console.log(` ${s.length-i} more threads pending (run again or increase --max)`),c}async function xa(e,t,n){if(!ka)return null;console.log(`
|
|
307
309
|
\u2550\u2550 PHASE 2.5: Auto-enrich-replies \u2550\u2550
|
|
308
|
-
`);let o=new Set(n.map(m=>m.name)),s=J(),i=Date.now(),r
|
|
309
|
-
`),{picked:0,enriched:0,skipped:0,errors:0,dryRun:W};c.sort((m,w)=>{let
|
|
310
|
-
[${m+1}/${a.length}] Enriching ${w.name} ${w.profileUrl}`);try{let
|
|
311
|
-
Auto-enrich done: ${
|
|
312
|
-
`),{picked:a.length,enriched:
|
|
310
|
+
`);let o=new Set(n.map(m=>m.name)),s=J(),i=Date.now(),r=$a*24*60*60*1e3,c=[];for(let m of o){let w=t[m];if(!w||w.lastMessageBy!=="them")continue;let h=w.profileUrl;if(!h)continue;let y=s[h]?._lastEnrichedAt;if(y){let S=i-new Date(y).getTime();if(Number.isFinite(S)&&S<r)continue}c.push({name:m,profileUrl:h,lastMessageTime:w.lastMessageTime||null})}if(c.length===0)return console.log(` No stale contacts to enrich. Skipping phase.
|
|
311
|
+
`),{picked:0,enriched:0,skipped:0,errors:0,dryRun:W};c.sort((m,w)=>{let h=new Date(m.lastMessageTime||0).getTime();return new Date(w.lastMessageTime||0).getTime()-h});let a=c.slice(0,Us),l=c.length-a.length;if(console.log(` Candidates: ${c.length} | picking ${a.length} (cap ${Us}) | skipping ${l}`),l>0&&console.log(" (raise --auto-enrich-max=N to lift the cap, but be mindful of ban-risk)"),W){console.log(" [DRY RUN] Would enrich:");for(let m of a)console.log(` - ${m.name} ${m.profileUrl} (last msg: ${m.lastMessageTime||"unknown"})`);return console.log(""),{picked:a.length,enriched:0,skipped:l,errors:0,dryRun:!0}}let{viewProfile:u}=await Ms().then(()=>Ns),f=0,d=0;for(let m=0;m<a.length;m++){let w=a[m];console.log(`
|
|
312
|
+
[${m+1}/${a.length}] Enriching ${w.name} ${w.profileUrl}`);try{let h=await u(e.page,w.profileUrl,{extractExperience:!0,extractFeatured:!0,extractEducation:!0,extractSkills:!0,extractRecommendations:!0,extractCertifications:!0});if(!h||!h.name){console.log(" \u2717 viewProfile returned no data \u2014 skipping save"),d++;continue}let b={name:h.name,title:h.title,location:h.location,about:h.about,currentCompany:h.currentCompany,currentSchool:h.currentSchool,topSkills:h.topSkills,availableSections:h.availableSections,connectionsLevel:h.connectionsLevel,mutualConnectionsCount:h.mutualConnectionsCount,followers:h.followers,openToWork:h.openToWork,hiring:h.hiring,hasVerifiedBadge:h.hasVerifiedBadge,photoUrl:h.photoUrl,source:"auto-enrich-replies"},y=!1;for(let[S,g]of[["experience",h.experience],["featured",h.featured],["education",h.education],["skillsFull",h.skillsFull],["recommendations",h.recommendations],["certifications",h.certifications]])Array.isArray(g)&&g.length>0&&(b[S]=g,y=!0);y&&(b._lastEnrichedAt=new Date().toISOString()),Te(w.profileUrl,b),h.resolvedUrl&&Dt(w.profileUrl,h.resolvedUrl),f++,console.log(` \u2713 saved (rich sections: ${y?"yes":"no \u2014 basic only"})`)}catch(h){if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(h.message||""))return console.log(" \u26A0 Session expired during auto-enrich. Stopping phase."),console.log(" Sync-all post-processing will still run on already-enriched data."),{picked:a.length,enriched:f,skipped:l,errors:d,authWall:!0};console.log(` \u2717 ${h.message?.slice(0,200)}`),d++}m+1<a.length&&await k(8e3)}return console.log(`
|
|
313
|
+
Auto-enrich done: ${f} enriched, ${d} errors, ${l} skipped (over cap)
|
|
314
|
+
`),{picked:a.length,enriched:f,skipped:l,errors:d}}function _a(e,t){console.log(`
|
|
313
315
|
\u2550\u2550 PHASE 3: Post-processing & Enrichment \u2550\u2550
|
|
314
|
-
`);let n=J();for(let o of t){let{name:s}=o,i=e[s];if(!i?.messages?.length)continue;try{
|
|
316
|
+
`);let n=J();for(let o of t){let{name:s}=o,i=e[s];if(!i?.messages?.length)continue;try{Ut(i,s,n)}catch(a){console.warn(` [!] Enrichment failed for ${s}: ${a.message}`)}i._cardSynced&&delete i._cardSynced;let r=i.profileUrl,c=null;if(r&&(c=n[r]||null),!c){let a=Object.entries(n).filter(([,l])=>l.name===s);a.length===1&&(r||(r=a[0][0],i.profileUrl=r),c=a[0][1])}!c&&r&&(c=Te(r,{name:s,source:"sync-all"})),c&&(i.category&&!c.category&&(c.category=i.category),c.conversationStatus=i.conversationStatus,c.lastUpdated=new Date().toISOString()),r&&c&&(i.isConnection=c.connectionStatus==="connected")}W||(Re(n),we(e)),console.log(` Enriched ${t.length} conversations.`),Bs(e)}function Bs(e){let t=new Map;for(let[s,i]of Object.entries(e)){if(!i.profileUrl)continue;let r=i.profileUrl.toLowerCase().replace(/\/$/,"");t.has(r)||t.set(r,[]),t.get(r).push(s)}let n=[...t.entries()].filter(([,s])=>s.length===2);if(n.length===0)return;let o=0;for(let[,s]of n){let[i,r]=s.map(u=>({name:u,conv:e[u]})),c=(i.conv.messages?.length||0)>=(r.conv.messages?.length||0)?i:r,a=c===i?r:i,l=new Set((c.conv.messages||[]).map(u=>`${u.text?.slice(0,80)}|${u.time}`));for(let u of a.conv.messages||[]){let f=`${u.text?.slice(0,80)}|${u.time}`;l.has(f)||(c.conv.messages.push(u),l.add(f))}c.conv.messages.sort((u,f)=>(u.time||"").localeCompare(f.time||"")),a.conv.notes&&!c.conv.notes&&(c.conv.notes=a.conv.notes),a.conv.priority&&!c.conv.priority&&(c.conv.priority=a.conv.priority),a.conv.categorySource==="manual"&&c.conv.categorySource!=="manual"&&(c.conv.category=a.conv.category,c.conv.categorySource="manual"),(a.conv.lastSynced||"")>(c.conv.lastSynced||"")&&(c.conv.lastSynced=a.conv.lastSynced),delete e[a.name],console.log(` Merged: "${a.name}" \u2192 "${c.name}"`),o++}o>0&&(W||we(e),console.log(` ${o} duplicates merged.`))}function Ta(){let e=ct(),t=J(),n=Object.entries(e);console.log(`
|
|
315
317
|
\u2550\u2550 ENRICHMENT: Re-processing all conversations \u2550\u2550
|
|
316
|
-
`);let o=0,s=0,i=0;for(let[d
|
|
317
|
-
People enriched: ${l}`),console.log(` People skipped (have conversation or not connected): ${u}`),console.log(` People total: ${a.length}`),
|
|
318
|
+
`);let o=0,s=0,i=0;for(let[f,d]of n){if(!d.profileUrl){let m=Object.entries(t).filter(([,w])=>w.name===f);m.length===1&&(d.profileUrl=m[0][0],i++)}if(!d.messages||d.messages.length===0){s++;continue}try{Ut(d,f,t)}catch(m){console.warn(` [!] Enrichment failed for ${f}: ${m.message}`)}o++}Bs(e),W||we(e),console.log(` Enriched: ${o}`),console.log(` Skipped (no messages): ${s}`),i>0&&console.log(` Linked profileUrl from people.json: ${i}`),console.log(` Total: ${n.length}`);let r=new Set(Object.keys(e)),c=new Set(Object.values(e).map(f=>f.profileUrl).filter(Boolean)),a=Object.entries(t),l=0,u=0;for(let[f,d]of a){if(c.has(f)){u++;continue}if(d.name&&r.has(d.name)){u++;continue}if(d.connectionStatus!=="connected"){u++;continue}$n(d,f),l++}W||Re(t),console.log(`
|
|
319
|
+
People enriched: ${l}`),console.log(` People skipped (have conversation or not connected): ${u}`),console.log(` People total: ${a.length}`),Hn(e,null,null)}function Hn(e,t,n,o={}){let s=Object.entries(e),i=J(),{unreadCards:r=null,readUnread:c=!1}=o;console.log(`
|
|
318
320
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SYNC REPORT"),console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
319
|
-
`),t&&(console.log(" Inbox Scan:"),console.log(` Conversations seen: ${t.allCards.size}`),console.log(` Needed reading: ${t.toReRead.size}`)),n&&console.log(` Actually read: ${n.length}`);let a=s.length,l=s.filter(([,$])=>$.messages?.length>0).length,u=s.filter(([,$])=>!$.messages||$.messages.length===0).length,
|
|
320
|
-
Database:`),console.log(` Total conversations: ${a}`),console.log(` With messages: ${l}`),console.log(` Without messages: ${u}`),console.log(` With profileUrl: ${
|
|
321
|
-
Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${w} (${m>0?(w/m*100).toFixed(1):0}%)`);let
|
|
322
|
-
Statuses:`);for(let[$,
|
|
323
|
-
Categories:`);for(let[$,
|
|
324
|
-
Actions Needed:`);for(let[$,
|
|
325
|
-
Duplicates (${
|
|
321
|
+
`),t&&(console.log(" Inbox Scan:"),console.log(` Conversations seen: ${t.allCards.size}`),console.log(` Needed reading: ${t.toReRead.size}`)),n&&console.log(` Actually read: ${n.length}`);let a=s.length,l=s.filter(([,$])=>$.messages?.length>0).length,u=s.filter(([,$])=>!$.messages||$.messages.length===0).length,f=s.filter(([,$])=>$.profileUrl).length,d=s.filter(([,$])=>!$.profileUrl).length;console.log(`
|
|
322
|
+
Database:`),console.log(` Total conversations: ${a}`),console.log(` With messages: ${l}`),console.log(` Without messages: ${u}`),console.log(` With profileUrl: ${f}`),console.log(` Without profileUrl: ${d}`);let m=0,w=0;for(let[,$]of s)for(let E of $.messages||[])m++,(!E.sender||E.sender==="Unknown")&&w++;console.log(`
|
|
323
|
+
Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${w} (${m>0?(w/m*100).toFixed(1):0}%)`);let h={};for(let[,$]of s){let E=$.conversationStatus||"null";h[E]=(h[E]||0)+1}console.log(`
|
|
324
|
+
Statuses:`);for(let[$,E]of Object.entries(h).sort((T,O)=>O[1]-T[1]))console.log(` ${$}: ${E}`);let b={};for(let[,$]of s){let E=$.category||"(none)";b[E]=(b[E]||0)+1}console.log(`
|
|
325
|
+
Categories:`);for(let[$,E]of Object.entries(b).sort((T,O)=>O[1]-T[1]))console.log(` ${$}: ${E}`);let y={};for(let[,$]of s){let E=$.actionNeeded||"(none)";y[E]=(y[E]||0)+1}if(Object.keys(y).length>1||!y["(none)"]){console.log(`
|
|
326
|
+
Actions Needed:`);for(let[$,E]of Object.entries(y).sort((T,O)=>O[1]-T[1]))console.log(` ${$}: ${E}`)}let S=new Map;for(let[$,E]of s){if(!E.profileUrl)continue;let T=E.profileUrl.toLowerCase().replace(/\/$/,"");S.has(T)||S.set(T,[]),S.get(T).push($)}let g=[...S.entries()].filter(([,$])=>$.length>1);if(g.length>0){console.log(`
|
|
327
|
+
Duplicates (${g.length}):`);for(let[$,E]of g)console.log(` ${E.join(" | ")} \u2192 ${$}`)}let p=s.filter(([,$])=>$.conversationStatus==="unanswered_by_us").sort(($,E)=>(E[1].lastSynced||"").localeCompare($[1].lastSynced||"")),v=s.filter(([,$])=>Xe($));if(console.log(`
|
|
326
328
|
\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(" ACTION NEEDED"),console.log(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
327
329
|
`),r&&!c&&r.size>0){let $=[...r.entries()];console.log(` STILL UNREAD ON LINKEDIN (${$.length}) \u2014 kept bold; read them in the LinkedIn UI:
|
|
328
|
-
`);let
|
|
329
|
-
... and ${$.length-
|
|
330
|
+
`);let E=30;for(let[T,O]of $.slice(0,E)){let H=e[T],ie=H?.category?` [${H.category}]`:"",ae=O.lastMessageTime||H?.lastMessageTime||"",j=(O.lastMessagePreview||"").slice(0,80),L=H?.summary,U=H?.personContext?.title?`${H.personContext.title}${H.personContext.company?` at ${H.personContext.company}`:""}`:null;console.log(` ${T}${ie}${ae?` \u2014 ${ae}`:""}`),j&&console.log(` "${j}"`),L?console.log(` ${L}`):U&&console.log(` ${U}`)}$.length>E&&console.log(`
|
|
331
|
+
... and ${$.length-E} more`),console.log(`
|
|
330
332
|
To pull them into the local DB (will lose unread badges): npm run sync-all -- --read-unread
|
|
331
|
-
`)}if(v.length>0){let $=v.filter(([,T])=>Xe(T)===V.CONFIRMED),
|
|
332
|
-
`);for(let[$,
|
|
333
|
-
`);let $=20;for(let[
|
|
334
|
-
... and ${_.length-$} more`)}p.length===0&&console.log(" All caught up \u2014 no unanswered messages.");let A=new Set(Object.keys(e)),I=new Set(Object.values(e).map($=>$.profileUrl).filter(Boolean)),P=Object.entries(i).filter(([$,
|
|
333
|
+
`)}if(v.length>0){let $=v.filter(([,T])=>Xe(T)===V.CONFIRMED),E=v.filter(([,T])=>{let O=Xe(T);return O===V.DRAFT||O===V.NEEDS_REVIEW});console.log(` Drafts: ${v.length} total (${$.length} confirmed, ${E.length} pending)`),E.length>0&&console.log(" Review: npm run messages -- --review-drafts"),$.length>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let C=p.filter(([,$])=>$.actionNeeded==="schedule_call"),_=p.filter(([,$])=>$.actionNeeded!=="schedule_call");if(_.sort(($,E)=>{let T={high:0,medium:1,low:2}[$[1].suggestedPriority]??3,O={high:0,medium:1,low:2}[E[1].suggestedPriority]??3;return T-O}),C.length>0){console.log(` SCHEDULE CALL (${C.length}):
|
|
334
|
+
`);for(let[$,E]of C){let T=E.category||"",O=E.summary||"";console.log(` ${$}${T?` [${T}]`:""} \u2192 schedule_call`),O&&console.log(` ${O}`)}console.log()}if(_.length>0){console.log(` REPLY NEEDED (${_.length}):
|
|
335
|
+
`);let $=20;for(let[E,T]of _.slice(0,$)){let O=T.category||"",H=T.suggestedPriority?`[${T.suggestedPriority}]`:"",ie=(T.autoTags||[]).slice(0,4).join(", "),ae=T.summary||"",L=[...T.messages||[]].reverse().find(U=>U.sender!==K&&U.sender!=="Unknown")?.text?.slice(0,80)||T.lastMessagePreview?.slice(0,80)||"";console.log(` ${H} ${E}${O?` [${O}]`:""}`),console.log(ae?` ${ae}`:` "${L}"`),ie&&console.log(` #${ie.replace(/, /g," #")}`)}_.length>$&&console.log(`
|
|
336
|
+
... and ${_.length-$} more`)}p.length===0&&console.log(" All caught up \u2014 no unanswered messages.");let A=new Set(Object.keys(e)),I=new Set(Object.values(e).map($=>$.profileUrl).filter(Boolean)),P=Object.entries(i).filter(([$,E])=>E.connectionStatus==="connected"&&E.personActionNeeded==="initiate_contact"&&!I.has($)&&!(E.name&&A.has(E.name))).sort(($,E)=>{let T={high:0,medium:1,low:2}[$[1].personPriority]??3,O={high:0,medium:1,low:2}[E[1].personPriority]??3;return T!==O?T-O:(E[1].connectionDate||"").localeCompare($[1].connectionDate||"")});if(P.length>0){console.log(`
|
|
335
337
|
INITIATE CONTACT (${P.length}):
|
|
336
|
-
`);let $=20;for(let[
|
|
337
|
-
... and ${P.length-$} more`)}let
|
|
338
|
-
BALL IN THEIR COURT: ${
|
|
338
|
+
`);let $=20;for(let[E,T]of P.slice(0,$)){let O=T.personPriority?`[${T.personPriority.toUpperCase()}]`:"",H=T.personSummary||T.title||"";console.log(` ${O} ${T.name||"Unknown"} \u2014 ${H}`)}P.length>$&&console.log(`
|
|
339
|
+
... and ${P.length-$} more`)}let z=s.filter(([,$])=>$.conversationStatus==="awaiting_reply");z.length>0&&console.log(`
|
|
340
|
+
BALL IN THEIR COURT: ${z.length} conversations`),W&&console.log(`
|
|
339
341
|
[DRY RUN \u2014 no changes written]`),console.log(`
|
|
340
342
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
341
|
-
`)}async function
|
|
343
|
+
`)}async function Ra(e,t){console.log(`
|
|
342
344
|
\u2550\u2550 BACKFILL: Reading conversations with 0 messages \u2550\u2550
|
|
343
|
-
`);let n=Object.entries(t).filter(([,a])=>!a.messages||a.messages.length===0).map(([a,l])=>({name:a,preview:l.lastMessagePreview||"",lastBy:l.lastMessageBy}));if(n.length===0)return console.log(" All conversations already have messages."),[];n.sort((a,l)=>a.lastBy==="them"&&l.lastBy!=="them"?-1:a.lastBy!=="them"&&l.lastBy==="them"?1:0);let o=Math.min(n.length,
|
|
344
|
-
`);let s=[],i=0,r=0,c=[];for(let a=0;a<o;a++){let{name:l}=n[a];console.log(` [${a+1}/${o}] ${l}`);let u=e.page;try{if(await
|
|
345
|
-
Backfill complete: ${s.length} read, ${i} failed${r?`, ${r} skipped on CDP recovery`:""}`),n.length>o&&console.log(` ${n.length-o} more remaining (run again or increase --max)`),s}function
|
|
345
|
+
`);let n=Object.entries(t).filter(([,a])=>!a.messages||a.messages.length===0).map(([a,l])=>({name:a,preview:l.lastMessagePreview||"",lastBy:l.lastMessageBy}));if(n.length===0)return console.log(" All conversations already have messages."),[];n.sort((a,l)=>a.lastBy==="them"&&l.lastBy!=="them"?-1:a.lastBy!=="them"&&l.lastBy==="them"?1:0);let o=Math.min(n.length,Et);console.log(` ${n.length} conversations without messages, reading ${o} (--max=${Et})
|
|
346
|
+
`);let s=[],i=0,r=0,c=[];for(let a=0;a<o;a++){let{name:l}=n[a];console.log(` [${a+1}/${o}] ${l}`);let u=e.page;try{if(await ao(u),!(await Sn(u,l)).verified){console.log(" Not found or thread didn't load."),i++,await ve(u),await k(500);continue}let d=await yn(u);if(!d||d.length===0){console.log(" No messages extracted."),i++,await ve(u),await k(500);continue}if(!wn(d,l,c)){console.log(" Skipped \u2014 stale data."),i++,await ve(u),await k(500);continue}let w=await gn(u),h=t[l]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]};h.messages=bn(h.messages,d),h.lastSynced=new Date().toISOString(),w&&(h.profileUrl=w),t[l]=h,W||we(t),console.log(` \u2713 ${h.messages.length} msgs${w?" +url":""}`),s.push({name:l}),c=[...new Set(d.map(b=>b.sender).filter(b=>b&&b!=="Unknown"))],await ve(u),await k(500)}catch(f){if(!Pe(f))throw f;r++,await Yt(e,`Backfill thread ${a+1}/${o} (${l})`)}}return console.log(`
|
|
347
|
+
Backfill complete: ${s.length} read, ${i} failed${r?`, ${r} skipped on CDP recovery`:""}`),n.length>o&&console.log(` ${n.length-o} more remaining (run again or increase --max)`),s}function Ia(e){let t=ut(),n=Object.values(e),o=n.filter(a=>a.sources?.includes("recruiters-from-jobs")&&!a.connectionStatus).length,s=n.filter(a=>a.connectionStatus==="modal_failed").length,i=o+s,r=n.filter(a=>a.connectionStatus==="connected"&&a.connectionMethod).length,c=n.filter(a=>a.connectionStatus==="pending"||a.connectionStatus==="sent_without_note").length;console.log("\u2550\u2550\u2550 CONNECTION QUOTA & QUEUE \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Today: ${t.daily.sent}/${t.daily.max} sent (${t.daily.remaining} remaining)`),console.log(` Week: ${t.weekly.sent}/${t.weekly.max} sent (${t.weekly.remaining} remaining)`),console.log(` Queue: ${i} profiles (${o} new, ${s} retry)`),console.log(` Funnel: ${r} accepted, ${c} pending`),i===0&&console.log(" \u26A0 Queue empty \u2014 need new job applications to feed funnel"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}function Da(e){let t=Object.values(e).filter(n=>n.jobCount>=2).sort((n,o)=>(o.jobCount||0)-(n.jobCount||0)).slice(0,10);if(t.length!==0){console.log("\u2550\u2550\u2550 TOP RECRUITERS (by job count) \u2550\u2550\u2550");for(let n=0;n<t.length;n++){let o=t[n],s=o.connectionStatus==="connected"?"connected":o.connectionStatus==="pending"||o.connectionStatus==="sent_without_note"?"pending":o.connectionStatus||"unknown",i=o.lastJobTitle?ge(o.lastJobTitle,25):"",r=o.lastJobDate||"",c=i?` (last: ${i}${r?", "+r:""})`:"";console.log(` ${String(n+1).padStart(2)}. ${ge(o.name||"?",25).padEnd(25)} ${String(o.jobCount).padStart(2)} jobs | ${s.padEnd(10)}${c}`)}console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}}function Oa(){let e=Fo(10);if(e.length!==0){console.log("\u2550\u2550\u2550 TOP JOBS TO APPLY \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let t=0;t<e.length;t++){let{score:n,job:o}=e[t],s=ge(o.title||"?",30),i=ge(o.company||"?",15),r=o.salary?` \u2014 ${ge(o.salary,12)}`:"",c=o.location?` \u2014 ${ge(o.location,15)}`:"",a=o.recruiterUrl?" \u{1F464}":"";console.log(` ${String(t+1).padStart(2)}. [${String(n).padStart(2)}] ${s} @ ${i}${r}${c}${a}`)}console.log(" Apply: npm run apply-queue"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}}function Na(){let e=dn();e.totalJobs===0&&e.totalVisited===0||(console.log("\u2550\u2550\u2550 MARKET RESEARCH \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Scouted jobs: ${e.totalJobs}${e.lastScoutDate?` (last: ${e.lastScoutDate})`:""}`),console.log(` Discovered people: ${e.totalRecruiters}`),console.log(` Profile visits: ${e.totalVisited} unique (${e.todayVisited} today)`),e.topTech.length>0&&console.log(` Top tech: ${e.topTech.slice(0,5).join(", ")}`),e.topCompanies.length>0&&console.log(` Top companies: ${e.topCompanies.slice(0,5).join(", ")}`),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"))}function Ma(){let e=xo();if(e.totalApplications!==0){if(console.log(`\u2550\u2550\u2550 FAQ STATS (${e.totalApplications} applications) \u2550\u2550`),console.log(` Unique questions: ${e.uniqueQuestions}`),e.topQuestions.length>0){console.log(" Top questions:");for(let t of e.topQuestions.slice(0,8)){let n=ge(t.topAnswer,30);console.log(` "${ge(t.question,40)}" \u2014 ${t.count}x \u2192 ${n}`)}}if(e.inconsistent.length>0){console.log(` Inconsistent answers: ${e.inconsistent.length} \u26A0`);for(let t of e.inconsistent.slice(0,3))console.log(` "${ge(t.question,35)}" \u2014 ${t.answers.join(", ")}`)}console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}}function ge(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Pa(){let e=ct(),t=J(),n=new Set(Object.keys(e)),o=new Set(Object.values(e).map(g=>g.profileUrl).filter(Boolean));console.log(`
|
|
346
348
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" TODAY'S PRIORITIES"),console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
347
|
-
`),console.log(
|
|
348
|
-
`);for(let p=0;p<
|
|
349
|
-
`);for(let[
|
|
350
|
-
`);for(let p=0;p<
|
|
351
|
-
`);for(let p=0;p<
|
|
352
|
-
`);for(let p=0;p<
|
|
353
|
-
`);for(let p=0;p<
|
|
354
|
-
`);for(let p=0;p<
|
|
349
|
+
`),console.log(ps()),console.log(""),Ia(t),console.log(""),Da(t),console.log(""),Na(),console.log(""),Oa(),console.log(""),Ma(),console.log("");let s=Object.entries(e),i=s.filter(([,g])=>g.unread===!0).sort((g,p)=>(p[1].lastMessageTime||"").localeCompare(g[1].lastMessageTime||""));if(i.length>0){let g=i.slice(0,10);console.log(` UNREAD ON LINKEDIN (${i.length}) \u2014 bold in LinkedIn UI, not yet opened:
|
|
350
|
+
`);for(let p=0;p<g.length;p++){let[v,C]=g[p],_=C.category?` [${C.category}]`:"",A=C.summary||(C.personContext?.title?`${C.personContext.title}${C.personContext.company?` at ${C.personContext.company}`:""}`:null)||C.lastMessagePreview?.slice(0,60)||null;console.log(` ${p+1}. ${v}${_}${A?` \u2014 ${A}`:""}`)}i.length>10&&console.log(` ... +${i.length-10} more`),console.log()}let r=new Date().toISOString().slice(0,10),c=s.filter(([,g])=>g.followUpNote),a=c.filter(([,g])=>!g.followUpDate||g.followUpDate<=r),l=c.filter(([,g])=>g.followUpDate&&g.followUpDate>r);if(c.length>0){console.log(` FOLLOW-UPS (${a.length} due, ${l.length} scheduled):
|
|
351
|
+
`);for(let[g,p]of a){let v=p.followUpDate?` [due ${p.followUpDate}]`:" [no date]";console.log(` \u26A1 ${g}${v} \u2014 ${p.followUpNote}`)}for(let[g,p]of l.slice(0,5))console.log(` \u{1F4C5} ${g} [${p.followUpDate}] \u2014 ${p.followUpNote}`);l.length>5&&console.log(` ... +${l.length-5} more scheduled`),console.log()}let u=g=>g.actionNeeded&&g.actionNeeded!=="none"&&(!g.reviewedAtPreview||ze(g.lastMessagePreview)!==ze(g.reviewedAtPreview)),f=s.filter(([,g])=>u(g)).sort((g,p)=>(p[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(f.length>0){let g=f.slice(0,20);console.log(` UNREVIEWED \u2014 NEW MESSAGES (${f.length}):
|
|
352
|
+
`);for(let p=0;p<g.length;p++){let[v,C]=g[p],_=C.priority||C.suggestedPriority||"",A=C.category?` [${C.category}]`:"",I=C.summary||"";console.log(` ${p+1}. ${_?`[${_}] `:""}${v}${A} \u2014 ${I}`)}f.length>20&&console.log(` ... +${f.length-20} more`),console.log()}let d=s.filter(([,g])=>g.actionNeeded==="schedule_call").sort((g,p)=>{let v={high:0,medium:1,low:2}[g[1].suggestedPriority]??3,C={high:0,medium:1,low:2}[p[1].suggestedPriority]??3;return v-C});if(d.length>0){let g=d.slice(0,5);console.log(` CALLS TO SCHEDULE (${d.length}):
|
|
353
|
+
`);for(let p=0;p<g.length;p++){let[v,C]=g[p],_=C.summary||C.personContext?.title||"";console.log(` ${p+1}. ${v} \u2014 ${_}`)}d.length>5&&console.log(` ... +${d.length-5} more`),console.log()}let m=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us"&&g.actionNeeded!=="schedule_call"&&(g.suggestedPriority==="high"||g.priority==="high")&&!u(g)).sort((g,p)=>(p[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(m.length>0){let g=m.slice(0,8);console.log(` REPLY NEEDED \u2014 HIGH (${m.length}):
|
|
354
|
+
`);for(let p=0;p<g.length;p++){let[v,C]=g[p],_=C.category?` [${C.category}]`:"",A=C.summary||"";console.log(` ${p+1}. ${v}${_} \u2014 ${A}`)}m.length>8&&console.log(` ... +${m.length-8} more`),console.log()}let w=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us"&&g.actionNeeded!=="schedule_call"&&g.suggestedPriority==="medium"&&g.priority!=="high"&&!u(g)).sort((g,p)=>(p[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(w.length>0){let g=w.slice(0,5);console.log(` REPLY NEEDED \u2014 MEDIUM (${w.length}):
|
|
355
|
+
`);for(let p=0;p<g.length;p++){let[v,C]=g[p],_=C.category?` [${C.category}]`:"",A=C.summary||"";console.log(` ${p+1}. ${v}${_} \u2014 ${A}`)}w.length>5&&console.log(` ... +${w.length-5} more`),console.log()}let h=Object.entries(t).filter(([g,p])=>p.connectionStatus==="connected"&&p.personActionNeeded==="initiate_contact"&&!o.has(g)&&!(p.name&&n.has(p.name))).sort((g,p)=>{let v={high:0,medium:1,low:2}[g[1].personPriority]??3,C={high:0,medium:1,low:2}[p[1].personPriority]??3;return v!==C?v-C:(p[1].connectionDate||"").localeCompare(g[1].connectionDate||"")});if(h.length>0){let g=h.slice(0,10);console.log(` NEW CONNECTIONS TO MESSAGE (${h.length}):
|
|
356
|
+
`);for(let p=0;p<g.length;p++){let[,v]=g[p],C=v.personPriority?`[${v.personPriority.toUpperCase()}]`:"",_=v.connectionDate?ja(v.connectionDate):"",A=v.title?`${v.title}${v.company?` at ${v.company}`:""}`:v.company||"";console.log(` ${p+1}. ${C} ${v.name||"Unknown"} \u2014 ${A}${_?` (${_})`:""}`)}h.length>10&&console.log(` ... +${h.length-10} more`),console.log()}let b=s.filter(([,g])=>Xe(g));if(b.length>0){let g=b.filter(([,v])=>Xe(v)===V.CONFIRMED).length,p=b.filter(([,v])=>{let C=Xe(v);return C===V.DRAFT||C===V.NEEDS_REVIEW}).length;console.log(` DRAFTS: ${b.length} (${g} confirmed, ${p} pending)`),g>0&&console.log(" Send: npm run messages -- --push-drafts"),p>0&&console.log(" Review: npm run messages -- --review-drafts"),console.log()}let y=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us").length,S=s.filter(([,g])=>g.conversationStatus==="awaiting_reply").length;console.log(` Summary: ${i.length} unread on LinkedIn, ${f.length} unreviewed, ${y} need reply, ${h.length} new connections, ${S} ball in their court`),console.log(`
|
|
355
357
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
356
|
-
`)}function
|
|
358
|
+
`)}function ja(e){let t=new Date(e);if(isNaN(t))return"";let n=Math.floor((Date.now()-t.getTime())/864e5);return n===0?"today":n===1?"1d ago":`${n}d ago`}function La(){let e=ct();Hn(e,null,null)}async function Fa(){if(console.log(`
|
|
357
359
|
LinkedIn Sync-All
|
|
358
|
-
`),
|
|
359
|
-
\u26A0 Phase 1 CDP dead (attempt ${a}/${
|
|
360
|
+
`),Fs){Pa();return}if(Ps){let r=Ht("sync-all","report");La(),Ke(r,"success");return}if(Ls){let r=Ht("sync-all","enrich");try{Ta(),Ke(r,"success")}catch(c){throw Ke(r,"error",null,c.message),c}return}let e=js?"backfill":Un?"full":"incremental",t=Ht("sync-all",e),n={scanned:0,toReRead:0,threadsRead:0,newMessages:0};W&&console.log(" [DRY RUN mode]"),console.log(` Mode: ${e} | Max threads to read: ${Et}`);let o=ct(),s=await Qo(),i={browser:s.browser,page:s.page};try{await pn(i.page);let r=null,c=[];if(js)c=await Ra(i,o);else{let a=0;for(;;)try{r=await Aa(i.page,o);break}catch(d){if(!Pe(d))throw d;if(a++,a>=Fn)throw new Error(`Phase 1 failed ${Fn} times on CDP death \u2014 giving up. Last: ${d.message}`);console.log(`
|
|
361
|
+
\u26A0 Phase 1 CDP dead (attempt ${a}/${Fn}). Recovering and restarting Phase 1...`),await Yt(i,`Phase 1 attempt ${a}`)}let l=new Set;c=await Ea(i,r.toReRead,o,l),n.scanned=r.totalCards||0,n.toReRead=r.toReRead?.size||0;let u=new Set(c.map(d=>d.name)),f=0;for(let[d,{card:m}]of r.toReRead){if(u.has(d)||l.has(d))continue;let w=o[d];w&&(w.lastMessageBy=m.lastMessageBy,w.lastMessageTime=m.lastMessageTime||w.lastMessageTime,w.unread=m.unread,f++)}f>0&&(console.log(` Pending re-read: ${f} threads (raise --max or re-run to drain).`),W||we(o))}n.threadsRead=c.length,n.newMessages=c.reduce((a,l)=>a+(l.newMessages||0),0);try{let a=await xa(i,o,c);a&&(n.autoEnriched=a.enriched,a.authWall&&(n.autoEnrichAuthWall=!0))}catch(a){console.log(`
|
|
360
362
|
\u26A0 Auto-enrich phase crashed: ${a.message?.slice(0,200)}`),console.log(` Continuing with post-processing \u2014 data integrity is unaffected.
|
|
361
|
-
`)}c.length>0&&
|
|
362
|
-
CDP page recoveries this run: ${je.pageRecoveries}`),W||
|
|
363
|
-
Error:`,r.message),
|
|
363
|
+
`)}c.length>0&&_a(o,c),Hn(o,r,c,{unreadCards:r?.unreadCards,readUnread:Bn}),je.pageRecoveries>0&&console.log(`
|
|
364
|
+
CDP page recoveries this run: ${je.pageRecoveries}`),W||sn(),Ke(t,"success",n)}catch(r){console.error(`
|
|
365
|
+
Error:`,r.message),qn&&console.error(r.stack),Ke(t,"error",n,r.message)}finally{if(!W&&!Ps&&!Ls&&!Fs)try{sn()}catch{}await i.browser.close()}}Fa();
|