ilml-plugin-linkedin 1.14.0 → 1.14.2
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 +8 -0
- package/README.md +3 -1
- package/dist/applyQueue.mjs +24 -24
- package/dist/connect.mjs +81 -78
- package/dist/daily.mjs +16 -16
- package/dist/enrichProfile.mjs +9 -9
- package/dist/enrichProfiles.mjs +32 -32
- package/dist/funnelRunner.mjs +36 -36
- package/dist/messageBot.mjs +55 -55
- package/dist/migrationCli.mjs +16 -16
- package/dist/profileHistory.mjs +5 -5
- package/dist/quota.mjs +3 -3
- package/dist/run.mjs +36 -36
- package/dist/scout.mjs +19 -19
- package/dist/syncAll.mjs +64 -64
- package/dist/verifyAbout.mjs +11 -11
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +22 -22
- package/dist/visit.mjs +26 -26
- package/dist/warmScan.mjs +3 -3
- package/ilml-plugin.json +14 -6
- package/package.json +1 -1
package/dist/daily.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var
|
|
1
|
+
var _e=Object.defineProperty;var W=(e,n)=>{for(var t in n)_e(e,t,{get:n[t],enumerable:!0})};import{execFileSync as Go}from"child_process";import"dotenv/config";import*as S from"fs";import*as R from"path";import{fileURLToPath as Je}from"url";import"dotenv/config";import{createGraphClient as xe,resolveToken as Fe}from"@ilivemylife/graph-sdk";import{config as Le}from"dotenv";Le();var te=Fe()||process.env.TOKEN;te||(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 se=
|
|
5
|
+
`),process.exit(1));var se=xe({token:te});function Me(e){if(!e||e<1e3)return`${e||0}ms`;let n=Math.round(e/1e3);if(n<60)return`${n}s`;let t=Math.floor(n/60),o=n%60;return o?`${t}m ${o}s`:`${t}m`}function Pe({scriptName:e,mode:n,status:t,error:o,duration:s}){let r=t==="error"?"\u2717":t==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),a=s?` ${Me(s)}`:"",l=t==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:t==="quota-reached"?"daily quota reached":"done",u=n&&n!=="default"?` (${n})`:"";return`${r} ${e}${u} \u2014 ${l} \u2014 ${i}${a}`}async function re({scriptName:e,mode:n,status:t,summaryLines:o,error:s,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let l=`**${Pe({scriptName:e,mode:n,status:t,error:s,duration:r})}**
|
|
6
6
|
|
|
7
7
|
${o.join(`
|
|
8
|
-
`)}`;try{await se.addMessage(i,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Je=Pe(import.meta.url),Ue=R.dirname(R.dirname(Je)),q=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"collected-profiles"):R.join(Ue,"collected-profiles"),Y=R.join(q,"run-log.json");function Be(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";S.writeFileSync(o,t);for(let s=0;s<3;s++)try{S.renameSync(o,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function ie(){try{if(!S.existsSync(Y))return{runs:[]};let e=JSON.parse(S.readFileSync(Y,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ce(e){S.existsSync(q)||S.mkdirSync(q,{recursive:!0});try{Be(Y,e)}catch(n){console.error(`[!] Failed to save run-log.json: ${n.message}`)}}function le(e,n="default"){let t=ie();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,s={timestamp:o.toISOString(),script:e,mode:n,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(i=>new Date(i.timestamp).getTime()>r),ce(t),{script:e,mode:n,startTime:o.getTime(),runIndex:t.runs.length-1}}function ae(e,n,t=null,o=null){if(!e)return;let s=null;try{let i=ie(),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,s=a.duration;else{let l=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());l&&(l.status=n,l.result=n,l.duration=Date.now()-e.startTime,l.stats=t,l.error=o,s=l.duration)}ce(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=t&&Array.isArray(t.summaryLines)?t.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=n==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";re({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:o,duration:s??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import{getPluginConfig as Ve}from"@ilivemylife/graph-sdk";var We=await Ve();for(let[e,n]of Object.entries(We))process.env[e]===void 0&&(process.env[e]=n);var cn=process.env.LINKEDIN_NAME,N=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ln=Object.freeze(new Set([N.DRAFT,N.CONFIRMED,N.NEEDS_REVIEW])),an=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 qe}from"url";var Ye=qe(import.meta.url),Ge=m.dirname(m.dirname(Ye)),A=process.env.DATA_DIR?m.resolve(process.env.DATA_DIR,"collected-profiles"):m.join(Ge,"collected-profiles"),mn=m.join(A,"people.json"),hn=m.join(A,"jobs.json"),He=m.join(A,"quota.json"),gn=m.join(A,"conversations.json"),yn=m.join(A,"sync-state.json"),Sn=m.join(A,"application-questions.json"),bn=m.join(A,"profile-history"),M=20,P=100,Ke=null,Qe=null,I=null,ze=null,Xe=null,Ze=null;function ue(){Ke=null,Qe=null,I=null,ze=null,Xe=null,Ze=null}function eo(){d.existsSync(A)||d.mkdirSync(A,{recursive:!0})}function oo(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 s=JSON.parse(d.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{d.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{d.copyFileSync(e,e+".corrupted")}catch{}return null}}function fe(){return new Date().toISOString().split("T")[0]}function no(){return I||(eo(),I=oo(He,"quota.json"),(!I||!I.connections)&&(I={connections:[]}),I)}function pe(){let e=no(),n=new Date;n.setDate(n.getDate()-7);let t=n.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=t)}function de(){let e=pe(),n=fe(),t=e.filter(l=>l.date===n).length,o=e.length,s=t>=M,r=o>=P,i=!s&&!r,a={allowed:i,daily:{sent:t,max:M},weekly:{sent:o,max:P}};return i||(a.reason=s?`Daily limit reached (${t}/${M})`:`Weekly limit reached (${o}/${P})`),a}function me(){let e=pe(),n=fe(),t=e.filter(s=>s.date===n).length,o=e.length;return{daily:{sent:t,max:M,remaining:M-t},weekly:{sent:o,max:P,remaining:P-o}}}import"dotenv/config";import*as c from"fs";import*as Z from"os";import*as f from"path";import{fileURLToPath as Io}from"url";var K={};W(K,{NAME:()=>so,VERSION:()=>to,up:()=>co});import*as b from"fs";import*as B from"path";var to=1,so="normalize-jobs-and-questions",ro=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],io=50;function G(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(s){try{b.unlinkSync(o)}catch{}throw s}try{b.renameSync(o,e)}catch(s){try{b.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function co(e,n){let t=B.join(e,"jobs.json"),o=B.join(n,"scouted-jobs.json"),s=B.join(e,"application-questions.json"),r=G(t)||{},i=G(o)||{},a=0,l=[];for(let p of Object.keys(r)){if(!i[p])continue;let w=i[p],h=r[p];for(let O of ro)w[O]!=null&&h[O]==null&&(h[O]=w[O]);l.push(p),a++}a>0?(H(t,r),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=G(s);if(u&&Array.isArray(u.applications)){let p={},w=0;for(let h of u.applications){let O=h.jobId||"unknown";p[O]||(p[O]={applications:[]});let ne=(h.questions||[]).map(k=>{let F={type:k.type||"input",question:k.question||"",answer:k.answer||""};return k.options&&(k.options.length<=io?F.options=k.options:(F.optionsOmitted=!0,w++)),k.page&&(F.page=k.page),k.wasPreFilled&&(F.wasPreFilled=!0),k.wasRetry&&(F.wasRetry=!0),F});p[O].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||ne.length,questions:ne})}H(s,p),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),w>0&&console.log(` Phase 2: Stripped bloated options from ${w} 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(l.length>0){for(let p of l)delete i[p];H(o,i),console.log(` Phase 3: Removed ${l.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={};W(Q,{NAME:()=>ao,VERSION:()=>lo,up:()=>po});import*as v from"fs";import*as he from"path";var lo=2,ao="reset-unread-flags";function uo(e){return v.existsSync(e)?JSON.parse(v.readFileSync(e,"utf-8")):null}function fo(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{v.writeFileSync(o,t)}catch(s){try{v.unlinkSync(o)}catch{}throw s}try{v.renameSync(o,e)}catch(s){try{v.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function po(e){let n=he.join(e,"conversations.json"),t=uo(n);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(t))t[s].unread===!0&&(t[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}fo(n,t),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var z={};W(z,{NAME:()=>ho,VERSION:()=>mo,up:()=>vo});import*as $ from"fs";import*as ge from"path";var mo=3,ho="recompute-last-message-by",go=new Set(["draft","confirmed","rejected","needs_review"]);function yo(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function So(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{$.writeFileSync(o,t)}catch(s){try{$.unlinkSync(o)}catch{}throw s}try{$.renameSync(o,e)}catch(s){try{$.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function bo(e,n){if(!e||e.length===0)return"them";let t=e.filter(r=>!go.has(r.status));if(t.length===0)return"them";let o=t.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),s=o.length>0?o:[...t].reverse();for(let r of s){let i=r.sender;if(i===n)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function vo(e){let n=ge.join(e,"conversations.json"),t=yo(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 s=0,r=0,i=0;for(let a of Object.keys(t)){let l=t[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,r++);let u=Array.isArray(l.messages)?l.messages:[],p=bo(u,o),w=p==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==p&&i++,l.lastMessageBy=p,l.conversationStatus=w,s++}if(s===0){console.log(" No conversations to recompute.");return}So(n,t),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}import"dotenv/config";import*as y from"path";import{fileURLToPath as $o}from"url";var wo=$o(import.meta.url),ko=y.dirname(y.dirname(wo)),J=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"market-research"):y.join(ko,"market-research"),kn=y.join(J,"scouted-jobs.json"),jn=y.join(J,"discovered-people.json"),An=y.join(J,"visit-log.json"),En=y.join(J,"companies.json"),On=y.join(J,"job-decisions.json");function ye(){jo=null,Ao=null,Eo=null,Oo=null,Ro=null}var jo=null;var Ao=null;var Eo=null;var Oo=null;var Ro=null;var To=Io(import.meta.url),Do=f.dirname(To),No=f.dirname(f.dirname(Do));function Co(e){return e&&(e==="~"?Z.homedir():e.startsWith("~/")||e.startsWith("~\\")?f.join(Z.homedir(),e.slice(2)):e)}var j=process.env.DATA_DIR?f.resolve(Co(process.env.DATA_DIR)):No,_=f.join(j,"collected-profiles"),x=f.join(j,"market-research"),g=f.join(j,".schema-version"),Se=[f.join(_,".schema-version"),f.join(x,".schema-version")],T=3,E=[{version:1,module:K},{version:2,module:Q},{version:3,module:z}];(function(){E.sort((o,s)=>o.version-s.version);let n=new Set;for(let o of E){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 s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let t=E.length?E[E.length-1].version:0;if(t!==T)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${T}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<E.length;o++){let s=o+1;if(E[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${E[o].version}`)}})();function we(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
8
|
+
`)}`;try{await se.addMessage(i,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Ue=Je(import.meta.url),Be=R.dirname(R.dirname(Ue)),Y=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"collected-profiles"):R.join(Be,"collected-profiles"),q=R.join(Y,"run-log.json");function Ve(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";S.writeFileSync(o,t);for(let s=0;s<3;s++)try{S.renameSync(o,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function ie(){try{if(!S.existsSync(q))return{runs:[]};let e=JSON.parse(S.readFileSync(q,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ce(e){S.existsSync(Y)||S.mkdirSync(Y,{recursive:!0});try{Ve(q,e)}catch(n){console.error(`[!] Failed to save run-log.json: ${n.message}`)}}function le(e,n="default"){let t=ie();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,s={timestamp:o.toISOString(),script:e,mode:n,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(i=>new Date(i.timestamp).getTime()>r),ce(t),{script:e,mode:n,startTime:o.getTime(),runIndex:t.runs.length-1}}function ae(e,n,t=null,o=null){if(!e)return;let s=null;try{let i=ie(),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,s=a.duration;else{let l=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());l&&(l.status=n,l.result=n,l.duration=Date.now()-e.startTime,l.stats=t,l.error=o,s=l.duration)}ce(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=t&&Array.isArray(t.summaryLines)?t.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=n==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";re({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:o,duration:s??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import{getPluginConfig as We}from"@ilivemylife/graph-sdk";var Ye=await We();for(let[e,n]of Object.entries(Ye))process.env[e]===void 0&&(process.env[e]=n);var ln=process.env.LINKEDIN_NAME,N=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),an=Object.freeze(new Set([N.DRAFT,N.CONFIRMED,N.NEEDS_REVIEW])),un=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 qe}from"url";var Ge=qe(import.meta.url),He=m.dirname(m.dirname(Ge)),A=process.env.DATA_DIR?m.resolve(process.env.DATA_DIR,"collected-profiles"):m.join(He,"collected-profiles"),hn=m.join(A,"people.json"),gn=m.join(A,"jobs.json"),Ke=m.join(A,"quota.json"),yn=m.join(A,"conversations.json"),Sn=m.join(A,"sync-state.json"),bn=m.join(A,"application-questions.json"),vn=m.join(A,"profile-history"),ue=(e,n)=>{let t=parseInt(e,10);return Number.isInteger(t)&&t>=0?t:n},M=ue(process.env.CONNECT_MAX_DAILY,20),P=ue(process.env.CONNECT_MAX_WEEKLY,100),Qe=null,ze=null,I=null,Xe=null,Ze=null,eo=null;function fe(){Qe=null,ze=null,I=null,Xe=null,Ze=null,eo=null}function oo(){d.existsSync(A)||d.mkdirSync(A,{recursive:!0})}function no(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 s=JSON.parse(d.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{d.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{d.copyFileSync(e,e+".corrupted")}catch{}return null}}function pe(){return new Date().toISOString().split("T")[0]}function to(){return I||(oo(),I=no(Ke,"quota.json"),(!I||!I.connections)&&(I={connections:[]}),I)}function de(){let e=to(),n=new Date;n.setDate(n.getDate()-7);let t=n.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=t)}function me(){let e=de(),n=pe(),t=e.filter(l=>l.date===n).length,o=e.length,s=t>=M,r=o>=P,i=!s&&!r,a={allowed:i,daily:{sent:t,max:M},weekly:{sent:o,max:P}};return i||(a.reason=s?`Daily limit reached (${t}/${M})`:`Weekly limit reached (${o}/${P})`),a}function he(){let e=de(),n=pe(),t=e.filter(s=>s.date===n).length,o=e.length;return{daily:{sent:t,max:M,remaining:M-t},weekly:{sent:o,max:P,remaining:P-o}}}import"dotenv/config";import*as c from"fs";import*as Z from"os";import*as f from"path";import{fileURLToPath as To}from"url";var K={};W(K,{NAME:()=>ro,VERSION:()=>so,up:()=>lo});import*as b from"fs";import*as B from"path";var so=1,ro="normalize-jobs-and-questions",io=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],co=50;function G(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(s){try{b.unlinkSync(o)}catch{}throw s}try{b.renameSync(o,e)}catch(s){try{b.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function lo(e,n){let t=B.join(e,"jobs.json"),o=B.join(n,"scouted-jobs.json"),s=B.join(e,"application-questions.json"),r=G(t)||{},i=G(o)||{},a=0,l=[];for(let p of Object.keys(r)){if(!i[p])continue;let w=i[p],h=r[p];for(let O of io)w[O]!=null&&h[O]==null&&(h[O]=w[O]);l.push(p),a++}a>0?(H(t,r),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=G(s);if(u&&Array.isArray(u.applications)){let p={},w=0;for(let h of u.applications){let O=h.jobId||"unknown";p[O]||(p[O]={applications:[]});let ne=(h.questions||[]).map(k=>{let F={type:k.type||"input",question:k.question||"",answer:k.answer||""};return k.options&&(k.options.length<=co?F.options=k.options:(F.optionsOmitted=!0,w++)),k.page&&(F.page=k.page),k.wasPreFilled&&(F.wasPreFilled=!0),k.wasRetry&&(F.wasRetry=!0),F});p[O].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||ne.length,questions:ne})}H(s,p),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),w>0&&console.log(` Phase 2: Stripped bloated options from ${w} 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(l.length>0){for(let p of l)delete i[p];H(o,i),console.log(` Phase 3: Removed ${l.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={};W(Q,{NAME:()=>uo,VERSION:()=>ao,up:()=>mo});import*as v from"fs";import*as ge from"path";var ao=2,uo="reset-unread-flags";function fo(e){return v.existsSync(e)?JSON.parse(v.readFileSync(e,"utf-8")):null}function po(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{v.writeFileSync(o,t)}catch(s){try{v.unlinkSync(o)}catch{}throw s}try{v.renameSync(o,e)}catch(s){try{v.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function mo(e){let n=ge.join(e,"conversations.json"),t=fo(n);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(t))t[s].unread===!0&&(t[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}po(n,t),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var z={};W(z,{NAME:()=>go,VERSION:()=>ho,up:()=>$o});import*as $ from"fs";import*as ye from"path";var ho=3,go="recompute-last-message-by",yo=new Set(["draft","confirmed","rejected","needs_review"]);function So(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function bo(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{$.writeFileSync(o,t)}catch(s){try{$.unlinkSync(o)}catch{}throw s}try{$.renameSync(o,e)}catch(s){try{$.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function vo(e,n){if(!e||e.length===0)return"them";let t=e.filter(r=>!yo.has(r.status));if(t.length===0)return"them";let o=t.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),s=o.length>0?o:[...t].reverse();for(let r of s){let i=r.sender;if(i===n)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function $o(e){let n=ye.join(e,"conversations.json"),t=So(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 s=0,r=0,i=0;for(let a of Object.keys(t)){let l=t[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,r++);let u=Array.isArray(l.messages)?l.messages:[],p=vo(u,o),w=p==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==p&&i++,l.lastMessageBy=p,l.conversationStatus=w,s++}if(s===0){console.log(" No conversations to recompute.");return}bo(n,t),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}import"dotenv/config";import*as y from"path";import{fileURLToPath as wo}from"url";var ko=wo(import.meta.url),jo=y.dirname(y.dirname(ko)),J=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"market-research"):y.join(jo,"market-research"),jn=y.join(J,"scouted-jobs.json"),An=y.join(J,"discovered-people.json"),En=y.join(J,"visit-log.json"),On=y.join(J,"companies.json"),Rn=y.join(J,"job-decisions.json");function Se(){Ao=null,Eo=null,Oo=null,Ro=null,Io=null}var Ao=null;var Eo=null;var Oo=null;var Ro=null;var Io=null;var Do=To(import.meta.url),No=f.dirname(Do),Co=f.dirname(f.dirname(No));function _o(e){return e&&(e==="~"?Z.homedir():e.startsWith("~/")||e.startsWith("~\\")?f.join(Z.homedir(),e.slice(2)):e)}var j=process.env.DATA_DIR?f.resolve(_o(process.env.DATA_DIR)):Co,_=f.join(j,"collected-profiles"),x=f.join(j,"market-research"),g=f.join(j,".schema-version"),be=[f.join(_,".schema-version"),f.join(x,".schema-version")],T=3,E=[{version:1,module:K},{version:2,module:Q},{version:3,module:z}];(function(){E.sort((o,s)=>o.version-s.version);let n=new Set;for(let o of E){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 s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let t=E.length?E[E.length-1].version:0;if(t!==T)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${T}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<E.length;o++){let s=o+1;if(E[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${E[o].version}`)}})();function ke(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
9
9
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
10
10
|
`),process.exit(1));try{c.mkdirSync(j,{recursive:!0})}catch(n){n.code!=="EEXIST"&&(console.error(`
|
|
11
11
|
[FATAL] Cannot create DATA_DIR (${j}): ${n.message}`),console.error(` Fix the path or permissions and try again.
|
|
@@ -15,39 +15,39 @@ ${o.join(`
|
|
|
15
15
|
[FATAL] DATA_DIR (${j}) 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
16
|
`),process.exit(1));for(let n of[_,x]){let t;try{t=c.lstatSync(n)}catch(o){if(o.code==="ENOENT")continue;throw o}t.isSymbolicLink()&&(console.error(`
|
|
17
17
|
[FATAL] Data subdirectory is a symbolic link: ${n}`),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 C=f.join(j,".migration-lock");function
|
|
18
|
+
`),process.exit(1))}}var C=f.join(j,".migration-lock");function xo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return c.writeFileSync(C,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let n;try{n=JSON.parse(c.readFileSync(C,"utf-8"))}catch{n=null}if(n&&Number.isInteger(n.pid)){let o=!1;try{process.kill(n.pid,0),o=!0}catch(i){i.code==="EPERM"&&(o=!0)}let s=24*60*60*1e3,r=1/0;if(n.startedAt){let i=Date.parse(n.startedAt);Number.isNaN(i)||(r=Date.now()-i)}o&&r<s&&(console.error(`
|
|
19
19
|
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${n.pid}`),console.error(` Started at: ${n.startedAt||"(unknown)"}`),console.error(` Lock file: ${C}
|
|
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)),o&&r>=s&&console.log(` Lock holder PID ${n.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${n?.pid??"?"} found \u2014 taking over.`);let t=C+".tmp";try{return c.writeFileSync(t,e),c.renameSync(t,C),!0}catch(o){try{c.unlinkSync(t)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function ee(){try{if(JSON.parse(c.readFileSync(C,"utf-8")).pid!==process.pid)return;c.unlinkSync(C)}catch{}}var
|
|
21
|
+
`),process.exit(1)),o&&r>=s&&console.log(` Lock holder PID ${n.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${n?.pid??"?"} found \u2014 taking over.`);let t=C+".tmp";try{return c.writeFileSync(t,e),c.renameSync(t,C),!0}catch(o){try{c.unlinkSync(t)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function ee(){try{if(JSON.parse(c.readFileSync(C,"utf-8")).pid!==process.pid)return;c.unlinkSync(C)}catch{}}var ve=!1;function Fo(){if(ve)return;ve=!0;let e=()=>{try{ee()}catch{}process.exit(1)};for(let n of["SIGINT","SIGTERM","SIGHUP"])try{process.on(n,e)}catch{}}function Lo(){if(c.existsSync(g))return;let e=[],n=[];for(let r of be)if(c.existsSync(r))try{e.push({file:r,schema:V(r)})}catch(i){n.push({file:r,err:i.message})}if(n.length>0){console.error(`
|
|
22
22
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of n)console.error(` ${r.file}: ${r.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(r=>r.schema.version);if(new Set(t).size>1){console.error(`
|
|
25
25
|
[FATAL] Legacy .schema-version files disagree:`);for(let r of e)console.error(` ${r.file}: v${r.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 o=e[0].schema,s=g+".tmp";try{c.writeFileSync(s,JSON.stringify(o,null,2)),c.renameSync(s,g)}catch(r){try{c.unlinkSync(s)}catch{}throw r}for(let r of
|
|
26
|
+
`),process.exit(1)}let o=e[0].schema,s=g+".tmp";try{c.writeFileSync(s,JSON.stringify(o,null,2)),c.renameSync(s,g)}catch(r){try{c.unlinkSync(s)}catch{}throw r}for(let r of be)if(c.existsSync(r))try{c.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${g}`)}function Mo(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=Number(e.version);return!Number.isFinite(n)||n<0||!Number.isInteger(n)?null:(e.version=n,Array.isArray(e.migrations)||(e.migrations=[]),e)}function V(e){let n=c.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function $e(){if(Lo(),!c.existsSync(g))return{version:0,migrations:[]};let e;try{e=V(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 n=
|
|
28
|
+
`),process.exit(1)}let n=Mo(e);return n===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)),n}function
|
|
30
|
+
`),process.exit(1)),n}function je(e){try{c.chmodSync(e,384)}catch{}}function Po(e){if(ke(),c.existsSync(g))try{if(c.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 n=g+".tmp";try{c.writeFileSync(n,JSON.stringify(e,null,2)),je(n),c.renameSync(n,g)}catch(t){try{c.unlinkSync(n)}catch{}throw t}}function we(e,n){if(!c.existsSync(e))return;let t=`.pre-v${String(n).padStart(3,"0")}.backup`,o=c.readdirSync(e).filter(a=>{let l=a.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return c.statSync(f.join(e,a)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let a of o){let l=f.join(e,a),u=f.join(e,a+t);if(c.existsSync(u)){r++;continue}try{Ee(l,u),s++}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(l=>`${l.file} (${l.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(s>0||r>0){let a=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${f.basename(e)}/ (${t})${a}`)}}var X=!1;async function Ae(){if(X)return;ke(),Wo();let n=$e().version;if(n===T){X=!0;return}Fo(),xo(),process.on("exit",ee),n>T&&(console.error(`
|
|
31
31
|
[FATAL] Your data schema is at v${n}, but this plugin build only understands up to v${T}.`),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${T}.
|
|
33
33
|
`),process.exit(1)),console.log(`
|
|
34
|
-
\u{1F4E6} Schema migration: v${n} \u2192 v${T}`);let t=
|
|
34
|
+
\u{1F4E6} Schema migration: v${n} \u2192 v${T}`);let t=Yo();if(!t.ok){console.error(`
|
|
35
35
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of t.broken)console.error(` ${s.dir}/${s.file}: ${s.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
37
|
`),process.exit(1)}let o=E.filter(s=>s.version>n);for(let s of o){console.log(`
|
|
38
|
-
Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{
|
|
38
|
+
Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{we(_,s.version),we(x,s.version)}catch(l){console.error(`
|
|
39
39
|
[FATAL] Pre-migration backup failed for ${r}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
40
40
|
`),process.exit(1)}let a=s.module;try{await a.up(_,x)}catch(l){console.error(`
|
|
41
41
|
[FATAL] Migration ${r} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let u=qo(i);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${n}.`),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 l=new Date().toISOString(),u={version:s.version,name:a.NAME||r,appliedAt:l},p
|
|
44
|
+
`)}process.exit(1)}try{let l=new Date().toISOString(),u={version:s.version,name:a.NAME||r,appliedAt:l},p=$e();p.version=s.version,p.migratedAt=l,p.migrations=p.migrations||[],p.migrations.push(u),Po(p)}catch(l){console.error(`
|
|
45
45
|
[FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${n}.`),console.error(` On next plugin command the runner will try to re-apply ${r}. 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 ${r} complete`)}try{
|
|
46
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{fe()}catch{}try{Se()}catch{}X=!0,ee(),console.log(`
|
|
47
47
|
\u2713 Schema is now at v${T}
|
|
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 n=
|
|
48
|
+
`)}var Jo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Uo(e){let n=e.toLowerCase();return Jo.some(t=>t.test(n))}var Bo=6e4;function Vo(){let e=Date.now(),n=[];for(let t of[j,_,x]){if(!c.existsSync(t))continue;let o;try{o=c.readdirSync(t)}catch{continue}for(let s of o){if(!Uo(s))continue;let r=f.join(t,s);try{let i=c.statSync(r);if(!i.isFile()||e-i.mtimeMs<Bo)continue;n.push({dir:t,file:s,fullPath:r})}catch{}}}return n}function Wo({verbose:e=!1}={}){let n=Vo();if(n.length===0)return e&&console.log(" No orphan .tmp files found."),0;let t=0;for(let o of n)try{c.unlinkSync(o.fullPath),t++,e&&console.log(` Removed orphan: ${f.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&t>0&&console.log(` Cleaned up ${t} orphan .tmp file(s) from previous run.`),t}function Yo(){let e=[];for(let n of[_,x]){if(!c.existsSync(n))continue;let t=c.readdirSync(n).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of t){let s=f.join(n,o);try{V(s)}catch(r){e.push({dir:f.basename(n),file:o,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function qo(e){let n=[],t=[];for(let r of[_,x]){if(!c.existsSync(r))continue;let i=c.readdirSync(r).filter(a=>a.endsWith(e));for(let a of i){let l=f.join(r,a),u=a.slice(0,-e.length),p=f.join(r,u);try{u.toLowerCase().endsWith(".json")?V(l):c.accessSync(l,c.constants.R_OK),n.push({backupPath:l,originalPath:p,fileName:a,dir:r})}catch(w){t.push(`${f.basename(r)}/${a}: ${w.message}`)}}}if(t.length>0)return{ok:!1,error:t.join("; "),restored:0};let o=0,s=[];for(let{backupPath:r,originalPath:i,fileName:a,dir:l}of n)try{Ee(r,i),o++}catch(u){s.push(`${f.basename(l)}/${a}: ${u.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function Ee(e,n){let t=n+".tmp";try{c.copyFileSync(e,t),je(t)}catch(o){try{c.unlinkSync(t)}catch{}throw o}try{c.renameSync(t,n)}catch(o){try{c.unlinkSync(t)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=new Error(`File locked: ${n} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=o.code,s}throw o}}await Ae();var U=process.argv.slice(2),oe=new Set((U.find(e=>e.startsWith("--skip="))?.split("=")[1]||"").split(",").filter(Boolean)),Oe=new Set((U.find(e=>e.startsWith("--only="))?.split("=")[1]||"").split(",").filter(Boolean)),Te=U.includes("--dry-run"),De=U.includes("--jobs"),Ne=U.includes("--comms"),Re=["apply-queue","apply","funnel","scout","visit"],Ie=["sync","today"],Ce=De?Re:Ne?Ie:[...Re,...Ie];function D(e){return Oe.size>0?Oe.has(e):!oe.has(e)&&Ce.includes(e)}function L(e,n,t=[],{optional:o=!1}={}){if(console.log(`
|
|
49
|
+
${"\u2550".repeat(50)}`),console.log(` STEP: ${e}`),console.log("\u2550".repeat(50)),Te)return console.log(` [DRY RUN] Would run: node ${n} ${t.join(" ")}`),!0;try{return Go("node",[n,...t],{stdio:"inherit",timeout:18e6}),console.log(` \u2713 ${e} completed`),!0}catch(s){return o?(console.log(` \u26A0 ${e} failed (optional): ${s.message?.slice(0,80)}`),!1):(console.error(` \u2717 ${e} failed: ${s.message?.slice(0,80)}`),!1)}}async function Ho(){let e=De?"jobs":Ne?"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 n=Ce.filter(D);console.log(` Steps: ${n.join(" \u2192 ")}`),oe.size>0&&console.log(` Skipping: ${[...oe].join(", ")}`),Te&&console.log(" [DRY RUN MODE]");let t=le("daily",e),o={};if(D("apply-queue")&&(o["apply-queue"]=L("Apply Queue (scored jobs)","applyQueue.mjs",["--max=50","--min-score=50"],{optional:!0})),D("apply")){let r=he();o.apply=L("Apply from Search","run.mjs",[],{optional:!0})}if(D("funnel")&&!D("apply")){let r=me();r.allowed?o.funnel=L("Connection Funnel","funnelRunner.mjs",["--max=20"],{optional:!0}):(console.log(`
|
|
51
51
|
\u26A0 Funnel skipped: ${r.reason}`),o.funnel="skipped_quota")}D("scout")&&(o.scout=L("Scout Jobs for Tomorrow","scout.mjs",["--max=300","--verbose"],{optional:!0})),D("sync")&&(o.sync=L("Sync Inbox","syncAll.mjs")),D("today")&&(o.today=L("Daily Report","syncAll.mjs",["--today"])),console.log(`
|
|
52
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[r,i]of Object.entries(o))console.log(` ${i===!0?"\u2713":i===!1?"\u2717":"\u26A0"} ${r}: ${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 s=Object.values(o).some(r=>r===!1);ae(t,s?"partial":"success",o)}
|
|
53
|
+
`);let s=Object.values(o).some(r=>r===!1);ae(t,s?"partial":"success",o)}Ho().catch(e=>{console.error("Daily pipeline failed:",e),process.exit(1)});
|
package/dist/enrichProfile.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
1
|
+
var et=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var tt=(t,e)=>{for(var n in e)et(t,n,{get:e[n],enumerable:!0})};async function w(t){let e=Math.floor(Math.random()*2001),n=t+e;return new Promise(o=>setTimeout(o,n))}async function $e(t){return await t.evaluate(()=>{let e=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of e){let i=o.innerText||"",s=i.includes("Premium")||i.includes("premium")||i.includes("Upgrade")||i.includes("upgrade"),f=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||f||d){let D=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(D)return D.click(),{dismissed:!0,matched:i.substring(0,80)};let $=o.querySelectorAll("button");for(let a of $){let S=a.innerText?.trim().toLowerCase()||"",p=a.getAttribute("aria-label")?.toLowerCase()||"";if(S==="not now"||S==="no thanks"||S==="dismiss"||p.includes("dismiss"))return a.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 re=Ae(()=>{});var je={};tt(je,{extractCertificationsFromDetails:()=>St,extractEducationFromDetails:()=>yt,extractExperienceFromDetails:()=>wt,extractFeaturedFromDetails:()=>gt,extractRecommendationsFromDetails:()=>kt,extractSkillsFromDetails:()=>bt});async function wt(t,e){let n=e.replace(/\/+$/,"")+"/details/experience/";try{await t.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=t.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let s=0;s<5;s++)await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(900);await w(1e3);let i=0;for(;i<5&&await t.evaluate(()=>{for(let f of document.querySelectorAll("button"))if(/^Load more$/i.test((f.textContent||"").trim()))return f.click(),!0;return!1});)i++,await w(1500),await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await t.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function f(a){let S=[];for(let p of a.querySelectorAll("div")){let h=Array.from(p.children).filter(v=>v.tagName==="DIV");if(h.length<3)continue;let y=h.filter(v=>(v.textContent||"").trim().length>50);y.length<3||(p.textContent||"").length<500||S.push({el:p,count:y.length,totalText:(p.textContent||"").length})}return S.sort((p,h)=>h.count-p.count||p.totalText-h.totalText),S[0]?.el}let d=f(s);if(!d)return[];let D=Array.from(d.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function $(a){let S=a[0]||null,p=null,h=null;if(a[1]){let c=a[1].split("\xB7").map(k=>k.trim());p=c[0]||null,c[1]&&(h=c[1])}let y=a.findIndex(c=>/(\d{4}|present)/i.test(c)&&/(-|–|—)/i.test(c)&&c.length<80),v=null,L=null;if(y>=0){let c=a[y].split("\xB7").map(k=>k.trim());v=c[0]||null,c[1]&&(L=c[1])}let M=null,ne=-1;if(y>=0&&a[y+1]){let c=a[y+1],k=/^[>*\-•]|^>/.test(c),P=/https?:\/\//.test(c),x=/\d{4}/.test(c),V=/,/.test(c)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(c);!k&&!P&&!x&&c.length<100&&V&&(M=c,ne=y+1)}let b=null,j=-1,I=a[a.length-1];if(I&&/and\s+\+\d+\s+skills?$/i.test(I)){j=a.length-1;let c=I.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);c&&(b={listed:c[1].split(",").map(k=>k.trim()),additional:parseInt(c[2],10)})}let T=new Set([0,1,y,ne,j].filter(c=>c>=0)),C=a.filter((c,k)=>!T.has(k)),oe=C.length>0?C.join(`
|
|
2
2
|
|
|
3
3
|
`):null;return{title:S,company:p,employmentType:h,dates:v,duration:L,location:M,description:oe,skills:b,_raw:a}}return D.map(a=>{let p=(a.innerText||"").trim().split(`
|
|
4
|
-
`).map(h=>h.trim()).filter(h=>h&&h.length<5e3);return $(p)}).filter(a=>a.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${e}: ${o.message?.slice(0,120)}`),[]}}async function B(t,e,n){let o=e.replace(/\/+$/,"")+`/details/${n}/`;await t.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let i=t.url();if(/\/(login|authwall|checkpoint)/i.test(i))throw new Error(`Session expired \u2014 bounced to ${i} when fetching /details/${n}/`);if(!i.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${i})`);for(let f=0;f<4;f++)await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);await w(800);let s=0;for(;s<5&&await t.evaluate(()=>{for(let d of document.querySelectorAll("button"))if(/^Load more$/i.test((d.textContent||"").trim()))return d.click(),!0;return!1});)s++,await w(1300),await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function U(t,e,n,o){try{return await o()}catch(i){let s=i.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(s))throw i;return/not available on profile/i.test(s)?(console.log(` (${e}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${t}: ${s.slice(0,120)}`),[])}}async function
|
|
4
|
+
`).map(h=>h.trim()).filter(h=>h&&h.length<5e3);return $(p)}).filter(a=>a.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${e}: ${o.message?.slice(0,120)}`),[]}}async function B(t,e,n){let o=e.replace(/\/+$/,"")+`/details/${n}/`;await t.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let i=t.url();if(/\/(login|authwall|checkpoint)/i.test(i))throw new Error(`Session expired \u2014 bounced to ${i} when fetching /details/${n}/`);if(!i.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${i})`);for(let f=0;f<4;f++)await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);await w(800);let s=0;for(;s<5&&await t.evaluate(()=>{for(let d of document.querySelectorAll("button"))if(/^Load more$/i.test((d.textContent||"").trim()))return d.click(),!0;return!1});)s++,await w(1300),await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function U(t,e,n,o){try{return await o()}catch(i){let s=i.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(s))throw i;return/not available on profile/i.test(s)?(console.log(` (${e}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${t}: ${s.slice(0,120)}`),[])}}async function gt(t,e){return U(e,"featured","extractFeaturedFromDetails",async()=>(await B(t,e,"featured"),await t.evaluate(`(() => {
|
|
5
5
|
${H}
|
|
6
6
|
|
|
7
7
|
const main = document.querySelector('main');
|
|
@@ -42,7 +42,7 @@ var Xe=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var et=(t,e)=>{
|
|
|
42
42
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
43
43
|
return true;
|
|
44
44
|
});
|
|
45
|
-
})()`)))}async function
|
|
45
|
+
})()`)))}async function yt(t,e){return U(e,"education","extractEducationFromDetails",async()=>(await B(t,e,"education"),await t.evaluate(`(() => {
|
|
46
46
|
${H}
|
|
47
47
|
|
|
48
48
|
const main = document.querySelector('main');
|
|
@@ -79,7 +79,7 @@ var Xe=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var et=(t,e)=>{
|
|
|
79
79
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
80
80
|
return true;
|
|
81
81
|
});
|
|
82
|
-
})()`)))}async function
|
|
82
|
+
})()`)))}async function bt(t,e){return U(e,"skills","extractSkillsFromDetails",async()=>(await B(t,e,"skills"),await t.evaluate(`(() => {
|
|
83
83
|
${H}
|
|
84
84
|
|
|
85
85
|
const main = document.querySelector('main');
|
|
@@ -111,7 +111,7 @@ var Xe=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var et=(t,e)=>{
|
|
|
111
111
|
skills.push({ name, endorsements, _raw: lines });
|
|
112
112
|
}
|
|
113
113
|
return skills;
|
|
114
|
-
})()`)))}async function
|
|
114
|
+
})()`)))}async function St(t,e){return U(e,"certifications","extractCertificationsFromDetails",async()=>(await B(t,e,"certifications"),await t.evaluate(`(() => {
|
|
115
115
|
${H}
|
|
116
116
|
|
|
117
117
|
const main = document.querySelector('main');
|
|
@@ -136,7 +136,7 @@ var Xe=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var et=(t,e)=>{
|
|
|
136
136
|
|
|
137
137
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
138
138
|
}).filter(e => e.name);
|
|
139
|
-
})()`)))}async function
|
|
139
|
+
})()`)))}async function kt(t,e){return U(e,"recommendations","extractRecommendationsFromDetails",async()=>(await B(t,e,"recommendations"),await t.evaluate(`(() => {
|
|
140
140
|
${H}
|
|
141
141
|
|
|
142
142
|
const main = document.querySelector('main');
|
|
@@ -172,7 +172,7 @@ var Xe=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var et=(t,e)=>{
|
|
|
172
172
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
173
173
|
return true;
|
|
174
174
|
});
|
|
175
|
-
})()`)))}var H,
|
|
175
|
+
})()`)))}var H,Pe=Ae(()=>{re();H=`
|
|
176
176
|
function findEntryContainer(root) {
|
|
177
177
|
const candidates = [];
|
|
178
178
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -235,7 +235,7 @@ function findEntryContainer(root) {
|
|
|
235
235
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
236
236
|
return candidates[0]?.el;
|
|
237
237
|
}
|
|
238
|
-
`});import"dotenv/config";import Et from"puppeteer";re();import{getPluginConfig as tt}from"@ilivemylife/graph-sdk";var nt=await tt();for(let[t,e]of Object.entries(nt))process.env[t]===void 0&&(process.env[t]=e);var Dt=process.env.LINKEDIN_NAME,F=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Lt=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.NEEDS_REVIEW])),Mt=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.REJECTED,F.NEEDS_REVIEW]));import"dotenv/config";import*as m from"fs";import*as g from"path";import{fileURLToPath as ot}from"url";var it=ot(import.meta.url),st=g.dirname(g.dirname(it)),A=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(st,"collected-profiles"),le=g.join(A,"people.json"),jt=g.join(A,"jobs.json"),Pt=g.join(A,"quota.json"),Ot=g.join(A,"conversations.json"),qt=g.join(A,"sync-state.json"),Bt=g.join(A,"application-questions.json"),ae=g.join(A,"profile-history");var q=null;function Le(){m.existsSync(A)||m.mkdirSync(A,{recursive:!0})}function Me(t,e){let n=JSON.stringify(e,null,2),o=t+".tmp";m.writeFileSync(o,n);for(let i=0;i<3;i++)try{m.renameSync(o,t);return}catch(s){if(i<2&&(s.code==="EPERM"||s.code==="EBUSY")){let f=Date.now();for(;Date.now()-f<200;);continue}throw s}}function Te(t,e){if(!m.existsSync(t))return null;try{let n=JSON.parse(m.readFileSync(t,"utf-8"));try{m.copyFileSync(t,t+".backup")}catch{}return n}catch(n){console.error(`[!] ${e} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(t)}`);let o=t+".backup";if(m.existsSync(o))try{let i=JSON.parse(m.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{m.copyFileSync(o,t)}catch{}return i}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${t}.corrupted`);try{m.copyFileSync(t,t+".corrupted")}catch{}return null}}function rt(){return new Date().toISOString().split("T")[0]}var lt=["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"],at=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function ce(t){if(!t)return null;let e=t.match(/\/in\/([^/?#]+)/);return e?e[1].toLowerCase():null}function ct(){m.existsSync(ae)||m.mkdirSync(ae,{recursive:!0})}function Fe(t){let e=ce(t);return e?g.join(ae,`${e}.json`):null}function ut(t){let e=Fe(t);return e?Te(e,`profile-history/${ce(t)}.json`)||[]:[]}function dt(t,e){let n=Fe(t);if(!n)return;ct();let o=ut(t);o.unshift(e);try{Me(n,o)}catch(i){console.error(`[!] Failed to append profile-history for ${ce(t)}: ${i.message}`)}}function _e(t){return!!(t==null||Array.isArray(t)&&t.length===0||typeof t=="string"&&!t.trim())}function De(t){return Array.isArray(t)?[...t].map(e=>String(e).trim()).sort().join("||"):typeof t=="string"?t.replace(/\s+/g," ").trim():t}function ft(t,e){if(!t)return[];let n=[];for(let o of at){let i=t[o],s=e[o];_e(i)||_e(s)||De(i)!==De(s)&&n.push(o)}return n}function mt(t){let e=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,i]of Object.entries(t))e.has(o)||(n[o]=i);return n}function Re(){return q||(Le(),q=Te(le,"people.json")||{},q)}function pt(t){Le(),q=t;try{Me(le,t)}catch(e){console.error(`[!] Failed to save people.json: ${e.message}`),console.error(` Path: ${g.resolve(le)}`)}}function ue(t,e={}){if(!t)return null;let n=Re(),o=rt(),i=new Date().toISOString(),s=n[t];if(s){let f=ft(s,e);f.length>0&&(dt(t,{capturedAt:i,previousLastUpdated:s.lastUpdated||null,changedFields:f,snapshot:mt(s)}),s.lastSnapshotAt=i),s.seenCount=(s.seenCount||1)+1,s.lastSeen=o,s.lastUpdated=i,e.source&&!s.sources?.includes(e.source)&&(s.sources=s.sources||[],s.sources.push(e.source));for(let d of lt)if(e[d]!=null){if(Array.isArray(e[d])&&e[d].length===0&&Array.isArray(s[d])&&s[d].length>0)continue;s[d]=e[d]}Array.isArray(e.availableSections)&&(s.lastFullVisitAt=i)}else n[t]={name:e.name||null,title:e.title||null,location:e.location||null,company:e.company||null,about:e.about||null,connectionDegree:e.connectionDegree||null,connectionsCount:e.connectionsCount||null,mutualConnections:e.mutualConnections||null,photoUrl:e.photoUrl||null,hasVerifiedBadge:e.hasVerifiedBadge||!1,currentCompany:e.currentCompany||null,currentSchool:e.currentSchool||null,connectionsLevel:e.connectionsLevel||null,mutualConnectionsCount:e.mutualConnectionsCount||null,followers:e.followers||null,openToWork:e.openToWork||!1,hiring:e.hiring||!1,topSkills:e.topSkills||null,availableSections:e.availableSections||null,experience:e.experience||null,featuredLinks:e.featuredLinks||null,_lastEnrichedAt:e._lastEnrichedAt||null,featured:e.featured||null,education:e.education||null,skillsFull:e.skillsFull||null,recommendations:e.recommendations||null,certifications:e.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:e.source?[e.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:i,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(e.availableSections)?i:null};return pt(n),n[t]}async function kt(t,e){let n=t.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: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=t.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function Pe(t,e,n={}){let{extractExperience:o=!1,extractFeatured:i=!1,extractEducation:s=!1,extractSkills:f=!1,extractRecommendations:d=!1,extractCertifications:D=!1}=n;try{await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await $e(t)&&(console.log(" Dismissed Premium overlay"),await w(1500),await kt(t,e));let a=0;for(let b=0;b<2;b++){let j=await t.evaluate(()=>document.body.scrollHeight);for(let T=1;T<=6;T++)await t.evaluate(C=>window.scrollTo(0,C),j*T/6),await w(900);let I=await t.evaluate(()=>document.body.scrollHeight);if(I===a)break;a=I}await w(800);let S=await t.evaluate(()=>{let b=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),j=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"]),I=r=>{let l=(r||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(l)},T={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 T;let oe=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],c=Array.from(C.querySelectorAll("h2")),k=oe.find(r=>{let l=r.textContent&&r.textContent.trim(),u=(l||"").replace(/\s*\(\d+\)$/,"").trim();return l&&l.length>1&&l.length<100&&!b.has(u)&&!j.has(u)}),P=k?k.textContent.trim():null,x=k?k.parentElement:null;for(;x&&x!==C&&!Array.from(x.children).filter(l=>l.tagName==="P").some(l=>{let u=l.textContent&&l.textContent.trim();return u&&u.length>5&&!I(u)});)x=x.parentElement;let V=null,pe=null,he=null,ie=null;if(x&&x!==C){let r=Array.from(x.children).filter(u=>u.tagName==="P").filter(u=>{let _=u.textContent&&u.textContent.trim();return _&&_.length>5&&!I(_)});if(r[0]&&(V=r[0].textContent.trim()),r[1]){let u=r[1].textContent.trim().split(/\s*[·•]\s*/);pe=u[0]||null,u.length>1&&(he=u.slice(1).join(" \xB7 "))}let l=Array.from(x.children).filter(u=>u.tagName==="DIV");for(let u=l.length-1;u>=0;u--){let _=l[u].textContent&&l[u].textContent.trim();if(_&&!(P&&_.startsWith(P))&&(ie=_.split(/[·•]/)[0].trim(),ie))break}}let we=null;if(x){let r=x.querySelectorAll("p, span, div");for(let l of r){let u=(l.textContent||"").trim().replace(/^[·•]\s*/,"");if(u==="1st"||u==="2nd"||u==="3rd"){we=u;break}}}let Je=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),ge=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ke=ge&&ge.src||null,W=C.textContent||"",ye=null,be=W.match(/(\d+\+?)\s+connections\b/i);be&&(ye=be[1]+" connections");let J=null,Se=W.match(/(\d+)\s+mutual connection/i),ke=W.match(/and\s+(\d+)\s+other mutual/i),Ye=W.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Se?J=parseInt(Se[1],10):ke?J=2+parseInt(ke[1],10):Ye&&(J=2);let Ce=null,xe=null,ve=c.find(r=>r.textContent&&r.textContent.trim()==="About");if(ve){let r=ve.parentElement;for(;r&&r.tagName!=="SECTION";)r=r.parentElement;if(r){let l=(r.textContent||"").trim();l=l.replace(/^About\s*/,"").trim();let u=l.match(/Top skills\s*(.+?)$/i);if(u){let se=u[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Ze=>Ze.trim()).filter(Boolean);se.length>0&&se.length<10&&(xe=se)}l=l.split(/\n?…\s*more/i)[0].trim(),l=l.split(/\n?\.\.\.\s*more/i)[0].trim(),l=l.split(/\bTop skills\b/i)[0].trim(),l=l.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Ce=l||null}}let Ee=null,Ie=c.find(r=>r.textContent&&r.textContent.trim()==="Activity");if(Ie){let r=Ie.parentElement;for(;r&&r.tagName!=="SECTION";)r=r.parentElement;if(r){let l=(r.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);l&&(Ee=parseInt(l[1].replace(/,/g,""),10))}}let Ge=[...new Set(c.map(r=>(r.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(r=>r&&r.length>1&&r.length<60&&r!==P).filter(r=>b.has(r)))],O=document.body.textContent||"",Qe=/#OpenToWork\b/i.test(O)||/\bOpen to work\b/.test(O),ze=/#Hiring\b/i.test(O)||/\bI'?m hiring\b/i.test(O)||/\bWe are hiring\b/i.test(O);return{name:P,title:V,location:ie,currentCompany:pe,currentSchool:he,connectionDegree:we,hasVerifiedBadge:Je,photoUrl:Ke,connectionsLevel:ye,mutualConnectionsCount:J,followers:Ee,openToWork:Qe,hiring:ze,about:Ce,topSkills:xe,availableSections:Ge}});console.log(`Viewed: ${S.name} - ${S.title}`);let p=null,h=null,y=null,v=null,L=null,M=null;if(o||i||s||f||d||D){let b=await Promise.resolve().then(()=>(je(),Ne));o&&(p=await b.extractExperienceFromDetails(t,e),console.log(` + Experience: ${p.length} entries`)),i&&(h=await b.extractFeaturedFromDetails(t,e),console.log(` + Featured: ${h.length} entries`)),s&&(y=await b.extractEducationFromDetails(t,e),console.log(` + Education: ${y.length} entries`)),f&&(v=await b.extractSkillsFromDetails(t,e),console.log(` + Skills: ${v.length} entries`)),d&&(L=await b.extractRecommendationsFromDetails(t,e),console.log(` + Recommendations: ${L.length} entries`)),D&&(M=await b.extractCertificationsFromDetails(t,e),console.log(` + Certifications: ${M.length} entries`))}return{...S,profileUrl:e,...p!==null&&{experience:p},...h!==null&&{featured:h},...y!==null&&{education:y},...v!==null&&{skillsFull:v},...L!==null&&{recommendations:L},...M!==null&&{certifications:M}}}catch($){console.error(`Error viewing profile ${e}:`,$.message);try{await t.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test($.message||""))throw $;return null}}import Oe from"fs";import Ct from"path";var xt="cookies.json";function vt(){let t=process.env.ILML_SCOPE_DIR;return t?Ct.join(t,"plugins-state","linkedin","cookies.json"):xt}function qe(){let t=vt();if(!Oe.existsSync(t))throw new Error(`Cookies not found at ${t}. Run: ilml linkedin login`);let e;try{e=Oe.readFileSync(t,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${t}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(e)}catch{throw new Error(`Cookies file at ${t} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${t} is empty or not an array. Run: ilml linkedin login`);return n}function Be(t){return t?t.replace(/^https?:\/\/(www\.|m\.)?linkedin\.com/i,"https://linkedin.com").split("?")[0].split("#")[0].replace(/\/+$/,"").toLowerCase():""}function He(t){return(t||"").replace(/ /g," ").replace(/\s+/g," ").trim().toLowerCase()}var E=process.argv.slice(2),It=E.includes("--help")||E.includes("-h"),R=E.find(t=>t.startsWith("http")),N=E.includes("--full"),Y=N||E.includes("--with-experience"),G=N||E.includes("--with-featured"),Q=N||E.includes("--with-education"),z=N||E.includes("--with-skills"),Z=N||E.includes("--with-recommendations"),X=N||E.includes("--with-certifications"),Ue=[["experience",Y],["featured",G],["education",Q],["skills",z],["recommendations",Z],["certifications",X]],Ve=Ue.filter(([,t])=>t).length,fe=1+Ve;function We(){console.log(`
|
|
238
|
+
`});import"dotenv/config";import It from"puppeteer";re();import{getPluginConfig as nt}from"@ilivemylife/graph-sdk";var ot=await nt();for(let[t,e]of Object.entries(ot))process.env[t]===void 0&&(process.env[t]=e);var Lt=process.env.LINKEDIN_NAME,F=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Mt=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.NEEDS_REVIEW])),Tt=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.REJECTED,F.NEEDS_REVIEW]));import"dotenv/config";import*as m from"fs";import*as g from"path";import{fileURLToPath as it}from"url";var st=it(import.meta.url),rt=g.dirname(g.dirname(st)),A=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(rt,"collected-profiles"),le=g.join(A,"people.json"),Pt=g.join(A,"jobs.json"),Ot=g.join(A,"quota.json"),qt=g.join(A,"conversations.json"),Bt=g.join(A,"sync-state.json"),Ht=g.join(A,"application-questions.json"),ae=g.join(A,"profile-history"),Le=(t,e)=>{let n=parseInt(t,10);return Number.isInteger(n)&&n>=0?n:e},Ut=Le(process.env.CONNECT_MAX_DAILY,20),Vt=Le(process.env.CONNECT_MAX_WEEKLY,100),q=null;function Me(){m.existsSync(A)||m.mkdirSync(A,{recursive:!0})}function Te(t,e){let n=JSON.stringify(e,null,2),o=t+".tmp";m.writeFileSync(o,n);for(let i=0;i<3;i++)try{m.renameSync(o,t);return}catch(s){if(i<2&&(s.code==="EPERM"||s.code==="EBUSY")){let f=Date.now();for(;Date.now()-f<200;);continue}throw s}}function Fe(t,e){if(!m.existsSync(t))return null;try{let n=JSON.parse(m.readFileSync(t,"utf-8"));try{m.copyFileSync(t,t+".backup")}catch{}return n}catch(n){console.error(`[!] ${e} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(t)}`);let o=t+".backup";if(m.existsSync(o))try{let i=JSON.parse(m.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{m.copyFileSync(o,t)}catch{}return i}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${t}.corrupted`);try{m.copyFileSync(t,t+".corrupted")}catch{}return null}}function lt(){return new Date().toISOString().split("T")[0]}var at=["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"],ct=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function ce(t){if(!t)return null;let e=t.match(/\/in\/([^/?#]+)/);return e?e[1].toLowerCase():null}function ut(){m.existsSync(ae)||m.mkdirSync(ae,{recursive:!0})}function Ne(t){let e=ce(t);return e?g.join(ae,`${e}.json`):null}function dt(t){let e=Ne(t);return e?Fe(e,`profile-history/${ce(t)}.json`)||[]:[]}function ft(t,e){let n=Ne(t);if(!n)return;ut();let o=dt(t);o.unshift(e);try{Te(n,o)}catch(i){console.error(`[!] Failed to append profile-history for ${ce(t)}: ${i.message}`)}}function _e(t){return!!(t==null||Array.isArray(t)&&t.length===0||typeof t=="string"&&!t.trim())}function De(t){return Array.isArray(t)?[...t].map(e=>String(e).trim()).sort().join("||"):typeof t=="string"?t.replace(/\s+/g," ").trim():t}function mt(t,e){if(!t)return[];let n=[];for(let o of ct){let i=t[o],s=e[o];_e(i)||_e(s)||De(i)!==De(s)&&n.push(o)}return n}function pt(t){let e=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,i]of Object.entries(t))e.has(o)||(n[o]=i);return n}function Re(){return q||(Me(),q=Fe(le,"people.json")||{},q)}function ht(t){Me(),q=t;try{Te(le,t)}catch(e){console.error(`[!] Failed to save people.json: ${e.message}`),console.error(` Path: ${g.resolve(le)}`)}}function ue(t,e={}){if(!t)return null;let n=Re(),o=lt(),i=new Date().toISOString(),s=n[t];if(s){let f=mt(s,e);f.length>0&&(ft(t,{capturedAt:i,previousLastUpdated:s.lastUpdated||null,changedFields:f,snapshot:pt(s)}),s.lastSnapshotAt=i),s.seenCount=(s.seenCount||1)+1,s.lastSeen=o,s.lastUpdated=i,e.source&&!s.sources?.includes(e.source)&&(s.sources=s.sources||[],s.sources.push(e.source));for(let d of at)if(e[d]!=null){if(Array.isArray(e[d])&&e[d].length===0&&Array.isArray(s[d])&&s[d].length>0)continue;s[d]=e[d]}Array.isArray(e.availableSections)&&(s.lastFullVisitAt=i)}else n[t]={name:e.name||null,title:e.title||null,location:e.location||null,company:e.company||null,about:e.about||null,connectionDegree:e.connectionDegree||null,connectionsCount:e.connectionsCount||null,mutualConnections:e.mutualConnections||null,photoUrl:e.photoUrl||null,hasVerifiedBadge:e.hasVerifiedBadge||!1,currentCompany:e.currentCompany||null,currentSchool:e.currentSchool||null,connectionsLevel:e.connectionsLevel||null,mutualConnectionsCount:e.mutualConnectionsCount||null,followers:e.followers||null,openToWork:e.openToWork||!1,hiring:e.hiring||!1,topSkills:e.topSkills||null,availableSections:e.availableSections||null,experience:e.experience||null,featuredLinks:e.featuredLinks||null,_lastEnrichedAt:e._lastEnrichedAt||null,featured:e.featured||null,education:e.education||null,skillsFull:e.skillsFull||null,recommendations:e.recommendations||null,certifications:e.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:e.source?[e.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:i,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(e.availableSections)?i:null};return ht(n),n[t]}async function Ct(t,e){let n=t.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: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=t.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function Oe(t,e,n={}){let{extractExperience:o=!1,extractFeatured:i=!1,extractEducation:s=!1,extractSkills:f=!1,extractRecommendations:d=!1,extractCertifications:D=!1}=n;try{await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await $e(t)&&(console.log(" Dismissed Premium overlay"),await w(1500),await Ct(t,e));let a=0;for(let b=0;b<2;b++){let j=await t.evaluate(()=>document.body.scrollHeight);for(let T=1;T<=6;T++)await t.evaluate(C=>window.scrollTo(0,C),j*T/6),await w(900);let I=await t.evaluate(()=>document.body.scrollHeight);if(I===a)break;a=I}await w(800);let S=await t.evaluate(()=>{let b=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),j=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"]),I=r=>{let l=(r||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(l)},T={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 T;let oe=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],c=Array.from(C.querySelectorAll("h2")),k=oe.find(r=>{let l=r.textContent&&r.textContent.trim(),u=(l||"").replace(/\s*\(\d+\)$/,"").trim();return l&&l.length>1&&l.length<100&&!b.has(u)&&!j.has(u)}),P=k?k.textContent.trim():null,x=k?k.parentElement:null;for(;x&&x!==C&&!Array.from(x.children).filter(l=>l.tagName==="P").some(l=>{let u=l.textContent&&l.textContent.trim();return u&&u.length>5&&!I(u)});)x=x.parentElement;let V=null,pe=null,he=null,ie=null;if(x&&x!==C){let r=Array.from(x.children).filter(u=>u.tagName==="P").filter(u=>{let _=u.textContent&&u.textContent.trim();return _&&_.length>5&&!I(_)});if(r[0]&&(V=r[0].textContent.trim()),r[1]){let u=r[1].textContent.trim().split(/\s*[·•]\s*/);pe=u[0]||null,u.length>1&&(he=u.slice(1).join(" \xB7 "))}let l=Array.from(x.children).filter(u=>u.tagName==="DIV");for(let u=l.length-1;u>=0;u--){let _=l[u].textContent&&l[u].textContent.trim();if(_&&!(P&&_.startsWith(P))&&(ie=_.split(/[·•]/)[0].trim(),ie))break}}let we=null;if(x){let r=x.querySelectorAll("p, span, div");for(let l of r){let u=(l.textContent||"").trim().replace(/^[·•]\s*/,"");if(u==="1st"||u==="2nd"||u==="3rd"){we=u;break}}}let Ke=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),ge=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ye=ge&&ge.src||null,W=C.textContent||"",ye=null,be=W.match(/(\d+\+?)\s+connections\b/i);be&&(ye=be[1]+" connections");let J=null,Se=W.match(/(\d+)\s+mutual connection/i),ke=W.match(/and\s+(\d+)\s+other mutual/i),Ge=W.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Se?J=parseInt(Se[1],10):ke?J=2+parseInt(ke[1],10):Ge&&(J=2);let Ce=null,xe=null,ve=c.find(r=>r.textContent&&r.textContent.trim()==="About");if(ve){let r=ve.parentElement;for(;r&&r.tagName!=="SECTION";)r=r.parentElement;if(r){let l=(r.textContent||"").trim();l=l.replace(/^About\s*/,"").trim();let u=l.match(/Top skills\s*(.+?)$/i);if(u){let se=u[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Xe=>Xe.trim()).filter(Boolean);se.length>0&&se.length<10&&(xe=se)}l=l.split(/\n?…\s*more/i)[0].trim(),l=l.split(/\n?\.\.\.\s*more/i)[0].trim(),l=l.split(/\bTop skills\b/i)[0].trim(),l=l.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Ce=l||null}}let Ee=null,Ie=c.find(r=>r.textContent&&r.textContent.trim()==="Activity");if(Ie){let r=Ie.parentElement;for(;r&&r.tagName!=="SECTION";)r=r.parentElement;if(r){let l=(r.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);l&&(Ee=parseInt(l[1].replace(/,/g,""),10))}}let Qe=[...new Set(c.map(r=>(r.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(r=>r&&r.length>1&&r.length<60&&r!==P).filter(r=>b.has(r)))],O=document.body.textContent||"",ze=/#OpenToWork\b/i.test(O)||/\bOpen to work\b/.test(O),Ze=/#Hiring\b/i.test(O)||/\bI'?m hiring\b/i.test(O)||/\bWe are hiring\b/i.test(O);return{name:P,title:V,location:ie,currentCompany:pe,currentSchool:he,connectionDegree:we,hasVerifiedBadge:Ke,photoUrl:Ye,connectionsLevel:ye,mutualConnectionsCount:J,followers:Ee,openToWork:ze,hiring:Ze,about:Ce,topSkills:xe,availableSections:Qe}});console.log(`Viewed: ${S.name} - ${S.title}`);let p=null,h=null,y=null,v=null,L=null,M=null;if(o||i||s||f||d||D){let b=await Promise.resolve().then(()=>(Pe(),je));o&&(p=await b.extractExperienceFromDetails(t,e),console.log(` + Experience: ${p.length} entries`)),i&&(h=await b.extractFeaturedFromDetails(t,e),console.log(` + Featured: ${h.length} entries`)),s&&(y=await b.extractEducationFromDetails(t,e),console.log(` + Education: ${y.length} entries`)),f&&(v=await b.extractSkillsFromDetails(t,e),console.log(` + Skills: ${v.length} entries`)),d&&(L=await b.extractRecommendationsFromDetails(t,e),console.log(` + Recommendations: ${L.length} entries`)),D&&(M=await b.extractCertificationsFromDetails(t,e),console.log(` + Certifications: ${M.length} entries`))}return{...S,profileUrl:e,...p!==null&&{experience:p},...h!==null&&{featured:h},...y!==null&&{education:y},...v!==null&&{skillsFull:v},...L!==null&&{recommendations:L},...M!==null&&{certifications:M}}}catch($){console.error(`Error viewing profile ${e}:`,$.message);try{await t.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test($.message||""))throw $;return null}}import qe from"fs";import xt from"path";var vt="cookies.json";function Et(){let t=process.env.ILML_SCOPE_DIR;return t?xt.join(t,"plugins-state","linkedin","cookies.json"):vt}function Be(){let t=Et();if(!qe.existsSync(t))throw new Error(`Cookies not found at ${t}. Run: ilml linkedin login`);let e;try{e=qe.readFileSync(t,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${t}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(e)}catch{throw new Error(`Cookies file at ${t} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${t} is empty or not an array. Run: ilml linkedin login`);return n}function He(t){return t?t.replace(/^https?:\/\/(www\.|m\.)?linkedin\.com/i,"https://linkedin.com").split("?")[0].split("#")[0].replace(/\/+$/,"").toLowerCase():""}function Ue(t){return(t||"").replace(/ /g," ").replace(/\s+/g," ").trim().toLowerCase()}var E=process.argv.slice(2),At=E.includes("--help")||E.includes("-h"),N=E.find(t=>t.startsWith("http")),R=E.includes("--full"),Y=R||E.includes("--with-experience"),G=R||E.includes("--with-featured"),Q=R||E.includes("--with-education"),z=R||E.includes("--with-skills"),Z=R||E.includes("--with-recommendations"),X=R||E.includes("--with-certifications"),Ve=[["experience",Y],["featured",G],["education",Q],["skills",z],["recommendations",Z],["certifications",X]],We=Ve.filter(([,t])=>t).length,fe=1+We;function Je(){console.log(`
|
|
239
239
|
enrich-profile \u2014 visit ONE LinkedIn profile and save what we learn
|
|
240
240
|
|
|
241
241
|
USAGE
|
|
@@ -286,4 +286,4 @@ WHEN TO USE
|
|
|
286
286
|
- Audit your own LinkedIn profile (--full prints everything to stdout)
|
|
287
287
|
- Deep-dive on one specific contact before reaching out
|
|
288
288
|
- Verify what we know about a recruiter / lead
|
|
289
|
-
`)}
|
|
289
|
+
`)}At&&(Je(),process.exit(0));N||(Je(),process.exit(1));/linkedin\.com\/in\//i.test(N)||(console.error(`URL doesn't look like a LinkedIn profile: ${N}`),console.error("Expected format: https://www.linkedin.com/in/<slug>/"),process.exit(1));var me=He(process.env.MY_LINKEDIN_URL||""),te=Ue(process.env.LINKEDIN_NAME||"");!me&&!te&&(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 ee=me&&He(N)===me,de=Ve.filter(([,t])=>t).map(([t])=>t);console.log("");console.log(` enrichProfile \u2014 ${N}`);R?console.log(` Mode: --full (${fe} page loads: main + ${de.join(" + ")})`):de.length>0?console.log(` Mode: rich (${fe} loads: main + ${de.join(" + ")})`):console.log(" Mode: basic (1 load \u2014 main page only)");console.log(ee?" Target: SELF (URL match) \u2014 will print to stdout, not saved to people.json":te?` 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)");We>0&&(console.log(""),console.log(` \u26A0 ${fe} 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 K=null;try{K=await It.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5});let t=await K.newPage();await t.setCookie(...Be());let e=await Oe(t,N,{extractExperience:Y,extractFeatured:G,extractEducation:Q,extractSkills:z,extractRecommendations:Z,extractCertifications:X});if((!e||!e.name)&&(console.error(" viewProfile returned no name \u2014 profile not loaded or DOM changed"),process.exit(1)),!ee&&te&&e.name&&Ue(e.name)===te&&(ee=!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: ${e.name}`),console.log(` title: ${e.title||"(none)"}`),console.log(` location: ${e.location||"(none)"}`),console.log(` about: ${e.about?`${e.about.length} chars`:"(none)"}`),console.log(` topSkills: ${e.topSkills?e.topSkills.join(", "):"(none)"}`),Y&&console.log(` experience: ${(e.experience||[]).length} entries`),G&&console.log(` featured: ${(e.featured||[]).length} entries`),Q&&console.log(` education: ${(e.education||[]).length} entries`),z&&console.log(` skillsFull: ${(e.skillsFull||[]).length} entries`),Z&&console.log(` recommendations: ${(e.recommendations||[]).length} entries`),X&&console.log(` certifications: ${(e.certifications||[]).length} entries`),console.log(""),ee)console.log(" \u2500\u2500\u2500 full data (self \u2014 not persisted) \u2500\u2500\u2500"),console.log(JSON.stringify(e,null,2));else{let n={name:e.name,title:e.title,location:e.location,about:e.about,currentCompany:e.currentCompany,currentSchool:e.currentSchool,topSkills:e.topSkills,availableSections:e.availableSections,connectionsLevel:e.connectionsLevel,mutualConnectionsCount:e.mutualConnectionsCount,followers:e.followers,openToWork:e.openToWork,hiring:e.hiring,hasVerifiedBadge:e.hasVerifiedBadge,photoUrl:e.photoUrl,source:"enrich-profile-single"},o=[["experience",Y,e.experience],["featured",G,e.featured],["education",Q,e.education],["skillsFull",z,e.skillsFull],["recommendations",Z,e.recommendations],["certifications",X,e.certifications]],i=!1;for(let[s,f,d]of o)f&&(Array.isArray(d)&&d.length>0?(n[s]=d,i=!0):console.log(` \u26A0 --with-${s==="skillsFull"?"skills":s} returned 0 entries \u2014 NOT writing ${s} (existing data preserved)`));i&&(n._lastEnrichedAt=new Date().toISOString()),ue(N,n),console.log(" \u2713 Saved to people.json")}}catch(t){console.error(" Error:",t.message),process.exit(1)}finally{K&&await K.close().catch(()=>{})}
|