ilml-plugin-linkedin 1.20.19 → 1.20.21

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
@@ -2,50 +2,50 @@ var Ue=Object.defineProperty;var q=(e,o)=>{for(var t in o)Ue(e,t,{get:o[t],enume
2
2
  [FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
3
3
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
4
4
  `),console.error(` Or add ILML_TOKEN=... to .env
5
- `),process.exit(1));var ie=Je({token:se});function Ve(e){if(!e||e<1e3)return`${e||0}ms`;let o=Math.round(e/1e3);if(o<60)return`${o}s`;let t=Math.floor(o/60),n=o%60;return n?`${t}m ${n}s`:`${t}m`}var We={apply:"Job apply","apply-queue":"Job apply (queue)",scout:"Job scout",connect:"Connect run",funnel:"Recruiter funnel",messages:"Messages",sync:"Connections sync","sync-all":"Inbox sync",visit:"Profile visits",viewers:"Profile viewers",daily:"Daily run"};function Ye(e){let o=String(e||"").toLowerCase();return/authwall|session expired|not logged in|re-?auth|logged out|sign ?in/.test(o)?"LinkedIn asked to sign in again. Run `ilml linkedin login`, then run this again.":/protocoltimeout|callfunctionon|target closed|session closed|detached|execution context|browser.*disconnected|connection closed/.test(o)?"The browser stopped responding partway through. This is usually temporary \u2014 just run it again.":/err_aborted|err_network|err_connection|err_name_not_resolved|net::/.test(o)?"A page failed to load (network hiccup). Try running it again in a moment.":/navigation timeout|timeout.*exceeded|waiting for selector|waiting for/.test(o)?"A page took too long to load. Try again in a moment.":/invite limit|weekly.*limit|too many|rate.?limit|quota/.test(o)?"You've reached a LinkedIn sending limit for now. Wait a while, then try again.":"Something went wrong partway through. It is safe to run the command again."}function Ge({scriptName:e,mode:o,status:t,summaryLines:n,error:r,duration:s}){let i=t==="error"?"\u2717":t==="quota-reached"?"\u26A0":"\u2713",a=t==="error"?"stopped early":t==="quota-reached"?"daily limit reached":"done",c=We[e]||e,u=o&&o!=="default"?` \xB7 ${o}`:"",f=new Date().toISOString().slice(0,16).replace("T"," "),S=s?` \xB7 ${Ve(s)}`:"",d=[];d.push(`## ${i} ${c} \u2014 ${a}`),d.push(`_${f}${u}${S}_`),d.push("");for(let g of n)d.push(`- ${g}`);if(t==="error"){d.push(""),d.push(`**What happened:** ${Ye(r)}`);let g=String(r||"").replace(/\s+/g," ").trim();g&&d.push(`_Technical detail: ${g.slice(0,140)}_`)}return d.join(`
6
- `)}async function le({scriptName:e,mode:o,status:t,summaryLines:n,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(n)||n.length===0)return;let a=Ge({scriptName:e,mode:o,status:t,summaryLines:n,error:r,duration:s});try{await ie.addMessage(i,a)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var Ke=He(import.meta.url),ze=I.dirname(I.dirname(Ke)),Y=process.env.DATA_DIR?I.resolve(process.env.DATA_DIR,"collected-profiles"):I.join(ze,"collected-profiles"),G=I.join(Y,"run-log.json");function Qe(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";w.writeFileSync(n,t);for(let r=0;r<3;r++)try{w.renameSync(n,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function ce(){try{if(!w.existsSync(G))return{runs:[]};let e=JSON.parse(w.readFileSync(G,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ae(e){w.existsSync(Y)||w.mkdirSync(Y,{recursive:!0});try{Qe(G,e)}catch(o){console.error(`[!] Failed to save run-log.json: ${o.message}`)}}function ue(e,o="default"){let t=ce();for(let i of t.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let n=new Date,r={timestamp:n.toISOString(),script:e,mode:o,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(i=>new Date(i.timestamp).getTime()>s),ae(t),{script:e,mode:o,startTime:n.getTime(),runIndex:t.runs.length-1}}function fe(e,o,t=null,n=null){if(!e)return;let r=null;try{let i=ce(),a=i.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=o,a.result=o,a.duration=Date.now()-e.startTime,a.stats=t,a.error=n,r=a.duration;else{let c=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());c&&(c.status=o,c.result=o,c.duration=Date.now()-e.startTime,c.stats=t,c.error=n,r=c.duration)}ae(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=t&&Array.isArray(t.summaryLines)?t.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=o==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";le({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:n,duration:r??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import{getPluginConfig as eo}from"@ilivemylife/graph-sdk";var Xe={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},pe=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function Ze(e){return String(e??"").split(/[,\s|]+/).map(o=>o.trim()).filter(Boolean)}function de(e=process.env){let o=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!o)return null;let t=new URLSearchParams;t.set("keywords",o);let n=(e.JOB_SEARCH_LOCATION||"").trim();n&&t.set("location",n);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&t.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&t.set("distance",String(s)),pe(e.JOB_SEARCH_EASY_APPLY)&&t.set("f_AL","true"),pe(e.JOB_SEARCH_IN_NETWORK)&&t.set("f_JIYN","true");let i=Ze(e.JOB_SEARCH_COMPANY_IDS);i.length&&t.set("f_C",i.join(","));let a=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();a&&t.set("f_TPR",Xe[a]||a),t.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let c="https://www.linkedin.com/jobs/search/?"+t.toString(),u=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return u&&(c+="&"+u),c}var oo=await eo();for(let[e,o]of Object.entries(oo))process.env[e]===void 0&&(process.env[e]=o);var me=de(process.env);me&&(process.env.LINKEDIN_SEARCH_URL=me);var jn=process.env.LINKEDIN_NAME,C=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Rn=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.NEEDS_REVIEW])),On=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.REJECTED,C.NEEDS_REVIEW]));import"dotenv/config";import*as m from"fs";import*as h from"path";import{fileURLToPath as no}from"url";var to=no(import.meta.url),ro=h.dirname(h.dirname(to)),R=process.env.DATA_DIR?h.resolve(process.env.DATA_DIR,"collected-profiles"):h.join(ro,"collected-profiles"),Cn=h.join(R,"people.json"),Nn=h.join(R,"jobs.json"),so=h.join(R,"quota.json"),xn=h.join(R,"conversations.json"),Fn=h.join(R,"sync-state.json"),Ln=h.join(R,"application-questions.json"),Mn=h.join(R,"profile-history"),he=(e,o)=>{let t=parseInt(e,10);return Number.isInteger(t)&&t>=0?t:o},P=he(process.env.CONNECT_MAX_DAILY,20),U=he(process.env.CONNECT_MAX_WEEKLY,100),io=null,lo=null,T=null,co=null,ao=null,uo=null;function ge(){io=null,lo=null,T=null,co=null,ao=null,uo=null}function fo(){m.existsSync(R)||m.mkdirSync(R,{recursive:!0})}function po(e,o){if(!m.existsSync(e))return null;try{let t=JSON.parse(m.readFileSync(e,"utf-8"));try{m.copyFileSync(e,e+".backup")}catch{}return t}catch(t){console.error(`[!] ${o} is corrupted: ${t.message}`),console.error(` File: ${h.resolve(e)}`);let n=e+".backup";if(m.existsSync(n))try{let r=JSON.parse(m.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{m.copyFileSync(n,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{m.copyFileSync(e,e+".corrupted")}catch{}return null}}function ye(){return new Date().toISOString().split("T")[0]}function mo(){return T||(fo(),T=po(so,"quota.json"),(!T||!T.connections)&&(T={connections:[]}),T)}function Se(){let e=mo(),o=new Date;o.setDate(o.getDate()-7);let t=o.toISOString().split("T")[0];return e.connections.filter(n=>n.date>=t)}function be(){let e=Se(),o=ye(),t=e.filter(c=>c.date===o).length,n=e.length,r=t>=P,s=n>=U,i=!r&&!s,a={allowed:i,daily:{sent:t,max:P},weekly:{sent:n,max:U}};return i||(a.reason=r?`Daily limit reached (${t}/${P})`:`Weekly limit reached (${n}/${U})`),a}function we(){let e=Se(),o=ye(),t=e.filter(r=>r.date===o).length,n=e.length;return{daily:{sent:t,max:P,remaining:P-t},weekly:{sent:n,max:U,remaining:U-n}}}import"dotenv/config";import*as l from"fs";import*as oe from"os";import*as p from"path";import{fileURLToPath as Yo}from"url";var z={};q(z,{NAME:()=>go,VERSION:()=>ho,up:()=>bo});import*as v from"fs";import*as V from"path";var ho=1,go="normalize-jobs-and-questions",yo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],So=50;function H(e){return v.existsSync(e)?JSON.parse(v.readFileSync(e,"utf-8")):null}function K(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{v.writeFileSync(n,t)}catch(r){try{v.unlinkSync(n)}catch{}throw r}try{v.renameSync(n,e)}catch(r){try{v.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function bo(e,o){let t=V.join(e,"jobs.json"),n=V.join(o,"scouted-jobs.json"),r=V.join(e,"application-questions.json"),s=H(t)||{},i=H(n)||{},a=0,c=[];for(let f of Object.keys(s)){if(!i[f])continue;let S=i[f],d=s[f];for(let g of yo)S[g]!=null&&d[g]==null&&(d[g]=S[g]);c.push(f),a++}a>0?(K(t,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=H(r);if(u&&Array.isArray(u.applications)){let f={},S=0;for(let d of u.applications){let g=d.jobId||"unknown";f[g]||(f[g]={applications:[]});let re=(d.questions||[]).map(E=>{let L={type:E.type||"input",question:E.question||"",answer:E.answer||""};return E.options&&(E.options.length<=So?L.options=E.options:(L.optionsOmitted=!0,S++)),E.page&&(L.page=E.page),E.wasPreFilled&&(L.wasPreFilled=!0),E.wasRetry&&(L.wasRetry=!0),L});f[g].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||re.length,questions:re})}K(r,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),S>0&&console.log(` Phase 2: Stripped bloated options from ${S} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(c.length>0){for(let f of c)delete i[f];K(n,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Q={};q(Q,{NAME:()=>vo,VERSION:()=>wo,up:()=>$o});import*as k from"fs";import*as ve from"path";var wo=2,vo="reset-unread-flags";function ko(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function Ao(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{k.writeFileSync(n,t)}catch(r){try{k.unlinkSync(n)}catch{}throw r}try{k.renameSync(n,e)}catch(r){try{k.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function $o(e){let o=ve.join(e,"conversations.json"),t=ko(o);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let r of Object.keys(t))t[r].unread===!0&&(t[r].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Ao(o,t),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var X={};q(X,{NAME:()=>jo,VERSION:()=>Eo,up:()=>_o});import*as A from"fs";import*as ke from"path";var Eo=3,jo="recompute-last-message-by",Ro=new Set(["draft","confirmed","rejected","needs_review"]);function Oo(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Io(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{A.writeFileSync(n,t)}catch(r){try{A.unlinkSync(n)}catch{}throw r}try{A.renameSync(n,e)}catch(r){try{A.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function To(e,o){if(!e||e.length===0)return"them";let t=e.filter(s=>!Ro.has(s.status));if(t.length===0)return"them";let n=t.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=n.length>0?n:[...t].reverse();for(let s of r){let i=s.sender;if(i===o)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function _o(e){let o=ke.join(e,"conversations.json"),t=Oo(o);if(!t){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let n=process.env.LINKEDIN_NAME;if(!n||typeof n!="string"||!n.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,s=0,i=0;for(let a of Object.keys(t)){let c=t[a];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,s++);let u=Array.isArray(c.messages)?c.messages:[],f=To(u,n),S=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=S,r++}if(r===0){console.log(" No conversations to recompute.");return}Io(o,t),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Z={};q(Z,{NAME:()=>Co,VERSION:()=>Do,up:()=>Lo});import*as $ from"fs";import*as Ae from"path";var Do=4,Co="split-connection-timestamps",No=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function xo(e){if(!$.existsSync(e))return null;let o=$.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Fo(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{$.writeFileSync(n,t)}catch(r){try{$.unlinkSync(n)}catch{}throw r}try{$.renameSync(n,e)}catch(r){try{$.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Lo(e){let o=Ae.join(e,"people.json"),t=xo(o);if(!t||typeof t!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let n=0,r=0;for(let s of Object.keys(t)){let i=t[s];!i||typeof i!="object"||(r++,No.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,n++))}if(n===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Fo(o,t),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${n} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as b from"path";import{fileURLToPath as Mo}from"url";var Po=Mo(import.meta.url),Uo=b.dirname(b.dirname(Po)),J=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"market-research"):b.join(Uo,"market-research"),Yn=b.join(J,"scouted-jobs.json"),Gn=b.join(J,"discovered-people.json"),Hn=b.join(J,"visit-log.json"),Kn=b.join(J,"companies.json"),zn=b.join(J,"job-decisions.json");function $e(){Jo=null,Bo=null,qo=null,Vo=null,Wo=null}var Jo=null;var Bo=null;var qo=null;var Vo=null;var Wo=null;var Go=Yo(import.meta.url),Ho=p.dirname(Go),Ko=p.dirname(p.dirname(Ho));function zo(e){return e&&(e==="~"?oe.homedir():e.startsWith("~/")||e.startsWith("~\\")?p.join(oe.homedir(),e.slice(2)):e)}var j=process.env.DATA_DIR?p.resolve(zo(process.env.DATA_DIR)):Ko,x=p.join(j,"collected-profiles"),F=p.join(j,"market-research"),y=p.join(j,".schema-version"),Ee=[p.join(x,".schema-version"),p.join(F,".schema-version")],_=4,O=[{version:1,module:z},{version:2,module:Q},{version:3,module:X},{version:4,module:Z}];(function(){O.sort((n,r)=>n.version-r.version);let o=new Set;for(let n of O){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(o.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);o.add(n.version);let r=n.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let t=O.length?O[O.length-1].version:0;if(t!==_)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${_}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<O.length;n++){let r=n+1;if(O[n].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${n} but found v${O[n].version}`)}})();function Ie(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
5
+ `),process.exit(1));var ie=Je({token:se});function Ve(e){if(!e||e<1e3)return`${e||0}ms`;let o=Math.round(e/1e3);if(o<60)return`${o}s`;let t=Math.floor(o/60),n=o%60;return n?`${t}m ${n}s`:`${t}m`}var We={apply:"Job apply","apply-queue":"Job apply (queue)",scout:"Job scout",connect:"Connect run",funnel:"Recruiter funnel",messages:"Messages",sync:"Connections sync","sync-all":"Inbox sync",visit:"Profile visits",viewers:"Profile viewers",daily:"Daily run"};function Ye(e){let o=String(e||"").toLowerCase();return/authwall|session expired|not logged in|re-?auth|logged out|sign ?in/.test(o)?"LinkedIn asked to sign in again. Run `ilml linkedin login`, then run this again.":/protocoltimeout|callfunctionon|target closed|session closed|detached|execution context|browser.*disconnected|connection closed/.test(o)?"The browser stopped responding partway through. This is usually temporary \u2014 just run it again.":/err_aborted|err_network|err_connection|err_name_not_resolved|net::/.test(o)?"A page failed to load (network hiccup). Try running it again in a moment.":/navigation timeout|timeout.*exceeded|waiting for selector|waiting for/.test(o)?"A page took too long to load. Try again in a moment.":/invite limit|weekly.*limit|too many|rate.?limit|quota/.test(o)?"You've reached a LinkedIn sending limit for now. Wait a while, then try again.":"Something went wrong partway through. It is safe to run the command again."}function Ge({scriptName:e,mode:o,status:t,summaryLines:n,error:r,duration:s}){let i=t==="error"?"\u2717":t==="quota-reached"?"\u26A0":"\u2713",a=t==="error"?"stopped early":t==="quota-reached"?"daily limit reached":"done",l=We[e]||e,u=o&&o!=="default"?` \xB7 ${o}`:"",f=new Date().toISOString().slice(0,16).replace("T"," "),S=s?` \xB7 ${Ve(s)}`:"",d=[];d.push(`## ${i} ${l} \u2014 ${a}`),d.push(`_${f}${u}${S}_`),d.push("");for(let g of n)d.push(`- ${g}`);if(t==="error"){d.push(""),d.push(`**What happened:** ${Ye(r)}`);let g=String(r||"").replace(/\s+/g," ").trim();g&&d.push(`_Technical detail: ${g.slice(0,140)}_`)}return d.join(`
6
+ `)}async function le({scriptName:e,mode:o,status:t,summaryLines:n,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(n)||n.length===0)return;let a=Ge({scriptName:e,mode:o,status:t,summaryLines:n,error:r,duration:s});try{await ie.addMessage(i,a)}catch(l){console.error(`[runReport] Failed to post end-of-session message: ${l.message}`)}}var Ke=He(import.meta.url),ze=I.dirname(I.dirname(Ke)),Y=process.env.DATA_DIR?I.resolve(process.env.DATA_DIR,"collected-profiles"):I.join(ze,"collected-profiles"),G=I.join(Y,"run-log.json");function Qe(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";w.writeFileSync(n,t);for(let r=0;r<3;r++)try{w.renameSync(n,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function ce(){try{if(!w.existsSync(G))return{runs:[]};let e=JSON.parse(w.readFileSync(G,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ae(e){w.existsSync(Y)||w.mkdirSync(Y,{recursive:!0});try{Qe(G,e)}catch(o){console.error(`[!] Failed to save run-log.json: ${o.message}`)}}function ue(e,o="default"){let t=ce();for(let i of t.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let n=new Date,r={timestamp:n.toISOString(),script:e,mode:o,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(i=>new Date(i.timestamp).getTime()>s),ae(t),{script:e,mode:o,startTime:n.getTime(),runIndex:t.runs.length-1}}function fe(e,o,t=null,n=null){if(!e)return;let r=null;try{let a=ce(),l=a.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=o,l.result=o,l.duration=Date.now()-e.startTime,l.stats=t,l.error=n,r=l.duration;else{let u=a.runs.find(f=>f.script===e.script&&f.status==="running"&&f.timestamp===new Date(e.startTime).toISOString());u&&(u.status=o,u.result=o,u.duration=Date.now()-e.startTime,u.stats=t,u.error=n,r=u.duration)}ae(a)}catch(a){console.error(`[runLog] Failed to end run: ${a.message}`)}let s=t&&Array.isArray(t.summaryLines)?t.summaryLines:null,i=t&&t.__deferReport===!0;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS&&!i){let a=o==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";le({scriptName:e.script,mode:e.mode,status:a,summaryLines:s,error:n,duration:r??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import{getPluginConfig as eo}from"@ilivemylife/graph-sdk";var Xe={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},pe=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function Ze(e){return String(e??"").split(/[,\s|]+/).map(o=>o.trim()).filter(Boolean)}function de(e=process.env){let o=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!o)return null;let t=new URLSearchParams;t.set("keywords",o);let n=(e.JOB_SEARCH_LOCATION||"").trim();n&&t.set("location",n);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&t.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&t.set("distance",String(s)),pe(e.JOB_SEARCH_EASY_APPLY)&&t.set("f_AL","true"),pe(e.JOB_SEARCH_IN_NETWORK)&&t.set("f_JIYN","true");let i=Ze(e.JOB_SEARCH_COMPANY_IDS);i.length&&t.set("f_C",i.join(","));let a=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();a&&t.set("f_TPR",Xe[a]||a),t.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let l="https://www.linkedin.com/jobs/search/?"+t.toString(),u=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return u&&(l+="&"+u),l}var oo=await eo();for(let[e,o]of Object.entries(oo))process.env[e]===void 0&&(process.env[e]=o);var me=de(process.env);me&&(process.env.LINKEDIN_SEARCH_URL=me);var jn=process.env.LINKEDIN_NAME,C=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Rn=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.NEEDS_REVIEW])),On=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.REJECTED,C.NEEDS_REVIEW]));import"dotenv/config";import*as m from"fs";import*as h from"path";import{fileURLToPath as no}from"url";var to=no(import.meta.url),ro=h.dirname(h.dirname(to)),R=process.env.DATA_DIR?h.resolve(process.env.DATA_DIR,"collected-profiles"):h.join(ro,"collected-profiles"),Cn=h.join(R,"people.json"),Nn=h.join(R,"jobs.json"),so=h.join(R,"quota.json"),xn=h.join(R,"conversations.json"),Fn=h.join(R,"sync-state.json"),Ln=h.join(R,"application-questions.json"),Pn=h.join(R,"profile-history"),he=(e,o)=>{let t=parseInt(e,10);return Number.isInteger(t)&&t>=0?t:o},M=he(process.env.CONNECT_MAX_DAILY,20),U=he(process.env.CONNECT_MAX_WEEKLY,100),io=null,lo=null,_=null,co=null,ao=null,uo=null;function ge(){io=null,lo=null,_=null,co=null,ao=null,uo=null}function fo(){m.existsSync(R)||m.mkdirSync(R,{recursive:!0})}function po(e,o){if(!m.existsSync(e))return null;try{let t=JSON.parse(m.readFileSync(e,"utf-8"));try{m.copyFileSync(e,e+".backup")}catch{}return t}catch(t){console.error(`[!] ${o} is corrupted: ${t.message}`),console.error(` File: ${h.resolve(e)}`);let n=e+".backup";if(m.existsSync(n))try{let r=JSON.parse(m.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{m.copyFileSync(n,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{m.copyFileSync(e,e+".corrupted")}catch{}return null}}function ye(){return new Date().toISOString().split("T")[0]}function mo(){return _||(fo(),_=po(so,"quota.json"),(!_||!_.connections)&&(_={connections:[]}),_)}function Se(){let e=mo(),o=new Date;o.setDate(o.getDate()-7);let t=o.toISOString().split("T")[0];return e.connections.filter(n=>n.date>=t)}function be(){let e=Se(),o=ye(),t=e.filter(l=>l.date===o).length,n=e.length,r=t>=M,s=n>=U,i=!r&&!s,a={allowed:i,daily:{sent:t,max:M},weekly:{sent:n,max:U}};return i||(a.reason=r?`Daily limit reached (${t}/${M})`:`Weekly limit reached (${n}/${U})`),a}function we(){let e=Se(),o=ye(),t=e.filter(r=>r.date===o).length,n=e.length;return{daily:{sent:t,max:M,remaining:M-t},weekly:{sent:n,max:U,remaining:U-n}}}import"dotenv/config";import*as c from"fs";import*as oe from"os";import*as p from"path";import{fileURLToPath as Yo}from"url";var z={};q(z,{NAME:()=>go,VERSION:()=>ho,up:()=>bo});import*as v from"fs";import*as V from"path";var ho=1,go="normalize-jobs-and-questions",yo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],So=50;function H(e){return v.existsSync(e)?JSON.parse(v.readFileSync(e,"utf-8")):null}function K(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{v.writeFileSync(n,t)}catch(r){try{v.unlinkSync(n)}catch{}throw r}try{v.renameSync(n,e)}catch(r){try{v.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function bo(e,o){let t=V.join(e,"jobs.json"),n=V.join(o,"scouted-jobs.json"),r=V.join(e,"application-questions.json"),s=H(t)||{},i=H(n)||{},a=0,l=[];for(let f of Object.keys(s)){if(!i[f])continue;let S=i[f],d=s[f];for(let g of yo)S[g]!=null&&d[g]==null&&(d[g]=S[g]);l.push(f),a++}a>0?(K(t,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=H(r);if(u&&Array.isArray(u.applications)){let f={},S=0;for(let d of u.applications){let g=d.jobId||"unknown";f[g]||(f[g]={applications:[]});let re=(d.questions||[]).map(E=>{let L={type:E.type||"input",question:E.question||"",answer:E.answer||""};return E.options&&(E.options.length<=So?L.options=E.options:(L.optionsOmitted=!0,S++)),E.page&&(L.page=E.page),E.wasPreFilled&&(L.wasPreFilled=!0),E.wasRetry&&(L.wasRetry=!0),L});f[g].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||re.length,questions:re})}K(r,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),S>0&&console.log(` Phase 2: Stripped bloated options from ${S} 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 f of l)delete i[f];K(n,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={};q(Q,{NAME:()=>vo,VERSION:()=>wo,up:()=>$o});import*as k from"fs";import*as ve from"path";var wo=2,vo="reset-unread-flags";function ko(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function Ao(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{k.writeFileSync(n,t)}catch(r){try{k.unlinkSync(n)}catch{}throw r}try{k.renameSync(n,e)}catch(r){try{k.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function $o(e){let o=ve.join(e,"conversations.json"),t=ko(o);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let r of Object.keys(t))t[r].unread===!0&&(t[r].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Ao(o,t),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var X={};q(X,{NAME:()=>jo,VERSION:()=>Eo,up:()=>To});import*as A from"fs";import*as ke from"path";var Eo=3,jo="recompute-last-message-by",Ro=new Set(["draft","confirmed","rejected","needs_review"]);function Oo(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Io(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{A.writeFileSync(n,t)}catch(r){try{A.unlinkSync(n)}catch{}throw r}try{A.renameSync(n,e)}catch(r){try{A.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function _o(e,o){if(!e||e.length===0)return"them";let t=e.filter(s=>!Ro.has(s.status));if(t.length===0)return"them";let n=t.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=n.length>0?n:[...t].reverse();for(let s of r){let i=s.sender;if(i===o)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function To(e){let o=ke.join(e,"conversations.json"),t=Oo(o);if(!t){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let n=process.env.LINKEDIN_NAME;if(!n||typeof n!="string"||!n.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,s=0,i=0;for(let a of Object.keys(t)){let l=t[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,s++);let u=Array.isArray(l.messages)?l.messages:[],f=_o(u,n),S=f==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==f&&i++,l.lastMessageBy=f,l.conversationStatus=S,r++}if(r===0){console.log(" No conversations to recompute.");return}Io(o,t),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Z={};q(Z,{NAME:()=>Co,VERSION:()=>Do,up:()=>Lo});import*as $ from"fs";import*as Ae from"path";var Do=4,Co="split-connection-timestamps",No=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function xo(e){if(!$.existsSync(e))return null;let o=$.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Fo(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{$.writeFileSync(n,t)}catch(r){try{$.unlinkSync(n)}catch{}throw r}try{$.renameSync(n,e)}catch(r){try{$.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Lo(e){let o=Ae.join(e,"people.json"),t=xo(o);if(!t||typeof t!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let n=0,r=0;for(let s of Object.keys(t)){let i=t[s];!i||typeof i!="object"||(r++,No.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,n++))}if(n===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Fo(o,t),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${n} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as b from"path";import{fileURLToPath as Po}from"url";var Mo=Po(import.meta.url),Uo=b.dirname(b.dirname(Mo)),J=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"market-research"):b.join(Uo,"market-research"),Yn=b.join(J,"scouted-jobs.json"),Gn=b.join(J,"discovered-people.json"),Hn=b.join(J,"visit-log.json"),Kn=b.join(J,"companies.json"),zn=b.join(J,"job-decisions.json");function $e(){Jo=null,Bo=null,qo=null,Vo=null,Wo=null}var Jo=null;var Bo=null;var qo=null;var Vo=null;var Wo=null;var Go=Yo(import.meta.url),Ho=p.dirname(Go),Ko=p.dirname(p.dirname(Ho));function zo(e){return e&&(e==="~"?oe.homedir():e.startsWith("~/")||e.startsWith("~\\")?p.join(oe.homedir(),e.slice(2)):e)}var j=process.env.DATA_DIR?p.resolve(zo(process.env.DATA_DIR)):Ko,x=p.join(j,"collected-profiles"),F=p.join(j,"market-research"),y=p.join(j,".schema-version"),Ee=[p.join(x,".schema-version"),p.join(F,".schema-version")],T=4,O=[{version:1,module:z},{version:2,module:Q},{version:3,module:X},{version:4,module:Z}];(function(){O.sort((n,r)=>n.version-r.version);let o=new Set;for(let n of O){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(o.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);o.add(n.version);let r=n.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let t=O.length?O[O.length-1].version:0;if(t!==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 n=0;n<O.length;n++){let r=n+1;if(O[n].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${n} but found v${O[n].version}`)}})();function Ie(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
7
7
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
8
- `),process.exit(1));try{l.mkdirSync(j,{recursive:!0})}catch(o){o.code!=="EEXIST"&&(console.error(`
8
+ `),process.exit(1));try{c.mkdirSync(j,{recursive:!0})}catch(o){o.code!=="EEXIST"&&(console.error(`
9
9
  [FATAL] Cannot create DATA_DIR (${j}): ${o.message}`),console.error(` Fix the path or permissions and try again.
10
- `),process.exit(1))}let e;try{e=l.statSync(j)}catch(o){console.error(`
10
+ `),process.exit(1))}let e;try{e=c.statSync(j)}catch(o){console.error(`
11
11
  [FATAL] DATA_DIR (${j}) is not accessible: ${o.message}
12
12
  `),process.exit(1)}e.isDirectory()||(console.error(`
13
13
  [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.
14
- `),process.exit(1));for(let o of[x,F]){let t;try{t=l.lstatSync(o)}catch(n){if(n.code==="ENOENT")continue;throw n}t.isSymbolicLink()&&(console.error(`
14
+ `),process.exit(1));for(let o of[x,F]){let t;try{t=c.lstatSync(o)}catch(n){if(n.code==="ENOENT")continue;throw n}t.isSymbolicLink()&&(console.error(`
15
15
  [FATAL] Data subdirectory is a symbolic link: ${o}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
16
- `),process.exit(1))}}var N=p.join(j,".migration-lock");function Qo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return l.writeFileSync(N,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let o;try{o=JSON.parse(l.readFileSync(N,"utf-8"))}catch{o=null}if(o&&Number.isInteger(o.pid)){let n=!1;try{process.kill(o.pid,0),n=!0}catch(i){i.code==="EPERM"&&(n=!0)}let r=24*60*60*1e3,s=1/0;if(o.startedAt){let i=Date.parse(o.startedAt);Number.isNaN(i)||(s=Date.now()-i)}n&&s<r&&(console.error(`
16
+ `),process.exit(1))}}var N=p.join(j,".migration-lock");function Qo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return c.writeFileSync(N,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let o;try{o=JSON.parse(c.readFileSync(N,"utf-8"))}catch{o=null}if(o&&Number.isInteger(o.pid)){let n=!1;try{process.kill(o.pid,0),n=!0}catch(i){i.code==="EPERM"&&(n=!0)}let r=24*60*60*1e3,s=1/0;if(o.startedAt){let i=Date.parse(o.startedAt);Number.isNaN(i)||(s=Date.now()-i)}n&&s<r&&(console.error(`
17
17
  [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${o.pid}`),console.error(` Started at: ${o.startedAt||"(unknown)"}`),console.error(` Lock file: ${N}
18
18
  `),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.
19
- `),process.exit(1)),n&&s>=r&&console.log(` Lock holder PID ${o.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${o?.pid??"?"} found \u2014 taking over.`);let t=N+".tmp";try{return l.writeFileSync(t,e),l.renameSync(t,N),!0}catch(n){try{l.unlinkSync(t)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function ne(){try{if(JSON.parse(l.readFileSync(N,"utf-8")).pid!==process.pid)return;l.unlinkSync(N)}catch{}}var je=!1;function Xo(){if(je)return;je=!0;let e=()=>{try{ne()}catch{}process.exit(1)};for(let o of["SIGINT","SIGTERM","SIGHUP"])try{process.on(o,e)}catch{}}function Zo(){if(l.existsSync(y))return;let e=[],o=[];for(let s of Ee)if(l.existsSync(s))try{e.push({file:s,schema:W(s)})}catch(i){o.push({file:s,err:i.message})}if(o.length>0){console.error(`
19
+ `),process.exit(1)),n&&s>=r&&console.log(` Lock holder PID ${o.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${o?.pid??"?"} found \u2014 taking over.`);let t=N+".tmp";try{return c.writeFileSync(t,e),c.renameSync(t,N),!0}catch(n){try{c.unlinkSync(t)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function ne(){try{if(JSON.parse(c.readFileSync(N,"utf-8")).pid!==process.pid)return;c.unlinkSync(N)}catch{}}var je=!1;function Xo(){if(je)return;je=!0;let e=()=>{try{ne()}catch{}process.exit(1)};for(let o of["SIGINT","SIGTERM","SIGHUP"])try{process.on(o,e)}catch{}}function Zo(){if(c.existsSync(y))return;let e=[],o=[];for(let s of Ee)if(c.existsSync(s))try{e.push({file:s,schema:W(s)})}catch(i){o.push({file:s,err:i.message})}if(o.length>0){console.error(`
20
20
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of o)console.error(` ${s.file}: ${s.err}`);console.error(`
21
21
  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.
22
22
  `),process.exit(1)}if(e.length===0)return;let t=e.map(s=>s.schema.version);if(new Set(t).size>1){console.error(`
23
23
  [FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
24
- `),process.exit(1)}let n=e[0].schema,r=y+".tmp";try{l.writeFileSync(r,JSON.stringify(n,null,2)),l.renameSync(r,y)}catch(s){try{l.unlinkSync(r)}catch{}throw s}for(let s of Ee)if(l.existsSync(s))try{l.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${y}`)}function en(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let o=Number(e.version);return!Number.isFinite(o)||o<0||!Number.isInteger(o)?null:(e.version=o,Array.isArray(e.migrations)||(e.migrations=[]),e)}function W(e){let o=l.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Re(){if(Zo(),!l.existsSync(y))return{version:0,migrations:[]};let e;try{e=W(y)}catch(t){if(t.code==="ENOENT")return{version:0,migrations:[]};console.error(`
24
+ `),process.exit(1)}let n=e[0].schema,r=y+".tmp";try{c.writeFileSync(r,JSON.stringify(n,null,2)),c.renameSync(r,y)}catch(s){try{c.unlinkSync(r)}catch{}throw s}for(let s of Ee)if(c.existsSync(s))try{c.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${y}`)}function en(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let o=Number(e.version);return!Number.isFinite(o)||o<0||!Number.isInteger(o)?null:(e.version=o,Array.isArray(e.migrations)||(e.migrations=[]),e)}function W(e){let o=c.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Re(){if(Zo(),!c.existsSync(y))return{version:0,migrations:[]};let e;try{e=W(y)}catch(t){if(t.code==="ENOENT")return{version:0,migrations:[]};console.error(`
25
25
  [FATAL] ${y} 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.
26
26
  `),process.exit(1)}let o=en(e);return o===null&&(console.error(`
27
27
  [FATAL] ${y} 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.
28
- `),process.exit(1)),o}function Te(e){try{l.chmodSync(e,384)}catch{}}function on(e){if(Ie(),l.existsSync(y))try{if(l.lstatSync(y).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${y}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(t){if(t.message?.includes("symbolic link"))throw t}let o=y+".tmp";try{l.writeFileSync(o,JSON.stringify(e,null,2)),Te(o),l.renameSync(o,y)}catch(t){try{l.unlinkSync(o)}catch{}throw t}}function Oe(e,o){if(!l.existsSync(e))return;let t=`.pre-v${String(o).padStart(3,"0")}.backup`,n=l.readdirSync(e).filter(a=>{let c=a.toLowerCase();if(c.includes(".backup")||c===".schema-version"||c.endsWith(".tmp"))return!1;try{return l.statSync(p.join(e,a)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let a of n){let c=p.join(e,a),u=p.join(e,a+t);if(l.existsSync(u)){s++;continue}try{De(c,u),r++}catch(f){i.push({file:a,err:f.message})}}if(i.length>0){let a=new Error(`Failed to back up ${i.length} file(s) in ${p.basename(e)}/: `+i.map(c=>`${c.file} (${c.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(r>0||s>0){let a=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${p.basename(e)}/ (${t})${a}`)}}var ee=!1;async function _e(){if(ee)return;Ie(),ln();let o=Re().version;if(o===_){ee=!0;return}Xo(),Qo(),process.on("exit",ne),o>_&&(console.error(`
29
- [FATAL] Your data schema is at v${o}, but this plugin build only understands up to v${_}.`),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.
30
- `),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${_}.
28
+ `),process.exit(1)),o}function _e(e){try{c.chmodSync(e,384)}catch{}}function on(e){if(Ie(),c.existsSync(y))try{if(c.lstatSync(y).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${y}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(t){if(t.message?.includes("symbolic link"))throw t}let o=y+".tmp";try{c.writeFileSync(o,JSON.stringify(e,null,2)),_e(o),c.renameSync(o,y)}catch(t){try{c.unlinkSync(o)}catch{}throw t}}function Oe(e,o){if(!c.existsSync(e))return;let t=`.pre-v${String(o).padStart(3,"0")}.backup`,n=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(p.join(e,a)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let a of n){let l=p.join(e,a),u=p.join(e,a+t);if(c.existsSync(u)){s++;continue}try{De(l,u),r++}catch(f){i.push({file:a,err:f.message})}}if(i.length>0){let a=new Error(`Failed to back up ${i.length} file(s) in ${p.basename(e)}/: `+i.map(l=>`${l.file} (${l.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(r>0||s>0){let a=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${p.basename(e)}/ (${t})${a}`)}}var ee=!1;async function Te(){if(ee)return;Ie(),ln();let o=Re().version;if(o===T){ee=!0;return}Xo(),Qo(),process.on("exit",ne),o>T&&(console.error(`
29
+ [FATAL] Your data schema is at v${o}, 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.
30
+ `),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}.
31
31
  `),process.exit(1)),console.log(`
32
- \u{1F4E6} Schema migration: v${o} \u2192 v${_}`);let t=cn();if(!t.ok){console.error(`
32
+ \u{1F4E6} Schema migration: v${o} \u2192 v${T}`);let t=cn();if(!t.ok){console.error(`
33
33
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of t.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
34
34
  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'.
35
35
  `),process.exit(1)}let n=O.filter(r=>r.version>o);for(let r of n){console.log(`
36
- Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{Oe(x,r.version),Oe(F,r.version)}catch(c){console.error(`
37
- [FATAL] Pre-migration backup failed for ${s}: ${c.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
38
- `),process.exit(1)}let a=r.module;try{await a.up(x,F)}catch(c){console.error(`
39
- [FATAL] Migration ${s} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let u=an(i);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${o}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
36
+ Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{Oe(x,r.version),Oe(F,r.version)}catch(l){console.error(`
37
+ [FATAL] Pre-migration backup failed for ${s}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
38
+ `),process.exit(1)}let a=r.module;try{await a.up(x,F)}catch(l){console.error(`
39
+ [FATAL] Migration ${s} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let u=an(i);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${o}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
40
40
  `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
41
41
  `))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
42
- `)}process.exit(1)}try{let c=new Date().toISOString(),u={version:r.version,name:a.NAME||s,appliedAt:c},f=Re();f.version=r.version,f.migratedAt=c,f.migrations=f.migrations||[],f.migrations.push(u),on(f)}catch(c){console.error(`
43
- [FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${c.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${o}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
42
+ `)}process.exit(1)}try{let l=new Date().toISOString(),u={version:r.version,name:a.NAME||s,appliedAt:l},f=Re();f.version=r.version,f.migratedAt=l,f.migrations=f.migrations||[],f.migrations.push(u),on(f)}catch(l){console.error(`
43
+ [FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${o}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
44
44
  `),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{ge()}catch{}try{$e()}catch{}ee=!0,ne(),console.log(`
45
- \u2713 Schema is now at v${_}
46
- `)}var nn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function tn(e){let o=e.toLowerCase();return nn.some(t=>t.test(o))}var rn=6e4;function sn(){let e=Date.now(),o=[];for(let t of[j,x,F]){if(!l.existsSync(t))continue;let n;try{n=l.readdirSync(t)}catch{continue}for(let r of n){if(!tn(r))continue;let s=p.join(t,r);try{let i=l.statSync(s);if(!i.isFile()||e-i.mtimeMs<rn)continue;o.push({dir:t,file:r,fullPath:s})}catch{}}}return o}function ln({verbose:e=!1}={}){let o=sn();if(o.length===0)return e&&console.log(" No orphan .tmp files found."),0;let t=0;for(let n of o)try{l.unlinkSync(n.fullPath),t++,e&&console.log(` Removed orphan: ${p.basename(n.dir)}/${n.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${n.fullPath}: ${r.message}`)}return!e&&t>0&&console.log(` Cleaned up ${t} orphan .tmp file(s) from previous run.`),t}function cn(){let e=[];for(let o of[x,F]){if(!l.existsSync(o))continue;let t=l.readdirSync(o).filter(n=>{let r=n.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let n of t){let r=p.join(o,n);try{W(r)}catch(s){e.push({dir:p.basename(o),file:n,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function an(e){let o=[],t=[];for(let s of[x,F]){if(!l.existsSync(s))continue;let i=l.readdirSync(s).filter(a=>a.endsWith(e));for(let a of i){let c=p.join(s,a),u=a.slice(0,-e.length),f=p.join(s,u);try{u.toLowerCase().endsWith(".json")?W(c):l.accessSync(c,l.constants.R_OK),o.push({backupPath:c,originalPath:f,fileName:a,dir:s})}catch(S){t.push(`${p.basename(s)}/${a}: ${S.message}`)}}}if(t.length>0)return{ok:!1,error:t.join("; "),restored:0};let n=0,r=[];for(let{backupPath:s,originalPath:i,fileName:a,dir:c}of o)try{De(s,i),n++}catch(u){r.push(`${p.basename(c)}/${a}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:n}:{ok:!0,restored:n}}function De(e,o){let t=o+".tmp";try{l.copyFileSync(e,t),Te(t)}catch(n){try{l.unlinkSync(t)}catch{}throw n}try{l.renameSync(t,o)}catch(n){try{l.unlinkSync(t)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${o} (${n.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=n.code,r}throw n}}await _e();var B=process.argv.slice(2),te=new Set((B.find(e=>e.startsWith("--skip="))?.split("=")[1]||"").split(",").filter(Boolean)),Ce=new Set((B.find(e=>e.startsWith("--only="))?.split("=")[1]||"").split(",").filter(Boolean)),Fe=B.includes("--dry-run"),Le=B.includes("--jobs"),Me=B.includes("--comms"),Ne=["apply-queue","apply","funnel","scout","visit"],xe=["sync","today"],Pe=Le?Ne:Me?xe:[...Ne,...xe];function D(e){return Ce.size>0?Ce.has(e):!te.has(e)&&Pe.includes(e)}function M(e,o,t=[],{optional:n=!1}={}){if(console.log(`
47
- ${"\u2550".repeat(50)}`),console.log(` STEP: ${e}`),console.log("\u2550".repeat(50)),Fe)return console.log(` [DRY RUN] Would run: node ${o} ${t.join(" ")}`),!0;try{return un("node",[o,...t],{stdio:"inherit",timeout:18e6}),console.log(` \u2713 ${e} completed`),!0}catch(r){return n?(console.log(` \u26A0 ${e} failed (optional): ${r.message?.slice(0,80)}`),!1):(console.error(` \u2717 ${e} failed: ${r.message?.slice(0,80)}`),!1)}}async function fn(){let e=Le?"jobs":Me?"comms":"full";console.log(`
48
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(` DAILY PIPELINE (${e})`),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let o=Pe.filter(D);console.log(` Steps: ${o.join(" \u2192 ")}`),te.size>0&&console.log(` Skipping: ${[...te].join(", ")}`),Fe&&console.log(" [DRY RUN MODE]");let t=ue("daily",e),n={};if(D("apply-queue")&&(n["apply-queue"]=M("Apply Queue (scored jobs)","applyQueue.mjs",["--max=50","--min-score=50"],{optional:!0})),D("apply")){let s=we();n.apply=M("Apply from Search","run.mjs",[],{optional:!0})}if(D("funnel")&&!D("apply")){let s=be();s.allowed?n.funnel=M("Connection Funnel","funnelRunner.mjs",["--max=20"],{optional:!0}):(console.log(`
49
- \u26A0 Funnel skipped: ${s.reason}`),n.funnel="skipped_quota")}D("scout")&&(n.scout=M("Scout Jobs for Tomorrow","scout.mjs",["--max=300","--verbose"],{optional:!0})),D("sync")&&(n.sync=M("Sync Inbox","syncAll.mjs")),D("today")&&(n.today=M("Daily Report","syncAll.mjs",["--today"])),console.log(`
45
+ \u2713 Schema is now at v${T}
46
+ `)}var nn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function tn(e){let o=e.toLowerCase();return nn.some(t=>t.test(o))}var rn=6e4;function sn(){let e=Date.now(),o=[];for(let t of[j,x,F]){if(!c.existsSync(t))continue;let n;try{n=c.readdirSync(t)}catch{continue}for(let r of n){if(!tn(r))continue;let s=p.join(t,r);try{let i=c.statSync(s);if(!i.isFile()||e-i.mtimeMs<rn)continue;o.push({dir:t,file:r,fullPath:s})}catch{}}}return o}function ln({verbose:e=!1}={}){let o=sn();if(o.length===0)return e&&console.log(" No orphan .tmp files found."),0;let t=0;for(let n of o)try{c.unlinkSync(n.fullPath),t++,e&&console.log(` Removed orphan: ${p.basename(n.dir)}/${n.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${n.fullPath}: ${r.message}`)}return!e&&t>0&&console.log(` Cleaned up ${t} orphan .tmp file(s) from previous run.`),t}function cn(){let e=[];for(let o of[x,F]){if(!c.existsSync(o))continue;let t=c.readdirSync(o).filter(n=>{let r=n.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let n of t){let r=p.join(o,n);try{W(r)}catch(s){e.push({dir:p.basename(o),file:n,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function an(e){let o=[],t=[];for(let s of[x,F]){if(!c.existsSync(s))continue;let i=c.readdirSync(s).filter(a=>a.endsWith(e));for(let a of i){let l=p.join(s,a),u=a.slice(0,-e.length),f=p.join(s,u);try{u.toLowerCase().endsWith(".json")?W(l):c.accessSync(l,c.constants.R_OK),o.push({backupPath:l,originalPath:f,fileName:a,dir:s})}catch(S){t.push(`${p.basename(s)}/${a}: ${S.message}`)}}}if(t.length>0)return{ok:!1,error:t.join("; "),restored:0};let n=0,r=[];for(let{backupPath:s,originalPath:i,fileName:a,dir:l}of o)try{De(s,i),n++}catch(u){r.push(`${p.basename(l)}/${a}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:n}:{ok:!0,restored:n}}function De(e,o){let t=o+".tmp";try{c.copyFileSync(e,t),_e(t)}catch(n){try{c.unlinkSync(t)}catch{}throw n}try{c.renameSync(t,o)}catch(n){try{c.unlinkSync(t)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${o} (${n.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=n.code,r}throw n}}await Te();var B=process.argv.slice(2),te=new Set((B.find(e=>e.startsWith("--skip="))?.split("=")[1]||"").split(",").filter(Boolean)),Ce=new Set((B.find(e=>e.startsWith("--only="))?.split("=")[1]||"").split(",").filter(Boolean)),Fe=B.includes("--dry-run"),Le=B.includes("--jobs"),Pe=B.includes("--comms"),Ne=["apply-queue","apply","funnel","scout","visit"],xe=["sync","today"],Me=Le?Ne:Pe?xe:[...Ne,...xe];function D(e){return Ce.size>0?Ce.has(e):!te.has(e)&&Me.includes(e)}function P(e,o,t=[],{optional:n=!1}={}){if(console.log(`
47
+ ${"\u2550".repeat(50)}`),console.log(` STEP: ${e}`),console.log("\u2550".repeat(50)),Fe)return console.log(` [DRY RUN] Would run: node ${o} ${t.join(" ")}`),!0;try{return un("node",[o,...t],{stdio:"inherit",timeout:18e6}),console.log(` \u2713 ${e} completed`),!0}catch(r){return n?(console.log(` \u26A0 ${e} failed (optional): ${r.message?.slice(0,80)}`),!1):(console.error(` \u2717 ${e} failed: ${r.message?.slice(0,80)}`),!1)}}async function fn(){let e=Le?"jobs":Pe?"comms":"full";console.log(`
48
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(` DAILY PIPELINE (${e})`),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let o=Me.filter(D);console.log(` Steps: ${o.join(" \u2192 ")}`),te.size>0&&console.log(` Skipping: ${[...te].join(", ")}`),Fe&&console.log(" [DRY RUN MODE]");let t=ue("daily",e),n={};if(D("apply-queue")&&(n["apply-queue"]=P("Apply Queue (scored jobs)","applyQueue.mjs",["--max=50","--min-score=50"],{optional:!0})),D("apply")){let s=we();n.apply=P("Apply from Search","run.mjs",[],{optional:!0})}if(D("funnel")&&!D("apply")){let s=be();s.allowed?n.funnel=P("Connection Funnel","funnelRunner.mjs",["--max=20"],{optional:!0}):(console.log(`
49
+ \u26A0 Funnel skipped: ${s.reason}`),n.funnel="skipped_quota")}D("scout")&&(n.scout=P("Scout Jobs for Tomorrow","scout.mjs",["--max=300","--verbose"],{optional:!0})),D("sync")&&(n.sync=P("Sync Inbox","syncAll.mjs")),D("today")&&(n.today=P("Daily Report","syncAll.mjs",["--today"])),console.log(`
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(" PIPELINE COMPLETE"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let[s,i]of Object.entries(n))console.log(` ${i===!0?"\u2713":i===!1?"\u2717":"\u26A0"} ${s}: ${i===!0?"success":i===!1?"failed":i}`);console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
51
51
  `);let r=Object.values(n).some(s=>s===!1);fe(t,r?"partial":"success",n)}fn().catch(e=>{console.error("Daily pipeline failed:",e),process.exit(1)});
@@ -1,8 +1,8 @@
1
- var Pn=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var pe=(e,t)=>{for(var n in t)Pn(e,n,{get:t[n],enumerable:!0})};import R from"fs";import q from"path";function Oe(){let e=process.env.ILML_SCOPE_DIR;return e?q.join(e,"plugins-state","linkedin","cookies.json"):Fn}function Mn(){let e=Oe(),t=q.dirname(e);return t&&t!=="."&&!R.existsSync(t)&&R.mkdirSync(t,{recursive:!0}),e}function St(e){let t=Mn();return R.writeFileSync(t,JSON.stringify(e)),t}function vt(){let e=Oe();if(!R.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=R.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function kt(){return R.existsSync(Oe())}function Un(){let e=process.env.ILML_SCOPE_DIR;return e?q.join(e,"plugins-state","linkedin"):"."}function Ct(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function qn(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Ct(t[1]):"default"}function xt(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return R.existsSync(t)||R.mkdirSync(t,{recursive:!0}),q.resolve(t);let n=Ct(e||qn()),o=q.join(Un(),"chrome-profile",n);return R.existsSync(o)||R.mkdirSync(o,{recursive:!0}),q.resolve(o)}function Et(e){return!R.existsSync(q.join(e,At))}function _t(e){try{R.writeFileSync(q.join(e,At),new Date().toISOString())}catch{}}function $t(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{R.rmSync(q.join(e,n),{force:!0}),t++}catch{}return t}var Fn,At,Ae=W(()=>{Fn="cookies.json";At=".ilml-seeded"});async function k(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function Bn(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let s=Date.now();for(;Date.now()-s<n;){try{if(await e.evaluate(l=>!!document.querySelector(l),t)){let l=Date.now()-s;return l>6e3&&console.log(` (waited ${Math.round(l/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(i=>setTimeout(i,o))}return!1}function Hn(e){return Rt.test(e||"")}async function Vn(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),r=o?t:Math.min(t,45e3),s=Date.now(),i=!1;for(;Date.now()-s<r;){let a="wait";try{a=await e.evaluate(u=>!new RegExp(u).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",Rt.source)}catch{}if(a==="in"){try{let u=await e.cookies();if(Array.isArray(u)&&u.some(m=>m.name==="li_at")){let m=St(u);console.log(` \u2713 Session recovered \u2014 re-saved ${u.length} cookies (${m}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(u){console.log(` \u2713 Session recovered (cookie re-save skipped: ${u.message}).`)}return!0}if(a==="creds"){if(!o){let u=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw u.code="SESSION_EXPIRED",u}i||(i=!0,console.log(`
1
+ var Pn=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var pe=(e,t)=>{for(var n in t)Pn(e,n,{get:t[n],enumerable:!0})};import R from"fs";import q from"path";function Oe(){let e=process.env.ILML_SCOPE_DIR;return e?q.join(e,"plugins-state","linkedin","cookies.json"):Fn}function Mn(){let e=Oe(),t=q.dirname(e);return t&&t!=="."&&!R.existsSync(t)&&R.mkdirSync(t,{recursive:!0}),e}function St(e){let t=Mn();return R.writeFileSync(t,JSON.stringify(e)),t}function vt(){let e=Oe();if(!R.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=R.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function kt(){return R.existsSync(Oe())}function Un(){let e=process.env.ILML_SCOPE_DIR;return e?q.join(e,"plugins-state","linkedin"):"."}function Ct(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function qn(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Ct(t[1]):"default"}function xt(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return R.existsSync(t)||R.mkdirSync(t,{recursive:!0}),q.resolve(t);let n=Ct(e||qn()),o=q.join(Un(),"chrome-profile",n);return R.existsSync(o)||R.mkdirSync(o,{recursive:!0}),q.resolve(o)}function At(e){return!R.existsSync(q.join(e,Et))}function _t(e){try{R.writeFileSync(q.join(e,Et),new Date().toISOString())}catch{}}function $t(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{R.rmSync(q.join(e,n),{force:!0}),t++}catch{}return t}var Fn,Et,Ee=W(()=>{Fn="cookies.json";Et=".ilml-seeded"});async function k(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function Bn(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let s=Date.now();for(;Date.now()-s<n;){try{if(await e.evaluate(l=>!!document.querySelector(l),t)){let l=Date.now()-s;return l>6e3&&console.log(` (waited ${Math.round(l/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(i=>setTimeout(i,o))}return!1}function Hn(e){return Rt.test(e||"")}async function Vn(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),r=o?t:Math.min(t,45e3),s=Date.now(),i=!1;for(;Date.now()-s<r;){let a="wait";try{a=await e.evaluate(u=>!new RegExp(u).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",Rt.source)}catch{}if(a==="in"){try{let u=await e.cookies();if(Array.isArray(u)&&u.some(m=>m.name==="li_at")){let m=St(u);console.log(` \u2713 Session recovered \u2014 re-saved ${u.length} cookies (${m}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(u){console.log(` \u2713 Session recovered (cookie re-save skipped: ${u.message}).`)}return!0}if(a==="creds"){if(!o){let u=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw u.code="SESSION_EXPIRED",u}i||(i=!0,console.log(`
2
2
  \u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
3
- `))}await new Promise(u=>setTimeout(u,2500))}let l=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}async function It(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await Bn(e,t,{timeout:o,label:n});if(!r&&Hn(e.url())){let s=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw s.code="SESSION_EXPIRED",s}return r}async function ue(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:s=6e4,autoRecover:i=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:s});try{return await It(e,{readySelector:n,label:o,timeout:r})}catch(l){if(i&&l.code==="SESSION_EXPIRED"){await Vn(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:s})}catch{}return await It(e,{readySelector:n,label:o,timeout:r})}throw l}}async function Tt(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",s=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),i=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),l=r.includes("Get hired faster")||r.includes("Get hired 2x");if(s||i||l){let a=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(a)return a.click(),{dismissed:!0,matched:r.substring(0,80)};let u=o.querySelectorAll("button");for(let c of u){let m=c.innerText?.trim().toLowerCase()||"",f=c.getAttribute("aria-label")?.toLowerCase()||"";if(m==="not now"||m==="no thanks"||m==="dismiss"||f.includes("dismiss"))return c.click(),{dismissed:!0,matched:r.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 Rt,he=W(()=>{Ae();Rt=/\/authwall|\/login|\/checkpoint|\/uas\/login/});function Wn(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function Ot(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let n=new URLSearchParams;n.set("keywords",t);let o=(e.JOB_SEARCH_LOCATION||"").trim();o&&n.set("location",o);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&n.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&n.set("distance",String(s)),Dt(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),Dt(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let i=Wn(e.JOB_SEARCH_COMPANY_IDS);i.length&&n.set("f_C",i.join(","));let l=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();l&&n.set("f_TPR",Jn[l]||l),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let a="https://www.linkedin.com/jobs/search/?"+n.toString(),u=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return u&&(a+="&"+u),a}var Jn,Dt,jt=W(()=>{Jn={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},Dt=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim())});import{getPluginConfig as Gn}from"@ilivemylife/graph-sdk";var Yn,Nt,Kn,te,ns,zn,je=W(async()=>{jt();Yn=await Gn();for(let[e,t]of Object.entries(Yn))process.env[e]===void 0&&(process.env[e]=t);Nt=Ot(process.env);Nt&&(process.env.LINKEDIN_SEARCH_URL=Nt);Kn=process.env.LINKEDIN_NAME,te=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ns=Object.freeze(new Set([te.DRAFT,te.CONFIRMED,te.NEEDS_REVIEW])),zn=Object.freeze(new Set([te.DRAFT,te.CONFIRMED,te.REJECTED,te.NEEDS_REVIEW]))});import"dotenv/config";import*as C from"fs";import*as A from"path";import{fileURLToPath as io}from"url";function Qt(){de=null,co=null,uo=null,fe=null,fo=null,mo=null}function Me(){C.existsSync(B)||C.mkdirSync(B,{recursive:!0})}function Ue(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";C.writeFileSync(o,n);for(let r=0;r<3;r++)try{C.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function qe(e,t){if(!C.existsSync(e))return null;try{let n=JSON.parse(C.readFileSync(e,"utf-8"));try{C.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${A.resolve(e)}`);let o=e+".backup";if(C.existsSync(o))try{let r=JSON.parse(C.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{C.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{C.copyFileSync(e,e+".corrupted")}catch{}return null}}function po(){return new Date().toISOString().split("T")[0]}function ne(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Wt(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Xt(e,t,n=null){if(!t||e[t])return t;let o=ne(t);if(!o)return t;let r=null;for(let[s,i]of Object.entries(e)){if(ne(i.profileUrl||s)===o)return s;!r&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}if(r){let s=Wt(n),i=Wt(e[r].name);if(s&&i&&s===i)return r}return t}function yo(){C.existsSync(Fe)||C.mkdirSync(Fe,{recursive:!0})}function Zt(e){let t=ne(e);return t?A.join(Fe,`${t}.json`):null}function wo(e){let t=Zt(e);return t?qe(t,`profile-history/${ne(e)}.json`)||[]:[]}function bo(e,t){let n=Zt(e);if(!n)return;yo();let o=wo(e);o.unshift(t);try{Ue(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${ne(e)}: ${r.message}`)}}function Gt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Yt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function So(e,t){if(!e)return[];let n=[];for(let o of go){let r=e[o],s=t[o];Gt(r)||Gt(s)||Yt(r)!==Yt(s)&&n.push(o)}return n}function vo(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function G(){return de||(Me(),de=qe(Pe,"people.json")||{},de)}function en(e){Me(),de=e;try{Ue(Pe,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${A.resolve(Pe)}`)}}function Be(){return fe||(Me(),fe=qe(Kt,"conversations.json")||{},ko(fe),fe)}function ko(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let r=(n.messages||[]).find(s=>s.status==="draft");r&&n.draftStatus&&n.draftStatus!=="pending"&&(r.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{Ue(Kt,e)}catch{}}}function He(e,t={}){if(!e)return null;let n=G(),o=po(),r=new Date().toISOString(),s=Xt(n,e,t.name),i=n[s];if(i){let l=So(i,t);l.length>0&&(bo(s,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:l,snapshot:vo(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let a of ho)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(i[a])&&i[a].length>0)continue;i[a]=t[a]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[s]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return en(n),n[s]}function Ve(e,t,n={}){if(n.dryRun||!e||!t)return;let o=ne(t);if(!o)return;let r=G(),s=Xt(r,e),i=r[s];if(!i)return;let l=ne(i.profileUrl||s);o!==l&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(o)||(i.aliases.push(o),i.lastUpdated=new Date().toISOString(),en(r)))}var lo,ao,B,Pe,Cs,xs,Kt,As,Es,Fe,zt,_s,$s,de,co,uo,fe,fo,mo,ho,go,we=W(async()=>{await je();lo=io(import.meta.url),ao=A.dirname(A.dirname(lo)),B=process.env.DATA_DIR?A.resolve(process.env.DATA_DIR,"collected-profiles"):A.join(ao,"collected-profiles"),Pe=A.join(B,"people.json"),Cs=A.join(B,"jobs.json"),xs=A.join(B,"quota.json"),Kt=A.join(B,"conversations.json"),As=A.join(B,"sync-state.json"),Es=A.join(B,"application-questions.json"),Fe=A.join(B,"profile-history"),zt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},_s=zt(process.env.CONNECT_MAX_DAILY,20),$s=zt(process.env.CONNECT_MAX_WEEKLY,100),de=null,co=null,uo=null,fe=null,fo=null,mo=null;ho=["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"],go=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var tn={};pe(tn,{extractCertificationsFromDetails:()=>_o,extractEducationFromDetails:()=>Ao,extractExperienceFromDetails:()=>Co,extractFeaturedFromDetails:()=>xo,extractRecommendationsFromDetails:()=>$o,extractSkillsFromDetails:()=>Eo});async function Co(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await ue(e,n,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await k(1e3);let o=e.url();if(!o.toLowerCase().includes("/details/experience/"))throw new Error(`Section /details/experience/ not available on profile (landed on ${o})`);for(let s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(900);await k(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let i of document.querySelectorAll("button"))if(/^Load more$/i.test((i.textContent||"").trim()))return i.click(),!0;return!1});)r++,await k(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function i(c){let m=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(w=>w.tagName==="DIV");if(p.length<3)continue;let v=p.filter(w=>(w.textContent||"").trim().length>50);v.length<3||(f.textContent||"").length<500||m.push({el:f,count:v.length,totalText:(f.textContent||"").length})}return m.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),m[0]?.el}let l=i(s);if(!l)return[];let a=Array.from(l.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function u(c){let m=c[0]||null,f=null,p=null;if(c[1]){let b=c[1].split("\xB7").map($=>$.trim());f=b[0]||null,b[1]&&(p=b[1])}let v=c.findIndex(b=>/(\d{4}|present)/i.test(b)&&/(-|–|—)/i.test(b)&&b.length<80),w=null,E=null;if(v>=0){let b=c[v].split("\xB7").map($=>$.trim());w=b[0]||null,b[1]&&(E=b[1])}let Q=null,X=-1;if(v>=0&&c[v+1]){let b=c[v+1],$=/^[>*\-•]|^&gt;/.test(b),ae=/https?:\/\//.test(b),ce=/\d{4}/.test(b),I=/,/.test(b)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(b);!$&&!ae&&!ce&&b.length<100&&I&&(Q=b,X=v+1)}let Re=null,x=-1,Z=c[c.length-1];if(Z&&/and\s+\+\d+\s+skills?$/i.test(Z)){x=c.length-1;let b=Z.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);b&&(Re={listed:b[1].split(",").map($=>$.trim()),additional:parseInt(b[2],10)})}let ee=new Set([0,1,v,X,x].filter(b=>b>=0)),V=c.filter((b,$)=>!ee.has($)),D=V.length>0?V.join(`
3
+ `))}await new Promise(u=>setTimeout(u,2500))}let l=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}async function It(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await Bn(e,t,{timeout:o,label:n});if(!r&&Hn(e.url())){let s=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw s.code="SESSION_EXPIRED",s}return r}async function ue(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:s=6e4,autoRecover:i=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:s});try{return await It(e,{readySelector:n,label:o,timeout:r})}catch(l){if(i&&l.code==="SESSION_EXPIRED"){await Vn(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:s})}catch{}return await It(e,{readySelector:n,label:o,timeout:r})}throw l}}async function Tt(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",s=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),i=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),l=r.includes("Get hired faster")||r.includes("Get hired 2x");if(s||i||l){let a=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(a)return a.click(),{dismissed:!0,matched:r.substring(0,80)};let u=o.querySelectorAll("button");for(let c of u){let m=c.innerText?.trim().toLowerCase()||"",f=c.getAttribute("aria-label")?.toLowerCase()||"";if(m==="not now"||m==="no thanks"||m==="dismiss"||f.includes("dismiss"))return c.click(),{dismissed:!0,matched:r.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 Rt,he=W(()=>{Ee();Rt=/\/authwall|\/login|\/checkpoint|\/uas\/login/});function Wn(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function Ot(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let n=new URLSearchParams;n.set("keywords",t);let o=(e.JOB_SEARCH_LOCATION||"").trim();o&&n.set("location",o);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&n.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&n.set("distance",String(s)),Dt(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),Dt(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let i=Wn(e.JOB_SEARCH_COMPANY_IDS);i.length&&n.set("f_C",i.join(","));let l=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();l&&n.set("f_TPR",Jn[l]||l),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let a="https://www.linkedin.com/jobs/search/?"+n.toString(),u=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return u&&(a+="&"+u),a}var Jn,Dt,Nt=W(()=>{Jn={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},Dt=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim())});import{getPluginConfig as Gn}from"@ilivemylife/graph-sdk";var Yn,jt,Kn,te,ns,zn,Ne=W(async()=>{Nt();Yn=await Gn();for(let[e,t]of Object.entries(Yn))process.env[e]===void 0&&(process.env[e]=t);jt=Ot(process.env);jt&&(process.env.LINKEDIN_SEARCH_URL=jt);Kn=process.env.LINKEDIN_NAME,te=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ns=Object.freeze(new Set([te.DRAFT,te.CONFIRMED,te.NEEDS_REVIEW])),zn=Object.freeze(new Set([te.DRAFT,te.CONFIRMED,te.REJECTED,te.NEEDS_REVIEW]))});import"dotenv/config";import*as C from"fs";import*as E from"path";import{fileURLToPath as io}from"url";function Qt(){de=null,co=null,uo=null,fe=null,fo=null,mo=null}function Me(){C.existsSync(B)||C.mkdirSync(B,{recursive:!0})}function Ue(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";C.writeFileSync(o,n);for(let r=0;r<3;r++)try{C.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function qe(e,t){if(!C.existsSync(e))return null;try{let n=JSON.parse(C.readFileSync(e,"utf-8"));try{C.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${E.resolve(e)}`);let o=e+".backup";if(C.existsSync(o))try{let r=JSON.parse(C.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{C.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{C.copyFileSync(e,e+".corrupted")}catch{}return null}}function po(){return new Date().toISOString().split("T")[0]}function ne(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Wt(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Xt(e,t,n=null){if(!t||e[t])return t;let o=ne(t);if(!o)return t;let r=null;for(let[s,i]of Object.entries(e)){if(ne(i.profileUrl||s)===o)return s;!r&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}if(r){let s=Wt(n),i=Wt(e[r].name);if(s&&i&&s===i)return r}return t}function yo(){C.existsSync(Fe)||C.mkdirSync(Fe,{recursive:!0})}function Zt(e){let t=ne(e);return t?E.join(Fe,`${t}.json`):null}function wo(e){let t=Zt(e);return t?qe(t,`profile-history/${ne(e)}.json`)||[]:[]}function bo(e,t){let n=Zt(e);if(!n)return;yo();let o=wo(e);o.unshift(t);try{Ue(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${ne(e)}: ${r.message}`)}}function Gt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Yt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function So(e,t){if(!e)return[];let n=[];for(let o of go){let r=e[o],s=t[o];Gt(r)||Gt(s)||Yt(r)!==Yt(s)&&n.push(o)}return n}function vo(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function G(){return de||(Me(),de=qe(Pe,"people.json")||{},de)}function en(e){Me(),de=e;try{Ue(Pe,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${E.resolve(Pe)}`)}}function Be(){return fe||(Me(),fe=qe(Kt,"conversations.json")||{},ko(fe),fe)}function ko(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let r=(n.messages||[]).find(s=>s.status==="draft");r&&n.draftStatus&&n.draftStatus!=="pending"&&(r.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{Ue(Kt,e)}catch{}}}function He(e,t={}){if(!e)return null;let n=G(),o=po(),r=new Date().toISOString(),s=Xt(n,e,t.name),i=n[s];if(i){let l=So(i,t);l.length>0&&(bo(s,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:l,snapshot:vo(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let a of ho)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(i[a])&&i[a].length>0)continue;i[a]=t[a]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[s]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return en(n),n[s]}function Ve(e,t,n={}){if(n.dryRun||!e||!t)return;let o=ne(t);if(!o)return;let r=G(),s=Xt(r,e),i=r[s];if(!i)return;let l=ne(i.profileUrl||s);o!==l&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(o)||(i.aliases.push(o),i.lastUpdated=new Date().toISOString(),en(r)))}var lo,ao,B,Pe,Cs,xs,Kt,Es,As,Fe,zt,_s,$s,de,co,uo,fe,fo,mo,ho,go,we=W(async()=>{await Ne();lo=io(import.meta.url),ao=E.dirname(E.dirname(lo)),B=process.env.DATA_DIR?E.resolve(process.env.DATA_DIR,"collected-profiles"):E.join(ao,"collected-profiles"),Pe=E.join(B,"people.json"),Cs=E.join(B,"jobs.json"),xs=E.join(B,"quota.json"),Kt=E.join(B,"conversations.json"),Es=E.join(B,"sync-state.json"),As=E.join(B,"application-questions.json"),Fe=E.join(B,"profile-history"),zt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},_s=zt(process.env.CONNECT_MAX_DAILY,20),$s=zt(process.env.CONNECT_MAX_WEEKLY,100),de=null,co=null,uo=null,fe=null,fo=null,mo=null;ho=["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"],go=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var tn={};pe(tn,{extractCertificationsFromDetails:()=>_o,extractEducationFromDetails:()=>Eo,extractExperienceFromDetails:()=>Co,extractFeaturedFromDetails:()=>xo,extractRecommendationsFromDetails:()=>$o,extractSkillsFromDetails:()=>Ao});async function Co(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await ue(e,n,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await k(1e3);let o=e.url();if(!o.toLowerCase().includes("/details/experience/"))throw new Error(`Section /details/experience/ not available on profile (landed on ${o})`);for(let s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(900);await k(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let i of document.querySelectorAll("button"))if(/^Load more$/i.test((i.textContent||"").trim()))return i.click(),!0;return!1});)r++,await k(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function i(c){let m=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(w=>w.tagName==="DIV");if(p.length<3)continue;let v=p.filter(w=>(w.textContent||"").trim().length>50);v.length<3||(f.textContent||"").length<500||m.push({el:f,count:v.length,totalText:(f.textContent||"").length})}return m.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),m[0]?.el}let l=i(s);if(!l)return[];let a=Array.from(l.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function u(c){let m=c[0]||null,f=null,p=null;if(c[1]){let b=c[1].split("\xB7").map($=>$.trim());f=b[0]||null,b[1]&&(p=b[1])}let v=c.findIndex(b=>/(\d{4}|present)/i.test(b)&&/(-|–|—)/i.test(b)&&b.length<80),w=null,A=null;if(v>=0){let b=c[v].split("\xB7").map($=>$.trim());w=b[0]||null,b[1]&&(A=b[1])}let Q=null,X=-1;if(v>=0&&c[v+1]){let b=c[v+1],$=/^[>*\-•]|^&gt;/.test(b),ae=/https?:\/\//.test(b),ce=/\d{4}/.test(b),I=/,/.test(b)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(b);!$&&!ae&&!ce&&b.length<100&&I&&(Q=b,X=v+1)}let Re=null,x=-1,Z=c[c.length-1];if(Z&&/and\s+\+\d+\s+skills?$/i.test(Z)){x=c.length-1;let b=Z.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);b&&(Re={listed:b[1].split(",").map($=>$.trim()),additional:parseInt(b[2],10)})}let ee=new Set([0,1,v,X,x].filter(b=>b>=0)),V=c.filter((b,$)=>!ee.has($)),D=V.length>0?V.join(`
4
4
 
5
- `):null;return{title:m,company:f,employmentType:p,dates:w,duration:E,location:Q,description:D,skills:Re,_raw:c}}return a.map(c=>{let f=(c.innerText||"").trim().split(`
5
+ `):null;return{title:m,company:f,employmentType:p,dates:w,duration:A,location:Q,description:D,skills:Re,_raw:c}}return a.map(c=>{let f=(c.innerText||"").trim().split(`
6
6
  `).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return u(f)}).filter(c=>c.title)})}catch(o){if(o.code==="SESSION_EXPIRED"||/^session expired/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function be(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await ue(e,o,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:`details/${n}`}),await k(1e3);let r=e.url();if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let i=0;i<4;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);await k(800);let s=0;for(;s<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)s++,await k(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(600)}async function ve(e,t,n,o){try{return await o()}catch(r){let s=r.message||"";if(r.code==="SESSION_EXPIRED"||/^session expired/i.test(s))throw r;return/not available on profile/i.test(s)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${s.slice(0,120)}`),[])}}async function xo(e,t){return ve(t,"featured","extractFeaturedFromDetails",async()=>(await be(e,t,"featured"),await e.evaluate(`(() => {
7
7
  ${Se}
8
8
 
@@ -44,7 +44,7 @@ var Pn=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var pe=(e,t)=>{f
44
44
  if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
45
45
  return true;
46
46
  });
47
- })()`)))}async function Ao(e,t){return ve(t,"education","extractEducationFromDetails",async()=>(await be(e,t,"education"),await e.evaluate(`(() => {
47
+ })()`)))}async function Eo(e,t){return ve(t,"education","extractEducationFromDetails",async()=>(await be(e,t,"education"),await e.evaluate(`(() => {
48
48
  ${Se}
49
49
 
50
50
  const main = document.querySelector('main');
@@ -81,7 +81,7 @@ var Pn=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var pe=(e,t)=>{f
81
81
  if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
82
82
  return true;
83
83
  });
84
- })()`)))}async function Eo(e,t){return ve(t,"skills","extractSkillsFromDetails",async()=>(await be(e,t,"skills"),await e.evaluate(`(() => {
84
+ })()`)))}async function Ao(e,t){return ve(t,"skills","extractSkillsFromDetails",async()=>(await be(e,t,"skills"),await e.evaluate(`(() => {
85
85
  ${Se}
86
86
 
87
87
  const main = document.querySelector('main');
@@ -237,12 +237,12 @@ function findEntryContainer(root) {
237
237
  candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
238
238
  return candidates[0]?.el;
239
239
  }
240
- `});var rn=W(()=>{});import"dotenv/config";import*as j from"fs";import*as O from"path";import{fileURLToPath as Ro}from"url";function Oo(){j.existsSync(re)||j.mkdirSync(re,{recursive:!0})}function jo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";j.writeFileSync(o,n);for(let r=0;r<3;r++)try{j.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function No(e){try{if(j.existsSync(e))return JSON.parse(j.readFileSync(e,"utf-8"))}catch{}return null}function ln(){Lo=null,Po=null,Fo=null,Mo=null,oe=null}function Je(){return oe||(oe=No(sn)||{visits:[]},Array.isArray(oe.visits)||(oe.visits=[]),oe)}function an(e,t={}){if(!e)return;Oo();let n=Je();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(r=>new Date(r.date).getTime()>o);try{jo(sn,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function cn(e){let t=Je();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}var To,Do,re,Ws,Gs,sn,Ys,Ks,Lo,Po,Fo,Mo,oe,We=W(()=>{rn();To=Ro(import.meta.url),Do=O.dirname(O.dirname(To)),re=process.env.DATA_DIR?O.resolve(process.env.DATA_DIR,"market-research"):O.join(Do,"market-research"),Ws=O.join(re,"scouted-jobs.json"),Gs=O.join(re,"discovered-people.json"),sn=O.join(re,"visit-log.json"),Ys=O.join(re,"companies.json"),Ks=O.join(re,"job-decisions.json");Lo=null,Po=null,Fo=null,Mo=null,oe=null});import oo from"puppeteer";import{addExtra as ro}from"puppeteer-extra";import so from"puppeteer-extra-plugin-stealth";he();await je();Ae();Ae();import Ne from"fs";import Qn from"path";var Xn={headless:!1,defaultViewport:null,protocolTimeout:3e5},ye=new Set,Lt=!1;async function Ee(){let e=[...ye].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});ye.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Zn(){if(Lt)return;Lt=!0;let e=t=>async()=>{await Ee(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Ee(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Ee(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Ee(),process.exit(0))}),process.on("exit",()=>{for(let t of ye)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function Le(e){return Qn.join(e,".ilml-browser-session.json")}function Ut(e,t={}){try{Ne.writeFileSync(Le(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function eo(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Ut(e,n?{wsEndpoint:n}:{})}catch{}}function to(e){let t=qt(e);t&&t.ownerPid===process.pid&&ge(e)}function ge(e){try{Ne.rmSync(Le(e),{force:!0})}catch{}}function qt(e){try{return JSON.parse(Ne.readFileSync(Le(e),"utf-8"))}catch{return null}}function Pt(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Ft(e,t,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(o),i),i=>{throw clearTimeout(o),i});return Promise.race([s,r])}async function Mt(e,t,{probeTimeoutMs:n=4e3}={}){let o=qt(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Pt(o.ownerPid)?"live":(ge(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await Ft(s,n,r);if(i===r)return s.then(a=>{if(a)try{a.disconnect()}catch{}}),"live";if(!i)return ge(t),"free";if(Pt(o.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Ft(i.close().then(()=>!0).catch(()=>!1),n,!1))return ge(t),"free";try{i.disconnect()}catch{}return"live"}function no(e,t){e&&(Zn(),ye.add(e),e.on("disconnected",()=>{ye.delete(e),t&&ge(t)}))}async function Bt(e,t={}){let n=xt(),o={...Xn,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Mt(e,n)==="live")throw new Error(r);Ut(n);let s;try{s=await e.launch(o)}catch{if(await Mt(e,n)==="live")throw new Error(r);$t(n);try{s=await e.launch(o)}catch(l){throw to(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${l.message})`)}}return no(s,n),eo(n,s),{browser:s,profileDir:n,needsSeed:Et(n)}}async function Ht(e,t){if(!t||!t.needsSeed)return!1;if(!kt())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...vt()),_t(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Vt=ro(oo);Vt.use(so());async function Jt(){let{browser:e,profileDir:t,needsSeed:n}=await Bt(Vt),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Ht(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}he();await we();async function Io(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function on(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:i=!1,extractRecommendations:l=!1,extractCertifications:a=!1}=n;try{await ue(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await k(1500),await Tt(e)&&(console.log(" Dismissed Premium overlay"),await k(1500),await Io(e,t));let c=0;for(let x=0;x<2;x++){let Z=await e.evaluate(()=>document.body.scrollHeight);for(let V=1;V<=6;V++)await e.evaluate(D=>window.scrollTo(0,D),Z*V/6),await k(900);let ee=await e.evaluate(()=>document.body.scrollHeight);if(ee===c)break;c=ee}await k(800);let m=null;try{let x=e.url();x&&/\/in\/[^/?#]/.test(x)&&(m=x.split("?")[0].replace(/\/+$/,""))}catch{}let f=await e.evaluate(()=>{let x=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"]),Z=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"]),ee=h=>{let g=(h||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(g)},V={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:[]},D=document.querySelector("main");if(!D)return V;let b=[...Array.from(D.querySelectorAll("h1")),...Array.from(D.querySelectorAll("h2"))],$=Array.from(D.querySelectorAll("h2")),ae=b.find(h=>{let g=h.textContent&&h.textContent.trim(),y=(g||"").replace(/\s*\(\d+\)$/,"").trim();return g&&g.length>1&&g.length<100&&!x.has(y)&&!Z.has(y)}),ce=ae?ae.textContent.trim():null,I=ae?ae.parentElement:null;for(;I&&I!==D&&!Array.from(I.children).filter(g=>g.tagName==="P").some(g=>{let y=g.textContent&&g.textContent.trim();return y&&y.length>5&&!ee(y)});)I=I.parentElement;let it=null,lt=null,at=null,Te=null;if(I&&I!==D){let h=Array.from(I.children).filter(y=>y.tagName==="P").filter(y=>{let J=y.textContent&&y.textContent.trim();return J&&J.length>5&&!ee(J)});if(h[0]&&(it=h[0].textContent.trim()),h[1]){let y=h[1].textContent.trim().split(/\s*[·•]\s*/);lt=y[0]||null,y.length>1&&(at=y.slice(1).join(" \xB7 "))}let g=Array.from(I.children).filter(y=>y.tagName==="DIV");for(let y=g.length-1;y>=0;y--){let J=g[y].textContent&&g[y].textContent.trim();if(J&&!(ce&&J.startsWith(ce))&&(Te=J.split(/[·•]/)[0].trim(),Te))break}}let ct=null;if(I){let h=I.querySelectorAll("p, span, div");for(let g of h){let y=(g.textContent||"").trim().replace(/^[·•]\s*/,"");if(y==="1st"||y==="2nd"||y==="3rd"){ct=y;break}}}let Rn=!!D.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),ut=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Tn=ut&&ut.src||null,Ce=D.textContent||"",ft=null,dt=Ce.match(/(\d+\+?)\s+connections\b/i);dt&&(ft=dt[1]+" connections");let xe=null,mt=Ce.match(/(\d+)\s+mutual connection/i),pt=Ce.match(/and\s+(\d+)\s+other mutual/i),Dn=Ce.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);mt?xe=parseInt(mt[1],10):pt?xe=2+parseInt(pt[1],10):Dn&&(xe=2);let ht=null,gt=null,yt=$.find(h=>h.textContent&&h.textContent.trim()==="About");if(yt){let h=yt.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let g=(h.textContent||"").trim();g=g.replace(/^About\s*/,"").trim();let y=g.match(/Top skills\s*(.+?)$/i);if(y){let De=y[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Ln=>Ln.trim()).filter(Boolean);De.length>0&&De.length<10&&(gt=De)}g=g.split(/\n?…\s*more/i)[0].trim(),g=g.split(/\n?\.\.\.\s*more/i)[0].trim(),g=g.split(/\bTop skills\b/i)[0].trim(),g=g.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),ht=g||null}}let wt=null,bt=$.find(h=>h.textContent&&h.textContent.trim()==="Activity");if(bt){let h=bt.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let g=(h.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);g&&(wt=parseInt(g[1].replace(/,/g,""),10))}}let On=[...new Set($.map(h=>(h.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(h=>h&&h.length>1&&h.length<60&&h!==ce).filter(h=>x.has(h)))],me=document.body.textContent||"",jn=/#OpenToWork\b/i.test(me)||/\bOpen to work\b/.test(me),Nn=/#Hiring\b/i.test(me)||/\bI'?m hiring\b/i.test(me)||/\bWe are hiring\b/i.test(me);return{name:ce,title:it,location:Te,currentCompany:lt,currentSchool:at,connectionDegree:ct,hasVerifiedBadge:Rn,photoUrl:Tn,connectionsLevel:ft,mutualConnectionsCount:xe,followers:wt,openToWork:jn,hiring:Nn,about:ht,topSkills:gt,availableSections:On}});console.log(`Viewed: ${f.name} - ${f.title}`);let p=null,v=null,w=null,E=null,Q=null,X=null;if(o||r||s||i||l||a){let x=await Promise.resolve().then(()=>(nn(),tn));o&&(p=await x.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),r&&(v=await x.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${v.length} entries`)),s&&(w=await x.extractEducationFromDetails(e,t),console.log(` + Education: ${w.length} entries`)),i&&(E=await x.extractSkillsFromDetails(e,t),console.log(` + Skills: ${E.length} entries`)),l&&(Q=await x.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${Q.length} entries`)),a&&(X=await x.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${X.length} entries`))}return{...f,profileUrl:t,resolvedUrl:m,...p!==null&&{experience:p},...v!==null&&{featured:v},...w!==null&&{education:w},...E!==null&&{skillsFull:E},...Q!==null&&{recommendations:Q},...X!==null&&{certifications:X}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}We();await we();he();async function un(e,t,n={}){let{maxVisits:o=50,delayBetween:r=4e3,skipRecentDays:s=7,verbose:i=!1,extractExperience:l=!1}=n,a={visited:0,skipped:0,errors:0},u=Date.now()-s*24*60*60*1e3;for(let c of t){if(a.visited>=o)break;if(!c.profileUrl)continue;let m=cn(c.profileUrl);if(m&&new Date(m).getTime()>u){a.skipped++;continue}try{let f=await on(e,c.profileUrl,{extractExperience:l}),p=c.source||"visit";if(f){let w={...f,source:p};l&&Array.isArray(f.experience)&&f.experience.length>0&&(w._lastEnrichedAt=new Date().toISOString()),He(c.profileUrl,w),f.resolvedUrl&&Ve(c.profileUrl,f.resolvedUrl)}an(c.profileUrl,{name:f?.name||c.name||null,source:p}),a.visited++,i?console.log(` [${a.visited}] ${f?.name||c.profileUrl} \u2014 ${f?.title?.slice(0,40)||"?"}`):a.visited%10===0&&console.log(` Visited: ${a.visited}`);let v=Math.random()*4e3;await k(r+v)}catch(f){a.errors++,i&&console.error(` Error visiting ${c.name||c.profileUrl}: ${f.message?.slice(0,60)}`);let p=(f.message||"").toLowerCase();if(p.includes("detached")||p.includes("session closed")||p.includes("target closed")||p.includes("session expired")||p.includes("bounced to")||p.includes("authwall")||p.includes("checkpoint")||p.includes("redirected to login")){console.log(" Fatal browser/session error \u2014 stopping visits");break}}}return a}await we();import"dotenv/config";import*as N from"fs";import*as Y from"path";import{fileURLToPath as Go}from"url";import"dotenv/config";import{createGraphClient as Uo,resolveToken as qo}from"@ilivemylife/graph-sdk";import{config as Bo}from"dotenv";Bo();var fn=qo()||process.env.TOKEN;fn||(console.error(`
240
+ `});var rn=W(()=>{});import"dotenv/config";import*as N from"fs";import*as O from"path";import{fileURLToPath as Ro}from"url";function Oo(){N.existsSync(re)||N.mkdirSync(re,{recursive:!0})}function No(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";N.writeFileSync(o,n);for(let r=0;r<3;r++)try{N.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function jo(e){try{if(N.existsSync(e))return JSON.parse(N.readFileSync(e,"utf-8"))}catch{}return null}function ln(){Lo=null,Po=null,Fo=null,Mo=null,oe=null}function Je(){return oe||(oe=jo(sn)||{visits:[]},Array.isArray(oe.visits)||(oe.visits=[]),oe)}function an(e,t={}){if(!e)return;Oo();let n=Je();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(r=>new Date(r.date).getTime()>o);try{No(sn,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function cn(e){let t=Je();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}var To,Do,re,Ws,Gs,sn,Ys,Ks,Lo,Po,Fo,Mo,oe,We=W(()=>{rn();To=Ro(import.meta.url),Do=O.dirname(O.dirname(To)),re=process.env.DATA_DIR?O.resolve(process.env.DATA_DIR,"market-research"):O.join(Do,"market-research"),Ws=O.join(re,"scouted-jobs.json"),Gs=O.join(re,"discovered-people.json"),sn=O.join(re,"visit-log.json"),Ys=O.join(re,"companies.json"),Ks=O.join(re,"job-decisions.json");Lo=null,Po=null,Fo=null,Mo=null,oe=null});import oo from"puppeteer";import{addExtra as ro}from"puppeteer-extra";import so from"puppeteer-extra-plugin-stealth";he();await Ne();Ee();Ee();import je from"fs";import Qn from"path";var Xn={headless:!1,defaultViewport:null,protocolTimeout:3e5},ye=new Set,Lt=!1;async function Ae(){let e=[...ye].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});ye.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Zn(){if(Lt)return;Lt=!0;let e=t=>async()=>{await Ae(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Ae(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Ae(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Ae(),process.exit(0))}),process.on("exit",()=>{for(let t of ye)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function Le(e){return Qn.join(e,".ilml-browser-session.json")}function Ut(e,t={}){try{je.writeFileSync(Le(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function eo(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Ut(e,n?{wsEndpoint:n}:{})}catch{}}function to(e){let t=qt(e);t&&t.ownerPid===process.pid&&ge(e)}function ge(e){try{je.rmSync(Le(e),{force:!0})}catch{}}function qt(e){try{return JSON.parse(je.readFileSync(Le(e),"utf-8"))}catch{return null}}function Pt(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Ft(e,t,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(o),i),i=>{throw clearTimeout(o),i});return Promise.race([s,r])}async function Mt(e,t,{probeTimeoutMs:n=4e3}={}){let o=qt(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Pt(o.ownerPid)?"live":(ge(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await Ft(s,n,r);if(i===r)return s.then(a=>{if(a)try{a.disconnect()}catch{}}),"live";if(!i)return ge(t),"free";if(Pt(o.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Ft(i.close().then(()=>!0).catch(()=>!1),n,!1))return ge(t),"free";try{i.disconnect()}catch{}return"live"}function no(e,t){e&&(Zn(),ye.add(e),e.on("disconnected",()=>{ye.delete(e),t&&ge(t)}))}async function Bt(e,t={}){let n=xt(),o={...Xn,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Mt(e,n)==="live")throw new Error(r);Ut(n);let s;try{s=await e.launch(o)}catch{if(await Mt(e,n)==="live")throw new Error(r);$t(n);try{s=await e.launch(o)}catch(l){throw to(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${l.message})`)}}return no(s,n),eo(n,s),{browser:s,profileDir:n,needsSeed:At(n)}}async function Ht(e,t){if(!t||!t.needsSeed)return!1;if(!kt())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...vt()),_t(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Vt=ro(oo);Vt.use(so());async function Jt(){let{browser:e,profileDir:t,needsSeed:n}=await Bt(Vt),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Ht(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}he();await we();async function Io(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function on(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:i=!1,extractRecommendations:l=!1,extractCertifications:a=!1}=n;try{await ue(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await k(1500),await Tt(e)&&(console.log(" Dismissed Premium overlay"),await k(1500),await Io(e,t));let c=0;for(let x=0;x<2;x++){let Z=await e.evaluate(()=>document.body.scrollHeight);for(let V=1;V<=6;V++)await e.evaluate(D=>window.scrollTo(0,D),Z*V/6),await k(900);let ee=await e.evaluate(()=>document.body.scrollHeight);if(ee===c)break;c=ee}await k(800);let m=null;try{let x=e.url();x&&/\/in\/[^/?#]/.test(x)&&(m=x.split("?")[0].replace(/\/+$/,""))}catch{}let f=await e.evaluate(()=>{let x=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"]),Z=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"]),ee=h=>{let g=(h||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(g)},V={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:[]},D=document.querySelector("main");if(!D)return V;let b=[...Array.from(D.querySelectorAll("h1")),...Array.from(D.querySelectorAll("h2"))],$=Array.from(D.querySelectorAll("h2")),ae=b.find(h=>{let g=h.textContent&&h.textContent.trim(),y=(g||"").replace(/\s*\(\d+\)$/,"").trim();return g&&g.length>1&&g.length<100&&!x.has(y)&&!Z.has(y)}),ce=ae?ae.textContent.trim():null,I=ae?ae.parentElement:null;for(;I&&I!==D&&!Array.from(I.children).filter(g=>g.tagName==="P").some(g=>{let y=g.textContent&&g.textContent.trim();return y&&y.length>5&&!ee(y)});)I=I.parentElement;let it=null,lt=null,at=null,Te=null;if(I&&I!==D){let h=Array.from(I.children).filter(y=>y.tagName==="P").filter(y=>{let J=y.textContent&&y.textContent.trim();return J&&J.length>5&&!ee(J)});if(h[0]&&(it=h[0].textContent.trim()),h[1]){let y=h[1].textContent.trim().split(/\s*[·•]\s*/);lt=y[0]||null,y.length>1&&(at=y.slice(1).join(" \xB7 "))}let g=Array.from(I.children).filter(y=>y.tagName==="DIV");for(let y=g.length-1;y>=0;y--){let J=g[y].textContent&&g[y].textContent.trim();if(J&&!(ce&&J.startsWith(ce))&&(Te=J.split(/[·•]/)[0].trim(),Te))break}}let ct=null;if(I){let h=I.querySelectorAll("p, span, div");for(let g of h){let y=(g.textContent||"").trim().replace(/^[·•]\s*/,"");if(y==="1st"||y==="2nd"||y==="3rd"){ct=y;break}}}let Rn=!!D.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),ut=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Tn=ut&&ut.src||null,Ce=D.textContent||"",ft=null,dt=Ce.match(/(\d+\+?)\s+connections\b/i);dt&&(ft=dt[1]+" connections");let xe=null,mt=Ce.match(/(\d+)\s+mutual connection/i),pt=Ce.match(/and\s+(\d+)\s+other mutual/i),Dn=Ce.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);mt?xe=parseInt(mt[1],10):pt?xe=2+parseInt(pt[1],10):Dn&&(xe=2);let ht=null,gt=null,yt=$.find(h=>h.textContent&&h.textContent.trim()==="About");if(yt){let h=yt.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let g=(h.textContent||"").trim();g=g.replace(/^About\s*/,"").trim();let y=g.match(/Top skills\s*(.+?)$/i);if(y){let De=y[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Ln=>Ln.trim()).filter(Boolean);De.length>0&&De.length<10&&(gt=De)}g=g.split(/\n?…\s*more/i)[0].trim(),g=g.split(/\n?\.\.\.\s*more/i)[0].trim(),g=g.split(/\bTop skills\b/i)[0].trim(),g=g.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),ht=g||null}}let wt=null,bt=$.find(h=>h.textContent&&h.textContent.trim()==="Activity");if(bt){let h=bt.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let g=(h.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);g&&(wt=parseInt(g[1].replace(/,/g,""),10))}}let On=[...new Set($.map(h=>(h.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(h=>h&&h.length>1&&h.length<60&&h!==ce).filter(h=>x.has(h)))],me=document.body.textContent||"",Nn=/#OpenToWork\b/i.test(me)||/\bOpen to work\b/.test(me),jn=/#Hiring\b/i.test(me)||/\bI'?m hiring\b/i.test(me)||/\bWe are hiring\b/i.test(me);return{name:ce,title:it,location:Te,currentCompany:lt,currentSchool:at,connectionDegree:ct,hasVerifiedBadge:Rn,photoUrl:Tn,connectionsLevel:ft,mutualConnectionsCount:xe,followers:wt,openToWork:Nn,hiring:jn,about:ht,topSkills:gt,availableSections:On}});console.log(`Viewed: ${f.name} - ${f.title}`);let p=null,v=null,w=null,A=null,Q=null,X=null;if(o||r||s||i||l||a){let x=await Promise.resolve().then(()=>(nn(),tn));o&&(p=await x.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),r&&(v=await x.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${v.length} entries`)),s&&(w=await x.extractEducationFromDetails(e,t),console.log(` + Education: ${w.length} entries`)),i&&(A=await x.extractSkillsFromDetails(e,t),console.log(` + Skills: ${A.length} entries`)),l&&(Q=await x.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${Q.length} entries`)),a&&(X=await x.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${X.length} entries`))}return{...f,profileUrl:t,resolvedUrl:m,...p!==null&&{experience:p},...v!==null&&{featured:v},...w!==null&&{education:w},...A!==null&&{skillsFull:A},...Q!==null&&{recommendations:Q},...X!==null&&{certifications:X}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}We();await we();he();async function un(e,t,n={}){let{maxVisits:o=10,delayBetween:r=4e3,skipRecentDays:s=7,verbose:i=!1,extractExperience:l=!1}=n,a={visited:0,skipped:0,errors:0},u=Date.now()-s*24*60*60*1e3;for(let c of t){if(a.visited>=o)break;if(!c.profileUrl)continue;let m=cn(c.profileUrl);if(m&&new Date(m).getTime()>u){a.skipped++;continue}try{let f=await on(e,c.profileUrl,{extractExperience:l}),p=c.source||"visit";if(f){let w={...f,source:p};l&&Array.isArray(f.experience)&&f.experience.length>0&&(w._lastEnrichedAt=new Date().toISOString()),He(c.profileUrl,w),f.resolvedUrl&&Ve(c.profileUrl,f.resolvedUrl)}an(c.profileUrl,{name:f?.name||c.name||null,source:p}),a.visited++,i?console.log(` [${a.visited}] ${f?.name||c.profileUrl} \u2014 ${f?.title?.slice(0,40)||"?"}`):a.visited%10===0&&console.log(` Visited: ${a.visited}`);let v=Math.random()*4e3;await k(r+v)}catch(f){a.errors++,i&&console.error(` Error visiting ${c.name||c.profileUrl}: ${f.message?.slice(0,60)}`);let p=(f.message||"").toLowerCase();if(p.includes("detached")||p.includes("session closed")||p.includes("target closed")||p.includes("session expired")||p.includes("bounced to")||p.includes("authwall")||p.includes("checkpoint")||p.includes("redirected to login")){console.log(" Fatal browser/session error \u2014 stopping visits");break}}}return a}await we();import"dotenv/config";import*as j from"fs";import*as Y from"path";import{fileURLToPath as Go}from"url";import"dotenv/config";import{createGraphClient as Uo,resolveToken as qo}from"@ilivemylife/graph-sdk";import{config as Bo}from"dotenv";Bo();var fn=qo()||process.env.TOKEN;fn||(console.error(`
241
241
  [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.
242
242
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
243
243
  `),console.error(` Or add ILML_TOKEN=... to .env
244
244
  `),process.exit(1));var dn=Uo({token:fn});function Ho(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}var Vo={apply:"Job apply","apply-queue":"Job apply (queue)",scout:"Job scout",connect:"Connect run",funnel:"Recruiter funnel",messages:"Messages",sync:"Connections sync","sync-all":"Inbox sync",visit:"Profile visits",viewers:"Profile viewers",daily:"Daily run"};function Jo(e){let t=String(e||"").toLowerCase();return/authwall|session expired|not logged in|re-?auth|logged out|sign ?in/.test(t)?"LinkedIn asked to sign in again. Run `ilml linkedin login`, then run this again.":/protocoltimeout|callfunctionon|target closed|session closed|detached|execution context|browser.*disconnected|connection closed/.test(t)?"The browser stopped responding partway through. This is usually temporary \u2014 just run it again.":/err_aborted|err_network|err_connection|err_name_not_resolved|net::/.test(t)?"A page failed to load (network hiccup). Try running it again in a moment.":/navigation timeout|timeout.*exceeded|waiting for selector|waiting for/.test(t)?"A page took too long to load. Try again in a moment.":/invite limit|weekly.*limit|too many|rate.?limit|quota/.test(t)?"You've reached a LinkedIn sending limit for now. Wait a while, then try again.":"Something went wrong partway through. It is safe to run the command again."}function Wo({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=n==="error"?"stopped early":n==="quota-reached"?"daily limit reached":"done",a=Vo[e]||e,u=t&&t!=="default"?` \xB7 ${t}`:"",c=new Date().toISOString().slice(0,16).replace("T"," "),m=s?` \xB7 ${Ho(s)}`:"",f=[];f.push(`## ${i} ${a} \u2014 ${l}`),f.push(`_${c}${u}${m}_`),f.push("");for(let p of o)f.push(`- ${p}`);if(n==="error"){f.push(""),f.push(`**What happened:** ${Jo(r)}`);let p=String(r||"").replace(/\s+/g," ").trim();p&&f.push(`_Technical detail: ${p.slice(0,140)}_`)}return f.join(`
245
- `)}async function mn({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let l=Wo({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s});try{await dn.addMessage(i,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Yo=Go(import.meta.url),Ko=Y.dirname(Y.dirname(Yo)),Ge=process.env.DATA_DIR?Y.resolve(process.env.DATA_DIR,"collected-profiles"):Y.join(Ko,"collected-profiles"),Ye=Y.join(Ge,"run-log.json");function zo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";N.writeFileSync(o,n);for(let r=0;r<3;r++)try{N.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function pn(){try{if(!N.existsSync(Ye))return{runs:[]};let e=JSON.parse(N.readFileSync(Ye,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function hn(e){N.existsSync(Ge)||N.mkdirSync(Ge,{recursive:!0});try{zo(Ye,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function gn(e,t="default"){let n=pn();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>s),hn(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Ke(e,t,n=null,o=null){if(!e)return;let r=null;try{let i=pn(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,r=l.duration;else{let a=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,r=a.duration)}hn(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";mn({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import"dotenv/config";import*as d from"fs";import*as ot from"os";import*as S from"path";import{fileURLToPath as Sr}from"url";var Xe={};pe(Xe,{NAME:()=>Xo,VERSION:()=>Qo,up:()=>tr});import*as L from"fs";import*as _e from"path";var Qo=1,Xo="normalize-jobs-and-questions",Zo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],er=50;function ze(e){return L.existsSync(e)?JSON.parse(L.readFileSync(e,"utf-8")):null}function Qe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{L.writeFileSync(o,n)}catch(r){try{L.unlinkSync(o)}catch{}throw r}try{L.renameSync(o,e)}catch(r){try{L.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function tr(e,t){let n=_e.join(e,"jobs.json"),o=_e.join(t,"scouted-jobs.json"),r=_e.join(e,"application-questions.json"),s=ze(n)||{},i=ze(o)||{},l=0,a=[];for(let c of Object.keys(s)){if(!i[c])continue;let m=i[c],f=s[c];for(let p of Zo)m[p]!=null&&f[p]==null&&(f[p]=m[p]);a.push(c),l++}l>0?(Qe(n,s),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=ze(r);if(u&&Array.isArray(u.applications)){let c={},m=0;for(let f of u.applications){let p=f.jobId||"unknown";c[p]||(c[p]={applications:[]});let v=(f.questions||[]).map(w=>{let E={type:w.type||"input",question:w.question||"",answer:w.answer||""};return w.options&&(w.options.length<=er?E.options=w.options:(E.optionsOmitted=!0,m++)),w.page&&(E.page=w.page),w.wasPreFilled&&(E.wasPreFilled=!0),w.wasRetry&&(E.wasRetry=!0),E});c[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||v.length,questions:v})}Qe(r,c),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} 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(a.length>0){for(let c of a)delete i[c];Qe(o,i),console.log(` Phase 3: Removed ${a.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 Ze={};pe(Ze,{NAME:()=>or,VERSION:()=>nr,up:()=>ir});import*as P from"fs";import*as yn from"path";var nr=2,or="reset-unread-flags";function rr(e){return P.existsSync(e)?JSON.parse(P.readFileSync(e,"utf-8")):null}function sr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{P.writeFileSync(o,n)}catch(r){try{P.unlinkSync(o)}catch{}throw r}try{P.renameSync(o,e)}catch(r){try{P.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function ir(e){let t=yn.join(e,"conversations.json"),n=rr(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}sr(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var et={};pe(et,{NAME:()=>ar,VERSION:()=>lr,up:()=>mr});import*as F from"fs";import*as wn from"path";var lr=3,ar="recompute-last-message-by",cr=new Set(["draft","confirmed","rejected","needs_review"]);function ur(e){return F.existsSync(e)?JSON.parse(F.readFileSync(e,"utf-8")):null}function fr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{F.writeFileSync(o,n)}catch(r){try{F.unlinkSync(o)}catch{}throw r}try{F.renameSync(o,e)}catch(r){try{F.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function dr(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!cr.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function mr(e){let t=wn.join(e,"conversations.json"),n=ur(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,s=0,i=0;for(let l of Object.keys(n)){let a=n[l];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,s++);let u=Array.isArray(a.messages)?a.messages:[],c=dr(u,o),m=c==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==c&&i++,a.lastMessageBy=c,a.conversationStatus=m,r++}if(r===0){console.log(" No conversations to recompute.");return}fr(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var tt={};pe(tt,{NAME:()=>hr,VERSION:()=>pr,up:()=>br});import*as M from"fs";import*as bn from"path";var pr=4,hr="split-connection-timestamps",gr=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function yr(e){if(!M.existsSync(e))return null;let t=M.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function wr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{M.writeFileSync(o,n)}catch(r){try{M.unlinkSync(o)}catch{}throw r}try{M.renameSync(o,e)}catch(r){try{M.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function br(e){let t=bn.join(e,"people.json"),n=yr(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let i=n[s];!i||typeof i!="object"||(r++,gr.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}wr(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await we();We();var vr=Sr(import.meta.url),kr=S.dirname(vr),Cr=S.dirname(S.dirname(kr));function xr(e){return e&&(e==="~"?ot.homedir():e.startsWith("~/")||e.startsWith("~\\")?S.join(ot.homedir(),e.slice(2)):e)}var U=process.env.DATA_DIR?S.resolve(xr(process.env.DATA_DIR)):Cr,ie=S.join(U,"collected-profiles"),le=S.join(U,"market-research"),T=S.join(U,".schema-version"),Sn=[S.join(ie,".schema-version"),S.join(le,".schema-version")],K=4,H=[{version:1,module:Xe},{version:2,module:Ze},{version:3,module:et},{version:4,module:tt}];(function(){H.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of H){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=H.length?H[H.length-1].version:0;if(n!==K)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${K}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<H.length;o++){let r=o+1;if(H[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${H[o].version}`)}})();function xn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
245
+ `)}async function mn({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let l=Wo({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s});try{await dn.addMessage(i,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Yo=Go(import.meta.url),Ko=Y.dirname(Y.dirname(Yo)),Ge=process.env.DATA_DIR?Y.resolve(process.env.DATA_DIR,"collected-profiles"):Y.join(Ko,"collected-profiles"),Ye=Y.join(Ge,"run-log.json");function zo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";j.writeFileSync(o,n);for(let r=0;r<3;r++)try{j.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function pn(){try{if(!j.existsSync(Ye))return{runs:[]};let e=JSON.parse(j.readFileSync(Ye,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function hn(e){j.existsSync(Ge)||j.mkdirSync(Ge,{recursive:!0});try{zo(Ye,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function gn(e,t="default"){let n=pn();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>s),hn(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Ke(e,t,n=null,o=null){if(!e)return;let r=null;try{let l=pn(),a=l.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,r=a.duration;else{let u=l.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());u&&(u.status=t,u.result=t,u.duration=Date.now()-e.startTime,u.stats=n,u.error=o,r=u.duration)}hn(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null,i=n&&n.__deferReport===!0;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS&&!i){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";mn({scriptName:e.script,mode:e.mode,status:l,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import"dotenv/config";import*as d from"fs";import*as ot from"os";import*as S from"path";import{fileURLToPath as Sr}from"url";var Xe={};pe(Xe,{NAME:()=>Xo,VERSION:()=>Qo,up:()=>tr});import*as L from"fs";import*as _e from"path";var Qo=1,Xo="normalize-jobs-and-questions",Zo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],er=50;function ze(e){return L.existsSync(e)?JSON.parse(L.readFileSync(e,"utf-8")):null}function Qe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{L.writeFileSync(o,n)}catch(r){try{L.unlinkSync(o)}catch{}throw r}try{L.renameSync(o,e)}catch(r){try{L.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function tr(e,t){let n=_e.join(e,"jobs.json"),o=_e.join(t,"scouted-jobs.json"),r=_e.join(e,"application-questions.json"),s=ze(n)||{},i=ze(o)||{},l=0,a=[];for(let c of Object.keys(s)){if(!i[c])continue;let m=i[c],f=s[c];for(let p of Zo)m[p]!=null&&f[p]==null&&(f[p]=m[p]);a.push(c),l++}l>0?(Qe(n,s),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=ze(r);if(u&&Array.isArray(u.applications)){let c={},m=0;for(let f of u.applications){let p=f.jobId||"unknown";c[p]||(c[p]={applications:[]});let v=(f.questions||[]).map(w=>{let A={type:w.type||"input",question:w.question||"",answer:w.answer||""};return w.options&&(w.options.length<=er?A.options=w.options:(A.optionsOmitted=!0,m++)),w.page&&(A.page=w.page),w.wasPreFilled&&(A.wasPreFilled=!0),w.wasRetry&&(A.wasRetry=!0),A});c[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||v.length,questions:v})}Qe(r,c),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} 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(a.length>0){for(let c of a)delete i[c];Qe(o,i),console.log(` Phase 3: Removed ${a.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 Ze={};pe(Ze,{NAME:()=>or,VERSION:()=>nr,up:()=>ir});import*as P from"fs";import*as yn from"path";var nr=2,or="reset-unread-flags";function rr(e){return P.existsSync(e)?JSON.parse(P.readFileSync(e,"utf-8")):null}function sr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{P.writeFileSync(o,n)}catch(r){try{P.unlinkSync(o)}catch{}throw r}try{P.renameSync(o,e)}catch(r){try{P.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function ir(e){let t=yn.join(e,"conversations.json"),n=rr(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}sr(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var et={};pe(et,{NAME:()=>ar,VERSION:()=>lr,up:()=>mr});import*as F from"fs";import*as wn from"path";var lr=3,ar="recompute-last-message-by",cr=new Set(["draft","confirmed","rejected","needs_review"]);function ur(e){return F.existsSync(e)?JSON.parse(F.readFileSync(e,"utf-8")):null}function fr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{F.writeFileSync(o,n)}catch(r){try{F.unlinkSync(o)}catch{}throw r}try{F.renameSync(o,e)}catch(r){try{F.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function dr(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!cr.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function mr(e){let t=wn.join(e,"conversations.json"),n=ur(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,s=0,i=0;for(let l of Object.keys(n)){let a=n[l];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,s++);let u=Array.isArray(a.messages)?a.messages:[],c=dr(u,o),m=c==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==c&&i++,a.lastMessageBy=c,a.conversationStatus=m,r++}if(r===0){console.log(" No conversations to recompute.");return}fr(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var tt={};pe(tt,{NAME:()=>hr,VERSION:()=>pr,up:()=>br});import*as M from"fs";import*as bn from"path";var pr=4,hr="split-connection-timestamps",gr=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function yr(e){if(!M.existsSync(e))return null;let t=M.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function wr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{M.writeFileSync(o,n)}catch(r){try{M.unlinkSync(o)}catch{}throw r}try{M.renameSync(o,e)}catch(r){try{M.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function br(e){let t=bn.join(e,"people.json"),n=yr(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let i=n[s];!i||typeof i!="object"||(r++,gr.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}wr(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await we();We();var vr=Sr(import.meta.url),kr=S.dirname(vr),Cr=S.dirname(S.dirname(kr));function xr(e){return e&&(e==="~"?ot.homedir():e.startsWith("~/")||e.startsWith("~\\")?S.join(ot.homedir(),e.slice(2)):e)}var U=process.env.DATA_DIR?S.resolve(xr(process.env.DATA_DIR)):Cr,ie=S.join(U,"collected-profiles"),le=S.join(U,"market-research"),T=S.join(U,".schema-version"),Sn=[S.join(ie,".schema-version"),S.join(le,".schema-version")],K=4,H=[{version:1,module:Xe},{version:2,module:Ze},{version:3,module:et},{version:4,module:tt}];(function(){H.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of H){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=H.length?H[H.length-1].version:0;if(n!==K)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${K}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<H.length;o++){let r=o+1;if(H[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${H[o].version}`)}})();function xn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
246
246
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
247
247
  `),process.exit(1));try{d.mkdirSync(U,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
248
248
  [FATAL] Cannot create DATA_DIR (${U}): ${t.message}`),console.error(` Fix the path or permissions and try again.
@@ -252,10 +252,10 @@ function findEntryContainer(root) {
252
252
  [FATAL] DATA_DIR (${U}) 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.
253
253
  `),process.exit(1));for(let t of[ie,le]){let n;try{n=d.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
254
254
  [FATAL] Data subdirectory is a symbolic link: ${t}`),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.
255
- `),process.exit(1))}}var se=S.join(U,".migration-lock");function Ar(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return d.writeFileSync(se,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(d.readFileSync(se,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(i){i.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,s=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(s=Date.now()-i)}o&&s<r&&(console.error(`
255
+ `),process.exit(1))}}var se=S.join(U,".migration-lock");function Er(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return d.writeFileSync(se,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(d.readFileSync(se,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(i){i.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,s=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(s=Date.now()-i)}o&&s<r&&(console.error(`
256
256
  [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${se}
257
257
  `),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.
258
- `),process.exit(1)),o&&s>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=se+".tmp";try{return d.writeFileSync(n,e),d.renameSync(n,se),!0}catch(o){try{d.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function rt(){try{if(JSON.parse(d.readFileSync(se,"utf-8")).pid!==process.pid)return;d.unlinkSync(se)}catch{}}var vn=!1;function Er(){if(vn)return;vn=!0;let e=()=>{try{rt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function _r(){if(d.existsSync(T))return;let e=[],t=[];for(let s of Sn)if(d.existsSync(s))try{e.push({file:s,schema:$e(s)})}catch(i){t.push({file:s,err:i.message})}if(t.length>0){console.error(`
258
+ `),process.exit(1)),o&&s>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=se+".tmp";try{return d.writeFileSync(n,e),d.renameSync(n,se),!0}catch(o){try{d.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function rt(){try{if(JSON.parse(d.readFileSync(se,"utf-8")).pid!==process.pid)return;d.unlinkSync(se)}catch{}}var vn=!1;function Ar(){if(vn)return;vn=!0;let e=()=>{try{rt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function _r(){if(d.existsSync(T))return;let e=[],t=[];for(let s of Sn)if(d.existsSync(s))try{e.push({file:s,schema:$e(s)})}catch(i){t.push({file:s,err:i.message})}if(t.length>0){console.error(`
259
259
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of t)console.error(` ${s.file}: ${s.err}`);console.error(`
260
260
  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.
261
261
  `),process.exit(1)}if(e.length===0)return;let n=e.map(s=>s.schema.version);if(new Set(n).size>1){console.error(`
@@ -264,11 +264,11 @@ function findEntryContainer(root) {
264
264
  [FATAL] ${T} is not valid JSON: ${n.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.
265
265
  `),process.exit(1)}let t=$r(e);return t===null&&(console.error(`
266
266
  [FATAL] ${T} 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.
267
- `),process.exit(1)),t}function An(e){try{d.chmodSync(e,384)}catch{}}function Ir(e){if(xn(),d.existsSync(T))try{if(d.lstatSync(T).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${T}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=T+".tmp";try{d.writeFileSync(t,JSON.stringify(e,null,2)),An(t),d.renameSync(t,T)}catch(n){try{d.unlinkSync(t)}catch{}throw n}}function Cn(e,t){if(!d.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=d.readdirSync(e).filter(l=>{let a=l.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return d.statSync(S.join(e,l)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let l of o){let a=S.join(e,l),u=S.join(e,l+n);if(d.existsSync(u)){s++;continue}try{_n(a,u),r++}catch(c){i.push({file:l,err:c.message})}}if(i.length>0){let l=new Error(`Failed to back up ${i.length} file(s) in ${S.basename(e)}/: `+i.map(a=>`${a.file} (${a.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(r>0||s>0){let l=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${S.basename(e)}/ (${n})${l}`)}}var nt=!1;async function En(){if(nt)return;xn(),jr();let t=kn().version;if(t===K){nt=!0;return}Er(),Ar(),process.on("exit",rt),t>K&&(console.error(`
267
+ `),process.exit(1)),t}function En(e){try{d.chmodSync(e,384)}catch{}}function Ir(e){if(xn(),d.existsSync(T))try{if(d.lstatSync(T).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${T}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=T+".tmp";try{d.writeFileSync(t,JSON.stringify(e,null,2)),En(t),d.renameSync(t,T)}catch(n){try{d.unlinkSync(t)}catch{}throw n}}function Cn(e,t){if(!d.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=d.readdirSync(e).filter(l=>{let a=l.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return d.statSync(S.join(e,l)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let l of o){let a=S.join(e,l),u=S.join(e,l+n);if(d.existsSync(u)){s++;continue}try{_n(a,u),r++}catch(c){i.push({file:l,err:c.message})}}if(i.length>0){let l=new Error(`Failed to back up ${i.length} file(s) in ${S.basename(e)}/: `+i.map(a=>`${a.file} (${a.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(r>0||s>0){let l=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${S.basename(e)}/ (${n})${l}`)}}var nt=!1;async function An(){if(nt)return;xn(),Nr();let t=kn().version;if(t===K){nt=!0;return}Ar(),Er(),process.on("exit",rt),t>K&&(console.error(`
268
268
  [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${K}.`),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.
269
269
  `),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${K}.
270
270
  `),process.exit(1)),console.log(`
271
- \u{1F4E6} Schema migration: v${t} \u2192 v${K}`);let n=Nr();if(!n.ok){console.error(`
271
+ \u{1F4E6} Schema migration: v${t} \u2192 v${K}`);let n=jr();if(!n.ok){console.error(`
272
272
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
273
273
  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'.
274
274
  `),process.exit(1)}let o=H.filter(r=>r.version>t);for(let r of o){console.log(`
@@ -282,7 +282,7 @@ function findEntryContainer(root) {
282
282
  [FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${a.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
283
283
  `),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{Qt()}catch{}try{ln()}catch{}nt=!0,rt(),console.log(`
284
284
  \u2713 Schema is now at v${K}
285
- `)}var Rr=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Tr(e){let t=e.toLowerCase();return Rr.some(n=>n.test(t))}var Dr=6e4;function Or(){let e=Date.now(),t=[];for(let n of[U,ie,le]){if(!d.existsSync(n))continue;let o;try{o=d.readdirSync(n)}catch{continue}for(let r of o){if(!Tr(r))continue;let s=S.join(n,r);try{let i=d.statSync(s);if(!i.isFile()||e-i.mtimeMs<Dr)continue;t.push({dir:n,file:r,fullPath:s})}catch{}}}return t}function jr({verbose:e=!1}={}){let t=Or();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{d.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${S.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function Nr(){let e=[];for(let t of[ie,le]){if(!d.existsSync(t))continue;let n=d.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=S.join(t,o);try{$e(r)}catch(s){e.push({dir:S.basename(t),file:o,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Lr(e){let t=[],n=[];for(let s of[ie,le]){if(!d.existsSync(s))continue;let i=d.readdirSync(s).filter(l=>l.endsWith(e));for(let l of i){let a=S.join(s,l),u=l.slice(0,-e.length),c=S.join(s,u);try{u.toLowerCase().endsWith(".json")?$e(a):d.accessSync(a,d.constants.R_OK),t.push({backupPath:a,originalPath:c,fileName:l,dir:s})}catch(m){n.push(`${S.basename(s)}/${l}: ${m.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:s,originalPath:i,fileName:l,dir:a}of t)try{_n(s,i),o++}catch(u){r.push(`${S.basename(a)}/${l}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function _n(e,t){let n=t+".tmp";try{d.copyFileSync(e,n),An(n)}catch(o){try{d.unlinkSync(n)}catch{}throw o}try{d.renameSync(n,t)}catch(o){try{d.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${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 r.code=o.code,r}throw o}}await En();var z=process.argv.slice(2),Ie=parseInt(z.find(e=>e.startsWith("--max="))?.split("=")[1]||"10"),ke=z.includes("--connections"),$n=z.find(e=>e.startsWith("--match-title="))?.split("=").slice(1).join("=")||null,_=$n?Ur($n):null,Pr=z.includes("--list"),Fr=z.includes("--verbose"),st=z.includes("--with-experience"),Mr=z.includes("--help")||z.includes("-h");Mr&&(console.log(`
285
+ `)}var Rr=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Tr(e){let t=e.toLowerCase();return Rr.some(n=>n.test(t))}var Dr=6e4;function Or(){let e=Date.now(),t=[];for(let n of[U,ie,le]){if(!d.existsSync(n))continue;let o;try{o=d.readdirSync(n)}catch{continue}for(let r of o){if(!Tr(r))continue;let s=S.join(n,r);try{let i=d.statSync(s);if(!i.isFile()||e-i.mtimeMs<Dr)continue;t.push({dir:n,file:r,fullPath:s})}catch{}}}return t}function Nr({verbose:e=!1}={}){let t=Or();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{d.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${S.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function jr(){let e=[];for(let t of[ie,le]){if(!d.existsSync(t))continue;let n=d.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=S.join(t,o);try{$e(r)}catch(s){e.push({dir:S.basename(t),file:o,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Lr(e){let t=[],n=[];for(let s of[ie,le]){if(!d.existsSync(s))continue;let i=d.readdirSync(s).filter(l=>l.endsWith(e));for(let l of i){let a=S.join(s,l),u=l.slice(0,-e.length),c=S.join(s,u);try{u.toLowerCase().endsWith(".json")?$e(a):d.accessSync(a,d.constants.R_OK),t.push({backupPath:a,originalPath:c,fileName:l,dir:s})}catch(m){n.push(`${S.basename(s)}/${l}: ${m.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:s,originalPath:i,fileName:l,dir:a}of t)try{_n(s,i),o++}catch(u){r.push(`${S.basename(a)}/${l}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function _n(e,t){let n=t+".tmp";try{d.copyFileSync(e,n),En(n)}catch(o){try{d.unlinkSync(n)}catch{}throw o}try{d.renameSync(n,t)}catch(o){try{d.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${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 r.code=o.code,r}throw o}}await An();var z=process.argv.slice(2),Ie=parseInt(z.find(e=>e.startsWith("--max="))?.split("=")[1]||"10"),ke=z.includes("--connections"),$n=z.find(e=>e.startsWith("--match-title="))?.split("=").slice(1).join("=")||null,_=$n?Ur($n):null,Pr=z.includes("--list"),Fr=z.includes("--verbose"),st=z.includes("--with-experience"),Mr=z.includes("--help")||z.includes("-h");Mr&&(console.log(`
286
286
  enrich-profiles \u2014 batch-visit contacts in people.json missing About text
287
287
 
288
288
  USAGE