ilml-plugin-linkedin 1.14.4 → 1.15.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/dist/daily.mjs CHANGED
@@ -1,53 +1,53 @@
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(`
1
+ var Le=Object.defineProperty;var q=(e,n)=>{for(var t in n)Le(e,t,{get:n[t],enumerable:!0})};import{execFileSync as nn}from"child_process";import"dotenv/config";import*as S from"fs";import*as I from"path";import{fileURLToPath as qe}from"url";import"dotenv/config";import{createGraphClient as Me,resolveToken as Pe}from"@ilivemylife/graph-sdk";import{config as Je}from"dotenv";Je();var re=Pe()||process.env.TOKEN;re||(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=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})}**
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 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(`
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=I.dirname(I.dirname(Ve)),Y=process.env.DATA_DIR?I.resolve(process.env.DATA_DIR,"collected-profiles"):I.join(We,"collected-profiles"),G=I.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"),jn=m.join(E,"people.json"),An=m.join(E,"jobs.json"),Xe=m.join(E,"quota.json"),En=m.join(E,"conversations.json"),On=m.join(E,"sync-state.json"),Rn=m.join(E,"application-questions.json"),In=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 R of ao)k[R]!=null&&h[R]==null&&(h[R]=k[R]);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 R=h.jobId||"unknown";p[R]||(p[R]={applications:[]});let se=(h.questions||[]).map(j=>{let L={type:j.type||"input",question:j.question||"",answer:j.answer||""};return j.options&&(j.options.length<=uo?L.options=j.options:(L.optionsOmitted=!0,k++)),j.page&&(L.page=j.page),j.wasPreFilled&&(L.wasPreFilled=!0),j.wasRetry&&(L.wasRetry=!0),L});p[R].applications.push({applicationId:h.applicationId,date:h.date,result:h.result||"submitted",formPages:h.formPages||null,duration:h.duration||null,retries:h.retries||0,failedField:h.failedField||null,questionCount:h.questionCount||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:()=>jo});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 jo(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:()=>Ao,up:()=>To});import*as w from"fs";import*as ve from"path";var Ao=4,Eo="split-connection-timestamps",Oo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ro(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 Io(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=Ro(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}Io(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 A=process.env.DATA_DIR?f.resolve(qo(process.env.DATA_DIR)):Bo,x=f.join(A,"collected-profiles"),F=f.join(A,"market-research"),g=f.join(A,".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
- `),process.exit(1));try{c.mkdirSync(j,{recursive:!0})}catch(n){n.code!=="EEXIST"&&(console.error(`
11
- [FATAL] Cannot create DATA_DIR (${j}): ${n.message}`),console.error(` Fix the path or permissions and try again.
12
- `),process.exit(1))}let e;try{e=c.statSync(j)}catch(n){console.error(`
13
- [FATAL] DATA_DIR (${j}) is not accessible: ${n.message}
10
+ `),process.exit(1));try{c.mkdirSync(A,{recursive:!0})}catch(n){n.code!=="EEXIST"&&(console.error(`
11
+ [FATAL] Cannot create DATA_DIR (${A}): ${n.message}`),console.error(` Fix the path or permissions and try again.
12
+ `),process.exit(1))}let e;try{e=c.statSync(A)}catch(n){console.error(`
13
+ [FATAL] DATA_DIR (${A}) is not accessible: ${n.message}
14
14
  `),process.exit(1)}e.isDirectory()||(console.error(`
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
- `),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(`
15
+ [FATAL] DATA_DIR (${A}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
16
+ `),process.exit(1));for(let 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 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(`
18
+ `),process.exit(1))}}var C=f.join(A,".migration-lock");function Vo(){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 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(`
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 ne(){try{if(JSON.parse(c.readFileSync(C,"utf-8")).pid!==process.pid)return;c.unlinkSync(C)}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(`
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 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(`
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 we)if(c.existsSync(r))try{c.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${g}`)}function Go(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 W(e){let n=c.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function je(){if(Yo(),!c.existsSync(g))return{version:0,migrations:[]};let e;try{e=W(g)}catch(t){if(t.code==="ENOENT")return{version:0,migrations:[]};console.error(`
27
27
  [FATAL] ${g} is not valid JSON: ${t.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
28
- `),process.exit(1)}let n=Mo(e);return n===null&&(console.error(`
28
+ `),process.exit(1)}let n=Go(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 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
- [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
- `),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}.
30
+ `),process.exit(1)),n}function Oe(e){try{c.chmodSync(e,384)}catch{}}function Ho(e){if(Ee(),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)),Oe(n),c.renameSync(n,g)}catch(t){try{c.unlinkSync(n)}catch{}throw t}}function Ae(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{Ie(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 ee=!1;async function Re(){if(ee)return;Ee(),Zo();let n=je().version;if(n===D){ee=!0;return}Wo(),Vo(),process.on("exit",ne),n>D&&(console.error(`
31
+ [FATAL] Your data schema is at v${n}, but this plugin build only understands up to v${D}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
32
+ `),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${D}.
33
33
  `),process.exit(1)),console.log(`
34
- \u{1F4E6} Schema migration: v${n} \u2192 v${T}`);let t=Yo();if(!t.ok){console.error(`
34
+ \u{1F4E6} Schema migration: v${n} \u2192 v${D}`);let t=en();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
- `),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{we(_,s.version),we(x,s.version)}catch(l){console.error(`
37
+ `),process.exit(1)}let o=O.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{Ae(x,s.version),Ae(F,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
- `),process.exit(1)}let a=s.module;try{await a.up(_,x)}catch(l){console.error(`
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.
40
+ `),process.exit(1)}let a=s.module;try{await a.up(x,F)}catch(l){console.error(`
41
+ [FATAL] Migration ${r} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let u=on(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=$e();p.version=s.version,p.migratedAt=l,p.migrations=p.migrations||[],p.migrations.push(u),Po(p)}catch(l){console.error(`
44
+ `)}process.exit(1)}try{let l=new Date().toISOString(),u={version:s.version,name:a.NAME||r,appliedAt:l},p=je();p.version=s.version,p.migratedAt=l,p.migrations=p.migrations||[],p.migrations.push(u),Ho(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{fe()}catch{}try{Se()}catch{}X=!0,ee(),console.log(`
47
- \u2713 Schema is now at v${T}
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
- \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(`
46
+ `),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{de()}catch{}try{$e()}catch{}ee=!0,ne(),console.log(`
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[A,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{Ie(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 Ie(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 Re();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)),_e=B.includes("--dry-run"),Ce=B.includes("--jobs"),xe=B.includes("--comms"),De=["apply-queue","apply","funnel","scout","visit"],Ne=["sync","today"],Fe=Ce?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)),_e)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=Ce?"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(", ")}`),_e&&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
+ \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
- `);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)});
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)});
@@ -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"),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 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,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 F=1;F<=6;F++)await t.evaluate(C=>window.scrollTo(0,C),j*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"]),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)},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)&&!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(`
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"),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 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 j=await t.evaluate(()=>document.body.scrollHeight);for(let F=1;F<=6;F++)await t.evaluate(C=>window.scrollTo(0,C),j*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"]),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)},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)&&!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