ilml-plugin-linkedin 1.16.0 → 1.17.0
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 +3 -0
- package/dist/applyQueue.mjs +12 -12
- package/dist/connect.mjs +68 -68
- package/dist/daily.mjs +7 -7
- package/dist/enrichProfile.mjs +15 -15
- package/dist/enrichProfiles.mjs +54 -54
- package/dist/funnelRunner.mjs +60 -60
- package/dist/migrationCli.mjs +5 -5
- package/dist/profileHistory.mjs +2 -2
- package/dist/quota.mjs +11 -11
- package/dist/run.mjs +65 -65
- package/dist/scout.mjs +5 -5
- package/dist/syncAll.mjs +102 -102
- package/dist/syncConnections.mjs +9 -9
- package/dist/verifyAbout.mjs +20 -20
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +4 -4
- package/dist/visit.mjs +45 -45
- package/dist/warmScan.mjs +2 -2
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/daily.mjs
CHANGED
|
@@ -5,7 +5,7 @@ var Le=Object.defineProperty;var q=(e,n)=>{for(var t in n)Le(e,t,{get:n[t],enume
|
|
|
5
5
|
`),process.exit(1));var ie=Me({token:re});function Ue(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 Be({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?` ${Ue(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 ce({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=`**${Be({scriptName:e,mode:n,status:t,error:s,duration:r})}**
|
|
6
6
|
|
|
7
7
|
${o.join(`
|
|
8
|
-
`)}`;try{await ie.addMessage(i,l)}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 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 le(){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=le();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),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 s=null;try{let i=le(),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)}ae(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";ce({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 Ge}from"@ilivemylife/graph-sdk";var He=await Ge();for(let[e,n]of Object.entries(He))process.env[e]===void 0&&(process.env[e]=n);var yn=process.env.LINKEDIN_NAME,_=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Sn=Object.freeze(new Set([_.DRAFT,_.CONFIRMED,_.NEEDS_REVIEW])),bn=Object.freeze(new Set([_.DRAFT,_.CONFIRMED,_.REJECTED,_.NEEDS_REVIEW]));import"dotenv/config";import*as d from"fs";import*as m from"path";import{fileURLToPath as Ke}from"url";var Qe=Ke(import.meta.url),ze=m.dirname(m.dirname(Qe)),E=process.env.DATA_DIR?m.resolve(process.env.DATA_DIR,"collected-profiles"):m.join(ze,"collected-profiles"),An=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),J=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 so(){d.existsSync(E)||d.mkdirSync(E,{recursive:!0})}function ro(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 me(){return new Date().toISOString().split("T")[0]}function io(){return T||(so(),T=ro(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(l=>l.date===n).length,o=e.length,s=t>=P,r=o>=J,i=!s&&!r,a={allowed:i,daily:{sent:t,max:P},weekly:{sent:o,max:J}};return i||(a.reason=s?`Daily limit reached (${t}/${P})`:`Weekly limit reached (${o}/${J})`),a}function ye(){let e=he(),n=me(),t=e.filter(s=>s.date===n).length,o=e.length;return{daily:{sent:t,max:P,remaining:P-t},weekly:{sent:o,max:J,remaining:J-o}}}import"dotenv/config";import*as c from"fs";import*as oe from"os";import*as f from"path";import{fileURLToPath as Po}from"url";var Q={};q(Q,{NAME:()=>lo,VERSION:()=>co,up:()=>fo});import*as b from"fs";import*as V from"path";var co=1,lo="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 H(e){return b.existsSync(e)?JSON.parse(b.readFileSync(e,"utf-8")):null}function K(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 fo(e,n){let t=V.join(e,"jobs.json"),o=V.join(n,"scouted-jobs.json"),s=V.join(e,"application-questions.json"),r=H(t)||{},i=H(o)||{},a=0,l=[];for(let p of Object.keys(r)){if(!i[p])continue;let k=i[p],h=r[p];for(let I of ao)k[I]!=null&&h[I]==null&&(h[I]=k[I]);l.push(p),a++}a>0?(K(t,r),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=H(s);if(u&&Array.isArray(u.applications)){let p={},k=0;for(let h of u.applications){let I=h.jobId||"unknown";p[I]||(p[I]={applications:[]});let se=(h.questions||[]).map(A=>{let L={type:A.type||"input",question:A.question||"",answer:A.answer||""};return A.options&&(A.options.length<=uo?L.options=A.options:(L.optionsOmitted=!0,k++)),A.page&&(L.page=A.page),A.wasPreFilled&&(L.wasPreFilled=!0),A.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||se.length,questions:se})}K(s,p),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),k>0&&console.log(` Phase 2: Stripped bloated options from ${k} 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];K(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 z={};q(z,{NAME:()=>mo,VERSION:()=>po,up:()=>yo});import*as v from"fs";import*as Se from"path";var po=2,mo="reset-unread-flags";function ho(e){return v.existsSync(e)?JSON.parse(v.readFileSync(e,"utf-8")):null}function go(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 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 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}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:()=>Ao});import*as $ from"fs";import*as be from"path";var So=3,bo="recompute-last-message-by",vo=new Set(["draft","confirmed","rejected","needs_review"]);function $o(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function wo(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 ko(e,n){if(!e||e.length===0)return"them";let t=e.filter(r=>!vo.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 Ao(e){let n=be.join(e,"conversations.json"),t=$o(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=ko(u,o),k=p==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==p&&i++,l.lastMessageBy=p,l.conversationStatus=k,s++}if(s===0){console.log(" No conversations to recompute.");return}wo(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.")}var Z={};q(Z,{NAME:()=>Eo,VERSION:()=>jo,up:()=>To});import*as w from"fs";import*as ve 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(!w.existsSync(e))return null;let n=w.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{w.writeFileSync(o,t)}catch(s){try{w.unlinkSync(o)}catch{}throw s}try{w.renameSync(o,e)}catch(s){try{w.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 To(e){let n=ve.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,s=0;for(let r of Object.keys(t)){let i=t[r];!i||typeof i!="object"||(s++,Oo.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ro(n,t),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as y from"path";import{fileURLToPath as Do}from"url";var No=Do(import.meta.url),_o=y.dirname(y.dirname(No)),U=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"market-research"):y.join(_o,"market-research"),_n=y.join(U,"scouted-jobs.json"),Cn=y.join(U,"discovered-people.json"),xn=y.join(U,"visit-log.json"),Fn=y.join(U,"companies.json"),Ln=y.join(U,"job-decisions.json");function $e(){Co=null,xo=null,Fo=null,Lo=null,Mo=null}var Co=null;var xo=null;var Fo=null;var Lo=null;var Mo=null;var Jo=Po(import.meta.url),Uo=f.dirname(Jo),Bo=f.dirname(f.dirname(Uo));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,x=f.join(j,"collected-profiles"),F=f.join(j,"market-research"),g=f.join(j,".schema-version"),we=[f.join(x,".schema-version"),f.join(F,".schema-version")],D=4,O=[{version:1,module:Q},{version:2,module:z},{version:3,module:X},{version:4,module:Z}];(function(){O.sort((o,s)=>o.version-s.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 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=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 s=o+1;if(O[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} 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(`
|
|
8
|
+
`)}`;try{await ie.addMessage(i,l)}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 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 le(){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=le();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),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 s=null;try{let i=le(),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)}ae(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";ce({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 Ge}from"@ilivemylife/graph-sdk";var He=await Ge();for(let[e,n]of Object.entries(He))process.env[e]===void 0&&(process.env[e]=n);var yn=process.env.LINKEDIN_NAME,C=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Sn=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.NEEDS_REVIEW])),bn=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 Ke}from"url";var Qe=Ke(import.meta.url),ze=m.dirname(m.dirname(Qe)),E=process.env.DATA_DIR?m.resolve(process.env.DATA_DIR,"collected-profiles"):m.join(ze,"collected-profiles"),An=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),J=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 so(){d.existsSync(E)||d.mkdirSync(E,{recursive:!0})}function ro(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 me(){return new Date().toISOString().split("T")[0]}function io(){return T||(so(),T=ro(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(l=>l.date===n).length,o=e.length,s=t>=P,r=o>=J,i=!s&&!r,a={allowed:i,daily:{sent:t,max:P},weekly:{sent:o,max:J}};return i||(a.reason=s?`Daily limit reached (${t}/${P})`:`Weekly limit reached (${o}/${J})`),a}function ye(){let e=he(),n=me(),t=e.filter(s=>s.date===n).length,o=e.length;return{daily:{sent:t,max:P,remaining:P-t},weekly:{sent:o,max:J,remaining:J-o}}}import"dotenv/config";import*as c from"fs";import*as oe from"os";import*as f from"path";import{fileURLToPath as Po}from"url";var Q={};q(Q,{NAME:()=>lo,VERSION:()=>co,up:()=>fo});import*as b from"fs";import*as V from"path";var co=1,lo="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 H(e){return b.existsSync(e)?JSON.parse(b.readFileSync(e,"utf-8")):null}function K(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 fo(e,n){let t=V.join(e,"jobs.json"),o=V.join(n,"scouted-jobs.json"),s=V.join(e,"application-questions.json"),r=H(t)||{},i=H(o)||{},a=0,l=[];for(let p of Object.keys(r)){if(!i[p])continue;let k=i[p],h=r[p];for(let I of ao)k[I]!=null&&h[I]==null&&(h[I]=k[I]);l.push(p),a++}a>0?(K(t,r),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=H(s);if(u&&Array.isArray(u.applications)){let p={},k=0;for(let h of u.applications){let I=h.jobId||"unknown";p[I]||(p[I]={applications:[]});let se=(h.questions||[]).map(A=>{let L={type:A.type||"input",question:A.question||"",answer:A.answer||""};return A.options&&(A.options.length<=uo?L.options=A.options:(L.optionsOmitted=!0,k++)),A.page&&(L.page=A.page),A.wasPreFilled&&(L.wasPreFilled=!0),A.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||se.length,questions:se})}K(s,p),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),k>0&&console.log(` Phase 2: Stripped bloated options from ${k} 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];K(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 z={};q(z,{NAME:()=>mo,VERSION:()=>po,up:()=>yo});import*as v from"fs";import*as Se from"path";var po=2,mo="reset-unread-flags";function ho(e){return v.existsSync(e)?JSON.parse(v.readFileSync(e,"utf-8")):null}function go(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 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 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}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:()=>Ao});import*as $ from"fs";import*as be from"path";var So=3,bo="recompute-last-message-by",vo=new Set(["draft","confirmed","rejected","needs_review"]);function $o(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function wo(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 ko(e,n){if(!e||e.length===0)return"them";let t=e.filter(r=>!vo.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 Ao(e){let n=be.join(e,"conversations.json"),t=$o(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=ko(u,o),k=p==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==p&&i++,l.lastMessageBy=p,l.conversationStatus=k,s++}if(s===0){console.log(" No conversations to recompute.");return}wo(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.")}var Z={};q(Z,{NAME:()=>Eo,VERSION:()=>jo,up:()=>To});import*as w from"fs";import*as ve 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(!w.existsSync(e))return null;let n=w.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{w.writeFileSync(o,t)}catch(s){try{w.unlinkSync(o)}catch{}throw s}try{w.renameSync(o,e)}catch(s){try{w.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 To(e){let n=ve.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,s=0;for(let r of Object.keys(t)){let i=t[r];!i||typeof i!="object"||(s++,Oo.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ro(n,t),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as y from"path";import{fileURLToPath as Do}from"url";var No=Do(import.meta.url),Co=y.dirname(y.dirname(No)),U=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"market-research"):y.join(Co,"market-research"),Cn=y.join(U,"scouted-jobs.json"),_n=y.join(U,"discovered-people.json"),xn=y.join(U,"visit-log.json"),Fn=y.join(U,"companies.json"),Ln=y.join(U,"job-decisions.json");function $e(){_o=null,xo=null,Fo=null,Lo=null,Mo=null}var _o=null;var xo=null;var Fo=null;var Lo=null;var Mo=null;var Jo=Po(import.meta.url),Uo=f.dirname(Jo),Bo=f.dirname(f.dirname(Uo));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,x=f.join(j,"collected-profiles"),F=f.join(j,"market-research"),g=f.join(j,".schema-version"),we=[f.join(x,".schema-version"),f.join(F,".schema-version")],D=4,O=[{version:1,module:Q},{version:2,module:z},{version:3,module:X},{version:4,module:Z}];(function(){O.sort((o,s)=>o.version-s.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 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=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 s=o+1;if(O[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} 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(`
|
|
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,10 +15,10 @@ ${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,F]){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
|
|
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: ${
|
|
18
|
+
`),process.exit(1))}}var _=f.join(j,".migration-lock");function Vo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return c.writeFileSync(_,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let n;try{n=JSON.parse(c.readFileSync(_,"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
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${n.pid}`),console.error(` Started at: ${n.startedAt||"(unknown)"}`),console.error(` Lock file: ${_}
|
|
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=
|
|
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=_+".tmp";try{return c.writeFileSync(t,e),c.renameSync(t,_),!0}catch(o){try{c.unlinkSync(t)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function ne(){try{if(JSON.parse(c.readFileSync(_,"utf-8")).pid!==process.pid)return;c.unlinkSync(_)}catch{}}var ke=!1;function Wo(){if(ke)return;ke=!0;let e=()=>{try{ne()}catch{}process.exit(1)};for(let n of["SIGINT","SIGTERM","SIGHUP"])try{process.on(n,e)}catch{}}function Yo(){if(c.existsSync(g))return;let e=[],n=[];for(let r of we)if(c.existsSync(r))try{e.push({file:r,schema:W(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(`
|
|
@@ -45,9 +45,9 @@ ${o.join(`
|
|
|
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
46
|
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{de()}catch{}try{$e()}catch{}ee=!0,ne(),console.log(`
|
|
47
47
|
\u2713 Schema is now at v${D}
|
|
48
|
-
`)}var Ko=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Qo(e){let n=e.toLowerCase();return Ko.some(t=>t.test(n))}var zo=6e4;function Xo(){let e=Date.now(),n=[];for(let t of[j,x,F]){if(!c.existsSync(t))continue;let o;try{o=c.readdirSync(t)}catch{continue}for(let s of o){if(!Qo(s))continue;let r=f.join(t,s);try{let i=c.statSync(r);if(!i.isFile()||e-i.mtimeMs<zo)continue;n.push({dir:t,file:s,fullPath:r})}catch{}}}return n}function Zo({verbose:e=!1}={}){let n=Xo();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 en(){let e=[];for(let n of[x,F]){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{W(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 on(e){let n=[],t=[];for(let r of[x,F]){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")?W(l):c.accessSync(l,c.constants.R_OK),n.push({backupPath:l,originalPath:p,fileName:a,dir:r})}catch(k){t.push(`${f.basename(r)}/${a}: ${k.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{Re(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 Re(e,n){let t=n+".tmp";try{c.copyFileSync(e,t),Oe(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 Ie();var B=process.argv.slice(2),te=new Set((B.find(e=>e.startsWith("--skip="))?.split("=")[1]||"").split(",").filter(Boolean)),Te=new Set((B.find(e=>e.startsWith("--only="))?.split("=")[1]||"").split(",").filter(Boolean)),
|
|
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=Fe.filter(N);console.log(` Steps: ${n.join(" \u2192 ")}`),te.size>0&&console.log(` Skipping: ${[...te].join(", ")}`),
|
|
48
|
+
`)}var Ko=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Qo(e){let n=e.toLowerCase();return Ko.some(t=>t.test(n))}var zo=6e4;function Xo(){let e=Date.now(),n=[];for(let t of[j,x,F]){if(!c.existsSync(t))continue;let o;try{o=c.readdirSync(t)}catch{continue}for(let s of o){if(!Qo(s))continue;let r=f.join(t,s);try{let i=c.statSync(r);if(!i.isFile()||e-i.mtimeMs<zo)continue;n.push({dir:t,file:s,fullPath:r})}catch{}}}return n}function Zo({verbose:e=!1}={}){let n=Xo();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 en(){let e=[];for(let n of[x,F]){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{W(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 on(e){let n=[],t=[];for(let r of[x,F]){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")?W(l):c.accessSync(l,c.constants.R_OK),n.push({backupPath:l,originalPath:p,fileName:a,dir:r})}catch(k){t.push(`${f.basename(r)}/${a}: ${k.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{Re(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 Re(e,n){let t=n+".tmp";try{c.copyFileSync(e,t),Oe(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 Ie();var B=process.argv.slice(2),te=new Set((B.find(e=>e.startsWith("--skip="))?.split("=")[1]||"").split(",").filter(Boolean)),Te=new Set((B.find(e=>e.startsWith("--only="))?.split("=")[1]||"").split(",").filter(Boolean)),Ce=B.includes("--dry-run"),_e=B.includes("--jobs"),xe=B.includes("--comms"),De=["apply-queue","apply","funnel","scout","visit"],Ne=["sync","today"],Fe=_e?De:xe?Ne:[...De,...Ne];function N(e){return Te.size>0?Te.has(e):!te.has(e)&&Fe.includes(e)}function M(e,n,t=[],{optional:o=!1}={}){if(console.log(`
|
|
49
|
+
${"\u2550".repeat(50)}`),console.log(` STEP: ${e}`),console.log("\u2550".repeat(50)),Ce)return console.log(` [DRY RUN] Would run: node ${n} ${t.join(" ")}`),!0;try{return nn("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 tn(){let e=_e?"jobs":xe?"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=Fe.filter(N);console.log(` Steps: ${n.join(" \u2192 ")}`),te.size>0&&console.log(` Skipping: ${[...te].join(", ")}`),Ce&&console.log(" [DRY RUN MODE]");let t=ue("daily",e),o={};if(N("apply-queue")&&(o["apply-queue"]=M("Apply Queue (scored jobs)","applyQueue.mjs",["--max=50","--min-score=50"],{optional:!0})),N("apply")){let r=ye();o.apply=M("Apply from Search","run.mjs",[],{optional:!0})}if(N("funnel")&&!N("apply")){let r=ge();r.allowed?o.funnel=M("Connection Funnel","funnelRunner.mjs",["--max=20"],{optional:!0}):(console.log(`
|
|
51
51
|
\u26A0 Funnel skipped: ${r.reason}`),o.funnel="skipped_quota")}N("scout")&&(o.scout=M("Scout Jobs for Tomorrow","scout.mjs",["--max=300","--verbose"],{optional:!0})),N("sync")&&(o.sync=M("Sync Inbox","syncAll.mjs")),N("today")&&(o.today=M("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
53
|
`);let s=Object.values(o).some(r=>r===!1);fe(t,s?"partial":"success",o)}tn().catch(e=>{console.error("Daily pipeline failed:",e),process.exit(1)});
|
package/dist/enrichProfile.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var st=Object.defineProperty;var De=(t,e)=>()=>(t&&(e=t(t=0)),e);var rt=(t,e)=>{for(var n in e)st(t,n,{get:e[n],enumerable:!0})};async function g(t){let e=Math.floor(Math.random()*2001),n=t+e;return new Promise(o=>setTimeout(o,n))}async function Le(t){return await t.evaluate(()=>{let e=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of e){let i=o.innerText||"",r=i.includes("Premium")||i.includes("premium")||i.includes("Upgrade")||i.includes("upgrade"),s=i.includes("Try for")||i.includes("free trial")||i.includes("/month")||i.includes("per month")||i.includes("Start my")||i.includes("Subscribe"),m=i.includes("Get hired faster")||i.includes("Get hired 2x");if(r||s||m){let b=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(b)return b.click(),{dismissed:!0,matched:i.substring(0,80)};let $=o.querySelectorAll("button");for(let c of $){let k=c.innerText?.trim().toLowerCase()||"",h=c.getAttribute("aria-label")?.toLowerCase()||"";if(k==="not now"||k==="no thanks"||k==="dismiss"||h.includes("dismiss"))return c.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 le=De(()=>{});var Be={};rt(Be,{extractCertificationsFromDetails:()=>vt,extractEducationFromDetails:()=>Ct,extractExperienceFromDetails:()=>St,extractFeaturedFromDetails:()=>kt,extractRecommendationsFromDetails:()=>Et,extractSkillsFromDetails:()=>xt});async function St(t,e){let n=e.replace(/\/+$/,"")+"/details/experience/";try{await t.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await g(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 r=0;r<5;r++)await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(900);await g(1e3);let i=0;for(;i<5&&await t.evaluate(()=>{for(let s of document.querySelectorAll("button"))if(/^Load more$/i.test((s.textContent||"").trim()))return s.click(),!0;return!1});)i++,await g(1500),await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(700);return await t.evaluate(()=>{let r=document.querySelector("main");if(!r)return[];function s(c){let k=[];for(let h of c.querySelectorAll("div")){let w=Array.from(h.children).filter(E=>E.tagName==="DIV");if(w.length<3)continue;let S=w.filter(E=>(E.textContent||"").trim().length>50);S.length<3||(h.textContent||"").length<500||k.push({el:h,count:S.length,totalText:(h.textContent||"").length})}return k.sort((h,w)=>w.count-h.count||h.totalText-w.totalText),k[0]?.el}let m=s(r);if(!m)return[];let b=Array.from(m.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function $(c){let k=c[0]||null,h=null,w=null;if(c[1]){let d=c[1].split("\xB7").map(C=>C.trim());h=d[0]||null,d[1]&&(w=d[1])}let S=c.findIndex(d=>/(\d{4}|present)/i.test(d)&&/(-|–|—)/i.test(d)&&d.length<80),E=null,M=null;if(S>=0){let d=c[S].split("\xB7").map(C=>C.trim());E=d[0]||null,d[1]&&(M=d[1])}let F=null,T=-1;if(S>=0&&c[S+1]){let d=c[S+1],C=/^[>*\-•]|^>/.test(d),q=/https?:\/\//.test(d),U=/\d{4}/.test(d),x=/,/.test(d)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(d);!C&&!q&&!U&&d.length<100&&x&&(F=d,T=S+1)}let ie=null,p=-1,N=c[c.length-1];if(N&&/and\s+\+\d+\s+skills?$/i.test(N)){p=c.length-1;let d=N.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);d&&(ie={listed:d[1].split(",").map(C=>C.trim()),additional:parseInt(d[2],10)})}let R=new Set([0,1,S,T,p].filter(d=>d>=0)),_=c.filter((d,C)=>!R.has(C)),v=_.length>0?_.join(`
|
|
2
2
|
|
|
3
|
-
`):null;return{title:
|
|
4
|
-
`).map(
|
|
5
|
-
${
|
|
3
|
+
`):null;return{title:k,company:h,employmentType:w,dates:E,duration:M,location:F,description:v,skills:ie,_raw:c}}return b.map(c=>{let h=(c.innerText||"").trim().split(`
|
|
4
|
+
`).map(w=>w.trim()).filter(w=>w&&w.length<5e3);return $(h)}).filter(c=>c.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 V(t,e,n){let o=e.replace(/\/+$/,"")+`/details/${n}/`;await t.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await g(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 s=0;s<4;s++)await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(700);await g(800);let r=0;for(;r<5&&await t.evaluate(()=>{for(let m of document.querySelectorAll("button"))if(/^Load more$/i.test((m.textContent||"").trim()))return m.click(),!0;return!1});)r++,await g(1300),await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(600)}async function J(t,e,n,o){try{return await o()}catch(i){let r=i.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(r))throw i;return/not available on profile/i.test(r)?(console.log(` (${e}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${t}: ${r.slice(0,120)}`),[])}}async function kt(t,e){return J(e,"featured","extractFeaturedFromDetails",async()=>(await V(t,e,"featured"),await t.evaluate(`(() => {
|
|
5
|
+
${W}
|
|
6
6
|
|
|
7
7
|
const main = document.querySelector('main');
|
|
8
8
|
if (!main) return [];
|
|
@@ -42,8 +42,8 @@ var et=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var tt=(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
|
|
46
|
-
${
|
|
45
|
+
})()`)))}async function Ct(t,e){return J(e,"education","extractEducationFromDetails",async()=>(await V(t,e,"education"),await t.evaluate(`(() => {
|
|
46
|
+
${W}
|
|
47
47
|
|
|
48
48
|
const main = document.querySelector('main');
|
|
49
49
|
if (!main) return [];
|
|
@@ -79,8 +79,8 @@ var et=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var tt=(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
|
|
83
|
-
${
|
|
82
|
+
})()`)))}async function xt(t,e){return J(e,"skills","extractSkillsFromDetails",async()=>(await V(t,e,"skills"),await t.evaluate(`(() => {
|
|
83
|
+
${W}
|
|
84
84
|
|
|
85
85
|
const main = document.querySelector('main');
|
|
86
86
|
if (!main) return [];
|
|
@@ -111,8 +111,8 @@ var et=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var tt=(t,e)=>{
|
|
|
111
111
|
skills.push({ name, endorsements, _raw: lines });
|
|
112
112
|
}
|
|
113
113
|
return skills;
|
|
114
|
-
})()`)))}async function
|
|
115
|
-
${
|
|
114
|
+
})()`)))}async function vt(t,e){return J(e,"certifications","extractCertificationsFromDetails",async()=>(await V(t,e,"certifications"),await t.evaluate(`(() => {
|
|
115
|
+
${W}
|
|
116
116
|
|
|
117
117
|
const main = document.querySelector('main');
|
|
118
118
|
if (!main) return [];
|
|
@@ -136,8 +136,8 @@ var et=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var tt=(t,e)=>{
|
|
|
136
136
|
|
|
137
137
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
138
138
|
}).filter(e => e.name);
|
|
139
|
-
})()`)))}async function
|
|
140
|
-
${
|
|
139
|
+
})()`)))}async function Et(t,e){return J(e,"recommendations","extractRecommendationsFromDetails",async()=>(await V(t,e,"recommendations"),await t.evaluate(`(() => {
|
|
140
|
+
${W}
|
|
141
141
|
|
|
142
142
|
const main = document.querySelector('main');
|
|
143
143
|
if (!main) return [];
|
|
@@ -172,7 +172,7 @@ var et=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var tt=(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
|
|
175
|
+
})()`)))}var W,He=De(()=>{le();W=`
|
|
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 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,T=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Mt=Object.freeze(new Set([T.DRAFT,T.CONFIRMED,T.NEEDS_REVIEW])),Ft=Object.freeze(new Set([T.DRAFT,T.CONFIRMED,T.REJECTED,T.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"),jt=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 Fe(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 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?Te(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{Fe(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=Te(le,"people.json")||{},q)}function ht(t){Me(),q=t;try{Fe(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,requestedConnectionAt: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 P=await t.evaluate(()=>document.body.scrollHeight);for(let F=1;F<=6;F++)await t.evaluate(C=>window.scrollTo(0,C),P*F/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"]),P=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)},F={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},C=document.querySelector("main");if(!C)return F;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)&&!P.has(u)}),j=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(_&&!(j&&_.startsWith(j))&&(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!==j).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:j,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(()=>(je(),Pe));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(`
|
|
238
|
+
`});import"dotenv/config";import Dt from"puppeteer";le();import{getPluginConfig as lt}from"@ilivemylife/graph-sdk";var at=await lt();for(let[t,e]of Object.entries(at))process.env[t]===void 0&&(process.env[t]=e);var Nt=process.env.LINKEDIN_NAME,P=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Rt=Object.freeze(new Set([P.DRAFT,P.CONFIRMED,P.NEEDS_REVIEW])),Pt=Object.freeze(new Set([P.DRAFT,P.CONFIRMED,P.REJECTED,P.NEEDS_REVIEW]));import"dotenv/config";import*as f from"fs";import*as y from"path";import{fileURLToPath as ct}from"url";var ut=ct(import.meta.url),dt=y.dirname(y.dirname(ut)),I=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"collected-profiles"):y.join(dt,"collected-profiles"),ae=y.join(I,"people.json"),Bt=y.join(I,"jobs.json"),Ht=y.join(I,"quota.json"),Vt=y.join(I,"conversations.json"),Wt=y.join(I,"sync-state.json"),Jt=y.join(I,"application-questions.json"),ce=y.join(I,"profile-history"),Ne=(t,e)=>{let n=parseInt(t,10);return Number.isInteger(n)&&n>=0?n:e},Kt=Ne(process.env.CONNECT_MAX_DAILY,20),Yt=Ne(process.env.CONNECT_MAX_WEEKLY,100),H=null;function Re(){f.existsSync(I)||f.mkdirSync(I,{recursive:!0})}function Pe(t,e){let n=JSON.stringify(e,null,2),o=t+".tmp";f.writeFileSync(o,n);for(let i=0;i<3;i++)try{f.renameSync(o,t);return}catch(r){if(i<2&&(r.code==="EPERM"||r.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw r}}function je(t,e){if(!f.existsSync(t))return null;try{let n=JSON.parse(f.readFileSync(t,"utf-8"));try{f.copyFileSync(t,t+".backup")}catch{}return n}catch(n){console.error(`[!] ${e} is corrupted: ${n.message}`),console.error(` File: ${y.resolve(t)}`);let o=t+".backup";if(f.existsSync(o))try{let i=JSON.parse(f.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{f.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{f.copyFileSync(t,t+".corrupted")}catch{}return null}}function ft(){return new Date().toISOString().split("T")[0]}var mt=["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"],pt=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function j(t){if(!t)return null;let e=t.match(/\/in\/([^/?#]+)/);return e?e[1].toLowerCase():null}function Me(t){return typeof t=="string"?t.replace(/\s+/g," ").trim().toLowerCase():""}function Oe(t,e,n=null){if(!e||t[e])return e;let o=j(e);if(!o)return e;let i=null;for(let[r,s]of Object.entries(t)){if(j(s.profileUrl||r)===o)return r;!i&&Array.isArray(s.aliases)&&s.aliases.includes(o)&&(i=r)}if(i){let r=Me(n),s=Me(t[i].name);if(r&&s&&r===s)return i}return e}function ht(){f.existsSync(ce)||f.mkdirSync(ce,{recursive:!0})}function qe(t){let e=j(t);return e?y.join(ce,`${e}.json`):null}function wt(t){let e=qe(t);return e?je(e,`profile-history/${j(t)}.json`)||[]:[]}function gt(t,e){let n=qe(t);if(!n)return;ht();let o=wt(t);o.unshift(e);try{Pe(n,o)}catch(i){console.error(`[!] Failed to append profile-history for ${j(t)}: ${i.message}`)}}function Fe(t){return!!(t==null||Array.isArray(t)&&t.length===0||typeof t=="string"&&!t.trim())}function Te(t){return Array.isArray(t)?[...t].map(e=>String(e).trim()).sort().join("||"):typeof t=="string"?t.replace(/\s+/g," ").trim():t}function yt(t,e){if(!t)return[];let n=[];for(let o of pt){let i=t[o],r=e[o];Fe(i)||Fe(r)||Te(i)!==Te(r)&&n.push(o)}return n}function bt(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 ue(){return H||(Re(),H=je(ae,"people.json")||{},H)}function Ue(t){Re(),H=t;try{Pe(ae,t)}catch(e){console.error(`[!] Failed to save people.json: ${e.message}`),console.error(` Path: ${y.resolve(ae)}`)}}function de(t,e={}){if(!t)return null;let n=ue(),o=ft(),i=new Date().toISOString(),r=Oe(n,t,e.name),s=n[r];if(s){let m=yt(s,e);m.length>0&&(gt(r,{capturedAt:i,previousLastUpdated:s.lastUpdated||null,changedFields:m,snapshot:bt(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 b of mt)if(e[b]!=null){if(Array.isArray(e[b])&&e[b].length===0&&Array.isArray(s[b])&&s[b].length>0)continue;s[b]=e[b]}Array.isArray(e.availableSections)&&(s.lastFullVisitAt=i)}else n[r]={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,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:i,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(e.availableSections)?i:null};return Ue(n),n[r]}function fe(t,e,n={}){if(n.dryRun||!t||!e)return;let o=j(e);if(!o)return;let i=ue(),r=Oe(i,t),s=i[r];if(!s)return;let m=j(s.profileUrl||r);o!==m&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(o)||(s.aliases.push(o),s.lastUpdated=new Date().toISOString(),Ue(i)))}async function At(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 g(3e3);let o=t.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function Ve(t,e,n={}){let{extractExperience:o=!1,extractFeatured:i=!1,extractEducation:r=!1,extractSkills:s=!1,extractRecommendations:m=!1,extractCertifications:b=!1}=n;try{await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await Le(t)&&(console.log(" Dismissed Premium overlay"),await g(1500),await At(t,e));let c=0;for(let p=0;p<2;p++){let N=await t.evaluate(()=>document.body.scrollHeight);for(let _=1;_<=6;_++)await t.evaluate(v=>window.scrollTo(0,v),N*_/6),await g(900);let R=await t.evaluate(()=>document.body.scrollHeight);if(R===c)break;c=R}await g(800);let k=null;try{let p=t.url();p&&/\/in\/[^/?#]/.test(p)&&(k=p.split("?")[0].replace(/\/+$/,""))}catch{}let h=await t.evaluate(()=>{let p=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),N=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"]),R=l=>{let a=(l||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(a)},_={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:[]},v=document.querySelector("main");if(!v)return _;let d=[...Array.from(v.querySelectorAll("h1")),...Array.from(v.querySelectorAll("h2"))],C=Array.from(v.querySelectorAll("h2")),q=d.find(l=>{let a=l.textContent&&l.textContent.trim(),u=(a||"").replace(/\s*\(\d+\)$/,"").trim();return a&&a.length>1&&a.length<100&&!p.has(u)&&!N.has(u)}),U=q?q.textContent.trim():null,x=q?q.parentElement:null;for(;x&&x!==v&&!Array.from(x.children).filter(a=>a.tagName==="P").some(a=>{let u=a.textContent&&a.textContent.trim();return u&&u.length>5&&!R(u)});)x=x.parentElement;let we=null,ge=null,ye=null,se=null;if(x&&x!==v){let l=Array.from(x.children).filter(u=>u.tagName==="P").filter(u=>{let D=u.textContent&&u.textContent.trim();return D&&D.length>5&&!R(D)});if(l[0]&&(we=l[0].textContent.trim()),l[1]){let u=l[1].textContent.trim().split(/\s*[·•]\s*/);ge=u[0]||null,u.length>1&&(ye=u.slice(1).join(" \xB7 "))}let a=Array.from(x.children).filter(u=>u.tagName==="DIV");for(let u=a.length-1;u>=0;u--){let D=a[u].textContent&&a[u].textContent.trim();if(D&&!(U&&D.startsWith(U))&&(se=D.split(/[·•]/)[0].trim(),se))break}}let be=null;if(x){let l=x.querySelectorAll("p, span, div");for(let a of l){let u=(a.textContent||"").trim().replace(/^[·•]\s*/,"");if(u==="1st"||u==="2nd"||u==="3rd"){be=u;break}}}let Ze=!!v.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),Se=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Xe=Se&&Se.src||null,K=v.textContent||"",ke=null,Ce=K.match(/(\d+\+?)\s+connections\b/i);Ce&&(ke=Ce[1]+" connections");let Y=null,xe=K.match(/(\d+)\s+mutual connection/i),ve=K.match(/and\s+(\d+)\s+other mutual/i),et=K.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);xe?Y=parseInt(xe[1],10):ve?Y=2+parseInt(ve[1],10):et&&(Y=2);let Ee=null,Ae=null,Ie=C.find(l=>l.textContent&&l.textContent.trim()==="About");if(Ie){let l=Ie.parentElement;for(;l&&l.tagName!=="SECTION";)l=l.parentElement;if(l){let a=(l.textContent||"").trim();a=a.replace(/^About\s*/,"").trim();let u=a.match(/Top skills\s*(.+?)$/i);if(u){let re=u[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(it=>it.trim()).filter(Boolean);re.length>0&&re.length<10&&(Ae=re)}a=a.split(/\n?…\s*more/i)[0].trim(),a=a.split(/\n?\.\.\.\s*more/i)[0].trim(),a=a.split(/\bTop skills\b/i)[0].trim(),a=a.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Ee=a||null}}let $e=null,_e=C.find(l=>l.textContent&&l.textContent.trim()==="Activity");if(_e){let l=_e.parentElement;for(;l&&l.tagName!=="SECTION";)l=l.parentElement;if(l){let a=(l.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);a&&($e=parseInt(a[1].replace(/,/g,""),10))}}let tt=[...new Set(C.map(l=>(l.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(l=>l&&l.length>1&&l.length<60&&l!==U).filter(l=>p.has(l)))],B=document.body.textContent||"",nt=/#OpenToWork\b/i.test(B)||/\bOpen to work\b/.test(B),ot=/#Hiring\b/i.test(B)||/\bI'?m hiring\b/i.test(B)||/\bWe are hiring\b/i.test(B);return{name:U,title:we,location:se,currentCompany:ge,currentSchool:ye,connectionDegree:be,hasVerifiedBadge:Ze,photoUrl:Xe,connectionsLevel:ke,mutualConnectionsCount:Y,followers:$e,openToWork:nt,hiring:ot,about:Ee,topSkills:Ae,availableSections:tt}});console.log(`Viewed: ${h.name} - ${h.title}`);let w=null,S=null,E=null,M=null,F=null,T=null;if(o||i||r||s||m||b){let p=await Promise.resolve().then(()=>(He(),Be));o&&(w=await p.extractExperienceFromDetails(t,e),console.log(` + Experience: ${w.length} entries`)),i&&(S=await p.extractFeaturedFromDetails(t,e),console.log(` + Featured: ${S.length} entries`)),r&&(E=await p.extractEducationFromDetails(t,e),console.log(` + Education: ${E.length} entries`)),s&&(M=await p.extractSkillsFromDetails(t,e),console.log(` + Skills: ${M.length} entries`)),m&&(F=await p.extractRecommendationsFromDetails(t,e),console.log(` + Recommendations: ${F.length} entries`)),b&&(T=await p.extractCertificationsFromDetails(t,e),console.log(` + Certifications: ${T.length} entries`))}return{...h,profileUrl:e,resolvedUrl:k,...w!==null&&{experience:w},...S!==null&&{featured:S},...E!==null&&{education:E},...M!==null&&{skillsFull:M},...F!==null&&{recommendations:F},...T!==null&&{certifications:T}}}catch($){console.error(`Error viewing profile ${e}:`,$.message);try{await t.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test($.message||""))throw $;return null}}import We from"fs";import It from"path";var $t="cookies.json";function _t(){let t=process.env.ILML_SCOPE_DIR;return t?It.join(t,"plugins-state","linkedin","cookies.json"):$t}function Je(){let t=_t();if(!We.existsSync(t))throw new Error(`Cookies not found at ${t}. Run: ilml linkedin login`);let e;try{e=We.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 Ke(t){return t?t.replace(/^https?:\/\/(www\.|m\.)?linkedin\.com/i,"https://linkedin.com").split("?")[0].split("#")[0].replace(/\/+$/,"").toLowerCase():""}function Ye(t){return(t||"").replace(/ /g," ").replace(/\s+/g," ").trim().toLowerCase()}var A=process.argv.slice(2),Lt=A.includes("--help")||A.includes("-h"),L=A.find(t=>t.startsWith("http")),O=A.includes("--full"),Q=O||A.includes("--with-experience"),z=O||A.includes("--with-featured"),Z=O||A.includes("--with-education"),X=O||A.includes("--with-skills"),ee=O||A.includes("--with-recommendations"),te=O||A.includes("--with-certifications"),Ge=[["experience",Q],["featured",z],["education",Z],["skills",X],["recommendations",ee],["certifications",te]],Qe=Ge.filter(([,t])=>t).length,pe=1+Qe;function ze(){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
|
+
`)}Lt&&(ze(),process.exit(0));L||(ze(),process.exit(1));/linkedin\.com\/in\//i.test(L)||(console.error(`URL doesn't look like a LinkedIn profile: ${L}`),console.error("Expected format: https://www.linkedin.com/in/<slug>/"),process.exit(1));var he=Ke(process.env.MY_LINKEDIN_URL||""),oe=Ye(process.env.LINKEDIN_NAME||"");!he&&!oe&&(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 ne=he&&Ke(L)===he,me=Ge.filter(([,t])=>t).map(([t])=>t);console.log("");console.log(` enrichProfile \u2014 ${L}`);O?console.log(` Mode: --full (${pe} page loads: main + ${me.join(" + ")})`):me.length>0?console.log(` Mode: rich (${pe} loads: main + ${me.join(" + ")})`):console.log(" Mode: basic (1 load \u2014 main page only)");console.log(ne?" Target: SELF (URL match) \u2014 will print to stdout, not saved to people.json":oe?` 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)");Qe>0&&(console.log(""),console.log(` \u26A0 ${pe} 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 G=null;try{G=await Dt.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5});let t=await G.newPage();await t.setCookie(...Je());let e=await Ve(t,L,{extractExperience:Q,extractFeatured:z,extractEducation:Z,extractSkills:X,extractRecommendations:ee,extractCertifications:te});if((!e||!e.name)&&(console.error(" viewProfile returned no name \u2014 profile not loaded or DOM changed"),process.exit(1)),!ne&&oe&&e.name&&Ye(e.name)===oe&&(ne=!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)"}`),Q&&console.log(` experience: ${(e.experience||[]).length} entries`),z&&console.log(` featured: ${(e.featured||[]).length} entries`),Z&&console.log(` education: ${(e.education||[]).length} entries`),X&&console.log(` skillsFull: ${(e.skillsFull||[]).length} entries`),ee&&console.log(` recommendations: ${(e.recommendations||[]).length} entries`),te&&console.log(` certifications: ${(e.certifications||[]).length} entries`),console.log(""),ne)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",Q,e.experience],["featured",z,e.featured],["education",Z,e.education],["skillsFull",X,e.skillsFull],["recommendations",ee,e.recommendations],["certifications",te,e.certifications]],i=!1;for(let[r,s,m]of o)s&&(Array.isArray(m)&&m.length>0?(n[r]=m,i=!0):console.log(` \u26A0 --with-${r==="skillsFull"?"skills":r} returned 0 entries \u2014 NOT writing ${r} (existing data preserved)`));i&&(n._lastEnrichedAt=new Date().toISOString()),de(L,n),e.resolvedUrl&&fe(L,e.resolvedUrl),console.log(" \u2713 Saved to people.json")}}catch(t){console.error(" Error:",t.message),process.exit(1)}finally{G&&await G.close().catch(()=>{})}
|