ilml-plugin-linkedin 1.20.3 → 1.20.5
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 +79 -79
- package/dist/enrichProfile.mjs +15 -15
- package/dist/enrichProfiles.mjs +48 -48
- package/dist/funnelRunner.mjs +50 -50
- package/dist/messageBot.mjs +59 -59
- package/dist/run.mjs +62 -62
- package/dist/scout.mjs +38 -38
- package/dist/syncAll.mjs +101 -101
- package/dist/syncConnections.mjs +1 -1
- package/dist/verifyAbout.mjs +18 -18
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +1 -1
- package/dist/visit.mjs +37 -37
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/syncConnections.mjs
CHANGED
|
@@ -5,7 +5,7 @@ var ln=Object.defineProperty;var V=(e,n)=>{for(var t in n)ln(e,t,{get:n[t],enume
|
|
|
5
5
|
`),process.exit(1));var Pe=Fn({token:Le});function Mn(e){if(!e||e<1e3)return`${e||0}ms`;let n=Math.round(e/1e3);if(n<60)return`${n}s`;let t=Math.floor(n/60),o=n%60;return o?`${t}m ${o}s`:`${t}m`}function Un({scriptName:e,mode:n,status:t,error:o,duration:r}){let s=t==="error"?"\u2717":t==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),l=r?` ${Mn(r)}`:"",c=t==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:t==="quota-reached"?"daily quota reached":"done",a=n&&n!=="default"?` (${n})`:"";return`${s} ${e}${a} \u2014 ${c} \u2014 ${i}${l}`}async function Me({scriptName:e,mode:n,status:t,summaryLines:o,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let c=`**${Un({scriptName:e,mode:n,status:t,error:r,duration:s})}**
|
|
6
6
|
|
|
7
7
|
${o.join(`
|
|
8
|
-
`)}`;try{await Pe.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Bn=qn(import.meta.url),Jn=O.dirname(O.dirname(Bn)),te=process.env.DATA_DIR?O.resolve(process.env.DATA_DIR,"collected-profiles"):O.join(Jn,"collected-profiles"),oe=O.join(te,"run-log.json");function Hn(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";A.writeFileSync(o,t);for(let r=0;r<3;r++)try{A.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ue(){try{if(!A.existsSync(oe))return{runs:[]};let e=JSON.parse(A.readFileSync(oe,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function qe(e){A.existsSync(te)||A.mkdirSync(te,{recursive:!0});try{Hn(oe,e)}catch(n){console.error(`[!] Failed to save run-log.json: ${n.message}`)}}function Be(e,n="default"){let t=Ue();for(let i of t.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:n,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(i=>new Date(i.timestamp).getTime()>s),qe(t),{script:e,mode:n,startTime:o.getTime(),runIndex:t.runs.length-1}}function re(e,n,t=null,o=null){if(!e)return;let r=null;try{let i=Ue(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=n,l.result=n,l.duration=Date.now()-e.startTime,l.stats=t,l.error=o,r=l.duration;else{let c=i.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());c&&(c.status=n,c.result=n,c.duration=Date.now()-e.startTime,c.stats=t,c.error=o,r=c.duration)}qe(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=t&&Array.isArray(t.summaryLines)?t.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=n==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";Me({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import"dotenv/config";import*as p from"fs";import*as pe from"os";import*as h from"path";import{fileURLToPath as kt}from"url";var ce={};V(ce,{NAME:()=>Vn,VERSION:()=>Wn,up:()=>Kn});import*as C from"fs";import*as z from"path";var Wn=1,Vn="normalize-jobs-and-questions",Gn=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Yn=50;function se(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function ie(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{C.writeFileSync(o,t)}catch(r){try{C.unlinkSync(o)}catch{}throw r}try{C.renameSync(o,e)}catch(r){try{C.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Kn(e,n){let t=z.join(e,"jobs.json"),o=z.join(n,"scouted-jobs.json"),r=z.join(e,"application-questions.json"),s=se(t)||{},i=se(o)||{},l=0,c=[];for(let f of Object.keys(s)){if(!i[f])continue;let u=i[f],m=s[f];for(let g of Gn)u[g]!=null&&m[g]==null&&(m[g]=u[g]);c.push(f),l++}l>0?(ie(t,s),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=se(r);if(a&&Array.isArray(a.applications)){let f={},u=0;for(let m of a.applications){let g=m.jobId||"unknown";f[g]||(f[g]={applications:[]});let v=(m.questions||[]).map(d=>{let w={type:d.type||"input",question:d.question||"",answer:d.answer||""};return d.options&&(d.options.length<=Yn?w.options=d.options:(w.optionsOmitted=!0,u++)),d.page&&(w.page=d.page),d.wasPreFilled&&(w.wasPreFilled=!0),d.wasRetry&&(w.wasRetry=!0),w});f[g].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||v.length,questions:v})}ie(r,f),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),u>0&&console.log(` Phase 2: Stripped bloated options from ${u} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(c.length>0){for(let f of c)delete i[f];ie(o,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var le={};V(le,{NAME:()=>Qn,VERSION:()=>zn,up:()=>et});import*as $ from"fs";import*as Je from"path";var zn=2,Qn="reset-unread-flags";function Xn(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function Zn(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{$.writeFileSync(o,t)}catch(r){try{$.unlinkSync(o)}catch{}throw r}try{$.renameSync(o,e)}catch(r){try{$.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function et(e){let n=Je.join(e,"conversations.json"),t=Xn(n);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(t))t[r].unread===!0&&(t[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Zn(n,t),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var ae={};V(ae,{NAME:()=>tt,VERSION:()=>nt,up:()=>ct});import*as E from"fs";import*as He from"path";var nt=3,tt="recompute-last-message-by",ot=new Set(["draft","confirmed","rejected","needs_review"]);function rt(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function st(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{E.writeFileSync(o,t)}catch(r){try{E.unlinkSync(o)}catch{}throw r}try{E.renameSync(o,e)}catch(r){try{E.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function it(e,n){if(!e||e.length===0)return"them";let t=e.filter(s=>!ot.has(s.status));if(t.length===0)return"them";let o=t.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...t].reverse();for(let s of r){let i=s.sender;if(i===n)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function ct(e){let n=He.join(e,"conversations.json"),t=rt(n);if(!t){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,s=0,i=0;for(let l of Object.keys(t)){let c=t[l];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,s++);let a=Array.isArray(c.messages)?c.messages:[],f=it(a,o),u=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=u,r++}if(r===0){console.log(" No conversations to recompute.");return}st(n,t),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var ue={};V(ue,{NAME:()=>at,VERSION:()=>lt,up:()=>dt});import*as x from"fs";import*as We from"path";var lt=4,at="split-connection-timestamps",ut=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ft(e){if(!x.existsSync(e))return null;let n=x.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function pt(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{x.writeFileSync(o,t)}catch(r){try{x.unlinkSync(o)}catch{}throw r}try{x.renameSync(o,e)}catch(r){try{x.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function dt(e){let n=We.join(e,"people.json"),t=ft(n);if(!t||typeof t!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(t)){let i=t[s];!i||typeof i!="object"||(r++,ut.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}pt(n,t),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as k from"path";import{fileURLToPath as mt}from"url";var ht=mt(import.meta.url),gt=k.dirname(k.dirname(ht)),W=process.env.DATA_DIR?k.resolve(process.env.DATA_DIR,"market-research"):k.join(gt,"market-research"),Vo=k.join(W,"scouted-jobs.json"),Go=k.join(W,"discovered-people.json"),Yo=k.join(W,"visit-log.json"),Ko=k.join(W,"companies.json"),zo=k.join(W,"job-decisions.json");function Ve(){yt=null,St=null,wt=null,bt=null,vt=null}var yt=null;var St=null;var wt=null;var bt=null;var vt=null;var At=kt(import.meta.url),Ct=h.dirname(At),$t=h.dirname(h.dirname(Ct));function Et(e){return e&&(e==="~"?pe.homedir():e.startsWith("~/")||e.startsWith("~\\")?h.join(pe.homedir(),e.slice(2)):e)}var T=process.env.DATA_DIR?h.resolve(Et(process.env.DATA_DIR)):$t,L=h.join(T,"collected-profiles"),P=h.join(T,"market-research"),b=h.join(T,".schema-version"),Ge=[h.join(L,".schema-version"),h.join(P,".schema-version")],j=4,D=[{version:1,module:ce},{version:2,module:le},{version:3,module:ae},{version:4,module:ue}];(function(){D.sort((o,r)=>o.version-r.version);let n=new Set;for(let o of D){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(n.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);n.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let t=D.length?D[D.length-1].version:0;if(t!==j)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${j}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<D.length;o++){let r=o+1;if(D[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${D[o].version}`)}})();function Qe(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
8
|
+
`)}`;try{await Pe.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Bn=qn(import.meta.url),Jn=O.dirname(O.dirname(Bn)),te=process.env.DATA_DIR?O.resolve(process.env.DATA_DIR,"collected-profiles"):O.join(Jn,"collected-profiles"),oe=O.join(te,"run-log.json");function Hn(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";A.writeFileSync(o,t);for(let r=0;r<3;r++)try{A.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ue(){try{if(!A.existsSync(oe))return{runs:[]};let e=JSON.parse(A.readFileSync(oe,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function qe(e){A.existsSync(te)||A.mkdirSync(te,{recursive:!0});try{Hn(oe,e)}catch(n){console.error(`[!] Failed to save run-log.json: ${n.message}`)}}function Be(e,n="default"){let t=Ue();for(let i of t.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:n,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(i=>new Date(i.timestamp).getTime()>s),qe(t),{script:e,mode:n,startTime:o.getTime(),runIndex:t.runs.length-1}}function re(e,n,t=null,o=null){if(!e)return;let r=null;try{let i=Ue(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=n,l.result=n,l.duration=Date.now()-e.startTime,l.stats=t,l.error=o,r=l.duration;else{let c=i.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());c&&(c.status=n,c.result=n,c.duration=Date.now()-e.startTime,c.stats=t,c.error=o,r=c.duration)}qe(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=t&&Array.isArray(t.summaryLines)?t.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=n==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";Me({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import"dotenv/config";import*as p from"fs";import*as pe from"os";import*as h from"path";import{fileURLToPath as kt}from"url";var ce={};V(ce,{NAME:()=>Vn,VERSION:()=>Wn,up:()=>Kn});import*as C from"fs";import*as z from"path";var Wn=1,Vn="normalize-jobs-and-questions",Gn=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Yn=50;function se(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function ie(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{C.writeFileSync(o,t)}catch(r){try{C.unlinkSync(o)}catch{}throw r}try{C.renameSync(o,e)}catch(r){try{C.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Kn(e,n){let t=z.join(e,"jobs.json"),o=z.join(n,"scouted-jobs.json"),r=z.join(e,"application-questions.json"),s=se(t)||{},i=se(o)||{},l=0,c=[];for(let f of Object.keys(s)){if(!i[f])continue;let u=i[f],m=s[f];for(let g of Gn)u[g]!=null&&m[g]==null&&(m[g]=u[g]);c.push(f),l++}l>0?(ie(t,s),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=se(r);if(a&&Array.isArray(a.applications)){let f={},u=0;for(let m of a.applications){let g=m.jobId||"unknown";f[g]||(f[g]={applications:[]});let v=(m.questions||[]).map(d=>{let w={type:d.type||"input",question:d.question||"",answer:d.answer||""};return d.options&&(d.options.length<=Yn?w.options=d.options:(w.optionsOmitted=!0,u++)),d.page&&(w.page=d.page),d.wasPreFilled&&(w.wasPreFilled=!0),d.wasRetry&&(w.wasRetry=!0),w});f[g].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||v.length,questions:v})}ie(r,f),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),u>0&&console.log(` Phase 2: Stripped bloated options from ${u} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(c.length>0){for(let f of c)delete i[f];ie(o,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var le={};V(le,{NAME:()=>Qn,VERSION:()=>zn,up:()=>et});import*as $ from"fs";import*as Je from"path";var zn=2,Qn="reset-unread-flags";function Xn(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function Zn(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{$.writeFileSync(o,t)}catch(r){try{$.unlinkSync(o)}catch{}throw r}try{$.renameSync(o,e)}catch(r){try{$.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function et(e){let n=Je.join(e,"conversations.json"),t=Xn(n);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(t))t[r].unread===!0&&(t[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Zn(n,t),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var ae={};V(ae,{NAME:()=>tt,VERSION:()=>nt,up:()=>ct});import*as E from"fs";import*as He from"path";var nt=3,tt="recompute-last-message-by",ot=new Set(["draft","confirmed","rejected","needs_review"]);function rt(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function st(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{E.writeFileSync(o,t)}catch(r){try{E.unlinkSync(o)}catch{}throw r}try{E.renameSync(o,e)}catch(r){try{E.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function it(e,n){if(!e||e.length===0)return"them";let t=e.filter(s=>!ot.has(s.status));if(t.length===0)return"them";let o=t.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...t].reverse();for(let s of r){let i=s.sender;if(i===n)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function ct(e){let n=He.join(e,"conversations.json"),t=rt(n);if(!t){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,s=0,i=0;for(let l of Object.keys(t)){let c=t[l];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,s++);let a=Array.isArray(c.messages)?c.messages:[],f=it(a,o),u=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=u,r++}if(r===0){console.log(" No conversations to recompute.");return}st(n,t),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var ue={};V(ue,{NAME:()=>at,VERSION:()=>lt,up:()=>dt});import*as x from"fs";import*as We from"path";var lt=4,at="split-connection-timestamps",ut=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ft(e){if(!x.existsSync(e))return null;let n=x.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function pt(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{x.writeFileSync(o,t)}catch(r){try{x.unlinkSync(o)}catch{}throw r}try{x.renameSync(o,e)}catch(r){try{x.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function dt(e){let n=We.join(e,"people.json"),t=ft(n);if(!t||typeof t!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(t)){let i=t[s];!i||typeof i!="object"||(r++,ut.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}pt(n,t),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as k from"path";import{fileURLToPath as mt}from"url";var ht=mt(import.meta.url),gt=k.dirname(k.dirname(ht)),W=process.env.DATA_DIR?k.resolve(process.env.DATA_DIR,"market-research"):k.join(gt,"market-research"),Go=k.join(W,"scouted-jobs.json"),Yo=k.join(W,"discovered-people.json"),Ko=k.join(W,"visit-log.json"),zo=k.join(W,"companies.json"),Qo=k.join(W,"job-decisions.json");function Ve(){yt=null,St=null,wt=null,bt=null,vt=null}var yt=null;var St=null;var wt=null;var bt=null;var vt=null;var At=kt(import.meta.url),Ct=h.dirname(At),$t=h.dirname(h.dirname(Ct));function Et(e){return e&&(e==="~"?pe.homedir():e.startsWith("~/")||e.startsWith("~\\")?h.join(pe.homedir(),e.slice(2)):e)}var T=process.env.DATA_DIR?h.resolve(Et(process.env.DATA_DIR)):$t,L=h.join(T,"collected-profiles"),P=h.join(T,"market-research"),b=h.join(T,".schema-version"),Ge=[h.join(L,".schema-version"),h.join(P,".schema-version")],j=4,D=[{version:1,module:ce},{version:2,module:le},{version:3,module:ae},{version:4,module:ue}];(function(){D.sort((o,r)=>o.version-r.version);let n=new Set;for(let o of D){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(n.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);n.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let t=D.length?D[D.length-1].version:0;if(t!==j)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${j}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<D.length;o++){let r=o+1;if(D[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${D[o].version}`)}})();function Qe(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
9
9
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
10
10
|
`),process.exit(1));try{p.mkdirSync(T,{recursive:!0})}catch(n){n.code!=="EEXIST"&&(console.error(`
|
|
11
11
|
[FATAL] Cannot create DATA_DIR (${T}): ${n.message}`),console.error(` Fix the path or permissions and try again.
|
package/dist/verifyAbout.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var ot=Object.defineProperty;var Q=(e,t)=>()=>(e&&(t=e(e=0)),t);var it=(e,t)=>{for(var n in t)ot(e,n,{get:t[n],enumerable:!0})};async function m(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function oe(e,t,{timeout:n=45e3,poll:o=1e3,label:i="page"}={}){let a=Date.now();for(;Date.now()-a<n;){try{if(await e.evaluate(f=>!!document.querySelector(f),t)){let f=Date.now()-a;return f>6e3&&console.log(` (waited ${Math.round(f/1e3)}s for LinkedIn to finish loading ${i})`),!0}}catch{}await new Promise(r=>setTimeout(r,o))}return!1}async function xe(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let i=o.innerText||"",a=i.includes("Premium")||i.includes("premium")||i.includes("Upgrade")||i.includes("upgrade"),r=i.includes("Try for")||i.includes("free trial")||i.includes("/month")||i.includes("per month")||i.includes("Start my")||i.includes("Subscribe"),f=i.includes("Get hired faster")||i.includes("Get hired 2x");if(a||r||f){let x=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(x)return x.click(),{dismissed:!0,matched:i.substring(0,80)};let I=o.querySelectorAll("button");for(let d of I){let S=d.innerText?.trim().toLowerCase()||"",h=d.getAttribute("aria-label")?.toLowerCase()||"";if(S==="not now"||S==="no thanks"||S==="dismiss"||h.includes("dismiss"))return d.click(),{dismissed:!0,matched:i.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})}var U=Q(()=>{});import{getPluginConfig as rt}from"@ilivemylife/graph-sdk";var st,lt,q,Bt,at,ie=Q(async()=>{st=await rt();for(let[e,t]of Object.entries(st))process.env[e]===void 0&&(process.env[e]=t);lt=process.env.LINKEDIN_NAME,q=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Bt=Object.freeze(new Set([q.DRAFT,q.CONFIRMED,q.NEEDS_REVIEW])),at=Object.freeze(new Set([q.DRAFT,q.CONFIRMED,q.REJECTED,q.NEEDS_REVIEW]))});import"dotenv/config";import*as g from"fs";import*as b from"path";import{fileURLToPath as vt}from"url";function _t(){g.existsSync(A)||g.mkdirSync(A,{recursive:!0})}function Et(e,t){if(!g.existsSync(e))return null;try{let n=JSON.parse(g.readFileSync(e,"utf-8"));try{g.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(g.existsSync(o))try{let i=JSON.parse(g.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{g.copyFileSync(o,e)}catch{}return i}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{g.copyFileSync(e,e+".corrupted")}catch{}return null}}function le(){return X||(_t(),X=Et(xt,"people.json")||{},X)}var Ct,kt,A,xt,fn,mn,pn,hn,wn,gn,Ve,yn,bn,X,ae=Q(async()=>{await ie();Ct=vt(import.meta.url),kt=b.dirname(b.dirname(Ct)),A=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"collected-profiles"):b.join(kt,"collected-profiles"),xt=b.join(A,"people.json"),fn=b.join(A,"jobs.json"),mn=b.join(A,"quota.json"),pn=b.join(A,"conversations.json"),hn=b.join(A,"sync-state.json"),wn=b.join(A,"application-questions.json"),gn=b.join(A,"profile-history"),Ve=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},yn=Ve(process.env.CONNECT_MAX_DAILY,20),bn=Ve(process.env.CONNECT_MAX_WEEKLY,100),X=null});var We={};it(We,{extractCertificationsFromDetails:()=>Tt,extractEducationFromDetails:()=>$t,extractExperienceFromDetails:()=>At,extractFeaturedFromDetails:()=>It,extractRecommendationsFromDetails:()=>Lt,extractSkillsFromDetails:()=>Dt});async function At(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await m(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let a=0;a<5;a++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await m(900);await m(1e3);let i=0;for(;i<5&&await e.evaluate(()=>{for(let r of document.querySelectorAll("button"))if(/^Load more$/i.test((r.textContent||"").trim()))return r.click(),!0;return!1});)i++,await m(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await m(700);return await e.evaluate(()=>{let a=document.querySelector("main");if(!a)return[];function r(d){let S=[];for(let h of d.querySelectorAll("div")){let w=Array.from(h.children).filter(v=>v.tagName==="DIV");if(w.length<3)continue;let y=w.filter(v=>(v.textContent||"").trim().length>50);y.length<3||(h.textContent||"").length<500||S.push({el:h,count:y.length,totalText:(h.textContent||"").length})}return S.sort((h,w)=>w.count-h.count||h.totalText-w.totalText),S[0]?.el}let f=r(a);if(!f)return[];let x=Array.from(f.children).filter(d=>d.tagName==="DIV").filter(d=>(d.textContent||"").trim().length>50);function I(d){let S=d[0]||null,h=null,w=null;if(d[1]){let l=d[1].split("\xB7").map(C=>C.trim());h=l[0]||null,l[1]&&(w=l[1])}let y=d.findIndex(l=>/(\d{4}|present)/i.test(l)&&/(-|–|—)/i.test(l)&&l.length<80),v=null,L=null;if(y>=0){let l=d[y].split("\xB7").map(C=>C.trim());v=l[0]||null,l[1]&&(L=l[1])}let P=null,R=-1;if(y>=0&&d[y+1]){let l=d[y+1],C=/^[>*\-•]|^>/.test(l),B=/https?:\/\//.test(l),j=/\d{4}/.test(l),N=/,/.test(l)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(l);!C&&!B&&!j&&l.length<100&&N&&(P=l,R=y+1)}let M=null,ee=-1,p=d[d.length-1];if(p&&/and\s+\+\d+\s+skills?$/i.test(p)){ee=d.length-1;let l=p.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);l&&(M={listed:l[1].split(",").map(C=>C.trim()),additional:parseInt(l[2],10)})}let O=new Set([0,1,y,R,ee].filter(l=>l>=0)),$=d.filter((l,C)=>!O.has(C)),F=$.length>0?$.join(`
|
|
2
2
|
|
|
3
|
-
`):null;return{title:S,company:h,employmentType:w,dates:
|
|
4
|
-
`).map(w=>w.trim()).filter(w=>w&&w.length<5e3);return
|
|
5
|
-
${
|
|
3
|
+
`):null;return{title:S,company:h,employmentType:w,dates:v,duration:L,location:P,description:F,skills:M,_raw:d}}return x.map(d=>{let h=(d.innerText||"").trim().split(`
|
|
4
|
+
`).map(w=>w.trim()).filter(w=>w&&w.length<5e3);return I(h)}).filter(d=>d.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 J(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await m(3e3);let i=e.url();if(/\/(login|authwall|checkpoint)/i.test(i))throw new Error(`Session expired \u2014 bounced to ${i} when fetching /details/${n}/`);if(!i.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${i})`);for(let r=0;r<4;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await m(700);await m(800);let a=0;for(;a<5&&await e.evaluate(()=>{for(let f of document.querySelectorAll("button"))if(/^Load more$/i.test((f.textContent||"").trim()))return f.click(),!0;return!1});)a++,await m(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await m(600)}async function K(e,t,n,o){try{return await o()}catch(i){let a=i.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(a))throw i;return/not available on profile/i.test(a)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${a.slice(0,120)}`),[])}}async function It(e,t){return K(t,"featured","extractFeaturedFromDetails",async()=>(await J(e,t,"featured"),await e.evaluate(`(() => {
|
|
5
|
+
${Y}
|
|
6
6
|
|
|
7
7
|
const main = document.querySelector('main');
|
|
8
8
|
if (!main) return [];
|
|
@@ -42,8 +42,8 @@ var tt=Object.defineProperty;var z=(e,t)=>()=>(e&&(t=e(e=0)),t);var nt=(e,t)=>{f
|
|
|
42
42
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
43
43
|
return true;
|
|
44
44
|
});
|
|
45
|
-
})()`)))}async function
|
|
46
|
-
${
|
|
45
|
+
})()`)))}async function $t(e,t){return K(t,"education","extractEducationFromDetails",async()=>(await J(e,t,"education"),await e.evaluate(`(() => {
|
|
46
|
+
${Y}
|
|
47
47
|
|
|
48
48
|
const main = document.querySelector('main');
|
|
49
49
|
if (!main) return [];
|
|
@@ -79,8 +79,8 @@ var tt=Object.defineProperty;var z=(e,t)=>()=>(e&&(t=e(e=0)),t);var nt=(e,t)=>{f
|
|
|
79
79
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
80
80
|
return true;
|
|
81
81
|
});
|
|
82
|
-
})()`)))}async function
|
|
83
|
-
${
|
|
82
|
+
})()`)))}async function Dt(e,t){return K(t,"skills","extractSkillsFromDetails",async()=>(await J(e,t,"skills"),await e.evaluate(`(() => {
|
|
83
|
+
${Y}
|
|
84
84
|
|
|
85
85
|
const main = document.querySelector('main');
|
|
86
86
|
if (!main) return [];
|
|
@@ -111,8 +111,8 @@ var tt=Object.defineProperty;var z=(e,t)=>()=>(e&&(t=e(e=0)),t);var nt=(e,t)=>{f
|
|
|
111
111
|
skills.push({ name, endorsements, _raw: lines });
|
|
112
112
|
}
|
|
113
113
|
return skills;
|
|
114
|
-
})()`)))}async function
|
|
115
|
-
${
|
|
114
|
+
})()`)))}async function Tt(e,t){return K(t,"certifications","extractCertificationsFromDetails",async()=>(await J(e,t,"certifications"),await e.evaluate(`(() => {
|
|
115
|
+
${Y}
|
|
116
116
|
|
|
117
117
|
const main = document.querySelector('main');
|
|
118
118
|
if (!main) return [];
|
|
@@ -136,8 +136,8 @@ var tt=Object.defineProperty;var z=(e,t)=>()=>(e&&(t=e(e=0)),t);var nt=(e,t)=>{f
|
|
|
136
136
|
|
|
137
137
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
138
138
|
}).filter(e => e.name);
|
|
139
|
-
})()`)))}async function
|
|
140
|
-
${
|
|
139
|
+
})()`)))}async function Lt(e,t){return K(t,"recommendations","extractRecommendationsFromDetails",async()=>(await J(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
140
|
+
${Y}
|
|
141
141
|
|
|
142
142
|
const main = document.querySelector('main');
|
|
143
143
|
if (!main) return [];
|
|
@@ -172,7 +172,7 @@ var tt=Object.defineProperty;var z=(e,t)=>()=>(e&&(t=e(e=0)),t);var nt=(e,t)=>{f
|
|
|
172
172
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
173
173
|
return true;
|
|
174
174
|
});
|
|
175
|
-
})()`)))}var
|
|
175
|
+
})()`)))}var Y,Je=Q(()=>{U();Y=`
|
|
176
176
|
function findEntryContainer(root) {
|
|
177
177
|
const candidates = [];
|
|
178
178
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -235,9 +235,9 @@ function findEntryContainer(root) {
|
|
|
235
235
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
236
236
|
return candidates[0]?.el;
|
|
237
237
|
}
|
|
238
|
-
`});import wt from"puppeteer";import{addExtra as gt}from"puppeteer-extra";import yt from"puppeteer-extra-plugin-stealth";H();await ne();import E from"fs";import L from"path";var lt="cookies.json";function ke(){let e=process.env.ILML_SCOPE_DIR;return e?L.join(e,"plugins-state","linkedin","cookies.json"):lt}function xe(){let e=ke();if(!E.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=E.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 _e(){return E.existsSync(ke())}function at(){let e=process.env.ILML_SCOPE_DIR;return e?L.join(e,"plugins-state","linkedin"):"."}function Ee(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function ct(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Ee(t[1]):"default"}function Ae(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return E.existsSync(t)||E.mkdirSync(t,{recursive:!0}),L.resolve(t);let n=Ee(e||ct()),o=L.join(at(),"chrome-profile",n);return E.existsSync(o)||E.mkdirSync(o,{recursive:!0}),L.resolve(o)}var Ie=".ilml-seeded";function $e(e){return!E.existsSync(L.join(e,Ie))}function De(e){try{E.writeFileSync(L.join(e,Ie),new Date().toISOString())}catch{}}function Te(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{E.rmSync(L.join(e,n),{force:!0}),t++}catch{}return t}import oe from"fs";import ut from"path";var dt={headless:!1,defaultViewport:null,protocolTimeout:3e5},V=new Set,Le=!1;async function Q(){let e=[...V].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});V.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function ft(){if(Le)return;Le=!0;let e=t=>async()=>{await Q(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Q(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Q(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Q(),process.exit(0))}),process.on("exit",()=>{for(let t of V)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function ie(e){return ut.join(e,".ilml-browser-session.json")}function Fe(e,t={}){try{oe.writeFileSync(ie(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function mt(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Fe(e,n?{wsEndpoint:n}:{})}catch{}}function pt(e){let t=qe(e);t&&t.ownerPid===process.pid&&U(e)}function U(e){try{oe.rmSync(ie(e),{force:!0})}catch{}}function qe(e){try{return JSON.parse(oe.readFileSync(ie(e),"utf-8"))}catch{return null}}function Pe(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Me(e,t,n){let o,i=new Promise(r=>{o=setTimeout(()=>r(n),t)}),a=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([a,i])}async function Re(e,t,{probeTimeoutMs:n=4e3}={}){let o=qe(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Pe(o.ownerPid)?"live":(U(t),"free");let i=Symbol("timeout"),a=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await Me(a,n,i);if(r===i)return a.then(_=>{if(_)try{_.disconnect()}catch{}}),"live";if(!r)return U(t),"free";if(Pe(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Me(r.close().then(()=>!0).catch(()=>!1),n,!1))return U(t),"free";try{r.disconnect()}catch{}return"live"}function ht(e,t){e&&(ft(),V.add(e),e.on("disconnected",()=>{V.delete(e),t&&U(t)}))}async function je(e,t={}){let n=Ae(),o={...dt,...t,userDataDir:n},i=`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 Re(e,n)==="live")throw new Error(i);Fe(n);let a;try{a=await e.launch(o)}catch{if(await Re(e,n)==="live")throw new Error(i);Te(n);try{a=await e.launch(o)}catch(m){throw pt(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: ${m.message})`)}}return ht(a,n),mt(n,a),{browser:a,profileDir:n,needsSeed:$e(n)}}async function Ne(e,t){if(!t||!t.needsSeed)return!1;if(!_e())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(...xe()),De(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Oe=gt(wt);Oe.use(yt());async function Be(){let{browser:e,profileDir:t,needsSeed:n}=await je(Oe),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Ne(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}H();await se();async function Tt(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 f(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function We(e,t,n={}){let{extractExperience:o=!1,extractFeatured:i=!1,extractEducation:a=!1,extractSkills:r=!1,extractRecommendations:m=!1,extractCertifications:_=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await f(3e3),await Ce(e)&&(console.log(" Dismissed Premium overlay"),await f(1500),await Tt(e,t));let c=0;for(let p=0;p<2;p++){let F=await e.evaluate(()=>document.body.scrollHeight);for(let D=1;D<=6;D++)await e.evaluate(k=>window.scrollTo(0,k),F*D/6),await f(900);let q=await e.evaluate(()=>document.body.scrollHeight);if(q===c)break;c=q}await f(800);let S=null;try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(S=p.split("?")[0].replace(/\/+$/,""))}catch{}let h=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"]),F=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"]),q=s=>{let l=(s||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(l)},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:[]},k=document.querySelector("main");if(!k)return D;let d=[...Array.from(k.querySelectorAll("h1")),...Array.from(k.querySelectorAll("h2"))],v=Array.from(k.querySelectorAll("h2")),N=d.find(s=>{let l=s.textContent&&s.textContent.trim(),u=(l||"").replace(/\s*\(\d+\)$/,"").trim();return l&&l.length>1&&l.length<100&&!p.has(u)&&!F.has(u)}),O=N?N.textContent.trim():null,C=N?N.parentElement:null;for(;C&&C!==k&&!Array.from(C.children).filter(l=>l.tagName==="P").some(l=>{let u=l.textContent&&l.textContent.trim();return u&&u.length>5&&!q(u)});)C=C.parentElement;let ae=null,ce=null,ue=null,ee=null;if(C&&C!==k){let s=Array.from(C.children).filter(u=>u.tagName==="P").filter(u=>{let T=u.textContent&&u.textContent.trim();return T&&T.length>5&&!q(T)});if(s[0]&&(ae=s[0].textContent.trim()),s[1]){let u=s[1].textContent.trim().split(/\s*[·•]\s*/);ce=u[0]||null,u.length>1&&(ue=u.slice(1).join(" \xB7 "))}let l=Array.from(C.children).filter(u=>u.tagName==="DIV");for(let u=l.length-1;u>=0;u--){let T=l[u].textContent&&l[u].textContent.trim();if(T&&!(O&&T.startsWith(O))&&(ee=T.split(/[·•]/)[0].trim(),ee))break}}let de=null;if(C){let s=C.querySelectorAll("p, span, div");for(let l of s){let u=(l.textContent||"").trim().replace(/^[·•]\s*/,"");if(u==="1st"||u==="2nd"||u==="3rd"){de=u;break}}}let Ke=!!k.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),fe=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ge=fe&&fe.src||null,K=k.textContent||"",me=null,pe=K.match(/(\d+\+?)\s+connections\b/i);pe&&(me=pe[1]+" connections");let G=null,he=K.match(/(\d+)\s+mutual connection/i),we=K.match(/and\s+(\d+)\s+other mutual/i),ze=K.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);he?G=parseInt(he[1],10):we?G=2+parseInt(we[1],10):ze&&(G=2);let ge=null,ye=null,be=v.find(s=>s.textContent&&s.textContent.trim()==="About");if(be){let s=be.parentElement;for(;s&&s.tagName!=="SECTION";)s=s.parentElement;if(s){let l=(s.textContent||"").trim();l=l.replace(/^About\s*/,"").trim();let u=l.match(/Top skills\s*(.+?)$/i);if(u){let te=u[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(et=>et.trim()).filter(Boolean);te.length>0&&te.length<10&&(ye=te)}l=l.split(/\n?…\s*more/i)[0].trim(),l=l.split(/\n?\.\.\.\s*more/i)[0].trim(),l=l.split(/\bTop skills\b/i)[0].trim(),l=l.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),ge=l||null}}let Se=null,ve=v.find(s=>s.textContent&&s.textContent.trim()==="Activity");if(ve){let s=ve.parentElement;for(;s&&s.tagName!=="SECTION";)s=s.parentElement;if(s){let l=(s.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);l&&(Se=parseInt(l[1].replace(/,/g,""),10))}}let Qe=[...new Set(v.map(s=>(s.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(s=>s&&s.length>1&&s.length<60&&s!==O).filter(s=>p.has(s)))],B=document.body.textContent||"",Ze=/#OpenToWork\b/i.test(B)||/\bOpen to work\b/.test(B),Xe=/#Hiring\b/i.test(B)||/\bI'?m hiring\b/i.test(B)||/\bWe are hiring\b/i.test(B);return{name:O,title:ae,location:ee,currentCompany:ce,currentSchool:ue,connectionDegree:de,hasVerifiedBadge:Ke,photoUrl:Ge,connectionsLevel:me,mutualConnectionsCount:G,followers:Se,openToWork:Ze,hiring:Xe,about:ge,topSkills:ye,availableSections:Qe}});console.log(`Viewed: ${h.name} - ${h.title}`);let w=null,y=null,x=null,P=null,M=null,R=null;if(o||i||a||r||m||_){let p=await Promise.resolve().then(()=>(Ve(),Ue));o&&(w=await p.extractExperienceFromDetails(e,t),console.log(` + Experience: ${w.length} entries`)),i&&(y=await p.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${y.length} entries`)),a&&(x=await p.extractEducationFromDetails(e,t),console.log(` + Education: ${x.length} entries`)),r&&(P=await p.extractSkillsFromDetails(e,t),console.log(` + Skills: ${P.length} entries`)),m&&(M=await p.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${M.length} entries`)),_&&(R=await p.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${R.length} entries`))}return{...h,profileUrl:t,resolvedUrl:S,...w!==null&&{experience:w},...y!==null&&{featured:y},...x!==null&&{education:x},...P!==null&&{skillsFull:P},...M!==null&&{recommendations:M},...R!==null&&{certifications:R}}}catch($){console.error(`Error viewing profile ${t}:`,$.message);try{await e.goto("about:blank",{timeout:1e4}),await f(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test($.message||""))throw $;return null}}await se();H();var le=process.argv.slice(2),Je=le.filter(e=>e.startsWith("http")),Ye=parseInt(le.find(e=>e.startsWith("--pick="))?.split("=")[1]||"0"),Lt=le.includes("--has-about");function Pt(e,t){return[...e].sort(()=>Math.random()-.5).slice(0,t)}function Mt(){if(Je.length>0)return Je.map(t=>({url:t,name:"(arg)"}));if(Ye>0){let t=re(),n=Object.entries(t).filter(([o])=>o.startsWith("http")).filter(([,o])=>Lt?!!(o.about&&o.about.trim()):!o.about);return Pt(n,Ye).map(([o,i])=>({url:o,name:i.name}))}let e=process.env.MY_LINKEDIN_URL;return e||(console.error("Pass a URL, use --pick=N, or set MY_LINKEDIN_URL in .env"),process.exit(1)),[{url:e,name:"(self)"}]}function A(e,t,n=80){if(t==null){console.log(` ${e.padEnd(20)} (null)`);return}let o=String(t),i=o.length>n?o.slice(0,n)+`\u2026 (+${o.length-n} chars)`:o;console.log(` ${e.padEnd(20)} ${i} [len=${o.length}]`)}async function Rt(){let e=Mt();console.log(`
|
|
238
|
+
`});import yt from"puppeteer";import{addExtra as bt}from"puppeteer-extra";import St from"puppeteer-extra-plugin-stealth";U();await ie();import _ from"fs";import T from"path";var ct="cookies.json";function _e(){let e=process.env.ILML_SCOPE_DIR;return e?T.join(e,"plugins-state","linkedin","cookies.json"):ct}function Ee(){let e=_e();if(!_.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=_.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 Ae(){return _.existsSync(_e())}function ut(){let e=process.env.ILML_SCOPE_DIR;return e?T.join(e,"plugins-state","linkedin"):"."}function Ie(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function dt(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Ie(t[1]):"default"}function $e(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return _.existsSync(t)||_.mkdirSync(t,{recursive:!0}),T.resolve(t);let n=Ie(e||dt()),o=T.join(ut(),"chrome-profile",n);return _.existsSync(o)||_.mkdirSync(o,{recursive:!0}),T.resolve(o)}var De=".ilml-seeded";function Te(e){return!_.existsSync(T.join(e,De))}function Le(e){try{_.writeFileSync(T.join(e,De),new Date().toISOString())}catch{}}function Pe(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{_.rmSync(T.join(e,n),{force:!0}),t++}catch{}return t}import re from"fs";import ft from"path";var mt={headless:!1,defaultViewport:null,protocolTimeout:3e5},W=new Set,Re=!1;async function Z(){let e=[...W].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});W.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function pt(){if(Re)return;Re=!0;let e=t=>async()=>{await Z(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Z(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Z(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Z(),process.exit(0))}),process.on("exit",()=>{for(let t of W)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function se(e){return ft.join(e,".ilml-browser-session.json")}function je(e,t={}){try{re.writeFileSync(se(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function ht(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();je(e,n?{wsEndpoint:n}:{})}catch{}}function wt(e){let t=Ne(e);t&&t.ownerPid===process.pid&&V(e)}function V(e){try{re.rmSync(se(e),{force:!0})}catch{}}function Ne(e){try{return JSON.parse(re.readFileSync(se(e),"utf-8"))}catch{return null}}function Me(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Fe(e,t,n){let o,i=new Promise(r=>{o=setTimeout(()=>r(n),t)}),a=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([a,i])}async function qe(e,t,{probeTimeoutMs:n=4e3}={}){let o=Ne(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Me(o.ownerPid)?"live":(V(t),"free");let i=Symbol("timeout"),a=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await Fe(a,n,i);if(r===i)return a.then(x=>{if(x)try{x.disconnect()}catch{}}),"live";if(!r)return V(t),"free";if(Me(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Fe(r.close().then(()=>!0).catch(()=>!1),n,!1))return V(t),"free";try{r.disconnect()}catch{}return"live"}function gt(e,t){e&&(pt(),W.add(e),e.on("disconnected",()=>{W.delete(e),t&&V(t)}))}async function Oe(e,t={}){let n=$e(),o={...mt,...t,userDataDir:n},i=`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 qe(e,n)==="live")throw new Error(i);je(n);let a;try{a=await e.launch(o)}catch{if(await qe(e,n)==="live")throw new Error(i);Pe(n);try{a=await e.launch(o)}catch(f){throw wt(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: ${f.message})`)}}return gt(a,n),ht(n,a),{browser:a,profileDir:n,needsSeed:Te(n)}}async function Be(e,t){if(!t||!t.needsSeed)return!1;if(!Ae())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(...Ee()),Le(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var He=bt(yt);He.use(St());async function Ue(){let{browser:e,profileDir:t,needsSeed:n}=await Oe(He),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Be(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}U();await ae();async function Pt(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 m(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function Ye(e,t,n={}){let{extractExperience:o=!1,extractFeatured:i=!1,extractEducation:a=!1,extractSkills:r=!1,extractRecommendations:f=!1,extractCertifications:x=!1}=n;try{if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),!await oe(e,".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",{timeout:45e3,label:"profile"})&&/\/authwall|\/login|\/checkpoint|\/uas\/login/.test(e.url()))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");await m(1500),await xe(e)&&(console.log(" Dismissed Premium overlay"),await m(1500),await Pt(e,t));let S=0;for(let p=0;p<2;p++){let O=await e.evaluate(()=>document.body.scrollHeight);for(let F=1;F<=6;F++)await e.evaluate(l=>window.scrollTo(0,l),O*F/6),await m(900);let $=await e.evaluate(()=>document.body.scrollHeight);if($===S)break;S=$}await m(800);let h=null;try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(h=p.split("?")[0].replace(/\/+$/,""))}catch{}let w=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"]),O=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"]),$=s=>{let c=(s||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(c)},F={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:[]},l=document.querySelector("main");if(!l)return F;let C=[...Array.from(l.querySelectorAll("h1")),...Array.from(l.querySelectorAll("h2"))],B=Array.from(l.querySelectorAll("h2")),j=C.find(s=>{let c=s.textContent&&s.textContent.trim(),u=(c||"").replace(/\s*\(\d+\)$/,"").trim();return c&&c.length>1&&c.length<100&&!p.has(u)&&!O.has(u)}),N=j?j.textContent.trim():null,k=j?j.parentElement:null;for(;k&&k!==l&&!Array.from(k.children).filter(c=>c.tagName==="P").some(c=>{let u=c.textContent&&c.textContent.trim();return u&&u.length>5&&!$(u)});)k=k.parentElement;let ue=null,de=null,fe=null,te=null;if(k&&k!==l){let s=Array.from(k.children).filter(u=>u.tagName==="P").filter(u=>{let D=u.textContent&&u.textContent.trim();return D&&D.length>5&&!$(D)});if(s[0]&&(ue=s[0].textContent.trim()),s[1]){let u=s[1].textContent.trim().split(/\s*[·•]\s*/);de=u[0]||null,u.length>1&&(fe=u.slice(1).join(" \xB7 "))}let c=Array.from(k.children).filter(u=>u.tagName==="DIV");for(let u=c.length-1;u>=0;u--){let D=c[u].textContent&&c[u].textContent.trim();if(D&&!(N&&D.startsWith(N))&&(te=D.split(/[·•]/)[0].trim(),te))break}}let me=null;if(k){let s=k.querySelectorAll("p, span, div");for(let c of s){let u=(c.textContent||"").trim().replace(/^[·•]\s*/,"");if(u==="1st"||u==="2nd"||u==="3rd"){me=u;break}}}let ze=!!l.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),pe=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Qe=pe&&pe.src||null,G=l.textContent||"",he=null,we=G.match(/(\d+\+?)\s+connections\b/i);we&&(he=we[1]+" connections");let z=null,ge=G.match(/(\d+)\s+mutual connection/i),ye=G.match(/and\s+(\d+)\s+other mutual/i),Ze=G.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);ge?z=parseInt(ge[1],10):ye?z=2+parseInt(ye[1],10):Ze&&(z=2);let be=null,Se=null,ve=B.find(s=>s.textContent&&s.textContent.trim()==="About");if(ve){let s=ve.parentElement;for(;s&&s.tagName!=="SECTION";)s=s.parentElement;if(s){let c=(s.textContent||"").trim();c=c.replace(/^About\s*/,"").trim();let u=c.match(/Top skills\s*(.+?)$/i);if(u){let ne=u[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(nt=>nt.trim()).filter(Boolean);ne.length>0&&ne.length<10&&(Se=ne)}c=c.split(/\n?…\s*more/i)[0].trim(),c=c.split(/\n?\.\.\.\s*more/i)[0].trim(),c=c.split(/\bTop skills\b/i)[0].trim(),c=c.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),be=c||null}}let Ce=null,ke=B.find(s=>s.textContent&&s.textContent.trim()==="Activity");if(ke){let s=ke.parentElement;for(;s&&s.tagName!=="SECTION";)s=s.parentElement;if(s){let c=(s.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);c&&(Ce=parseInt(c[1].replace(/,/g,""),10))}}let Xe=[...new Set(B.map(s=>(s.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(s=>s&&s.length>1&&s.length<60&&s!==N).filter(s=>p.has(s)))],H=document.body.textContent||"",et=/#OpenToWork\b/i.test(H)||/\bOpen to work\b/.test(H),tt=/#Hiring\b/i.test(H)||/\bI'?m hiring\b/i.test(H)||/\bWe are hiring\b/i.test(H);return{name:N,title:ue,location:te,currentCompany:de,currentSchool:fe,connectionDegree:me,hasVerifiedBadge:ze,photoUrl:Qe,connectionsLevel:he,mutualConnectionsCount:z,followers:Ce,openToWork:et,hiring:tt,about:be,topSkills:Se,availableSections:Xe}});console.log(`Viewed: ${w.name} - ${w.title}`);let y=null,v=null,L=null,P=null,R=null,M=null;if(o||i||a||r||f||x){let p=await Promise.resolve().then(()=>(Je(),We));o&&(y=await p.extractExperienceFromDetails(e,t),console.log(` + Experience: ${y.length} entries`)),i&&(v=await p.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${v.length} entries`)),a&&(L=await p.extractEducationFromDetails(e,t),console.log(` + Education: ${L.length} entries`)),r&&(P=await p.extractSkillsFromDetails(e,t),console.log(` + Skills: ${P.length} entries`)),f&&(R=await p.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${R.length} entries`)),x&&(M=await p.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${M.length} entries`))}return{...w,profileUrl:t,resolvedUrl:h,...y!==null&&{experience:y},...v!==null&&{featured:v},...L!==null&&{education:L},...P!==null&&{skillsFull:P},...R!==null&&{recommendations:R},...M!==null&&{certifications:M}}}catch(I){console.error(`Error viewing profile ${t}:`,I.message);try{await e.goto("about:blank",{timeout:1e4}),await m(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(I.message||""))throw I;return null}}await ae();U();var ce=process.argv.slice(2),Ke=ce.filter(e=>e.startsWith("http")),Ge=parseInt(ce.find(e=>e.startsWith("--pick="))?.split("=")[1]||"0"),Rt=ce.includes("--has-about");function Mt(e,t){return[...e].sort(()=>Math.random()-.5).slice(0,t)}function Ft(){if(Ke.length>0)return Ke.map(t=>({url:t,name:"(arg)"}));if(Ge>0){let t=le(),n=Object.entries(t).filter(([o])=>o.startsWith("http")).filter(([,o])=>Rt?!!(o.about&&o.about.trim()):!o.about);return Mt(n,Ge).map(([o,i])=>({url:o,name:i.name}))}let e=process.env.MY_LINKEDIN_URL;return e||(console.error("Pass a URL, use --pick=N, or set MY_LINKEDIN_URL in .env"),process.exit(1)),[{url:e,name:"(self)"}]}function E(e,t,n=80){if(t==null){console.log(` ${e.padEnd(20)} (null)`);return}let o=String(t),i=o.length>n?o.slice(0,n)+`\u2026 (+${o.length-n} chars)`:o;console.log(` ${e.padEnd(20)} ${i} [len=${o.length}]`)}async function qt(){let e=Ft();console.log(`
|
|
239
239
|
About-selector verification \u2014 ${e.length} profile(s)
|
|
240
|
-
`);let{browser:t,page:n}=await
|
|
241
|
-
`);continue}
|
|
242
|
-
Verdict: ${
|
|
243
|
-
`),o<e.length-1&&await
|
|
240
|
+
`);let{browser:t,page:n}=await Ue();try{for(let o=0;o<e.length;o++){let{url:i,name:a}=e[o];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"),console.log(` [${o+1}/${e.length}] ${a}`),console.log(` ${i}`),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");let r=await Ye(n,i);if(!r){console.log(` \u26A0 viewProfile returned null \u2014 selector failed entirely
|
|
241
|
+
`);continue}E("name",r.name),E("title",r.title),E("location",r.location),E("company",r.company),E("connectionDegree",r.connectionDegree),E("connectionsCount",r.connectionsCount),E("mutualConnections",r.mutualConnections),E("hasVerifiedBadge",r.hasVerifiedBadge),E("photoUrl",r.photoUrl,60),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 about \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),E("about",r.about,200);let f=[];r.name||f.push("NAME MISSING"),r.title||f.push("TITLE MISSING"),r.location||f.push("LOCATION MISSING"),r.about||f.push("ABOUT MISSING"),console.log(`
|
|
242
|
+
Verdict: ${f.length===0?"OK \u2014 all core fields present":f.join(", ")}
|
|
243
|
+
`),o<e.length-1&&await m(3e3+Math.random()*2e3)}}finally{await t.close().catch(()=>{})}}qt().catch(e=>{console.error("verify-about failed:",e),process.exit(1)});
|
package/dist/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.20.
|
|
1
|
+
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.20.5";try{let n=new URL("./ilml-plugin.json",import.meta.url);return JSON.parse(e(r(n),"utf-8")).version}catch{return"unknown"}}console.log(`ilml-plugin-linkedin ${i()}`);
|
package/dist/viewers.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var lt=Object.defineProperty;var K=(e,t)=>{for(var n in t)lt(e,n,{get:t[n],enumerable:!0})};import"dotenv/config";import*as $ from"fs";import*as U from"path";import{fileURLToPath as Uo}from"url";import kt from"puppeteer";import{addExtra as At}from"puppeteer-extra";import Et from"puppeteer-extra-plugin-stealth";async function z(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}import{getPluginConfig as at}from"@ilivemylife/graph-sdk";var ut=await at();for(let[e,t]of Object.entries(ut))process.env[e]===void 0&&(process.env[e]=t);var ft=process.env.LINKEDIN_NAME,j=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Ko=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.NEEDS_REVIEW])),pt=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.REJECTED,j.NEEDS_REVIEW]));import I from"fs";import D from"path";var dt="cookies.json";function he(){let e=process.env.ILML_SCOPE_DIR;return e?D.join(e,"plugins-state","linkedin","cookies.json"):dt}function ge(){let e=he();if(!I.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=I.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 ye(){return I.existsSync(he())}function mt(){let e=process.env.ILML_SCOPE_DIR;return e?D.join(e,"plugins-state","linkedin"):"."}function Se(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function ht(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Se(t[1]):"default"}function we(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return I.existsSync(t)||I.mkdirSync(t,{recursive:!0}),D.resolve(t);let n=Se(e||ht()),o=D.join(mt(),"chrome-profile",n);return I.existsSync(o)||I.mkdirSync(o,{recursive:!0}),D.resolve(o)}var ve=".ilml-seeded";function be(e){return!I.existsSync(D.join(e,ve))}function ke(e){try{I.writeFileSync(D.join(e,ve),new Date().toISOString())}catch{}}function Ae(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{I.rmSync(D.join(e,n),{force:!0}),t++}catch{}return t}import ee from"fs";import gt from"path";var yt={headless:!1,defaultViewport:null,protocolTimeout:3e5},H=new Set,Ee=!1;async function Q(){let e=[...H].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});H.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function St(){if(Ee)return;Ee=!0;let e=t=>async()=>{await Q(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Q(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Q(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Q(),process.exit(0))}),process.on("exit",()=>{for(let t of H)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function te(e){return gt.join(e,".ilml-browser-session.json")}function xe(e,t={}){try{ee.writeFileSync(te(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function wt(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();xe(e,n?{wsEndpoint:n}:{})}catch{}}function vt(e){let t=_e(e);t&&t.ownerPid===process.pid&&V(e)}function V(e){try{ee.rmSync(te(e),{force:!0})}catch{}}function _e(e){try{return JSON.parse(ee.readFileSync(te(e),"utf-8"))}catch{return null}}function Ce(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function $e(e,t,n){let o,r=new Promise(s=>{o=setTimeout(()=>s(n),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(o),s),s=>{throw clearTimeout(o),s});return Promise.race([i,r])}async function Ie(e,t,{probeTimeoutMs:n=4e3}={}){let o=_e(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Ce(o.ownerPid)?"live":(V(t),"free");let r=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await $e(i,n,r);if(s===r)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return V(t),"free";if(Ce(o.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await $e(s.close().then(()=>!0).catch(()=>!1),n,!1))return V(t),"free";try{s.disconnect()}catch{}return"live"}function bt(e,t){e&&(St(),H.add(e),e.on("disconnected",()=>{H.delete(e),t&&V(t)}))}async function Te(e,t={}){let n=we(),o={...yt,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Ie(e,n)==="live")throw new Error(r);xe(n);let i;try{i=await e.launch(o)}catch{if(await Ie(e,n)==="live")throw new Error(r);Ae(n);try{i=await e.launch(o)}catch(c){throw vt(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 bt(i,n),wt(n,i),{browser:i,profileDir:n,needsSeed:be(n)}}async function De(e,t){if(!t||!t.needsSeed)return!1;if(!ye())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(...ge()),ke(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Re=At(kt);Re.use(Et());async function Oe(){let{browser:e,profileDir:t,needsSeed:n}=await Te(Re),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await De(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}import"dotenv/config";import*as h from"fs";import*as g from"path";import{fileURLToPath as Ct}from"url";var $t=Ct(import.meta.url),It=g.dirname(g.dirname($t)),_=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(It,"collected-profiles"),xt=g.join(_,"people.json"),
|
|
1
|
+
var lt=Object.defineProperty;var K=(e,t)=>{for(var n in t)lt(e,n,{get:t[n],enumerable:!0})};import"dotenv/config";import*as $ from"fs";import*as U from"path";import{fileURLToPath as Uo}from"url";import kt from"puppeteer";import{addExtra as At}from"puppeteer-extra";import Et from"puppeteer-extra-plugin-stealth";async function z(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}import{getPluginConfig as at}from"@ilivemylife/graph-sdk";var ut=await at();for(let[e,t]of Object.entries(ut))process.env[e]===void 0&&(process.env[e]=t);var ft=process.env.LINKEDIN_NAME,j=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Ko=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.NEEDS_REVIEW])),pt=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.REJECTED,j.NEEDS_REVIEW]));import I from"fs";import D from"path";var dt="cookies.json";function he(){let e=process.env.ILML_SCOPE_DIR;return e?D.join(e,"plugins-state","linkedin","cookies.json"):dt}function ge(){let e=he();if(!I.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=I.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 ye(){return I.existsSync(he())}function mt(){let e=process.env.ILML_SCOPE_DIR;return e?D.join(e,"plugins-state","linkedin"):"."}function Se(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function ht(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Se(t[1]):"default"}function we(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return I.existsSync(t)||I.mkdirSync(t,{recursive:!0}),D.resolve(t);let n=Se(e||ht()),o=D.join(mt(),"chrome-profile",n);return I.existsSync(o)||I.mkdirSync(o,{recursive:!0}),D.resolve(o)}var ve=".ilml-seeded";function be(e){return!I.existsSync(D.join(e,ve))}function ke(e){try{I.writeFileSync(D.join(e,ve),new Date().toISOString())}catch{}}function Ae(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{I.rmSync(D.join(e,n),{force:!0}),t++}catch{}return t}import ee from"fs";import gt from"path";var yt={headless:!1,defaultViewport:null,protocolTimeout:3e5},H=new Set,Ee=!1;async function Q(){let e=[...H].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});H.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function St(){if(Ee)return;Ee=!0;let e=t=>async()=>{await Q(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Q(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Q(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Q(),process.exit(0))}),process.on("exit",()=>{for(let t of H)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function te(e){return gt.join(e,".ilml-browser-session.json")}function xe(e,t={}){try{ee.writeFileSync(te(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function wt(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();xe(e,n?{wsEndpoint:n}:{})}catch{}}function vt(e){let t=_e(e);t&&t.ownerPid===process.pid&&V(e)}function V(e){try{ee.rmSync(te(e),{force:!0})}catch{}}function _e(e){try{return JSON.parse(ee.readFileSync(te(e),"utf-8"))}catch{return null}}function Ce(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function $e(e,t,n){let o,r=new Promise(s=>{o=setTimeout(()=>s(n),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(o),s),s=>{throw clearTimeout(o),s});return Promise.race([i,r])}async function Ie(e,t,{probeTimeoutMs:n=4e3}={}){let o=_e(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Ce(o.ownerPid)?"live":(V(t),"free");let r=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await $e(i,n,r);if(s===r)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return V(t),"free";if(Ce(o.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await $e(s.close().then(()=>!0).catch(()=>!1),n,!1))return V(t),"free";try{s.disconnect()}catch{}return"live"}function bt(e,t){e&&(St(),H.add(e),e.on("disconnected",()=>{H.delete(e),t&&V(t)}))}async function Te(e,t={}){let n=we(),o={...yt,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Ie(e,n)==="live")throw new Error(r);xe(n);let i;try{i=await e.launch(o)}catch{if(await Ie(e,n)==="live")throw new Error(r);Ae(n);try{i=await e.launch(o)}catch(c){throw vt(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 bt(i,n),wt(n,i),{browser:i,profileDir:n,needsSeed:be(n)}}async function De(e,t){if(!t||!t.needsSeed)return!1;if(!ye())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(...ge()),ke(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Re=At(kt);Re.use(Et());async function Oe(){let{browser:e,profileDir:t,needsSeed:n}=await Te(Re),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await De(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}import"dotenv/config";import*as h from"fs";import*as g from"path";import{fileURLToPath as Ct}from"url";var $t=Ct(import.meta.url),It=g.dirname(g.dirname($t)),_=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(It,"collected-profiles"),xt=g.join(_,"people.json"),bn=g.join(_,"jobs.json"),kn=g.join(_,"quota.json"),An=g.join(_,"conversations.json"),En=g.join(_,"sync-state.json"),Cn=g.join(_,"application-questions.json"),$n=g.join(_,"profile-history"),je=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},In=je(process.env.CONNECT_MAX_DAILY,20),xn=je(process.env.CONNECT_MAX_WEEKLY,100),W=null,_t=null,Tt=null,Dt=null,Rt=null,Ot=null;function Ne(){W=null,_t=null,Tt=null,Dt=null,Rt=null,Ot=null}function jt(){h.existsSync(_)||h.mkdirSync(_,{recursive:!0})}function Nt(e,t){if(!h.existsSync(e))return null;try{let n=JSON.parse(h.readFileSync(e,"utf-8"));try{h.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(e)}`);let o=e+".backup";if(h.existsSync(o))try{let r=JSON.parse(h.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{h.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{h.copyFileSync(e,e+".corrupted")}catch{}return null}}function Fe(){return W||(jt(),W=Nt(xt,"people.json")||{},W)}import"dotenv/config";import*as F from"fs";import*as S from"path";import{fileURLToPath as Ft}from"url";var Lt=Ft(import.meta.url),Pt=S.dirname(S.dirname(Lt)),Y=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"market-research"):S.join(Pt,"market-research"),Fn=S.join(Y,"scouted-jobs.json"),Mt=S.join(Y,"discovered-people.json"),Ut=S.join(Y,"visit-log.json"),Ln=S.join(Y,"companies.json"),Pn=S.join(Y,"job-decisions.json");function Le(e){try{if(F.existsSync(e))return JSON.parse(F.readFileSync(e,"utf-8"))}catch{}return null}function Pe(){qt=null,Bt=null,G=null,Jt=null,N=null}var qt=null;var Bt=null;var G=null;function Me(){return G||(G=Le(Mt)||{},G)}var Jt=null;var N=null;function Ue(){return N||(N=Le(Ut)||{visits:[]},Array.isArray(N.visits)||(N.visits=[]),N)}async function qe(e){await e.goto("https://www.linkedin.com/analytics/profile-views/",{waitUntil:"domcontentloaded",timeout:6e4}),await z(5e3);for(let n=0;n<5;n++)await e.evaluate(()=>window.scrollBy(0,600)),await z(1e3);return await e.evaluate(()=>{let n=[],o=document.querySelectorAll('a[href*="/in/"]'),r=new Set;for(let i of o){let s=i.getAttribute("href")?.split("?")[0];if(!s||r.has(s))continue;r.add(s);let c=i;for(let p=0;p<8&&!(!c.parentElement||(c=c.parentElement,c.tagName==="LI"||c.classList?.contains("pvs-list__paged-list-wrapper")));p++);let l=c?.innerText?.trim()||"",u=l.split(`
|
|
2
2
|
`).map(p=>p.trim()).filter(Boolean),f="";for(let p of u)if(p.length>2&&p.length<60&&!p.includes("View")&&!p.includes("profile")&&!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&!p.startsWith("3rd")){f=p;break}f||(f=i.textContent?.trim()?.split(`
|
|
3
3
|
`)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let m=l.match(/·\s*(1st|2nd|3rd)/)?.[1]||null,v="",q=u.indexOf(f);if(q>=0&&q+1<u.length){let p=u[q+1];!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&(v=p)}f&&f.length>1&&n.push({profileUrl:s.startsWith("/")?"https://www.linkedin.com"+s:s,name:f,title:v||null,connectionDegree:m})}return n})}function Be(e){let t=Fe(),n=Ue(),o=Me(),r=new Map;for(let i of n.visits||[]){let s=r.get(i.profileUrl);(!s||i.date>s)&&r.set(i.profileUrl,i.date)}return e.map(i=>{let s=t[i.profileUrl],c=o[i.profileUrl],l=r.get(i.profileUrl);return{...i,isConnected:s?.connectionStatus==="connected",isPending:s?.connectionStatus==="pending"||s?.connectionStatus==="sent_without_note",isInPeopleDb:!!s,isDiscovered:!!c,weVisitedThem:!!l,ourVisitDate:l||null,category:s?.category||c?.role||null}})}import"dotenv/config";import*as b from"fs";import*as R from"path";import{fileURLToPath as Kt}from"url";import"dotenv/config";import{createGraphClient as Vt,resolveToken as Ht}from"@ilivemylife/graph-sdk";import{config as Wt}from"dotenv";Wt();var Je=Ht()||process.env.TOKEN;Je||(console.error(`
|
|
4
4
|
[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.
|