ilml-plugin-linkedin 1.20.11 → 1.20.13
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 +16 -0
- package/dist/applyQueue.mjs +26 -26
- package/dist/connect.mjs +52 -52
- package/dist/daily.mjs +33 -33
- package/dist/enrichProfile.mjs +16 -16
- package/dist/enrichProfiles.mjs +51 -51
- package/dist/funnelRunner.mjs +44 -44
- package/dist/messageBot.mjs +40 -40
- package/dist/migrationCli.mjs +43 -43
- package/dist/profileHistory.mjs +8 -8
- package/dist/quota.mjs +32 -32
- package/dist/readPost.mjs +9 -9
- package/dist/run.mjs +69 -66
- package/dist/scout.mjs +40 -39
- package/dist/src/saveLoginState.mjs +4 -4
- package/dist/syncAll.mjs +87 -87
- package/dist/syncConnections.mjs +30 -30
- package/dist/verifyAbout.mjs +19 -19
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +43 -43
- package/dist/visit.mjs +50 -50
- package/dist/warmScan.mjs +3 -3
- package/ilml-plugin.json +11 -2
- package/package.json +2 -2
package/dist/daily.mjs
CHANGED
|
@@ -1,53 +1,53 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Ue=Object.defineProperty;var q=(e,o)=>{for(var t in o)Ue(e,t,{get:o[t],enumerable:!0})};import{execFileSync as cn}from"child_process";import"dotenv/config";import*as S from"fs";import*as I from"path";import{fileURLToPath as Ye}from"url";import"dotenv/config";import{createGraphClient as Je,resolveToken as Be}from"@ilivemylife/graph-sdk";import{config as qe}from"dotenv";qe();var se=Be()||process.env.TOKEN;se||(console.error(`
|
|
2
2
|
[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.
|
|
3
3
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
4
4
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
5
|
-
`),process.exit(1));var ie=
|
|
5
|
+
`),process.exit(1));var ie=Je({token:se});function Ve(e){if(!e||e<1e3)return`${e||0}ms`;let o=Math.round(e/1e3);if(o<60)return`${o}s`;let t=Math.floor(o/60),n=o%60;return n?`${t}m ${n}s`:`${t}m`}function We({scriptName:e,mode:o,status:t,error:n,duration:r}){let s=t==="error"?"\u2717":t==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),a=r?` ${Ve(r)}`:"",c=t==="error"?`error${n?`: ${String(n).slice(0,80)}`:""}`:t==="quota-reached"?"daily quota reached":"done",u=o&&o!=="default"?` (${o})`:"";return`${s} ${e}${u} \u2014 ${c} \u2014 ${i}${a}`}async function le({scriptName:e,mode:o,status:t,summaryLines:n,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(n)||n.length===0)return;let c=`**${We({scriptName:e,mode:o,status:t,error:r,duration:s})}**
|
|
6
6
|
|
|
7
|
-
${
|
|
8
|
-
`)}`;try{await ie.addMessage(i,c)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Ve=qe(import.meta.url),We=R.dirname(R.dirname(Ve)),Y=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"collected-profiles"):R.join(We,"collected-profiles"),G=R.join(Y,"run-log.json");function Ye(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";S.writeFileSync(o,t);for(let r=0;r<3;r++)try{S.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 ce(){try{if(!S.existsSync(G))return{runs:[]};let e=JSON.parse(S.readFileSync(G,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ae(e){S.existsSync(Y)||S.mkdirSync(Y,{recursive:!0});try{Ye(G,e)}catch(n){console.error(`[!] Failed to save run-log.json: ${n.message}`)}}function ue(e,n="default"){let t=ce();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),ae(t),{script:e,mode:n,startTime:o.getTime(),runIndex:t.runs.length-1}}function fe(e,n,t=null,o=null){if(!e)return;let r=null;try{let i=ce(),a=i.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=n,a.result=n,a.duration=Date.now()-e.startTime,a.stats=t,a.error=o,r=a.duration;else{let c=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.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)}ae(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";le({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import{getPluginConfig as Ge}from"@ilivemylife/graph-sdk";var Ke=await Ge();for(let[e,n]of Object.entries(Ke))process.env[e]===void 0&&(process.env[e]=n);var yn=process.env.LINKEDIN_NAME,N=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Sn=Object.freeze(new Set([N.DRAFT,N.CONFIRMED,N.NEEDS_REVIEW])),bn=Object.freeze(new Set([N.DRAFT,N.CONFIRMED,N.REJECTED,N.NEEDS_REVIEW]));import"dotenv/config";import*as d from"fs";import*as m from"path";import{fileURLToPath as He}from"url";var ze=He(import.meta.url),Qe=m.dirname(m.dirname(ze)),E=process.env.DATA_DIR?m.resolve(process.env.DATA_DIR,"collected-profiles"):m.join(Qe,"collected-profiles"),$n=m.join(E,"people.json"),jn=m.join(E,"jobs.json"),Xe=m.join(E,"quota.json"),En=m.join(E,"conversations.json"),On=m.join(E,"sync-state.json"),In=m.join(E,"application-questions.json"),Rn=m.join(E,"profile-history"),pe=(e,n)=>{let t=parseInt(e,10);return Number.isInteger(t)&&t>=0?t:n},P=pe(process.env.CONNECT_MAX_DAILY,20),U=pe(process.env.CONNECT_MAX_WEEKLY,100),Ze=null,eo=null,T=null,oo=null,no=null,to=null;function de(){Ze=null,eo=null,T=null,oo=null,no=null,to=null}function ro(){d.existsSync(E)||d.mkdirSync(E,{recursive:!0})}function so(e,n){if(!d.existsSync(e))return null;try{let t=JSON.parse(d.readFileSync(e,"utf-8"));try{d.copyFileSync(e,e+".backup")}catch{}return t}catch(t){console.error(`[!] ${n} is corrupted: ${t.message}`),console.error(` File: ${m.resolve(e)}`);let o=e+".backup";if(d.existsSync(o))try{let r=JSON.parse(d.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{d.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{d.copyFileSync(e,e+".corrupted")}catch{}return null}}function me(){return new Date().toISOString().split("T")[0]}function io(){return T||(ro(),T=so(Xe,"quota.json"),(!T||!T.connections)&&(T={connections:[]}),T)}function he(){let e=io(),n=new Date;n.setDate(n.getDate()-7);let t=n.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=t)}function ge(){let e=he(),n=me(),t=e.filter(c=>c.date===n).length,o=e.length,r=t>=P,s=o>=U,i=!r&&!s,a={allowed:i,daily:{sent:t,max:P},weekly:{sent:o,max:U}};return i||(a.reason=r?`Daily limit reached (${t}/${P})`:`Weekly limit reached (${o}/${U})`),a}function ye(){let e=he(),n=me(),t=e.filter(r=>r.date===n).length,o=e.length;return{daily:{sent:t,max:P,remaining:P-t},weekly:{sent:o,max:U,remaining:U-o}}}import"dotenv/config";import*as l from"fs";import*as oe from"os";import*as f from"path";import{fileURLToPath as Po}from"url";var z={};q(z,{NAME:()=>co,VERSION:()=>lo,up:()=>fo});import*as b from"fs";import*as V from"path";var lo=1,co="normalize-jobs-and-questions",ao=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],uo=50;function K(e){return b.existsSync(e)?JSON.parse(b.readFileSync(e,"utf-8")):null}function H(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{b.writeFileSync(o,t)}catch(r){try{b.unlinkSync(o)}catch{}throw r}try{b.renameSync(o,e)}catch(r){try{b.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 fo(e,n){let t=V.join(e,"jobs.json"),o=V.join(n,"scouted-jobs.json"),r=V.join(e,"application-questions.json"),s=K(t)||{},i=K(o)||{},a=0,c=[];for(let p of Object.keys(s)){if(!i[p])continue;let A=i[p],h=s[p];for(let I of ao)A[I]!=null&&h[I]==null&&(h[I]=A[I]);c.push(p),a++}a>0?(H(t,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=K(r);if(u&&Array.isArray(u.applications)){let p={},A=0;for(let h of u.applications){let I=h.jobId||"unknown";p[I]||(p[I]={applications:[]});let re=(h.questions||[]).map($=>{let L={type:$.type||"input",question:$.question||"",answer:$.answer||""};return $.options&&($.options.length<=uo?L.options=$.options:(L.optionsOmitted=!0,A++)),$.page&&(L.page=$.page),$.wasPreFilled&&(L.wasPreFilled=!0),$.wasRetry&&(L.wasRetry=!0),L});p[I].applications.push({applicationId:h.applicationId,date:h.date,result:h.result||"submitted",formPages:h.formPages||null,duration:h.duration||null,retries:h.retries||0,failedField:h.failedField||null,questionCount:h.questionCount||re.length,questions:re})}H(r,p),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),A>0&&console.log(` Phase 2: Stripped bloated options from ${A} questions`)}else u&&!u.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 p of c)delete i[p];H(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 Q={};q(Q,{NAME:()=>mo,VERSION:()=>po,up:()=>yo});import*as w from"fs";import*as Se from"path";var po=2,mo="reset-unread-flags";function ho(e){return w.existsSync(e)?JSON.parse(w.readFileSync(e,"utf-8")):null}function go(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{w.writeFileSync(o,t)}catch(r){try{w.unlinkSync(o)}catch{}throw r}try{w.renameSync(o,e)}catch(r){try{w.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 yo(e){let n=Se.join(e,"conversations.json"),t=ho(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}go(n,t),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var X={};q(X,{NAME:()=>bo,VERSION:()=>So,up:()=>$o});import*as v from"fs";import*as be from"path";var So=3,bo="recompute-last-message-by",wo=new Set(["draft","confirmed","rejected","needs_review"]);function vo(e){return v.existsSync(e)?JSON.parse(v.readFileSync(e,"utf-8")):null}function ko(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{v.writeFileSync(o,t)}catch(r){try{v.unlinkSync(o)}catch{}throw r}try{v.renameSync(o,e)}catch(r){try{v.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 Ao(e,n){if(!e||e.length===0)return"them";let t=e.filter(s=>!wo.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 $o(e){let n=be.join(e,"conversations.json"),t=vo(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 a of Object.keys(t)){let c=t[a];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,s++);let u=Array.isArray(c.messages)?c.messages:[],p=Ao(u,o),A=p==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==p&&i++,c.lastMessageBy=p,c.conversationStatus=A,r++}if(r===0){console.log(" No conversations to recompute.");return}ko(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 Z={};q(Z,{NAME:()=>Eo,VERSION:()=>jo,up:()=>To});import*as k from"fs";import*as we from"path";var jo=4,Eo="split-connection-timestamps",Oo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Io(e){if(!k.existsSync(e))return null;let n=k.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function Ro(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{k.writeFileSync(o,t)}catch(r){try{k.unlinkSync(o)}catch{}throw r}try{k.renameSync(o,e)}catch(r){try{k.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 To(e){let n=we.join(e,"people.json"),t=Io(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++,Oo.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}Ro(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 y from"path";import{fileURLToPath as Do}from"url";var Co=Do(import.meta.url),No=y.dirname(y.dirname(Co)),J=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"market-research"):y.join(No,"market-research"),Ln=y.join(J,"scouted-jobs.json"),Mn=y.join(J,"discovered-people.json"),Pn=y.join(J,"visit-log.json"),Un=y.join(J,"companies.json"),Jn=y.join(J,"job-decisions.json");function ve(){xo=null,_o=null,Fo=null,Lo=null,Mo=null}var xo=null;var _o=null;var Fo=null;var Lo=null;var Mo=null;var Uo=Po(import.meta.url),Jo=f.dirname(Uo),Bo=f.dirname(f.dirname(Jo));function qo(e){return e&&(e==="~"?oe.homedir():e.startsWith("~/")||e.startsWith("~\\")?f.join(oe.homedir(),e.slice(2)):e)}var j=process.env.DATA_DIR?f.resolve(qo(process.env.DATA_DIR)):Bo,_=f.join(j,"collected-profiles"),F=f.join(j,"market-research"),g=f.join(j,".schema-version"),ke=[f.join(_,".schema-version"),f.join(F,".schema-version")],D=4,O=[{version:1,module:z},{version:2,module:Q},{version:3,module:X},{version:4,module:Z}];(function(){O.sort((o,r)=>o.version-r.version);let n=new Set;for(let o of O){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=O.length?O[O.length-1].version:0;if(t!==D)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${D}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<O.length;o++){let r=o+1;if(O[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${O[o].version}`)}})();function Ee(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
7
|
+
${n.join(`
|
|
8
|
+
`)}`;try{await ie.addMessage(i,c)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Ge=Ye(import.meta.url),He=I.dirname(I.dirname(Ge)),Y=process.env.DATA_DIR?I.resolve(process.env.DATA_DIR,"collected-profiles"):I.join(He,"collected-profiles"),G=I.join(Y,"run-log.json");function Ke(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";S.writeFileSync(n,t);for(let r=0;r<3;r++)try{S.renameSync(n,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 ce(){try{if(!S.existsSync(G))return{runs:[]};let e=JSON.parse(S.readFileSync(G,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ae(e){S.existsSync(Y)||S.mkdirSync(Y,{recursive:!0});try{Ke(G,e)}catch(o){console.error(`[!] Failed to save run-log.json: ${o.message}`)}}function ue(e,o="default"){let t=ce();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 n=new Date,r={timestamp:n.toISOString(),script:e,mode:o,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),ae(t),{script:e,mode:o,startTime:n.getTime(),runIndex:t.runs.length-1}}function fe(e,o,t=null,n=null){if(!e)return;let r=null;try{let i=ce(),a=i.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=o,a.result=o,a.duration=Date.now()-e.startTime,a.stats=t,a.error=n,r=a.duration;else{let c=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());c&&(c.status=o,c.result=o,c.duration=Date.now()-e.startTime,c.stats=t,c.error=n,r=c.duration)}ae(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=o==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";le({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:n,duration:r??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import{getPluginConfig as Xe}from"@ilivemylife/graph-sdk";var ze={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},pe=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function Qe(e){return String(e??"").split(/[,\s|]+/).map(o=>o.trim()).filter(Boolean)}function de(e=process.env){let o=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!o)return null;let t=new URLSearchParams;t.set("keywords",o);let n=(e.JOB_SEARCH_LOCATION||"").trim();n&&t.set("location",n);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&t.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&t.set("distance",String(s)),pe(e.JOB_SEARCH_EASY_APPLY)&&t.set("f_AL","true"),pe(e.JOB_SEARCH_IN_NETWORK)&&t.set("f_JIYN","true");let i=Qe(e.JOB_SEARCH_COMPANY_IDS);i.length&&t.set("f_C",i.join(","));let a=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();a&&t.set("f_TPR",ze[a]||a),t.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let c="https://www.linkedin.com/jobs/search/?"+t.toString(),u=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return u&&(c+="&"+u),c}var Ze=await Xe();for(let[e,o]of Object.entries(Ze))process.env[e]===void 0&&(process.env[e]=o);var me=de(process.env);me&&(process.env.LINKEDIN_SEARCH_URL=me);var $n=process.env.LINKEDIN_NAME,C=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),En=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.NEEDS_REVIEW])),jn=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.REJECTED,C.NEEDS_REVIEW]));import"dotenv/config";import*as d from"fs";import*as m from"path";import{fileURLToPath as eo}from"url";var oo=eo(import.meta.url),no=m.dirname(m.dirname(oo)),j=process.env.DATA_DIR?m.resolve(process.env.DATA_DIR,"collected-profiles"):m.join(no,"collected-profiles"),Dn=m.join(j,"people.json"),_n=m.join(j,"jobs.json"),to=m.join(j,"quota.json"),Cn=m.join(j,"conversations.json"),Nn=m.join(j,"sync-state.json"),xn=m.join(j,"application-questions.json"),Fn=m.join(j,"profile-history"),he=(e,o)=>{let t=parseInt(e,10);return Number.isInteger(t)&&t>=0?t:o},P=he(process.env.CONNECT_MAX_DAILY,20),U=he(process.env.CONNECT_MAX_WEEKLY,100),ro=null,so=null,T=null,io=null,lo=null,co=null;function ge(){ro=null,so=null,T=null,io=null,lo=null,co=null}function ao(){d.existsSync(j)||d.mkdirSync(j,{recursive:!0})}function uo(e,o){if(!d.existsSync(e))return null;try{let t=JSON.parse(d.readFileSync(e,"utf-8"));try{d.copyFileSync(e,e+".backup")}catch{}return t}catch(t){console.error(`[!] ${o} is corrupted: ${t.message}`),console.error(` File: ${m.resolve(e)}`);let n=e+".backup";if(d.existsSync(n))try{let r=JSON.parse(d.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{d.copyFileSync(n,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{d.copyFileSync(e,e+".corrupted")}catch{}return null}}function ye(){return new Date().toISOString().split("T")[0]}function fo(){return T||(ao(),T=uo(to,"quota.json"),(!T||!T.connections)&&(T={connections:[]}),T)}function Se(){let e=fo(),o=new Date;o.setDate(o.getDate()-7);let t=o.toISOString().split("T")[0];return e.connections.filter(n=>n.date>=t)}function be(){let e=Se(),o=ye(),t=e.filter(c=>c.date===o).length,n=e.length,r=t>=P,s=n>=U,i=!r&&!s,a={allowed:i,daily:{sent:t,max:P},weekly:{sent:n,max:U}};return i||(a.reason=r?`Daily limit reached (${t}/${P})`:`Weekly limit reached (${n}/${U})`),a}function we(){let e=Se(),o=ye(),t=e.filter(r=>r.date===o).length,n=e.length;return{daily:{sent:t,max:P,remaining:P-t},weekly:{sent:n,max:U,remaining:U-n}}}import"dotenv/config";import*as l from"fs";import*as oe from"os";import*as f from"path";import{fileURLToPath as Vo}from"url";var z={};q(z,{NAME:()=>mo,VERSION:()=>po,up:()=>yo});import*as b from"fs";import*as V from"path";var po=1,mo="normalize-jobs-and-questions",ho=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],go=50;function H(e){return b.existsSync(e)?JSON.parse(b.readFileSync(e,"utf-8")):null}function K(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{b.writeFileSync(n,t)}catch(r){try{b.unlinkSync(n)}catch{}throw r}try{b.renameSync(n,e)}catch(r){try{b.unlinkSync(n)}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 yo(e,o){let t=V.join(e,"jobs.json"),n=V.join(o,"scouted-jobs.json"),r=V.join(e,"application-questions.json"),s=H(t)||{},i=H(n)||{},a=0,c=[];for(let p of Object.keys(s)){if(!i[p])continue;let A=i[p],h=s[p];for(let R of ho)A[R]!=null&&h[R]==null&&(h[R]=A[R]);c.push(p),a++}a>0?(K(t,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=H(r);if(u&&Array.isArray(u.applications)){let p={},A=0;for(let h of u.applications){let R=h.jobId||"unknown";p[R]||(p[R]={applications:[]});let re=(h.questions||[]).map($=>{let L={type:$.type||"input",question:$.question||"",answer:$.answer||""};return $.options&&($.options.length<=go?L.options=$.options:(L.optionsOmitted=!0,A++)),$.page&&(L.page=$.page),$.wasPreFilled&&(L.wasPreFilled=!0),$.wasRetry&&(L.wasRetry=!0),L});p[R].applications.push({applicationId:h.applicationId,date:h.date,result:h.result||"submitted",formPages:h.formPages||null,duration:h.duration||null,retries:h.retries||0,failedField:h.failedField||null,questionCount:h.questionCount||re.length,questions:re})}K(r,p),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),A>0&&console.log(` Phase 2: Stripped bloated options from ${A} questions`)}else u&&!u.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 p of c)delete i[p];K(n,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 Q={};q(Q,{NAME:()=>bo,VERSION:()=>So,up:()=>ko});import*as w from"fs";import*as ve from"path";var So=2,bo="reset-unread-flags";function wo(e){return w.existsSync(e)?JSON.parse(w.readFileSync(e,"utf-8")):null}function vo(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{w.writeFileSync(n,t)}catch(r){try{w.unlinkSync(n)}catch{}throw r}try{w.renameSync(n,e)}catch(r){try{w.unlinkSync(n)}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 ko(e){let o=ve.join(e,"conversations.json"),t=wo(o);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let r of Object.keys(t))t[r].unread===!0&&(t[r].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}vo(o,t),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var X={};q(X,{NAME:()=>$o,VERSION:()=>Ao,up:()=>Io});import*as v from"fs";import*as ke from"path";var Ao=3,$o="recompute-last-message-by",Eo=new Set(["draft","confirmed","rejected","needs_review"]);function jo(e){return v.existsSync(e)?JSON.parse(v.readFileSync(e,"utf-8")):null}function Oo(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{v.writeFileSync(n,t)}catch(r){try{v.unlinkSync(n)}catch{}throw r}try{v.renameSync(n,e)}catch(r){try{v.unlinkSync(n)}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 Ro(e,o){if(!e||e.length===0)return"them";let t=e.filter(s=>!Eo.has(s.status));if(t.length===0)return"them";let n=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=n.length>0?n:[...t].reverse();for(let s of r){let i=s.sender;if(i===o)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Io(e){let o=ke.join(e,"conversations.json"),t=jo(o);if(!t){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let n=process.env.LINKEDIN_NAME;if(!n||typeof n!="string"||!n.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 a of Object.keys(t)){let c=t[a];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,s++);let u=Array.isArray(c.messages)?c.messages:[],p=Ro(u,n),A=p==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==p&&i++,c.lastMessageBy=p,c.conversationStatus=A,r++}if(r===0){console.log(" No conversations to recompute.");return}Oo(o,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 Z={};q(Z,{NAME:()=>Do,VERSION:()=>To,up:()=>xo});import*as k from"fs";import*as Ae from"path";var To=4,Do="split-connection-timestamps",_o=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Co(e){if(!k.existsSync(e))return null;let o=k.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function No(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{k.writeFileSync(n,t)}catch(r){try{k.unlinkSync(n)}catch{}throw r}try{k.renameSync(n,e)}catch(r){try{k.unlinkSync(n)}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 xo(e){let o=Ae.join(e,"people.json"),t=Co(o);if(!t||typeof t!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let n=0,r=0;for(let s of Object.keys(t)){let i=t[s];!i||typeof i!="object"||(r++,_o.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,n++))}if(n===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}No(o,t),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${n} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as y from"path";import{fileURLToPath as Fo}from"url";var Lo=Fo(import.meta.url),Mo=y.dirname(y.dirname(Lo)),J=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"market-research"):y.join(Mo,"market-research"),Vn=y.join(J,"scouted-jobs.json"),Wn=y.join(J,"discovered-people.json"),Yn=y.join(J,"visit-log.json"),Gn=y.join(J,"companies.json"),Hn=y.join(J,"job-decisions.json");function $e(){Po=null,Uo=null,Jo=null,Bo=null,qo=null}var Po=null;var Uo=null;var Jo=null;var Bo=null;var qo=null;var Wo=Vo(import.meta.url),Yo=f.dirname(Wo),Go=f.dirname(f.dirname(Yo));function Ho(e){return e&&(e==="~"?oe.homedir():e.startsWith("~/")||e.startsWith("~\\")?f.join(oe.homedir(),e.slice(2)):e)}var E=process.env.DATA_DIR?f.resolve(Ho(process.env.DATA_DIR)):Go,x=f.join(E,"collected-profiles"),F=f.join(E,"market-research"),g=f.join(E,".schema-version"),Ee=[f.join(x,".schema-version"),f.join(F,".schema-version")],D=4,O=[{version:1,module:z},{version:2,module:Q},{version:3,module:X},{version:4,module:Z}];(function(){O.sort((n,r)=>n.version-r.version);let o=new Set;for(let n of O){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(o.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);o.add(n.version);let r=n.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let t=O.length?O[O.length-1].version:0;if(t!==D)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${D}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<O.length;n++){let r=n+1;if(O[n].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${n} but found v${O[n].version}`)}})();function Ie(){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
|
-
`),process.exit(1));try{l.mkdirSync(
|
|
11
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
12
|
-
`),process.exit(1))}let e;try{e=l.statSync(
|
|
13
|
-
[FATAL] DATA_DIR (${
|
|
10
|
+
`),process.exit(1));try{l.mkdirSync(E,{recursive:!0})}catch(o){o.code!=="EEXIST"&&(console.error(`
|
|
11
|
+
[FATAL] Cannot create DATA_DIR (${E}): ${o.message}`),console.error(` Fix the path or permissions and try again.
|
|
12
|
+
`),process.exit(1))}let e;try{e=l.statSync(E)}catch(o){console.error(`
|
|
13
|
+
[FATAL] DATA_DIR (${E}) is not accessible: ${o.message}
|
|
14
14
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
15
|
-
[FATAL] DATA_DIR (${
|
|
16
|
-
`),process.exit(1));for(let
|
|
17
|
-
[FATAL] Data subdirectory is a symbolic link: ${
|
|
18
|
-
`),process.exit(1))}}var
|
|
19
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${
|
|
15
|
+
[FATAL] DATA_DIR (${E}) 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.
|
|
16
|
+
`),process.exit(1));for(let o of[x,F]){let t;try{t=l.lstatSync(o)}catch(n){if(n.code==="ENOENT")continue;throw n}t.isSymbolicLink()&&(console.error(`
|
|
17
|
+
[FATAL] Data subdirectory is a symbolic link: ${o}`),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.
|
|
18
|
+
`),process.exit(1))}}var N=f.join(E,".migration-lock");function Ko(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return l.writeFileSync(N,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let o;try{o=JSON.parse(l.readFileSync(N,"utf-8"))}catch{o=null}if(o&&Number.isInteger(o.pid)){let n=!1;try{process.kill(o.pid,0),n=!0}catch(i){i.code==="EPERM"&&(n=!0)}let r=24*60*60*1e3,s=1/0;if(o.startedAt){let i=Date.parse(o.startedAt);Number.isNaN(i)||(s=Date.now()-i)}n&&s<r&&(console.error(`
|
|
19
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${o.pid}`),console.error(` Started at: ${o.startedAt||"(unknown)"}`),console.error(` Lock file: ${N}
|
|
20
20
|
`),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.
|
|
21
|
-
`),process.exit(1)),
|
|
22
|
-
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of
|
|
21
|
+
`),process.exit(1)),n&&s>=r&&console.log(` Lock holder PID ${o.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${o?.pid??"?"} found \u2014 taking over.`);let t=N+".tmp";try{return l.writeFileSync(t,e),l.renameSync(t,N),!0}catch(n){try{l.unlinkSync(t)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function ne(){try{if(JSON.parse(l.readFileSync(N,"utf-8")).pid!==process.pid)return;l.unlinkSync(N)}catch{}}var je=!1;function zo(){if(je)return;je=!0;let e=()=>{try{ne()}catch{}process.exit(1)};for(let o of["SIGINT","SIGTERM","SIGHUP"])try{process.on(o,e)}catch{}}function Qo(){if(l.existsSync(g))return;let e=[],o=[];for(let s of Ee)if(l.existsSync(s))try{e.push({file:s,schema:W(s)})}catch(i){o.push({file:s,err:i.message})}if(o.length>0){console.error(`
|
|
22
|
+
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of o)console.error(` ${s.file}: ${s.err}`);console.error(`
|
|
23
23
|
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.
|
|
24
24
|
`),process.exit(1)}if(e.length===0)return;let t=e.map(s=>s.schema.version);if(new Set(t).size>1){console.error(`
|
|
25
25
|
[FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
26
|
-
`),process.exit(1)}let
|
|
26
|
+
`),process.exit(1)}let n=e[0].schema,r=g+".tmp";try{l.writeFileSync(r,JSON.stringify(n,null,2)),l.renameSync(r,g)}catch(s){try{l.unlinkSync(r)}catch{}throw s}for(let s of Ee)if(l.existsSync(s))try{l.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${g}`)}function Xo(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let o=Number(e.version);return!Number.isFinite(o)||o<0||!Number.isInteger(o)?null:(e.version=o,Array.isArray(e.migrations)||(e.migrations=[]),e)}function W(e){let o=l.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Oe(){if(Qo(),!l.existsSync(g))return{version:0,migrations:[]};let e;try{e=W(g)}catch(t){if(t.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
27
27
|
[FATAL] ${g} is not valid JSON: ${t.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.
|
|
28
|
-
`),process.exit(1)}let
|
|
28
|
+
`),process.exit(1)}let o=Xo(e);return o===null&&(console.error(`
|
|
29
29
|
[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.
|
|
30
|
-
`),process.exit(1)),
|
|
31
|
-
[FATAL] Your data schema is at v${
|
|
30
|
+
`),process.exit(1)),o}function Te(e){try{l.chmodSync(e,384)}catch{}}function Zo(e){if(Ie(),l.existsSync(g))try{if(l.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(t){if(t.message?.includes("symbolic link"))throw t}let o=g+".tmp";try{l.writeFileSync(o,JSON.stringify(e,null,2)),Te(o),l.renameSync(o,g)}catch(t){try{l.unlinkSync(o)}catch{}throw t}}function Re(e,o){if(!l.existsSync(e))return;let t=`.pre-v${String(o).padStart(3,"0")}.backup`,n=l.readdirSync(e).filter(a=>{let c=a.toLowerCase();if(c.includes(".backup")||c===".schema-version"||c.endsWith(".tmp"))return!1;try{return l.statSync(f.join(e,a)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let a of n){let c=f.join(e,a),u=f.join(e,a+t);if(l.existsSync(u)){s++;continue}try{_e(c,u),r++}catch(p){i.push({file:a,err:p.message})}}if(i.length>0){let a=new Error(`Failed to back up ${i.length} file(s) in ${f.basename(e)}/: `+i.map(c=>`${c.file} (${c.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(r>0||s>0){let a=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${f.basename(e)}/ (${t})${a}`)}}var ee=!1;async function De(){if(ee)return;Ie(),rn();let o=Oe().version;if(o===D){ee=!0;return}zo(),Ko(),process.on("exit",ne),o>D&&(console.error(`
|
|
31
|
+
[FATAL] Your data schema is at v${o}, but this plugin build only understands up to v${D}.`),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.
|
|
32
32
|
`),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${D}.
|
|
33
33
|
`),process.exit(1)),console.log(`
|
|
34
|
-
\u{1F4E6} Schema migration: v${
|
|
34
|
+
\u{1F4E6} Schema migration: v${o} \u2192 v${D}`);let t=sn();if(!t.ok){console.error(`
|
|
35
35
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of t.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
|
|
36
36
|
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'.
|
|
37
|
-
`),process.exit(1)}let
|
|
38
|
-
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{
|
|
37
|
+
`),process.exit(1)}let n=O.filter(r=>r.version>o);for(let r of n){console.log(`
|
|
38
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{Re(x,r.version),Re(F,r.version)}catch(c){console.error(`
|
|
39
39
|
[FATAL] Pre-migration backup failed for ${s}: ${c.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
40
|
-
`),process.exit(1)}let a=r.module;try{await a.up(
|
|
41
|
-
[FATAL] Migration ${s} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let u=
|
|
40
|
+
`),process.exit(1)}let a=r.module;try{await a.up(x,F)}catch(c){console.error(`
|
|
41
|
+
[FATAL] Migration ${s} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let u=ln(i);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${o}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
42
42
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
43
43
|
`))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
44
|
-
`)}process.exit(1)}try{let c=new Date().toISOString(),u={version:r.version,name:a.NAME||s,appliedAt:c},p
|
|
45
|
-
[FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${c.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${
|
|
46
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{
|
|
44
|
+
`)}process.exit(1)}try{let c=new Date().toISOString(),u={version:r.version,name:a.NAME||s,appliedAt:c},p=Oe();p.version=r.version,p.migratedAt=c,p.migrations=p.migrations||[],p.migrations.push(u),Zo(p)}catch(c){console.error(`
|
|
45
|
+
[FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${c.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${o}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
46
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{ge()}catch{}try{$e()}catch{}ee=!0,ne(),console.log(`
|
|
47
47
|
\u2713 Schema is now at v${D}
|
|
48
|
-
`)}var
|
|
49
|
-
${"\u2550".repeat(50)}`),console.log(` STEP: ${e}`),console.log("\u2550".repeat(50)),
|
|
50
|
-
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(` DAILY PIPELINE (${e})`),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
|
|
51
|
-
\u26A0 Funnel skipped: ${s.reason}`),
|
|
52
|
-
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" PIPELINE COMPLETE"),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");for(let[s,i]of Object.entries(
|
|
53
|
-
`);let r=Object.values(
|
|
48
|
+
`)}var en=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function on(e){let o=e.toLowerCase();return en.some(t=>t.test(o))}var nn=6e4;function tn(){let e=Date.now(),o=[];for(let t of[E,x,F]){if(!l.existsSync(t))continue;let n;try{n=l.readdirSync(t)}catch{continue}for(let r of n){if(!on(r))continue;let s=f.join(t,r);try{let i=l.statSync(s);if(!i.isFile()||e-i.mtimeMs<nn)continue;o.push({dir:t,file:r,fullPath:s})}catch{}}}return o}function rn({verbose:e=!1}={}){let o=tn();if(o.length===0)return e&&console.log(" No orphan .tmp files found."),0;let t=0;for(let n of o)try{l.unlinkSync(n.fullPath),t++,e&&console.log(` Removed orphan: ${f.basename(n.dir)}/${n.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${n.fullPath}: ${r.message}`)}return!e&&t>0&&console.log(` Cleaned up ${t} orphan .tmp file(s) from previous run.`),t}function sn(){let e=[];for(let o of[x,F]){if(!l.existsSync(o))continue;let t=l.readdirSync(o).filter(n=>{let r=n.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let n of t){let r=f.join(o,n);try{W(r)}catch(s){e.push({dir:f.basename(o),file:n,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function ln(e){let o=[],t=[];for(let s of[x,F]){if(!l.existsSync(s))continue;let i=l.readdirSync(s).filter(a=>a.endsWith(e));for(let a of i){let c=f.join(s,a),u=a.slice(0,-e.length),p=f.join(s,u);try{u.toLowerCase().endsWith(".json")?W(c):l.accessSync(c,l.constants.R_OK),o.push({backupPath:c,originalPath:p,fileName:a,dir:s})}catch(A){t.push(`${f.basename(s)}/${a}: ${A.message}`)}}}if(t.length>0)return{ok:!1,error:t.join("; "),restored:0};let n=0,r=[];for(let{backupPath:s,originalPath:i,fileName:a,dir:c}of o)try{_e(s,i),n++}catch(u){r.push(`${f.basename(c)}/${a}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:n}:{ok:!0,restored:n}}function _e(e,o){let t=o+".tmp";try{l.copyFileSync(e,t),Te(t)}catch(n){try{l.unlinkSync(t)}catch{}throw n}try{l.renameSync(t,o)}catch(n){try{l.unlinkSync(t)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${o} (${n.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=n.code,r}throw n}}await De();var B=process.argv.slice(2),te=new Set((B.find(e=>e.startsWith("--skip="))?.split("=")[1]||"").split(",").filter(Boolean)),Ce=new Set((B.find(e=>e.startsWith("--only="))?.split("=")[1]||"").split(",").filter(Boolean)),Fe=B.includes("--dry-run"),Le=B.includes("--jobs"),Me=B.includes("--comms"),Ne=["apply-queue","apply","funnel","scout","visit"],xe=["sync","today"],Pe=Le?Ne:Me?xe:[...Ne,...xe];function _(e){return Ce.size>0?Ce.has(e):!te.has(e)&&Pe.includes(e)}function M(e,o,t=[],{optional:n=!1}={}){if(console.log(`
|
|
49
|
+
${"\u2550".repeat(50)}`),console.log(` STEP: ${e}`),console.log("\u2550".repeat(50)),Fe)return console.log(` [DRY RUN] Would run: node ${o} ${t.join(" ")}`),!0;try{return cn("node",[o,...t],{stdio:"inherit",timeout:18e6}),console.log(` \u2713 ${e} completed`),!0}catch(r){return n?(console.log(` \u26A0 ${e} failed (optional): ${r.message?.slice(0,80)}`),!1):(console.error(` \u2717 ${e} failed: ${r.message?.slice(0,80)}`),!1)}}async function an(){let e=Le?"jobs":Me?"comms":"full";console.log(`
|
|
50
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(` DAILY PIPELINE (${e})`),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 o=Pe.filter(_);console.log(` Steps: ${o.join(" \u2192 ")}`),te.size>0&&console.log(` Skipping: ${[...te].join(", ")}`),Fe&&console.log(" [DRY RUN MODE]");let t=ue("daily",e),n={};if(_("apply-queue")&&(n["apply-queue"]=M("Apply Queue (scored jobs)","applyQueue.mjs",["--max=50","--min-score=50"],{optional:!0})),_("apply")){let s=we();n.apply=M("Apply from Search","run.mjs",[],{optional:!0})}if(_("funnel")&&!_("apply")){let s=be();s.allowed?n.funnel=M("Connection Funnel","funnelRunner.mjs",["--max=20"],{optional:!0}):(console.log(`
|
|
51
|
+
\u26A0 Funnel skipped: ${s.reason}`),n.funnel="skipped_quota")}_("scout")&&(n.scout=M("Scout Jobs for Tomorrow","scout.mjs",["--max=300","--verbose"],{optional:!0})),_("sync")&&(n.sync=M("Sync Inbox","syncAll.mjs")),_("today")&&(n.today=M("Daily Report","syncAll.mjs",["--today"])),console.log(`
|
|
52
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" PIPELINE COMPLETE"),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");for(let[s,i]of Object.entries(n))console.log(` ${i===!0?"\u2713":i===!1?"\u2717":"\u26A0"} ${s}: ${i===!0?"success":i===!1?"failed":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
|
|
53
|
+
`);let r=Object.values(n).some(s=>s===!1);fe(t,r?"partial":"success",n)}an().catch(e=>{console.error("Daily pipeline failed:",e),process.exit(1)});
|
package/dist/enrichProfile.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Ot=Object.defineProperty;var V=(e,t)=>()=>(e&&(t=e(e=0)),t);var jt=(e,t)=>{for(var n in t)Ot(e,n,{get:t[n],enumerable:!0})};import E from"fs";import D from"path";function he(){let e=process.env.ILML_SCOPE_DIR;return e?D.join(e,"plugins-state","linkedin","cookies.json"):qt}function Bt(){let e=he(),t=D.dirname(e);return t&&t!=="."&&!E.existsSync(t)&&E.mkdirSync(t,{recursive:!0}),e}function He(e){let t=Bt();return E.writeFileSync(t,JSON.stringify(e)),t}function Ue(){let e=he();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 Ve(){return E.existsSync(he())}function Ht(){let e=process.env.ILML_SCOPE_DIR;return e?D.join(e,"plugins-state","linkedin"):"."}function Je(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Ut(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Je(t[1]):"default"}function We(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return E.existsSync(t)||E.mkdirSync(t,{recursive:!0}),D.resolve(t);let n=Je(e||Ut()),o=D.join(Ht(),"chrome-profile",n);return E.existsSync(o)||E.mkdirSync(o,{recursive:!0}),D.resolve(o)}function Ye(e){return!E.existsSync(D.join(e,Ke))}function Ge(e){try{E.writeFileSync(D.join(e,Ke),new Date().toISOString())}catch{}}function ze(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{E.rmSync(D.join(e,n),{force:!0}),t++}catch{}return t}var qt,Ke,te=V(()=>{qt="cookies.json";Ke=".ilml-seeded"});async function S(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function Vt(e,t,{timeout:n=45e3,poll:o=1e3,label:i="page"}={}){let s=Date.now();for(;Date.now()-s<n;){try{if(await e.evaluate(a=>!!document.querySelector(a),t)){let a=Date.now()-s;return a>6e3&&console.log(` (waited ${Math.round(a/1e3)}s for LinkedIn to finish loading ${i})`),!0}}catch{}await new Promise(r=>setTimeout(r,o))}return!1}function Jt(e){return Xe.test(e||"")}async function Wt(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),i=o?t:Math.min(t,45e3),s=Date.now(),r=!1;for(;Date.now()-s<i;){let f="wait";try{f=await e.evaluate(p=>!new RegExp(p).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",Xe.source)}catch{}if(f==="in"){try{let p=await e.cookies();if(Array.isArray(p)&&p.some(b=>b.name==="li_at")){let b=He(p);console.log(` \u2713 Session recovered \u2014 re-saved ${p.length} cookies (${b}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(p){console.log(` \u2713 Session recovered (cookie re-save skipped: ${p.message}).`)}return!0}if(f==="creds"){if(!o){let p=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw p.code="SESSION_EXPIRED",p}r||(r=!0,console.log(`
|
|
2
2
|
\u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
|
|
3
|
-
`))}await new Promise(l=>setTimeout(l,2500))}let d=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw d.code="SESSION_EXPIRED",d}async function te(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let i=await qt(e,t,{timeout:o,label:n});if(!i&&Bt(e.url())){let s=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw s.code="SESSION_EXPIRED",s}return i}async function Ze(e,t,{readySelector:n,label:o="page",timeout:i=45e3,gotoTimeout:s=6e4,autoRecover:r=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:s});try{return await te(e,{readySelector:n,label:o,timeout:i})}catch(d){if(r&&d.code==="SESSION_EXPIRED"){await Ut(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:s})}catch{}return await te(e,{readySelector:n,label:o,timeout:i})}throw d}}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||"",s=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"),d=i.includes("Get hired faster")||i.includes("Get hired 2x");if(s||r||d){let m=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(m)return m.click(),{dismissed:!0,matched:i.substring(0,80)};let l=o.querySelectorAll("button");for(let S of l){let p=S.innerText?.trim().toLowerCase()||"",g=S.getAttribute("aria-label")?.toLowerCase()||"";if(p==="not now"||p==="no thanks"||p==="dismiss"||g.includes("dismiss"))return S.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 Qe,we=W(()=>{ee();Qe=/\/authwall|\/login|\/checkpoint|\/uas\/login/});import{getPluginConfig as Ht}from"@ilivemylife/graph-sdk";var Vt,En,F,In,An,et=W(async()=>{Vt=await Ht();for(let[e,t]of Object.entries(Vt))process.env[e]===void 0&&(process.env[e]=t);En=process.env.LINKEDIN_NAME,F=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),In=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.NEEDS_REVIEW])),An=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.REJECTED,F.NEEDS_REVIEW]))});import"dotenv/config";import*as w from"fs";import*as b from"path";import{fileURLToPath as Wt}from"url";function rt(){w.existsSync(_)||w.mkdirSync(_,{recursive:!0})}function st(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";w.writeFileSync(o,n);for(let i=0;i<3;i++)try{w.renameSync(o,e);return}catch(s){if(i<2&&(s.code==="EPERM"||s.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw s}}function lt(e,t){if(!w.existsSync(e))return null;try{let n=JSON.parse(w.readFileSync(e,"utf-8"));try{w.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(w.existsSync(o))try{let i=JSON.parse(w.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{w.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{w.copyFileSync(e,e+".corrupted")}catch{}return null}}function Yt(){return new Date().toISOString().split("T")[0]}function O(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function tt(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function at(e,t,n=null){if(!t||e[t])return t;let o=O(t);if(!o)return t;let i=null;for(let[s,r]of Object.entries(e)){if(O(r.profileUrl||s)===o)return s;!i&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(i=s)}if(i){let s=tt(n),r=tt(e[i].name);if(s&&r&&s===r)return i}return t}function Qt(){w.existsSync(ye)||w.mkdirSync(ye,{recursive:!0})}function ct(e){let t=O(e);return t?b.join(ye,`${t}.json`):null}function Zt(e){let t=ct(e);return t?lt(t,`profile-history/${O(e)}.json`)||[]:[]}function Xt(e,t){let n=ct(e);if(!n)return;Qt();let o=Zt(e);o.unshift(t);try{st(n,o)}catch(i){console.error(`[!] Failed to append profile-history for ${O(e)}: ${i.message}`)}}function nt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function ot(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function en(e,t){if(!e)return[];let n=[];for(let o of zt){let i=e[o],s=t[o];nt(i)||nt(s)||ot(i)!==ot(s)&&n.push(o)}return n}function tn(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,i]of Object.entries(e))t.has(o)||(n[o]=i);return n}function be(){return J||(rt(),J=lt(ge,"people.json")||{},J)}function ut(e){rt(),J=e;try{st(ge,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${b.resolve(ge)}`)}}function Se(e,t={}){if(!e)return null;let n=be(),o=Yt(),i=new Date().toISOString(),s=at(n,e,t.name),r=n[s];if(r){let d=en(r,t);d.length>0&&(Xt(s,{capturedAt:i,previousLastUpdated:r.lastUpdated||null,changedFields:d,snapshot:tn(r)}),r.lastSnapshotAt=i),r.seenCount=(r.seenCount||1)+1,r.lastSeen=o,r.lastUpdated=i,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let m of Gt)if(t[m]!=null){if(Array.isArray(t[m])&&t[m].length===0&&Array.isArray(r[m])&&r[m].length>0)continue;r[m]=t[m]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=i)}else n[s]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:i,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?i:null};return ut(n),n[s]}function ke(e,t,n={}){if(n.dryRun||!e||!t)return;let o=O(t);if(!o)return;let i=be(),s=at(i,e),r=i[s];if(!r)return;let d=O(r.profileUrl||s);o!==d&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(o)||(r.aliases.push(o),r.lastUpdated=new Date().toISOString(),ut(i)))}var Jt,Kt,_,ge,Rn,Pn,Tn,Nn,Mn,ye,it,Fn,On,J,Gt,zt,ve=W(async()=>{await et();Jt=Wt(import.meta.url),Kt=b.dirname(b.dirname(Jt)),_=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"collected-profiles"):b.join(Kt,"collected-profiles"),ge=b.join(_,"people.json"),Rn=b.join(_,"jobs.json"),Pn=b.join(_,"quota.json"),Tn=b.join(_,"conversations.json"),Nn=b.join(_,"sync-state.json"),Mn=b.join(_,"application-questions.json"),ye=b.join(_,"profile-history"),it=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Fn=it(process.env.CONNECT_MAX_DAILY,20),On=it(process.env.CONNECT_MAX_WEEKLY,100),J=null;Gt=["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"],zt=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var dt={};Nt(dt,{extractCertificationsFromDetails:()=>ln,extractEducationFromDetails:()=>rn,extractExperienceFromDetails:()=>nn,extractFeaturedFromDetails:()=>on,extractRecommendationsFromDetails:()=>an,extractSkillsFromDetails:()=>sn});async function nn(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await te(e,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await y(1e3);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await y(900);await y(1e3);let o=0;for(;o<5&&await e.evaluate(()=>{for(let s of document.querySelectorAll("button"))if(/^Load more$/i.test((s.textContent||"").trim()))return s.click(),!0;return!1});)o++,await y(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await y(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function s(l){let S=[];for(let p of l.querySelectorAll("div")){let g=Array.from(p.children).filter(C=>C.tagName==="DIV");if(g.length<3)continue;let k=g.filter(C=>(C.textContent||"").trim().length>50);k.length<3||(p.textContent||"").length<500||S.push({el:p,count:k.length,totalText:(p.textContent||"").length})}return S.sort((p,g)=>g.count-p.count||p.totalText-g.totalText),S[0]?.el}let r=s(i);if(!r)return[];let d=Array.from(r.children).filter(l=>l.tagName==="DIV").filter(l=>(l.textContent||"").trim().length>50);function m(l){let S=l[0]||null,p=null,g=null;if(l[1]){let c=l[1].split("\xB7").map(x=>x.trim());p=c[0]||null,c[1]&&(g=c[1])}let k=l.findIndex(c=>/(\d{4}|present)/i.test(c)&&/(-|–|—)/i.test(c)&&c.length<80),C=null,R=null;if(k>=0){let c=l[k].split("\xB7").map(x=>x.trim());C=c[0]||null,c[1]&&(R=c[1])}let P=null,T=-1;if(k>=0&&l[k+1]){let c=l[k+1],x=/^[>*\-•]|^>/.test(c),H=/https?:\/\//.test(c),q=/\d{4}/.test(c),B=/,/.test(c)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(c);!x&&!H&&!q&&c.length<100&&B&&(P=c,T=k+1)}let N=null,fe=-1,h=l[l.length-1];if(h&&/and\s+\+\d+\s+skills?$/i.test(h)){fe=l.length-1;let c=h.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);c&&(N={listed:c[1].split(",").map(x=>x.trim()),additional:parseInt(c[2],10)})}let U=new Set([0,1,k,T,fe].filter(c=>c>=0)),$=l.filter((c,x)=>!U.has(x)),M=$.length>0?$.join(`
|
|
3
|
+
`))}await new Promise(p=>setTimeout(p,2500))}let a=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw a.code="SESSION_EXPIRED",a}async function Qe(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let i=await Vt(e,t,{timeout:o,label:n});if(!i&&Jt(e.url())){let s=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw s.code="SESSION_EXPIRED",s}return i}async function W(e,t,{readySelector:n,label:o="page",timeout:i=45e3,gotoTimeout:s=6e4,autoRecover:r=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:s});try{return await Qe(e,{readySelector:n,label:o,timeout:i})}catch(a){if(r&&a.code==="SESSION_EXPIRED"){await Wt(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:s})}catch{}return await Qe(e,{readySelector:n,label:o,timeout:i})}throw a}}async function Ze(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let i=o.innerText||"",s=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"),a=i.includes("Get hired faster")||i.includes("Get hired 2x");if(s||r||a){let f=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(f)return f.click(),{dismissed:!0,matched:i.substring(0,80)};let p=o.querySelectorAll("button");for(let u of p){let b=u.innerText?.trim().toLowerCase()||"",g=u.getAttribute("aria-label")?.toLowerCase()||"";if(b==="not now"||b==="no thanks"||b==="dismiss"||g.includes("dismiss"))return u.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 Xe,we=V(()=>{te();Xe=/\/authwall|\/login|\/checkpoint|\/uas\/login/});function Yt(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function tt(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let n=new URLSearchParams;n.set("keywords",t);let o=(e.JOB_SEARCH_LOCATION||"").trim();o&&n.set("location",o);let i=(e.JOB_SEARCH_GEO_ID||"").trim();i&&n.set("geoId",i);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&n.set("distance",String(s)),et(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),et(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let r=Yt(e.JOB_SEARCH_COMPANY_IDS);r.length&&n.set("f_C",r.join(","));let a=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();a&&n.set("f_TPR",Kt[a]||a),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let f="https://www.linkedin.com/jobs/search/?"+n.toString(),p=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return p&&(f+="&"+p),f}var Kt,et,nt=V(()=>{Kt={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},et=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim())});import{getPluginConfig as Gt}from"@ilivemylife/graph-sdk";var zt,ot,Pn,j,Tn,Nn,it=V(async()=>{nt();zt=await Gt();for(let[e,t]of Object.entries(zt))process.env[e]===void 0&&(process.env[e]=t);ot=tt(process.env);ot&&(process.env.LINKEDIN_SEARCH_URL=ot);Pn=process.env.LINKEDIN_NAME,j=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Tn=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.NEEDS_REVIEW])),Nn=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.REJECTED,j.NEEDS_REVIEW]))});import"dotenv/config";import*as h from"fs";import*as k from"path";import{fileURLToPath as Qt}from"url";function ct(){h.existsSync($)||h.mkdirSync($,{recursive:!0})}function ut(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";h.writeFileSync(o,n);for(let i=0;i<3;i++)try{h.renameSync(o,e);return}catch(s){if(i<2&&(s.code==="EPERM"||s.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw s}}function dt(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: ${k.resolve(e)}`);let o=e+".backup";if(h.existsSync(o))try{let i=JSON.parse(h.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{h.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{h.copyFileSync(e,e+".corrupted")}catch{}return null}}function en(){return new Date().toISOString().split("T")[0]}function q(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function rt(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function ft(e,t,n=null){if(!t||e[t])return t;let o=q(t);if(!o)return t;let i=null;for(let[s,r]of Object.entries(e)){if(q(r.profileUrl||s)===o)return s;!i&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(i=s)}if(i){let s=rt(n),r=rt(e[i].name);if(s&&r&&s===r)return i}return t}function on(){h.existsSync(ye)||h.mkdirSync(ye,{recursive:!0})}function mt(e){let t=q(e);return t?k.join(ye,`${t}.json`):null}function rn(e){let t=mt(e);return t?dt(t,`profile-history/${q(e)}.json`)||[]:[]}function sn(e,t){let n=mt(e);if(!n)return;on();let o=rn(e);o.unshift(t);try{ut(n,o)}catch(i){console.error(`[!] Failed to append profile-history for ${q(e)}: ${i.message}`)}}function st(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function lt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function ln(e,t){if(!e)return[];let n=[];for(let o of nn){let i=e[o],s=t[o];st(i)||st(s)||lt(i)!==lt(s)&&n.push(o)}return n}function an(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,i]of Object.entries(e))t.has(o)||(n[o]=i);return n}function Se(){return K||(ct(),K=dt(ge,"people.json")||{},K)}function pt(e){ct(),K=e;try{ut(ge,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${k.resolve(ge)}`)}}function be(e,t={}){if(!e)return null;let n=Se(),o=en(),i=new Date().toISOString(),s=ft(n,e,t.name),r=n[s];if(r){let a=ln(r,t);a.length>0&&(sn(s,{capturedAt:i,previousLastUpdated:r.lastUpdated||null,changedFields:a,snapshot:an(r)}),r.lastSnapshotAt=i),r.seenCount=(r.seenCount||1)+1,r.lastSeen=o,r.lastUpdated=i,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let f of tn)if(t[f]!=null){if(Array.isArray(t[f])&&t[f].length===0&&Array.isArray(r[f])&&r[f].length>0)continue;r[f]=t[f]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=i)}else n[s]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:i,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?i:null};return pt(n),n[s]}function ke(e,t,n={}){if(n.dryRun||!e||!t)return;let o=q(t);if(!o)return;let i=Se(),s=ft(i,e),r=i[s];if(!r)return;let a=q(r.profileUrl||s);o!==a&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(o)||(r.aliases.push(o),r.lastUpdated=new Date().toISOString(),pt(i)))}var Xt,Zt,$,ge,qn,Bn,Hn,Un,Vn,ye,at,Jn,Wn,K,tn,nn,Ce=V(async()=>{await it();Xt=Qt(import.meta.url),Zt=k.dirname(k.dirname(Xt)),$=process.env.DATA_DIR?k.resolve(process.env.DATA_DIR,"collected-profiles"):k.join(Zt,"collected-profiles"),ge=k.join($,"people.json"),qn=k.join($,"jobs.json"),Bn=k.join($,"quota.json"),Hn=k.join($,"conversations.json"),Un=k.join($,"sync-state.json"),Vn=k.join($,"application-questions.json"),ye=k.join($,"profile-history"),at=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Jn=at(process.env.CONNECT_MAX_DAILY,20),Wn=at(process.env.CONNECT_MAX_WEEKLY,100),K=null;tn=["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"],nn=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var ht={};jt(ht,{extractCertificationsFromDetails:()=>mn,extractEducationFromDetails:()=>dn,extractExperienceFromDetails:()=>cn,extractFeaturedFromDetails:()=>un,extractRecommendationsFromDetails:()=>pn,extractSkillsFromDetails:()=>fn});async function cn(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await W(e,n,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await S(1e3);let o=e.url();if(!o.toLowerCase().includes("/details/experience/"))throw new Error(`Section /details/experience/ not available on profile (landed on ${o})`);for(let s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(900);await S(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 S(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function r(u){let b=[];for(let g of u.querySelectorAll("div")){let y=Array.from(g.children).filter(I=>I.tagName==="DIV");if(y.length<3)continue;let C=y.filter(I=>(I.textContent||"").trim().length>50);C.length<3||(g.textContent||"").length<500||b.push({el:g,count:C.length,totalText:(g.textContent||"").length})}return b.sort((g,y)=>y.count-g.count||g.totalText-y.totalText),b[0]?.el}let a=r(s);if(!a)return[];let f=Array.from(a.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function p(u){let b=u[0]||null,g=null,y=null;if(u[1]){let m=u[1].split("\xB7").map(v=>v.trim());g=m[0]||null,m[1]&&(y=m[1])}let C=u.findIndex(m=>/(\d{4}|present)/i.test(m)&&/(-|–|—)/i.test(m)&&m.length<80),I=null,T=null;if(C>=0){let m=u[C].split("\xB7").map(v=>v.trim());I=m[0]||null,m[1]&&(T=m[1])}let N=null,M=-1;if(C>=0&&u[C+1]){let m=u[C+1],v=/^[>*\-•]|^>/.test(m),H=/https?:\/\//.test(m),U=/\d{4}/.test(m),x=/,/.test(m)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(m);!v&&!H&&!U&&m.length<100&&x&&(N=m,M=C+1)}let fe=null,w=-1,F=u[u.length-1];if(F&&/and\s+\+\d+\s+skills?$/i.test(F)){w=u.length-1;let m=F.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);m&&(fe={listed:m[1].split(",").map(v=>v.trim()),additional:parseInt(m[2],10)})}let O=new Set([0,1,C,M,w].filter(m=>m>=0)),R=u.filter((m,v)=>!O.has(v)),_=R.length>0?R.join(`
|
|
4
4
|
|
|
5
|
-
`):null;return{title:
|
|
6
|
-
`).map(
|
|
7
|
-
${
|
|
5
|
+
`):null;return{title:b,company:g,employmentType:y,dates:I,duration:T,location:N,description:_,skills:fe,_raw:u}}return f.map(u=>{let g=(u.innerText||"").trim().split(`
|
|
6
|
+
`).map(y=>y.trim()).filter(y=>y&&y.length<5e3);return p(g)}).filter(u=>u.title)})}catch(o){if(o.code==="SESSION_EXPIRED"||/^session expired/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function Y(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await W(e,o,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:`details/${n}`}),await S(1e3);let i=e.url();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 S(700);await S(800);let s=0;for(;s<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)s++,await S(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(600)}async function z(e,t,n,o){try{return await o()}catch(i){let s=i.message||"";if(i.code==="SESSION_EXPIRED"||/^session expired/i.test(s))throw i;return/not available on profile/i.test(s)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${s.slice(0,120)}`),[])}}async function un(e,t){return z(t,"featured","extractFeaturedFromDetails",async()=>(await Y(e,t,"featured"),await e.evaluate(`(() => {
|
|
7
|
+
${G}
|
|
8
8
|
|
|
9
9
|
const main = document.querySelector('main');
|
|
10
10
|
if (!main) return [];
|
|
@@ -44,8 +44,8 @@ var Tt=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var Nt=(e,t)=>{f
|
|
|
44
44
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
45
45
|
return true;
|
|
46
46
|
});
|
|
47
|
-
})()`)))}async function
|
|
48
|
-
${
|
|
47
|
+
})()`)))}async function dn(e,t){return z(t,"education","extractEducationFromDetails",async()=>(await Y(e,t,"education"),await e.evaluate(`(() => {
|
|
48
|
+
${G}
|
|
49
49
|
|
|
50
50
|
const main = document.querySelector('main');
|
|
51
51
|
if (!main) return [];
|
|
@@ -81,8 +81,8 @@ var Tt=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var Nt=(e,t)=>{f
|
|
|
81
81
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
82
82
|
return true;
|
|
83
83
|
});
|
|
84
|
-
})()`)))}async function
|
|
85
|
-
${
|
|
84
|
+
})()`)))}async function fn(e,t){return z(t,"skills","extractSkillsFromDetails",async()=>(await Y(e,t,"skills"),await e.evaluate(`(() => {
|
|
85
|
+
${G}
|
|
86
86
|
|
|
87
87
|
const main = document.querySelector('main');
|
|
88
88
|
if (!main) return [];
|
|
@@ -113,8 +113,8 @@ var Tt=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var Nt=(e,t)=>{f
|
|
|
113
113
|
skills.push({ name, endorsements, _raw: lines });
|
|
114
114
|
}
|
|
115
115
|
return skills;
|
|
116
|
-
})()`)))}async function
|
|
117
|
-
${
|
|
116
|
+
})()`)))}async function mn(e,t){return z(t,"certifications","extractCertificationsFromDetails",async()=>(await Y(e,t,"certifications"),await e.evaluate(`(() => {
|
|
117
|
+
${G}
|
|
118
118
|
|
|
119
119
|
const main = document.querySelector('main');
|
|
120
120
|
if (!main) return [];
|
|
@@ -138,8 +138,8 @@ var Tt=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var Nt=(e,t)=>{f
|
|
|
138
138
|
|
|
139
139
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
140
140
|
}).filter(e => e.name);
|
|
141
|
-
})()`)))}async function
|
|
142
|
-
${
|
|
141
|
+
})()`)))}async function pn(e,t){return z(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Y(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
142
|
+
${G}
|
|
143
143
|
|
|
144
144
|
const main = document.querySelector('main');
|
|
145
145
|
if (!main) return [];
|
|
@@ -174,7 +174,7 @@ var Tt=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var Nt=(e,t)=>{f
|
|
|
174
174
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
175
175
|
return true;
|
|
176
176
|
});
|
|
177
|
-
})()`)))}var
|
|
177
|
+
})()`)))}var G,wt=V(()=>{we();G=`
|
|
178
178
|
function findEntryContainer(root) {
|
|
179
179
|
const candidates = [];
|
|
180
180
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -237,7 +237,7 @@ function findEntryContainer(root) {
|
|
|
237
237
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
238
238
|
return candidates[0]?.el;
|
|
239
239
|
}
|
|
240
|
-
`});import"dotenv/config";import wn from"puppeteer";we();await ve();async function cn(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 y(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function mt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:i=!1,extractEducation:s=!1,extractSkills:r=!1,extractRecommendations:d=!1,extractCertifications:m=!1}=n;try{await Ze(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await y(1500),await Xe(e)&&(console.log(" Dismissed Premium overlay"),await y(1500),await cn(e,t));let S=0;for(let h=0;h<2;h++){let U=await e.evaluate(()=>document.body.scrollHeight);for(let M=1;M<=6;M++)await e.evaluate(c=>window.scrollTo(0,c),U*M/6),await y(900);let $=await e.evaluate(()=>document.body.scrollHeight);if($===S)break;S=$}await y(800);let p=null;try{let h=e.url();h&&/\/in\/[^/?#]/.test(h)&&(p=h.split("?")[0].replace(/\/+$/,""))}catch{}let g=await e.evaluate(()=>{let h=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"]),U=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),$=a=>{let u=(a||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(u)},M={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},c=document.querySelector("main");if(!c)return M;let x=[...Array.from(c.querySelectorAll("h1")),...Array.from(c.querySelectorAll("h2"))],H=Array.from(c.querySelectorAll("h2")),q=x.find(a=>{let u=a.textContent&&a.textContent.trim(),f=(u||"").replace(/\s*\(\d+\)$/,"").trim();return u&&u.length>1&&u.length<100&&!h.has(f)&&!U.has(f)}),B=q?q.textContent.trim():null,E=q?q.parentElement:null;for(;E&&E!==c&&!Array.from(E.children).filter(u=>u.tagName==="P").some(u=>{let f=u.textContent&&u.textContent.trim();return f&&f.length>5&&!$(f)});)E=E.parentElement;let _e=null,$e=null,De=null,me=null;if(E&&E!==c){let a=Array.from(E.children).filter(f=>f.tagName==="P").filter(f=>{let D=f.textContent&&f.textContent.trim();return D&&D.length>5&&!$(D)});if(a[0]&&(_e=a[0].textContent.trim()),a[1]){let f=a[1].textContent.trim().split(/\s*[·•]\s*/);$e=f[0]||null,f.length>1&&(De=f.slice(1).join(" \xB7 "))}let u=Array.from(E.children).filter(f=>f.tagName==="DIV");for(let f=u.length-1;f>=0;f--){let D=u[f].textContent&&u[f].textContent.trim();if(D&&!(B&&D.startsWith(B))&&(me=D.split(/[·•]/)[0].trim(),me))break}}let Le=null;if(E){let a=E.querySelectorAll("p, span, div");for(let u of a){let f=(u.textContent||"").trim().replace(/^[·•]\s*/,"");if(f==="1st"||f==="2nd"||f==="3rd"){Le=f;break}}}let At=!!c.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),Re=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),_t=Re&&Re.src||null,Z=c.textContent||"",Pe=null,Te=Z.match(/(\d+\+?)\s+connections\b/i);Te&&(Pe=Te[1]+" connections");let X=null,Ne=Z.match(/(\d+)\s+mutual connection/i),Me=Z.match(/and\s+(\d+)\s+other mutual/i),$t=Z.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Ne?X=parseInt(Ne[1],10):Me?X=2+parseInt(Me[1],10):$t&&(X=2);let Fe=null,Oe=null,je=H.find(a=>a.textContent&&a.textContent.trim()==="About");if(je){let a=je.parentElement;for(;a&&a.tagName!=="SECTION";)a=a.parentElement;if(a){let u=(a.textContent||"").trim();u=u.replace(/^About\s*/,"").trim();let f=u.match(/Top skills\s*(.+?)$/i);if(f){let pe=f[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Pt=>Pt.trim()).filter(Boolean);pe.length>0&&pe.length<10&&(Oe=pe)}u=u.split(/\n?…\s*more/i)[0].trim(),u=u.split(/\n?\.\.\.\s*more/i)[0].trim(),u=u.split(/\bTop skills\b/i)[0].trim(),u=u.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Fe=u||null}}let qe=null,Be=H.find(a=>a.textContent&&a.textContent.trim()==="Activity");if(Be){let a=Be.parentElement;for(;a&&a.tagName!=="SECTION";)a=a.parentElement;if(a){let u=(a.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);u&&(qe=parseInt(u[1].replace(/,/g,""),10))}}let Dt=[...new Set(H.map(a=>(a.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(a=>a&&a.length>1&&a.length<60&&a!==B).filter(a=>h.has(a)))],V=document.body.textContent||"",Lt=/#OpenToWork\b/i.test(V)||/\bOpen to work\b/.test(V),Rt=/#Hiring\b/i.test(V)||/\bI'?m hiring\b/i.test(V)||/\bWe are hiring\b/i.test(V);return{name:B,title:_e,location:me,currentCompany:$e,currentSchool:De,connectionDegree:Le,hasVerifiedBadge:At,photoUrl:_t,connectionsLevel:Pe,mutualConnectionsCount:X,followers:qe,openToWork:Lt,hiring:Rt,about:Fe,topSkills:Oe,availableSections:Dt}});console.log(`Viewed: ${g.name} - ${g.title}`);let k=null,C=null,R=null,P=null,T=null,N=null;if(o||i||s||r||d||m){let h=await Promise.resolve().then(()=>(ft(),dt));o&&(k=await h.extractExperienceFromDetails(e,t),console.log(` + Experience: ${k.length} entries`)),i&&(C=await h.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${C.length} entries`)),s&&(R=await h.extractEducationFromDetails(e,t),console.log(` + Education: ${R.length} entries`)),r&&(P=await h.extractSkillsFromDetails(e,t),console.log(` + Skills: ${P.length} entries`)),d&&(T=await h.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${T.length} entries`)),m&&(N=await h.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${N.length} entries`))}return{...g,profileUrl:t,resolvedUrl:p,...k!==null&&{experience:k},...C!==null&&{featured:C},...R!==null&&{education:R},...P!==null&&{skillsFull:P},...T!==null&&{recommendations:T},...N!==null&&{certifications:N}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await y(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(l.message||""))throw l;return null}}await ve();ee();ee();import Ce from"fs";import un from"path";var dn={headless:!1,defaultViewport:null,protocolTimeout:3e5},Q=new Set,pt=!1;async function ne(){let e=[...Q].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});Q.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function fn(){if(pt)return;pt=!0;let e=t=>async()=>{await ne(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await ne(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await ne(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await ne(),process.exit(0))}),process.on("exit",()=>{for(let t of Q)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function xe(e){return un.join(e,".ilml-browser-session.json")}function yt(e,t={}){try{Ce.writeFileSync(xe(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function mn(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();yt(e,n?{wsEndpoint:n}:{})}catch{}}function pn(e){let t=bt(e);t&&t.ownerPid===process.pid&&z(e)}function z(e){try{Ce.rmSync(xe(e),{force:!0})}catch{}}function bt(e){try{return JSON.parse(Ce.readFileSync(xe(e),"utf-8"))}catch{return null}}function ht(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function wt(e,t,n){let o,i=new Promise(r=>{o=setTimeout(()=>r(n),t)}),s=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([s,i])}async function gt(e,t,{probeTimeoutMs:n=4e3}={}){let o=bt(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&ht(o.ownerPid)?"live":(z(t),"free");let i=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await wt(s,n,i);if(r===i)return s.then(m=>{if(m)try{m.disconnect()}catch{}}),"live";if(!r)return z(t),"free";if(ht(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await wt(r.close().then(()=>!0).catch(()=>!1),n,!1))return z(t),"free";try{r.disconnect()}catch{}return"live"}function hn(e,t){e&&(fn(),Q.add(e),e.on("disconnected",()=>{Q.delete(e),t&&z(t)}))}async function St(e,t={}){let n=Je(),o={...dn,...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 gt(e,n)==="live")throw new Error(i);yt(n);let s;try{s=await e.launch(o)}catch{if(await gt(e,n)==="live")throw new Error(i);ze(n);try{s=await e.launch(o)}catch(d){throw pn(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: ${d.message})`)}}return hn(s,n),mn(n,s),{browser:s,profileDir:n,needsSeed:Ye(n)}}async function kt(e,t){if(!t||!t.needsSeed)return!1;if(!Ve())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(...He()),Ge(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}function vt(e){return e?e.replace(/^https?:\/\/(www\.|m\.)?linkedin\.com/i,"https://linkedin.com").split("?")[0].split("#")[0].replace(/\/+$/,"").toLowerCase():""}function Ct(e){return(e||"").replace(/ /g," ").replace(/\s+/g," ").trim().toLowerCase()}var I=process.argv.slice(2),gn=I.includes("--help")||I.includes("-h"),L=I.find(e=>e.startsWith("http")),j=I.includes("--full"),ie=j||I.includes("--with-experience"),re=j||I.includes("--with-featured"),se=j||I.includes("--with-education"),le=j||I.includes("--with-skills"),ae=j||I.includes("--with-recommendations"),ce=j||I.includes("--with-certifications"),xt=[["experience",ie],["featured",re],["education",se],["skills",le],["recommendations",ae],["certifications",ce]],Et=xt.filter(([,e])=>e).length,Ie=1+Et;function It(){console.log(`
|
|
240
|
+
`});import"dotenv/config";import Cn from"puppeteer";we();await Ce();async function hn(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 S(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function gt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:i=!1,extractEducation:s=!1,extractSkills:r=!1,extractRecommendations:a=!1,extractCertifications:f=!1}=n;try{await W(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await S(1500),await Ze(e)&&(console.log(" Dismissed Premium overlay"),await S(1500),await hn(e,t));let u=0;for(let w=0;w<2;w++){let F=await e.evaluate(()=>document.body.scrollHeight);for(let R=1;R<=6;R++)await e.evaluate(_=>window.scrollTo(0,_),F*R/6),await S(900);let O=await e.evaluate(()=>document.body.scrollHeight);if(O===u)break;u=O}await S(800);let b=null;try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(b=w.split("?")[0].replace(/\/+$/,""))}catch{}let g=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),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"]),O=l=>{let c=(l||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(c)},R={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:[]},_=document.querySelector("main");if(!_)return R;let m=[...Array.from(_.querySelectorAll("h1")),...Array.from(_.querySelectorAll("h2"))],v=Array.from(_.querySelectorAll("h2")),H=m.find(l=>{let c=l.textContent&&l.textContent.trim(),d=(c||"").replace(/\s*\(\d+\)$/,"").trim();return c&&c.length>1&&c.length<100&&!w.has(d)&&!F.has(d)}),U=H?H.textContent.trim():null,x=H?H.parentElement:null;for(;x&&x!==_&&!Array.from(x.children).filter(c=>c.tagName==="P").some(c=>{let d=c.textContent&&c.textContent.trim();return d&&d.length>5&&!O(d)});)x=x.parentElement;let Ae=null,De=null,$e=null,me=null;if(x&&x!==_){let l=Array.from(x.children).filter(d=>d.tagName==="P").filter(d=>{let L=d.textContent&&d.textContent.trim();return L&&L.length>5&&!O(L)});if(l[0]&&(Ae=l[0].textContent.trim()),l[1]){let d=l[1].textContent.trim().split(/\s*[·•]\s*/);De=d[0]||null,d.length>1&&($e=d.slice(1).join(" \xB7 "))}let c=Array.from(x.children).filter(d=>d.tagName==="DIV");for(let d=c.length-1;d>=0;d--){let L=c[d].textContent&&c[d].textContent.trim();if(L&&!(U&&L.startsWith(U))&&(me=L.split(/[·•]/)[0].trim(),me))break}}let Re=null;if(x){let l=x.querySelectorAll("p, span, div");for(let c of l){let d=(c.textContent||"").trim().replace(/^[·•]\s*/,"");if(d==="1st"||d==="2nd"||d==="3rd"){Re=d;break}}}let Rt=!!_.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),Le=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Lt=Le&&Le.src||null,Z=_.textContent||"",Pe=null,Te=Z.match(/(\d+\+?)\s+connections\b/i);Te&&(Pe=Te[1]+" connections");let ee=null,Ne=Z.match(/(\d+)\s+mutual connection/i),Me=Z.match(/and\s+(\d+)\s+other mutual/i),Pt=Z.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Ne?ee=parseInt(Ne[1],10):Me?ee=2+parseInt(Me[1],10):Pt&&(ee=2);let Fe=null,Oe=null,je=v.find(l=>l.textContent&&l.textContent.trim()==="About");if(je){let l=je.parentElement;for(;l&&l.tagName!=="SECTION";)l=l.parentElement;if(l){let c=(l.textContent||"").trim();c=c.replace(/^About\s*/,"").trim();let d=c.match(/Top skills\s*(.+?)$/i);if(d){let pe=d[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Ft=>Ft.trim()).filter(Boolean);pe.length>0&&pe.length<10&&(Oe=pe)}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(),Fe=c||null}}let qe=null,Be=v.find(l=>l.textContent&&l.textContent.trim()==="Activity");if(Be){let l=Be.parentElement;for(;l&&l.tagName!=="SECTION";)l=l.parentElement;if(l){let c=(l.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);c&&(qe=parseInt(c[1].replace(/,/g,""),10))}}let Tt=[...new Set(v.map(l=>(l.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(l=>l&&l.length>1&&l.length<60&&l!==U).filter(l=>w.has(l)))],J=document.body.textContent||"",Nt=/#OpenToWork\b/i.test(J)||/\bOpen to work\b/.test(J),Mt=/#Hiring\b/i.test(J)||/\bI'?m hiring\b/i.test(J)||/\bWe are hiring\b/i.test(J);return{name:U,title:Ae,location:me,currentCompany:De,currentSchool:$e,connectionDegree:Re,hasVerifiedBadge:Rt,photoUrl:Lt,connectionsLevel:Pe,mutualConnectionsCount:ee,followers:qe,openToWork:Nt,hiring:Mt,about:Fe,topSkills:Oe,availableSections:Tt}});console.log(`Viewed: ${g.name} - ${g.title}`);let y=null,C=null,I=null,T=null,N=null,M=null;if(o||i||s||r||a||f){let w=await Promise.resolve().then(()=>(wt(),ht));o&&(y=await w.extractExperienceFromDetails(e,t),console.log(` + Experience: ${y.length} entries`)),i&&(C=await w.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${C.length} entries`)),s&&(I=await w.extractEducationFromDetails(e,t),console.log(` + Education: ${I.length} entries`)),r&&(T=await w.extractSkillsFromDetails(e,t),console.log(` + Skills: ${T.length} entries`)),a&&(N=await w.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${N.length} entries`)),f&&(M=await w.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${M.length} entries`))}return{...g,profileUrl:t,resolvedUrl:b,...y!==null&&{experience:y},...C!==null&&{featured:C},...I!==null&&{education:I},...T!==null&&{skillsFull:T},...N!==null&&{recommendations:N},...M!==null&&{certifications:M}}}catch(p){console.error(`Error viewing profile ${t}:`,p.message);try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(p.message||""))throw p;return null}}await Ce();te();te();import ve from"fs";import wn from"path";var gn={headless:!1,defaultViewport:null,protocolTimeout:3e5},X=new Set,yt=!1;async function ne(){let e=[...X].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});X.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function yn(){if(yt)return;yt=!0;let e=t=>async()=>{await ne(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await ne(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await ne(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await ne(),process.exit(0))}),process.on("exit",()=>{for(let t of X)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function xe(e){return wn.join(e,".ilml-browser-session.json")}function Ct(e,t={}){try{ve.writeFileSync(xe(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Sn(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Ct(e,n?{wsEndpoint:n}:{})}catch{}}function bn(e){let t=vt(e);t&&t.ownerPid===process.pid&&Q(e)}function Q(e){try{ve.rmSync(xe(e),{force:!0})}catch{}}function vt(e){try{return JSON.parse(ve.readFileSync(xe(e),"utf-8"))}catch{return null}}function St(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function bt(e,t,n){let o,i=new Promise(r=>{o=setTimeout(()=>r(n),t)}),s=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([s,i])}async function kt(e,t,{probeTimeoutMs:n=4e3}={}){let o=vt(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&St(o.ownerPid)?"live":(Q(t),"free");let i=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await bt(s,n,i);if(r===i)return s.then(f=>{if(f)try{f.disconnect()}catch{}}),"live";if(!r)return Q(t),"free";if(St(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await bt(r.close().then(()=>!0).catch(()=>!1),n,!1))return Q(t),"free";try{r.disconnect()}catch{}return"live"}function kn(e,t){e&&(yn(),X.add(e),e.on("disconnected",()=>{X.delete(e),t&&Q(t)}))}async function xt(e,t={}){let n=We(),o={...gn,...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 kt(e,n)==="live")throw new Error(i);Ct(n);let s;try{s=await e.launch(o)}catch{if(await kt(e,n)==="live")throw new Error(i);ze(n);try{s=await e.launch(o)}catch(a){throw bn(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: ${a.message})`)}}return kn(s,n),Sn(n,s),{browser:s,profileDir:n,needsSeed:Ye(n)}}async function Et(e,t){if(!t||!t.needsSeed)return!1;if(!Ve())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(...Ue()),Ge(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}function _t(e){return e?e.replace(/^https?:\/\/(www\.|m\.)?linkedin\.com/i,"https://linkedin.com").split("?")[0].split("#")[0].replace(/\/+$/,"").toLowerCase():""}function It(e){return(e||"").replace(/ /g," ").replace(/\s+/g," ").trim().toLowerCase()}var A=process.argv.slice(2),vn=A.includes("--help")||A.includes("-h"),P=A.find(e=>e.startsWith("http")),B=A.includes("--full"),ie=B||A.includes("--with-experience"),re=B||A.includes("--with-featured"),se=B||A.includes("--with-education"),le=B||A.includes("--with-skills"),ae=B||A.includes("--with-recommendations"),ce=B||A.includes("--with-certifications"),At=[["experience",ie],["featured",re],["education",se],["skills",le],["recommendations",ae],["certifications",ce]],Dt=At.filter(([,e])=>e).length,_e=1+Dt;function $t(){console.log(`
|
|
241
241
|
enrich-profile \u2014 visit ONE LinkedIn profile and save what we learn
|
|
242
242
|
|
|
243
243
|
USAGE
|
|
@@ -288,4 +288,4 @@ WHEN TO USE
|
|
|
288
288
|
- Audit your own LinkedIn profile (--full prints everything to stdout)
|
|
289
289
|
- Deep-dive on one specific contact before reaching out
|
|
290
290
|
- Verify what we know about a recruiter / lead
|
|
291
|
-
`)}
|
|
291
|
+
`)}vn&&($t(),process.exit(0));P||($t(),process.exit(1));/linkedin\.com\/in\//i.test(P)||(console.error(`URL doesn't look like a LinkedIn profile: ${P}`),console.error("Expected format: https://www.linkedin.com/in/<slug>/"),process.exit(1));var Ie=_t(process.env.MY_LINKEDIN_URL||""),de=It(process.env.LINKEDIN_NAME||"");!Ie&&!de&&(console.error(""),console.error(" \u26D4 Refusing to run: cannot self-detect without configuration."),console.error(""),console.error(" Set EITHER (preferably both) of:"),console.error(" MY_LINKEDIN_URL=https://www.linkedin.com/in/<your-slug>"),console.error(' LINKEDIN_NAME="Your Full Name"'),console.error(""),console.error(" in .env (dev) or via `ilml plugin config linkedin set <KEY> <VALUE>` (prod)."),console.error(" This prevents your own profile from accidentally landing in people.json."),console.error(""),process.exit(1));var ue=Ie&&_t(P)===Ie,Ee=At.filter(([,e])=>e).map(([e])=>e);console.log("");console.log(` enrichProfile \u2014 ${P}`);B?console.log(` Mode: --full (${_e} page loads: main + ${Ee.join(" + ")})`):Ee.length>0?console.log(` Mode: rich (${_e} loads: main + ${Ee.join(" + ")})`):console.log(" Mode: basic (1 load \u2014 main page only)");console.log(ue?" Target: SELF (URL match) \u2014 will print to stdout, not saved to people.json":de?` Target: TBD \u2014 name-match against "${process.env.LINKEDIN_NAME}" after fetch`:" Target: will save to people.json (no MY_LINKEDIN_URL or LINKEDIN_NAME set for self-check)");Dt>0&&(console.log(""),console.log(` \u26A0 ${_e} page loads on the SAME profile = normal "deep read" pattern.`),console.log(" This is intentionally single-URL \u2014 DO NOT batch. For batch enrichment"),console.log(" use `enrichProfiles.mjs --with-experience` (gated, capped)."));console.log("");var oe=null;try{let e=await xt(Cn);oe=e.browser;let t=await oe.newPage();await Et(t,e);let n=await gt(t,P,{extractExperience:ie,extractFeatured:re,extractEducation:se,extractSkills:le,extractRecommendations:ae,extractCertifications:ce});if((!n||!n.name)&&(console.error(" viewProfile returned no name \u2014 profile not loaded or DOM changed"),process.exit(1)),!ue&&de&&n.name&&It(n.name)===de&&(ue=!0,console.log(" \u2191 Detected self via LINKEDIN_NAME match \u2014 will NOT save to people.json")),console.log(""),console.log(" \u2500\u2500\u2500 extracted \u2500\u2500\u2500"),console.log(` name: ${n.name}`),console.log(` title: ${n.title||"(none)"}`),console.log(` location: ${n.location||"(none)"}`),console.log(` about: ${n.about?`${n.about.length} chars`:"(none)"}`),console.log(` topSkills: ${n.topSkills?n.topSkills.join(", "):"(none)"}`),ie&&console.log(` experience: ${(n.experience||[]).length} entries`),re&&console.log(` featured: ${(n.featured||[]).length} entries`),se&&console.log(` education: ${(n.education||[]).length} entries`),le&&console.log(` skillsFull: ${(n.skillsFull||[]).length} entries`),ae&&console.log(` recommendations: ${(n.recommendations||[]).length} entries`),ce&&console.log(` certifications: ${(n.certifications||[]).length} entries`),console.log(""),ue)console.log(" \u2500\u2500\u2500 full data (self \u2014 not persisted) \u2500\u2500\u2500"),console.log(JSON.stringify(n,null,2));else{let o={name:n.name,title:n.title,location:n.location,about:n.about,currentCompany:n.currentCompany,currentSchool:n.currentSchool,topSkills:n.topSkills,availableSections:n.availableSections,connectionsLevel:n.connectionsLevel,mutualConnectionsCount:n.mutualConnectionsCount,followers:n.followers,openToWork:n.openToWork,hiring:n.hiring,hasVerifiedBadge:n.hasVerifiedBadge,photoUrl:n.photoUrl,source:"enrich-profile-single"},i=[["experience",ie,n.experience],["featured",re,n.featured],["education",se,n.education],["skillsFull",le,n.skillsFull],["recommendations",ae,n.recommendations],["certifications",ce,n.certifications]],s=!1;for(let[r,a,f]of i)a&&(Array.isArray(f)&&f.length>0?(o[r]=f,s=!0):console.log(` \u26A0 --with-${r==="skillsFull"?"skills":r} returned 0 entries \u2014 NOT writing ${r} (existing data preserved)`));s&&(o._lastEnrichedAt=new Date().toISOString()),be(P,o),n.resolvedUrl&&ke(P,n.resolvedUrl),console.log(" \u2713 Saved to people.json")}}catch(e){console.error(" Error:",e.message),process.exit(1)}finally{oe&&await oe.close().catch(()=>{})}
|