ilml-plugin-linkedin 1.20.22 → 1.20.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/applyQueue.mjs +38 -38
- package/dist/connect.mjs +78 -77
- package/dist/daily.mjs +34 -34
- package/dist/enrichProfiles.mjs +50 -50
- package/dist/funnelRunner.mjs +61 -60
- package/dist/messageBot.mjs +67 -67
- package/dist/migrationCli.mjs +44 -44
- package/dist/peopleSearchCli.mjs +13 -0
- package/dist/quota.mjs +34 -34
- package/dist/run.mjs +65 -64
- package/dist/scout.mjs +33 -33
- package/dist/syncAll.mjs +99 -98
- package/dist/syncConnections.mjs +48 -48
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +35 -35
- package/dist/visit.mjs +48 -48
- package/ilml-plugin.json +19 -1
- package/package.json +2 -1
package/dist/migrationCli.mjs
CHANGED
|
@@ -1,62 +1,62 @@
|
|
|
1
|
-
var Ee=Object.defineProperty;var P=(e,n)=>{for(var o in n)Ee(e,o,{get:n[o],enumerable:!0})};import"dotenv/config";import"dotenv/config";import*as i from"fs";import*as K from"os";import*as c from"path";import{fileURLToPath as go}from"url";var W={};P(W,{NAME:()=>$e,VERSION:()=>je,up:()=>Ce});import*as E from"fs";import*as U from"path";var je=1,$e="normalize-jobs-and-questions",Ie=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Oe=50;function V(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function q(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{E.writeFileSync(t,o)}catch(r){try{E.unlinkSync(t)}catch{}throw r}try{E.renameSync(t,e)}catch(r){try{E.unlinkSync(t)}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 Ce(e,n){let o=U.join(e,"jobs.json"),t=U.join(n,"scouted-jobs.json"),r=U.join(e,"application-questions.json"),s=V(o)||{},l=V(t)||{},g=0,a=[];for(let p of Object.keys(s)){if(!l[p])continue;let k=l[p],d=s[p];for(let O of Ie)k[O]!=null&&d[O]==null&&(d[O]=k[O]);a.push(p),g++}g>0?(q(o,s),console.log(` Phase 1: Merged ${g} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=V(r);if(f&&Array.isArray(f.applications)){let p={},k=0;for(let d of f.applications){let O=d.jobId||"unknown";p[O]||(p[O]={applications:[]});let N=(d.questions||[]).map(y=>{let v={type:y.type||"input",question:y.question||"",answer:y.answer||""};return y.options&&(y.options.length<=Oe?v.options=y.options:(v.optionsOmitted=!0,k++)),y.page&&(v.page=y.page),y.wasPreFilled&&(v.wasPreFilled=!0),y.wasRetry&&(v.wasRetry=!0),v});p[O].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||N.length,questions:N})}q(r,p),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),k>0&&console.log(` Phase 2: Stripped bloated options from ${k} questions`)}else f&&!f.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 p of a)delete l[p];q(t,l),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var G={};P(G,{NAME:()=>_e,VERSION:()=>Re,up:()=>Te});import*as j from"fs";import*as X from"path";var Re=2,_e="reset-unread-flags";function Ne(e){return j.existsSync(e)?JSON.parse(j.readFileSync(e,"utf-8")):null}function De(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{j.writeFileSync(t,o)}catch(r){try{j.unlinkSync(t)}catch{}throw r}try{j.renameSync(t,e)}catch(r){try{j.unlinkSync(t)}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 Te(e){let n=X.join(e,"conversations.json"),o=Ne(n);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let t=0;for(let r of Object.keys(o))o[r].unread===!0&&(o[r].unread=!1,t++);if(t===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}De(n,o),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Y={};P(Y,{NAME:()=>Fe,VERSION:()=>xe,up:()=>Je});import*as $ from"fs";import*as Z from"path";var xe=3,Fe="recompute-last-message-by",Le=new Set(["draft","confirmed","rejected","needs_review"]);function Me(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function Pe(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{$.writeFileSync(t,o)}catch(r){try{$.unlinkSync(t)}catch{}throw r}try{$.renameSync(t,e)}catch(r){try{$.unlinkSync(t)}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 Ue(e,n){if(!e||e.length===0)return"them";let o=e.filter(s=>!Le.has(s.status));if(o.length===0)return"them";let t=o.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,l)=>l.t-s.t).map(s=>s.m),r=t.length>0?t:[...o].reverse();for(let s of r){let l=s.sender;if(l===n)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function Je(e){let n=Z.join(e,"conversations.json"),o=Me(n);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let t=process.env.LINKEDIN_NAME;if(!t||typeof t!="string"||!t.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,l=0;for(let g of Object.keys(o)){let a=o[g];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,s++);let f=Array.isArray(a.messages)?a.messages:[],p=Ue(f,t),k=p==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==p&&l++,a.lastMessageBy=p,a.conversationStatus=k,r++}if(r===0){console.log(" No conversations to recompute.");return}Pe(n,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${l} 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 H={};P(H,{NAME:()=>Ve,VERSION:()=>Be,up:()=>Ye});import*as I from"fs";import*as ee from"path";var Be=4,Ve="split-connection-timestamps",qe=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function We(e){if(!I.existsSync(e))return null;let n=I.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function Ge(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{I.writeFileSync(t,o)}catch(r){try{I.unlinkSync(t)}catch{}throw r}try{I.renameSync(t,e)}catch(r){try{I.unlinkSync(t)}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 Ye(e){let n=ee.join(e,"people.json"),o=We(n);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let t=0,r=0;for(let s of Object.keys(o)){let l=o[s];!l||typeof l!="object"||(r++,qe.has(l.connectionStatus)&&l.connectionDate&&!l.requestedConnectionAt&&(l.requestedConnectionAt=l.connectionDate,l.connectionDate=null,t++))}if(t===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ge(n,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${t} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import{getPluginConfig as ze}from"@ilivemylife/graph-sdk";var He={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},oe=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function Ke(e){return String(e??"").split(/[,\s|]+/).map(n=>n.trim()).filter(Boolean)}function ne(e=process.env){let n=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!n)return null;let o=new URLSearchParams;o.set("keywords",n);let t=(e.JOB_SEARCH_LOCATION||"").trim();t&&o.set("location",t);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&o.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&o.set("distance",String(s)),oe(e.JOB_SEARCH_EASY_APPLY)&&o.set("f_AL","true"),oe(e.JOB_SEARCH_IN_NETWORK)&&o.set("f_JIYN","true");let l=Ke(e.JOB_SEARCH_COMPANY_IDS);l.length&&o.set("f_C",l.join(","));let g=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();g&&o.set("f_TPR",He[g]||g),o.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let a="https://www.linkedin.com/jobs/search/?"+o.toString(),f=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return f&&(a+="&"+f),a}var Qe=await ze();for(let[e,n]of Object.entries(Qe))process.env[e]===void 0&&(process.env[e]=n);var te=ne(process.env);te&&(process.env.LINKEDIN_SEARCH_URL=te);var xo=process.env.LINKEDIN_NAME,D=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Fo=Object.freeze(new Set([D.DRAFT,D.CONFIRMED,D.NEEDS_REVIEW])),Lo=Object.freeze(new Set([D.DRAFT,D.CONFIRMED,D.REJECTED,D.NEEDS_REVIEW]));import"dotenv/config";import*as S from"path";import{fileURLToPath as Xe}from"url";var Ze=Xe(import.meta.url),eo=S.dirname(S.dirname(Ze)),T=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"collected-profiles"):S.join(eo,"collected-profiles"),Bo=S.join(T,"people.json"),Vo=S.join(T,"jobs.json"),qo=S.join(T,"quota.json"),Wo=S.join(T,"conversations.json"),Go=S.join(T,"sync-state.json"),Yo=S.join(T,"application-questions.json"),Ho=S.join(T,"profile-history"),re=(e,n)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:n},Ko=re(process.env.CONNECT_MAX_DAILY,20),zo=re(process.env.CONNECT_MAX_WEEKLY,100),oo=null,no=null,to=null,ro=null,so=null,io=null;function se(){oo=null,no=null,to=null,ro=null,so=null,io=null}import"dotenv/config";import*as w from"path";import{fileURLToPath as lo}from"url";var co=lo(import.meta.url),ao=w.dirname(w.dirname(co)),L=process.env.DATA_DIR?w.resolve(process.env.DATA_DIR,"market-research"):w.join(ao,"market-research"),rn=w.join(L,"scouted-jobs.json"),sn=w.join(L,"discovered-people.json"),ln=w.join(L,"visit-log.json"),cn=w.join(L,"companies.json"),an=w.join(L,"job-decisions.json");function ie(){uo=null,fo=null,po=null,mo=null,ho=null}var uo=null;var fo=null;var po=null;var mo=null;var ho=null;var yo=go(import.meta.url),So=c.dirname(yo),bo=c.dirname(c.dirname(So));function ko(e){return e&&(e==="~"?K.homedir():e.startsWith("~/")||e.startsWith("~\\")?c.join(K.homedir(),e.slice(2)):e)}var b=process.env.DATA_DIR?c.resolve(ko(process.env.DATA_DIR)):bo,R=c.join(b,"collected-profiles"),_=c.join(b,"market-research"),h=c.join(b,".schema-version"),le=[c.join(R,".schema-version"),c.join(_,".schema-version")],J=4,C=[{version:1,module:W},{version:2,module:G},{version:3,module:Y},{version:4,module:H}];(function(){C.sort((t,r)=>t.version-r.version);let n=new Set;for(let t of C){if(!Number.isInteger(t.version)||t.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(t.version)} (must be positive integer)`);if(n.has(t.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${t.version}`);n.add(t.version);let r=t.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${t.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==t.version)throw new Error(`MIGRATION_REGISTRY: v${t.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=C.length?C[C.length-1].version:0;if(o!==J)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${J}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<C.length;t++){let r=t+1;if(C[t].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${t} but found v${C[t].version}`)}})();function fe(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
1
|
+
var Ce=Object.defineProperty;var P=(e,o)=>{for(var n in o)Ce(e,n,{get:o[n],enumerable:!0})};import"dotenv/config";import"dotenv/config";import*as i from"fs";import*as Z from"os";import*as u from"path";import{fileURLToPath as Oo}from"url";var H={};P(H,{NAME:()=>_e,VERSION:()=>Re,up:()=>De});import*as E from"fs";import*as V from"path";var Re=1,_e="normalize-jobs-and-questions",Ne=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],xe=50;function G(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function Y(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{E.writeFileSync(t,n)}catch(r){try{E.unlinkSync(t)}catch{}throw r}try{E.renameSync(t,e)}catch(r){try{E.unlinkSync(t)}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 De(e,o){let n=V.join(e,"jobs.json"),t=V.join(o,"scouted-jobs.json"),r=V.join(e,"application-questions.json"),s=G(n)||{},c=G(t)||{},m=0,l=[];for(let p of Object.keys(s)){if(!c[p])continue;let h=c[p],d=s[p];for(let C of Ne)h[C]!=null&&d[C]==null&&(d[C]=h[C]);l.push(p),m++}m>0?(Y(n,s),console.log(` Phase 1: Merged ${m} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=G(r);if(a&&Array.isArray(a.applications)){let p={},h=0;for(let d of a.applications){let C=d.jobId||"unknown";p[C]||(p[C]={applications:[]});let x=(d.questions||[]).map(S=>{let v={type:S.type||"input",question:S.question||"",answer:S.answer||""};return S.options&&(S.options.length<=xe?v.options=S.options:(v.optionsOmitted=!0,h++)),S.page&&(v.page=S.page),S.wasPreFilled&&(v.wasPreFilled=!0),S.wasRetry&&(v.wasRetry=!0),v});p[C].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||x.length,questions:x})}Y(r,p),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),h>0&&console.log(` Phase 2: Stripped bloated options from ${h} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let p of l)delete c[p];Y(t,c),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(c).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var K={};P(K,{NAME:()=>Fe,VERSION:()=>Te,up:()=>Pe});import*as j from"fs";import*as ne from"path";var Te=2,Fe="reset-unread-flags";function Le(e){return j.existsSync(e)?JSON.parse(j.readFileSync(e,"utf-8")):null}function Me(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{j.writeFileSync(t,n)}catch(r){try{j.unlinkSync(t)}catch{}throw r}try{j.renameSync(t,e)}catch(r){try{j.unlinkSync(t)}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 Pe(e){let o=ne.join(e,"conversations.json"),n=Le(o);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let t=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,t++);if(t===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Me(o,n),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var z={};P(z,{NAME:()=>Je,VERSION:()=>Ue,up:()=>Ge});import*as $ from"fs";import*as te from"path";var Ue=3,Je="recompute-last-message-by",Be=new Set(["draft","confirmed","rejected","needs_review"]);function Ve(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function qe(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{$.writeFileSync(t,n)}catch(r){try{$.unlinkSync(t)}catch{}throw r}try{$.renameSync(t,e)}catch(r){try{$.unlinkSync(t)}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 We(e,o){if(!e||e.length===0)return"them";let n=e.filter(s=>!Be.has(s.status));if(n.length===0)return"them";let t=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,c)=>c.t-s.t).map(s=>s.m),r=t.length>0?t:[...n].reverse();for(let s of r){let c=s.sender;if(c===o)return"me";if(c!=="Unknown"&&c!=="")return"them"}return"them"}async function Ge(e){let o=te.join(e,"conversations.json"),n=Ve(o);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let t=process.env.LINKEDIN_NAME;if(!t||typeof t!="string"||!t.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,c=0;for(let m of Object.keys(n)){let l=n[m];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,s++);let a=Array.isArray(l.messages)?l.messages:[],p=We(a,t),h=p==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==p&&c++,l.lastMessageBy=p,l.conversationStatus=h,r++}if(r===0){console.log(" No conversations to recompute.");return}qe(o,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${c} 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 Q={};P(Q,{NAME:()=>He,VERSION:()=>Ye,up:()=>Xe});import*as O from"fs";import*as re from"path";var Ye=4,He="split-connection-timestamps",Ke=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ze(e){if(!O.existsSync(e))return null;let o=O.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Qe(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{O.writeFileSync(t,n)}catch(r){try{O.unlinkSync(t)}catch{}throw r}try{O.renameSync(t,e)}catch(r){try{O.unlinkSync(t)}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 Xe(e){let o=re.join(e,"people.json"),n=ze(o);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let t=0,r=0;for(let s of Object.keys(n)){let c=n[s];!c||typeof c!="object"||(r++,Ke.has(c.connectionStatus)&&c.connectionDate&&!c.requestedConnectionAt&&(c.requestedConnectionAt=c.connectionDate,c.connectionDate=null,t++))}if(t===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Qe(o,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${t} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var X={};P(X,{NAME:()=>eo,VERSION:()=>Ze,up:()=>ro});import*as I from"fs";import*as se from"path";var Ze=5,eo="rename-headline-to-title",D=/[·•]\s*(1st|2nd|3rd)\+?/i,oo=e=>(e||"").replace(/\s+/g," ").trim(),U=e=>oo(e).replace(/^[+·•\s]+/,"").replace(/[·•\s]+$/,"");function no(e){if(!I.existsSync(e))return null;let o=I.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function to(e,o){let n=JSON.stringify(o),t=e+".tmp";try{I.writeFileSync(t,n)}catch(r){try{I.unlinkSync(t)}catch{}throw r}try{I.renameSync(t,e)}catch(r){try{I.unlinkSync(t)}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 ro(e,o){let n=se.join(o,"discovered-people.json"),t=no(n);if(!t||typeof t!="object"){console.log(" discovered-people.json not found \u2014 nothing to migrate.");return}let r=Array.isArray(t)?t:Object.values(t),s=0,c=0,m=0;for(let l of r)if(!(!l||typeof l!="object")){if(s++,l.name&&D.test(l.name)){let a=U(String(l.name).split(D)[0]),p=String(l.name).match(/[·•]\s*(?:1st|2nd|3rd)\+?\s*(.+)$/i),h=p?U(p[1]):"";a&&(l.name=a,c++),h&&(!l.headline||D.test(String(l.headline))||!U(l.headline))&&(l.headline=h)}if(Object.prototype.hasOwnProperty.call(l,"headline")){let a=U(l.headline||"");D.test(a)&&(a=""),(!l.title||D.test(String(l.title)))&&(l.title=a||(l.title&&!D.test(String(l.title))?l.title:null)||null),delete l.headline,m++}else if(typeof l.title=="string"){let a=U(l.title);a&&!D.test(a)&&a!==l.title&&(l.title=a)}}if(m===0&&c===0){console.log(` Scanned ${s} discovered people \u2014 already unified (no headline field, clean names).`);return}to(n,t),console.log(` discovered-people.json: scanned ${s}, de-glued ${c} names, moved ${m} headline\u2192title.`),console.log(" Every record now carries a single `title` field (matches people.json).")}import{getPluginConfig as lo}from"@ilivemylife/graph-sdk";var so={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},ie=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function io(e){return String(e??"").split(/[,\s|]+/).map(o=>o.trim()).filter(Boolean)}function le(e=process.env){let o=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!o)return null;let n=new URLSearchParams;n.set("keywords",o);let t=(e.JOB_SEARCH_LOCATION||"").trim();t&&n.set("location",t);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)),ie(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),ie(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let c=io(e.JOB_SEARCH_COMPANY_IDS);c.length&&n.set("f_C",c.join(","));let m=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();m&&n.set("f_TPR",so[m]||m),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let l="https://www.linkedin.com/jobs/search/?"+n.toString(),a=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return a&&(l+="&"+a),l}var co=await lo();for(let[e,o]of Object.entries(co))process.env[e]===void 0&&(process.env[e]=o);var ce=le(process.env);ce&&(process.env.LINKEDIN_SEARCH_URL=ce);var Go=process.env.LINKEDIN_NAME,T=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Yo=Object.freeze(new Set([T.DRAFT,T.CONFIRMED,T.NEEDS_REVIEW])),Ho=Object.freeze(new Set([T.DRAFT,T.CONFIRMED,T.REJECTED,T.NEEDS_REVIEW]));import"dotenv/config";import*as b from"path";import{fileURLToPath as ao}from"url";var uo=ao(import.meta.url),fo=b.dirname(b.dirname(uo)),F=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"collected-profiles"):b.join(fo,"collected-profiles"),Zo=b.join(F,"people.json"),en=b.join(F,"jobs.json"),on=b.join(F,"quota.json"),nn=b.join(F,"conversations.json"),tn=b.join(F,"sync-state.json"),rn=b.join(F,"application-questions.json"),sn=b.join(F,"profile-history"),ae=(e,o)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:o},ln=ae(process.env.CONNECT_MAX_DAILY,20),cn=ae(process.env.CONNECT_MAX_WEEKLY,100),po=null,mo=null,ho=null,go=null,yo=null,So=null;function ue(){po=null,mo=null,ho=null,go=null,yo=null,So=null}import"dotenv/config";import*as w from"path";import{fileURLToPath as bo}from"url";var ko=bo(import.meta.url),vo=w.dirname(w.dirname(ko)),J=process.env.DATA_DIR?w.resolve(process.env.DATA_DIR,"market-research"):w.join(vo,"market-research"),gn=w.join(J,"scouted-jobs.json"),yn=w.join(J,"discovered-people.json"),Sn=w.join(J,"visit-log.json"),bn=w.join(J,"companies.json"),kn=w.join(J,"job-decisions.json");function fe(){wo=null,Ao=null,Eo=null,jo=null,$o=null}var wo=null;var Ao=null;var Eo=null;var jo=null;var $o=null;var Io=Oo(import.meta.url),Co=u.dirname(Io),Ro=u.dirname(u.dirname(Co));function _o(e){return e&&(e==="~"?Z.homedir():e.startsWith("~/")||e.startsWith("~\\")?u.join(Z.homedir(),e.slice(2)):e)}var k=process.env.DATA_DIR?u.resolve(_o(process.env.DATA_DIR)):Ro,_=u.join(k,"collected-profiles"),N=u.join(k,"market-research"),y=u.join(k,".schema-version"),pe=[u.join(_,".schema-version"),u.join(N,".schema-version")],q=5,R=[{version:1,module:H},{version:2,module:K},{version:3,module:z},{version:4,module:Q},{version:5,module:X}];(function(){R.sort((t,r)=>t.version-r.version);let o=new Set;for(let t of R){if(!Number.isInteger(t.version)||t.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(t.version)} (must be positive integer)`);if(o.has(t.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${t.version}`);o.add(t.version);let r=t.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${t.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==t.version)throw new Error(`MIGRATION_REGISTRY: v${t.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=R.length?R[R.length-1].version:0;if(n!==q)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${q}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<R.length;t++){let r=t+1;if(R[t].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${t} but found v${R[t].version}`)}})();function ge(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
2
2
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
3
|
-
`),process.exit(1));try{i.mkdirSync(
|
|
4
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
5
|
-
`),process.exit(1))}let e;try{e=i.statSync(
|
|
6
|
-
[FATAL] DATA_DIR (${
|
|
3
|
+
`),process.exit(1));try{i.mkdirSync(k,{recursive:!0})}catch(o){o.code!=="EEXIST"&&(console.error(`
|
|
4
|
+
[FATAL] Cannot create DATA_DIR (${k}): ${o.message}`),console.error(` Fix the path or permissions and try again.
|
|
5
|
+
`),process.exit(1))}let e;try{e=i.statSync(k)}catch(o){console.error(`
|
|
6
|
+
[FATAL] DATA_DIR (${k}) is not accessible: ${o.message}
|
|
7
7
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
8
|
-
[FATAL] DATA_DIR (${
|
|
9
|
-
`),process.exit(1));for(let
|
|
10
|
-
[FATAL] Data subdirectory is a symbolic link: ${
|
|
11
|
-
`),process.exit(1))}}var
|
|
12
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${
|
|
8
|
+
[FATAL] DATA_DIR (${k}) 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.
|
|
9
|
+
`),process.exit(1));for(let o of[_,N]){let n;try{n=i.lstatSync(o)}catch(t){if(t.code==="ENOENT")continue;throw t}n.isSymbolicLink()&&(console.error(`
|
|
10
|
+
[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.
|
|
11
|
+
`),process.exit(1))}}var L=u.join(k,".migration-lock");function ye(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return i.writeFileSync(L,e,{flag:"wx"}),!0}catch(t){if(t.code!=="EEXIST")throw t}let o;try{o=JSON.parse(i.readFileSync(L,"utf-8"))}catch{o=null}if(o&&Number.isInteger(o.pid)){let t=!1;try{process.kill(o.pid,0),t=!0}catch(c){c.code==="EPERM"&&(t=!0)}let r=24*60*60*1e3,s=1/0;if(o.startedAt){let c=Date.parse(o.startedAt);Number.isNaN(c)||(s=Date.now()-c)}t&&s<r&&(console.error(`
|
|
12
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${o.pid}`),console.error(` Started at: ${o.startedAt||"(unknown)"}`),console.error(` Lock file: ${L}
|
|
13
13
|
`),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.
|
|
14
|
-
`),process.exit(1)),t&&s>=r&&console.log(` Lock holder PID ${
|
|
15
|
-
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of
|
|
14
|
+
`),process.exit(1)),t&&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 n=L+".tmp";try{return i.writeFileSync(n,e),i.renameSync(n,L),!0}catch(t){try{i.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${t.message}`)}}function B(){try{if(JSON.parse(i.readFileSync(L,"utf-8")).pid!==process.pid)return;i.unlinkSync(L)}catch{}}var de=!1;function Se(){if(de)return;de=!0;let e=()=>{try{B()}catch{}process.exit(1)};for(let o of["SIGINT","SIGTERM","SIGHUP"])try{process.on(o,e)}catch{}}function No(){if(i.existsSync(y))return;let e=[],o=[];for(let s of pe)if(i.existsSync(s))try{e.push({file:s,schema:W(s)})}catch(c){o.push({file:s,err:c.message})}if(o.length>0){console.error(`
|
|
15
|
+
[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(`
|
|
16
16
|
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.
|
|
17
|
-
`),process.exit(1)}if(e.length===0)return;let
|
|
17
|
+
`),process.exit(1)}if(e.length===0)return;let n=e.map(s=>s.schema.version);if(new Set(n).size>1){console.error(`
|
|
18
18
|
[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.
|
|
19
|
-
`),process.exit(1)}let t=e[0].schema,r=
|
|
20
|
-
[FATAL] ${
|
|
21
|
-
`),process.exit(1)}let
|
|
22
|
-
[FATAL] ${
|
|
23
|
-
`),process.exit(1)),
|
|
19
|
+
`),process.exit(1)}let t=e[0].schema,r=y+".tmp";try{i.writeFileSync(r,JSON.stringify(t,null,2)),i.renameSync(r,y)}catch(s){try{i.unlinkSync(r)}catch{}throw s}for(let s of pe)if(i.existsSync(s))try{i.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${y}`)}function xo(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let o=Number(e.version);return!Number.isFinite(o)||o<0||!Number.isInteger(o)?null:(e.version=o,Array.isArray(e.migrations)||(e.migrations=[]),e)}function W(e){let o=i.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function ee(){if(No(),!i.existsSync(y))return{version:0,migrations:[]};let e;try{e=W(y)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
20
|
+
[FATAL] ${y} 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.
|
|
21
|
+
`),process.exit(1)}let o=xo(e);return o===null&&(console.error(`
|
|
22
|
+
[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.
|
|
23
|
+
`),process.exit(1)),o}function be(e){try{i.chmodSync(e,384)}catch{}}function Do(e){if(ge(),i.existsSync(y))try{if(i.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(n){if(n.message?.includes("symbolic link"))throw n}let o=y+".tmp";try{i.writeFileSync(o,JSON.stringify(e,null,2)),be(o),i.renameSync(o,y)}catch(n){try{i.unlinkSync(o)}catch{}throw n}}function me(e,o){return i.existsSync(e)?i.readdirSync(e).filter(n=>n.endsWith(o)):[]}var To=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Fo(e){let o=e.toLowerCase();return To.some(n=>n.test(o))}var Lo=6e4;function ke(){let e=Date.now(),o=[];for(let n of[k,_,N]){if(!i.existsSync(n))continue;let t;try{t=i.readdirSync(n)}catch{continue}for(let r of t){if(!Fo(r))continue;let s=u.join(n,r);try{let c=i.statSync(s);if(!c.isFile()||e-c.mtimeMs<Lo)continue;o.push({dir:n,file:r,fullPath:s})}catch{}}}return o}function Mo({verbose:e=!1}={}){let o=ke();if(o.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let t of o)try{i.unlinkSync(t.fullPath),n++,e&&console.log(` Removed orphan: ${u.basename(t.dir)}/${t.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${t.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function ve(){let e=[];for(let o of[_,N])if(i.existsSync(o))for(let n of i.readdirSync(o))/\.pre-rollback-v\d+\.backup$/.test(n)&&e.push({dir:o,file:n,fullPath:u.join(o,n)});return e}function we({removePreRollback:e=!0}={}){if(console.log(`
|
|
24
24
|
\u{1F4E6} Data cleanup
|
|
25
|
-
`),!i.existsSync(
|
|
26
|
-
`);return}
|
|
25
|
+
`),!i.existsSync(k)){console.log(` DATA_DIR not yet created (${k}) \u2014 nothing to clean.
|
|
26
|
+
`);return}ge();let o=!1;try{Se(),ye(),o=!0,process.on("exit",()=>{o&&B()})}catch(r){console.error(`
|
|
27
27
|
[ERROR] Could not acquire cleanup lock: ${r.message}
|
|
28
|
-
`),process.exit(1)}let
|
|
29
|
-
Done. Removed ${
|
|
30
|
-
`)}function
|
|
28
|
+
`),process.exit(1)}let n=Mo({verbose:!0}),t=0;if(e){let r=ve();if(r.length===0)console.log(" No pre-rollback snapshots found.");else for(let s of r)try{i.unlinkSync(s.fullPath),t++,console.log(` Removed pre-rollback snapshot: ${u.basename(s.dir)}/${s.file}`)}catch(c){console.warn(` [!] Could not remove ${s.fullPath}: ${c.message}`)}}o&&(B(),o=!1),console.log(`
|
|
29
|
+
Done. Removed ${n} orphan .tmp + ${t} pre-rollback snapshot(s).`),console.log(` NOTE: .pre-vNNN.backup files are kept \u2014 they're needed for 'rollback-data'.
|
|
30
|
+
`)}function Po(){let e=[];for(let o of[_,N]){if(!i.existsSync(o))continue;let n=i.readdirSync(o).filter(t=>{let r=t.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let t of n){let r=u.join(o,t);try{W(r)}catch(s){e.push({dir:u.basename(o),file:t,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function he(e,o){let n=o+".tmp";try{i.copyFileSync(e,n),be(n)}catch(t){try{i.unlinkSync(n)}catch{}throw t}try{i.renameSync(n,o)}catch(t){try{i.unlinkSync(n)}catch{}if(t.code==="EPERM"||t.code==="EBUSY"){let r=new Error(`File locked: ${o} (${t.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=t.code,r}throw t}}function Ae(){console.log(`
|
|
31
31
|
\u{1F4E6} Migration status
|
|
32
|
-
`);let e=
|
|
32
|
+
`);let e=ee();if(console.log(` Data root: ${k}`),console.log(` Schema file: ${y}${i.existsSync(y)?"":" (not yet created \u2014 fresh install)"}`),console.log(` Current version: v${e.version}`),e.migrations?.length){console.log(" Applied migrations:");for(let s of e.migrations){if(!s||typeof s!="object"){console.log(` (malformed entry: ${JSON.stringify(s)})`);continue}let c=String(s.version??"?").padStart(3,"0");console.log(` v${c} \u2014 ${s.name??"(no name)"} (at ${s.appliedAt??"?"})`)}}e.rolledBackAt&&console.log(` Last rollback: ${e.rolledBackAt}`);for(let[s,c]of[["collected-profiles",_],["market-research",N]]){if(!i.existsSync(c))continue;let m=i.readdirSync(c).filter(l=>/\.pre-v\d+\.backup$/.test(l));if(m.length){let l=[...new Set(m.map(a=>a.match(/\.pre-v(\d+)\.backup$/)[1]))].sort();console.log(` Pre-migration backups in ${s}/: ${l.map(a=>`v${a} (${m.filter(p=>p.includes(`pre-v${a}`)).length} files)`).join(", ")}`)}}let o=ve();o.length>0&&console.log(` Pre-rollback snapshots: ${o.length} file(s) (run 'data-cleanup' to remove)`);let n=ke();if(n.length>0){console.log(` Orphan .tmp files: ${n.length} (will be cleaned on next plugin run, or now via 'data-cleanup')`);for(let s of n)console.log(` ${u.basename(s.dir)}/${s.file}`)}console.log(),console.log(` Latest available schema: v${q}`);let t=R.filter(s=>s.version>e.version);t.length?(console.log(` Pending: ${t.map(s=>`v${String(s.version).padStart(3,"0")}`).join(", ")}`),console.log(" Run any plugin command (e.g. 'ilml linkedin today') to apply pending migrations.")):console.log(" \u2713 Up to date."),console.log();let r=Po();if(r.ok)console.log(" Data integrity: \u2713 all JSON files parse cleanly");else{console.log(` Data integrity: \u2717 ${r.broken.length} file(s) corrupted:`);for(let s of r.broken)console.log(` ${s.dir}/${s.file}: ${s.err}`);console.log(" Migrations will refuse to run until these are repaired.")}console.log()}async function Ee({confirmed:e=!1}={}){let n=ee().version;if(n===0){console.log(`
|
|
33
33
|
No migrations applied \u2014 nothing to roll back.
|
|
34
|
-
`);return}let t=!1,r=`.pre-v${String(
|
|
35
|
-
[ERROR] No backup files (${r}) found in either data directory.`),console.error(` Cannot roll back v${
|
|
34
|
+
`);return}let t=!1,r=`.pre-v${String(n).padStart(3,"0")}.backup`,s=me(_,r),c=me(N,r);if(s.length+c.length===0&&(console.error(`
|
|
35
|
+
[ERROR] No backup files (${r}) found in either data directory.`),console.error(` Cannot roll back v${n} \u2014 backups may have been deleted.
|
|
36
36
|
`),process.exit(1)),!e){console.log(`
|
|
37
37
|
\u26A0 rollback-data ONLY rolls back DATA, NOT the plugin code.
|
|
38
38
|
`),console.log(" The full rollback is a TWO-STEP procedure. Doing only step 1 leaves you"),console.log(` in a broken state where the next plugin run will re-apply the migration.
|
|
39
|
-
`),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` STEP 1 (this command): roll back DATA schema v${
|
|
40
|
-
`),console.log(" Between step 1 and step 2: DO NOT run any 'ilml linkedin' command."),console.log(` The current plugin (CURRENT_SCHEMA_VERSION=${
|
|
41
|
-
`),console.log(" This step 1 will also:"),console.log(" - OVERWRITE current data with the pre-migration backup"),console.log(` (${s.length} files in collected-profiles/, ${
|
|
39
|
+
`),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` STEP 1 (this command): roll back DATA schema v${n} \u2192 v${n-1}`),console.log(" STEP 2 (you, after): roll back CODE ilml plugin install linkedin@<previous>"),console.log(` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
40
|
+
`),console.log(" Between step 1 and step 2: DO NOT run any 'ilml linkedin' command."),console.log(` The current plugin (CURRENT_SCHEMA_VERSION=${q}) will see your data on v${n-1}`),console.log(` and immediately re-apply migration v${n}, undoing this rollback.
|
|
41
|
+
`),console.log(" This step 1 will also:"),console.log(" - OVERWRITE current data with the pre-migration backup"),console.log(` (${s.length} files in collected-profiles/, ${c.length} in market-research/)`),console.log(` - Permanently LOSE any data changes made after migration v${n}`),console.log(" (new conversations synced, drafts written, notes added \u2014 all gone)"),console.log(` - Snapshot current state to *.pre-rollback-v${String(n).padStart(3,"0")}.backup before overwriting
|
|
42
42
|
`),console.log(" If you only need to inspect old data without downgrading the plugin,"),console.log(" copy your DATA_DIR somewhere else and use that copy instead \u2014 leaves your"),console.log(` live setup untouched.
|
|
43
43
|
`),console.log(" Proceed with step 1? Re-run with --confirm:"),console.log(" npm run rollback:data -- --confirm"),console.log(` ilml linkedin rollback-data --confirm
|
|
44
|
-
`);return}
|
|
45
|
-
[FATAL] ${
|
|
46
|
-
Aborting rollback \u2014 without a complete snapshot of your CURRENT state, a`),console.error(' "change your mind" recovery would silently lose the data you have NOW.'),console.error(` Your current data is unchanged. Pre-rollback snapshots created so far: *${
|
|
47
|
-
`),process.exit(1)}console.log(` Snapshotted ${p} files \u2192 *${
|
|
48
|
-
[ERROR] ${d.length} backup file(s) are corrupted or unreadable:`);for(let
|
|
49
|
-
Aborting rollback BEFORE touching any original file \u2014`),console.error(" partial restore would leave the DB in an inconsistent state."),console.error(` Your current data is unchanged. Pre-rollback snapshots: *${
|
|
44
|
+
`);return}Se(),ye(),t=!0,process.on("exit",()=>{t&&B()});let l=`.pre-rollback-v${String(n).padStart(3,"0")}.backup`,a=[],p=0;for(let f of[_,N]){if(!i.existsSync(f))continue;let M;try{M=i.readdirSync(f).filter(g=>{let A=g.toLowerCase();if(A.includes(".backup")||A===".schema-version"||A.endsWith(".tmp"))return!1;try{return i.statSync(u.join(f,g)).isFile()}catch{return!1}})}catch(g){a.push(`${u.basename(f)}: ${g.message}`);continue}for(let g of M)try{he(u.join(f,g),u.join(f,g+l)),p++}catch(A){a.push(`${u.basename(f)}/${g}: ${A.message}`)}}if(a.length>0){console.error(`
|
|
45
|
+
[FATAL] ${a.length} file(s) could not be snapshotted:`);for(let f of a)console.error(` ${f}`);console.error(`
|
|
46
|
+
Aborting rollback \u2014 without a complete snapshot of your CURRENT state, a`),console.error(' "change your mind" recovery would silently lose the data you have NOW.'),console.error(` Your current data is unchanged. Pre-rollback snapshots created so far: *${l}`),console.error(" (run 'data-cleanup' to remove them, or retry the rollback once the underlying"),console.error(` issue is resolved \u2014 usually a transient file lock from antivirus or an editor).
|
|
47
|
+
`),process.exit(1)}console.log(` Snapshotted ${p} files \u2192 *${l} (in case you change your mind)`);let h=[],d=[];for(let[f,M]of[[_,s],[N,c]])for(let g of M){let A=u.join(f,g),oe=g.slice(0,-r.length),Oe=u.join(f,oe);try{oe.toLowerCase().endsWith(".json")?W(A):i.accessSync(A,i.constants.R_OK),h.push({backupPath:A,originalPath:Oe,fileName:g})}catch(Ie){d.push({file:g,dir:u.basename(f),err:Ie.message})}}if(d.length>0){console.error(`
|
|
48
|
+
[ERROR] ${d.length} backup file(s) are corrupted or unreadable:`);for(let f of d)console.error(` ${f.dir}/${f.file}: ${f.err}`);console.error(`
|
|
49
|
+
Aborting rollback BEFORE touching any original file \u2014`),console.error(" partial restore would leave the DB in an inconsistent state."),console.error(` Your current data is unchanged. Pre-rollback snapshots: *${l}
|
|
50
50
|
`),console.error(" Options:"),console.error(" - Restore the corrupted backup(s) from another source and re-run rollback"),console.error(` - Or accept the new schema and don't roll back
|
|
51
|
-
`),process.exit(1)}
|
|
51
|
+
`),process.exit(1)}h.length===0&&(console.error(`
|
|
52
52
|
[ERROR] No backup files found to restore. Aborting.
|
|
53
|
-
`),process.exit(1));let
|
|
54
|
-
[WARNING] ${v.length} file(s) could not be restored:`);for(let
|
|
55
|
-
Schema has been lowered to v${
|
|
56
|
-
`),process.exit(1)}try{
|
|
57
|
-
\u2713 STEP 1 DONE. Restored ${
|
|
58
|
-
`),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" \u26A0 STEP 2 REQUIRED \u2014 DO NOT RUN ANY 'ilml linkedin' COMMAND UNTIL"),console.log(` YOU DOWNGRADE THE PLUGIN CODE, or migration v${
|
|
53
|
+
`),process.exit(1));let C=new Date().toISOString(),x=ee();x.version=n-1,x.migrations=(x.migrations||[]).filter(f=>f&&Number.isInteger(f.version)&&f.version<n),x.rolledBackAt=C,Do(x);let S=0,v=[];for(let{backupPath:f,originalPath:M,fileName:g}of h)try{he(f,M),S++}catch(A){v.push({fileName:g,err:A.message})}if(v.length>0){console.error(`
|
|
54
|
+
[WARNING] ${v.length} file(s) could not be restored:`);for(let f of v)console.error(` ${f.fileName}: ${f.err}`);console.error(`
|
|
55
|
+
Schema has been lowered to v${n-1} but data is in a mixed state:`),console.error(` ${S} files restored from backup`),console.error(` ${v.length} files still in their post-migration form`),console.error(` The next plugin run will detect pending migration v${n} and re-apply it,`),console.error(" re-converging the data \u2014 but if you intended to roll back, that's not what you want."),console.error(` Manual fix: copy the missing *${r} files back over their originals, then`),console.error(" re-run 'rollback-data --confirm' to redo the rollback. Pre-rollback snapshots"),console.error(` (*${l}) are still on disk if you'd rather restore the v${n} state.
|
|
56
|
+
`),process.exit(1)}try{ue()}catch{}try{fe()}catch{}B(),t=!1,console.log(`
|
|
57
|
+
\u2713 STEP 1 DONE. Restored ${S} files. Data schema is now at v${n-1}.
|
|
58
|
+
`),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" \u26A0 STEP 2 REQUIRED \u2014 DO NOT RUN ANY 'ilml linkedin' COMMAND UNTIL"),console.log(` YOU DOWNGRADE THE PLUGIN CODE, or migration v${n} will be re-applied`),console.log(" and this rollback will be silently undone."),console.log(` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
59
59
|
`),console.log(" Run NOW (or as soon as possible):"),console.log(` ilml plugin install linkedin@<previous-version>
|
|
60
|
-
`),console.log(` If something looks wrong, your pre-rollback snapshot is in *${
|
|
61
|
-
`)}var
|
|
60
|
+
`),console.log(` If something looks wrong, your pre-rollback snapshot is in *${l} files`),console.log(` \u2014 copy them back manually to undo this rollback.
|
|
61
|
+
`)}var $e=process.argv.slice(2),je=$e[0],Uo=$e.includes("--confirm");async function Jo(){switch(je){case"status":Ae();break;case"rollback-data":await Ee({confirmed:Uo});break;case"data-cleanup":we();break;default:console.log("Usage:"),console.log(" node migrationCli.mjs status Show schema state + leftover files"),console.log(" node migrationCli.mjs data-cleanup Remove .tmp orphans + pre-rollback snapshots"),console.log(" node migrationCli.mjs rollback-data Preview data rollback (read-only)"),console.log(" node migrationCli.mjs rollback-data --confirm Actually roll back data"),console.log(""),console.log("Note: rollback-data only touches DATA. To roll back the plugin code as well,"),console.log("also run: ilml plugin install linkedin@<previous-version>"),process.exit(je?1:0)}}Jo().catch(e=>{console.error(`
|
|
62
62
|
[ERROR]`,e.message),process.env.VERBOSE&&console.error(e.stack),process.exit(1)});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import"dotenv/config";import dt from"puppeteer";import{addExtra as mt}from"puppeteer-extra";import pt from"puppeteer-extra-plugin-stealth";import _ from"fs";import v from"path";var Ke="cookies.json";function Y(){let e=process.env.ILML_SCOPE_DIR;return e?v.join(e,"plugins-state","linkedin","cookies.json"):Ke}function Ve(){let e=Y(),t=v.dirname(e);return t&&t!=="."&&!_.existsSync(t)&&_.mkdirSync(t,{recursive:!0}),e}function se(e){let t=Ve();return _.writeFileSync(t,JSON.stringify(e)),t}function ie(){let e=Y();if(!_.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=_.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 ae(){return _.existsSync(Y())}function ze(){let e=process.env.ILML_SCOPE_DIR;return e?v.join(e,"plugins-state","linkedin"):"."}function ce(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Qe(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?ce(t[1]):"default"}function le(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return _.existsSync(t)||_.mkdirSync(t,{recursive:!0}),v.resolve(t);let n=ce(e||Qe()),o=v.join(ze(),"chrome-profile",n);return _.existsSync(o)||_.mkdirSync(o,{recursive:!0}),v.resolve(o)}var ue=".ilml-seeded";function fe(e){return!_.existsSync(v.join(e,ue))}function de(e){try{_.writeFileSync(v.join(e,ue),new Date().toISOString())}catch{}}function me(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{_.rmSync(v.join(e,n),{force:!0}),t++}catch{}return t}async function G(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function Xe(e,t,{timeout:n=45e3,poll:o=1e3,label:s="page"}={}){let i=Date.now();for(;Date.now()-i<n;){try{if(await e.evaluate(u=>!!document.querySelector(u),t)){let u=Date.now()-i;return u>6e3&&console.log(` (waited ${Math.round(u/1e3)}s for LinkedIn to finish loading ${s})`),!0}}catch{}await new Promise(r=>setTimeout(r,o))}return!1}var he=/\/authwall|\/login|\/checkpoint|\/uas\/login/;function Ze(e){return he.test(e||"")}async function et(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),s=o?t:Math.min(t,45e3),i=Date.now(),r=!1;for(;Date.now()-i<s;){let f="wait";try{f=await e.evaluate(l=>!new RegExp(l).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",he.source)}catch{}if(f==="in"){try{let l=await e.cookies();if(Array.isArray(l)&&l.some(c=>c.name==="li_at")){let c=se(l);console.log(` \u2713 Session recovered \u2014 re-saved ${l.length} cookies (${c}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(l){console.log(` \u2713 Session recovered (cookie re-save skipped: ${l.message}).`)}return!0}if(f==="creds"){if(!o){let l=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}r||(r=!0,console.log(`
|
|
2
|
+
\u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
|
|
3
|
+
`))}await new Promise(l=>setTimeout(l,2500))}let u=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw u.code="SESSION_EXPIRED",u}async function pe(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let s=await Xe(e,t,{timeout:o,label:n});if(!s&&Ze(e.url())){let i=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw i.code="SESSION_EXPIRED",i}return s}async function K(e,t,{readySelector:n,label:o="page",timeout:s=45e3,gotoTimeout:i=6e4,autoRecover:r=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:i});try{return await pe(e,{readySelector:n,label:o,timeout:s})}catch(u){if(r&&u.code==="SESSION_EXPIRED"){await et(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:i})}catch{}return await pe(e,{readySelector:n,label:o,timeout:s})}throw u}}import{getPluginConfig as ot}from"@ilivemylife/graph-sdk";var tt={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},ge=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function nt(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function ye(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 s=(e.JOB_SEARCH_GEO_ID||"").trim();s&&n.set("geoId",s);let i=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(i)&&i>0&&n.set("distance",String(i)),ge(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),ge(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let r=nt(e.JOB_SEARCH_COMPANY_IDS);r.length&&n.set("f_C",r.join(","));let u=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();u&&n.set("f_TPR",tt[u]||u),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let f="https://www.linkedin.com/jobs/search/?"+n.toString(),l=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return l&&(f+="&"+l),f}var rt=await ot();for(let[e,t]of Object.entries(rt))process.env[e]===void 0&&(process.env[e]=t);var we=ye(process.env);we&&(process.env.LINKEDIN_SEARCH_URL=we);var Se=process.env.LINKEDIN_NAME,A=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),st=Object.freeze(new Set([A.DRAFT,A.CONFIRMED,A.NEEDS_REVIEW])),be=Object.freeze(new Set([A.DRAFT,A.CONFIRMED,A.REJECTED,A.NEEDS_REVIEW]));import V from"fs";import it from"path";var at={headless:!1,defaultViewport:null,protocolTimeout:3e5},O=new Set,_e=!1;async function F(){let e=[...O].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});O.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function ct(){if(_e)return;_e=!0;let e=t=>async()=>{await F(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await F(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await F(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await F(),process.exit(0))}),process.on("exit",()=>{for(let t of O)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function z(e){return it.join(e,".ilml-browser-session.json")}function xe(e,t={}){try{V.writeFileSync(z(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function lt(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();xe(e,n?{wsEndpoint:n}:{})}catch{}}function ut(e){let t=Ae(e);t&&t.ownerPid===process.pid&&j(e)}function j(e){try{V.rmSync(z(e),{force:!0})}catch{}}function Ae(e){try{return JSON.parse(V.readFileSync(z(e),"utf-8"))}catch{return null}}function Ce(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function ve(e,t,n){let o,s=new Promise(r=>{o=setTimeout(()=>r(n),t)}),i=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([i,s])}async function ke(e,t,{probeTimeoutMs:n=4e3}={}){let o=Ae(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Ce(o.ownerPid)?"live":(j(t),"free");let s=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await ve(i,n,s);if(r===s)return i.then(f=>{if(f)try{f.disconnect()}catch{}}),"live";if(!r)return j(t),"free";if(Ce(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await ve(r.close().then(()=>!0).catch(()=>!1),n,!1))return j(t),"free";try{r.disconnect()}catch{}return"live"}function ft(e,t){e&&(ct(),O.add(e),e.on("disconnected",()=>{O.delete(e),t&&j(t)}))}async function Ee(e,t={}){let n=le(),o={...at,...t,userDataDir:n},s=`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 ke(e,n)==="live")throw new Error(s);xe(n);let i;try{i=await e.launch(o)}catch{if(await ke(e,n)==="live")throw new Error(s);me(n);try{i=await e.launch(o)}catch(u){throw ut(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: ${u.message})`)}}return ft(i,n),lt(n,i),{browser:i,profileDir:n,needsSeed:fe(n)}}async function Te(e,t){if(!t||!t.needsSeed)return!1;if(!ae())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(...ie()),de(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var De=mt(dt);De.use(pt());async function Ie(){let{browser:e,profileDir:t,needsSeed:n}=await Ee(De),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Te(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}function ht(e){let t=e||(typeof document<"u"?document:null);if(!t)return[];let n=c=>(c||"").replace(/[ \t ]+/g," ").trim(),o=c=>{let d=String(c||"").match(/\/in\/([^/?#]+)/i);return d?d[1].toLowerCase():null},s=c=>/\bat\b|@/i.test(c)?!1:/\b(Canada|United States|United Kingdom|Australia|India|Germany|France|Spain|Italy|Netherlands|Singapore|Area|Region|Greater|Metropolitan|County|Province)\b/i.test(c)?!0:/,\s*[^,]+,\s*[^,]+$/.test(c),i=c=>/mutual connection/i.test(c)||/^(Connect|Message|Follow|Following|Pending|View|View\s)/i.test(c)||/status is (online|offline|reachable)/i.test(c)||/^\d+(st|nd|rd|th)?$/i.test(c),r=/•\s*(1st|2nd|3rd)\b/i,u=new Set,f=[],l=c=>{let d=(c.innerText||"").split(`
|
|
4
|
+
`).map(n).filter(Boolean),a=d.findIndex(C=>r.test(C));if(a<0)return null;let p=c.querySelector('a[href*="/in/"]'),w=o(p?.href||p?.getAttribute("href")||"");if(!w)return null;let b=n(d[a].split(/•/)[0]).replace(/^View\s+/i,"");if(!b&&a>0&&(b=n(d[a-1]).replace(/^View\s+/i,"")),!b)return null;let h=(d[a].match(r)||[,null])[1]?.toLowerCase()||null,y=d.slice(a+1).filter(C=>!i(C)),x=y[0]||null,R=null;for(let C of y.slice(1))if(s(C)){R=C;break}let P=d.find(C=>/mutual connection/i.test(C))||null;return{slug:w,url:`https://www.linkedin.com/in/${w}/`,name:b,degree:h,title:x,location:R,mutuals:P,isConnection:h==="1st"}},m=c=>{if(!c||u.has(c.slug))return;u.add(c.slug);let{slug:d,...a}=c;f.push(a)};for(let c of Array.from(t.querySelectorAll('[role="listitem"]')))m(l(c));if(f.length===0){let c=/•\s*(1st|2nd|3rd)\b/gi,d=new Set;for(let a of Array.from(t.querySelectorAll('a[href*="/in/"]'))){let p=a,w=null;for(let b=0;b<14&&p.parentElement;b++){p=p.parentElement;let h=(p.innerText||"").trim(),y=(h.match(c)||[]).length;if(y>1)break;y===1&&h.length>=40&&(w=p)}!w||d.has(w)||(d.add(w),m(l(w)))}}return f}function gt(e,t){try{let n=new URL(e);return n.searchParams.set("page",String(t)),n.toString()}catch{return e+(e.includes("?")?"&":"?")+"page="+t}}async function Re(e,t,n={}){let{maxPages:o=5,gotoWithReauth:s,delayed:i,onPage:r}=n,u=i||(m=>new Promise(c=>setTimeout(c,m))),f=new Map,l=m=>{let c=String(m||"").match(/\/in\/([^/?#]+)/i);return c?c[1].toLowerCase():null};for(let m=1;m<=o;m++){let c=gt(t,m);try{s?await s(e,c,{label:`people-search p${m}`}):await e.goto(c,{waitUntil:"domcontentloaded",timeout:6e4})}catch{break}let d=new Map,a=h=>{let y=String(h||"").match(/\/in\/([^/?#]+)/i);return y?y[1].toLowerCase():null},p=async()=>{let h=[];try{h=await e.evaluate(ht)}catch{h=[]}for(let y of h){let x=a(y.url);x&&!d.has(x)&&d.set(x,y)}};try{await p();let h=0,y=-1,x=-1;for(let R=0;R<40&&h<3;R++){await e.evaluate(()=>window.scrollBy(0,Math.max(500,Math.floor(window.innerHeight*.85)))),await u(600),await p();let P=0,C=!1;try{[P,C]=await e.evaluate(()=>[document.body.scrollHeight,window.innerHeight+window.scrollY>=document.body.scrollHeight-8])}catch{}if(d.size===y&&P===x?h++:h=0,y=d.size,x=P,C&&h>=2)break}}catch{}let w=Array.from(d.values()),b=0;for(let h of w){let y=l(h.url);!y||f.has(y)||(f.set(y,{...h,page:m}),b++)}if(r&&r({page:m,total:w.length,fresh:b}),b===0)break;await u(800+Math.floor(Math.random()*700))}return Array.from(f.values())}import"dotenv/config";import*as g from"fs";import*as S from"path";import{fileURLToPath as yt}from"url";var wt=yt(import.meta.url),St=S.dirname(S.dirname(wt)),k=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"collected-profiles"):S.join(St,"collected-profiles"),Q=S.join(k,"people.json"),_n=S.join(k,"jobs.json"),Cn=S.join(k,"quota.json"),vn=S.join(k,"conversations.json"),kn=S.join(k,"sync-state.json"),xn=S.join(k,"application-questions.json"),X=S.join(k,"profile-history"),Le=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},An=Le(process.env.CONNECT_MAX_DAILY,20),En=Le(process.env.CONNECT_MAX_WEEKLY,100),L=null;function Fe(){g.existsSync(k)||g.mkdirSync(k,{recursive:!0})}function M(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";g.writeFileSync(o,n);for(let s=0;s<3;s++)try{g.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function $(e,t){if(!g.existsSync(e))return null;try{let n=JSON.parse(g.readFileSync(e,"utf-8"));try{g.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${S.resolve(e)}`);let o=e+".backup";if(g.existsSync(o))try{let s=JSON.parse(g.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{g.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{g.copyFileSync(e,e+".corrupted")}catch{}return null}}function bt(){return new Date().toISOString().split("T")[0]}var _t=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],Ct=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function T(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Pe(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Me(e,t,n=null){if(!t||e[t])return t;let o=T(t);if(!o)return t;let s=null;for(let[i,r]of Object.entries(e)){if(T(r.profileUrl||i)===o)return i;!s&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}if(s){let i=Pe(n),r=Pe(e[s].name);if(i&&r&&i===r)return s}return t}function vt(){g.existsSync(X)||g.mkdirSync(X,{recursive:!0})}function $e(e){let t=T(e);return t?S.join(X,`${t}.json`):null}function kt(e){let t=$e(e);return t?$(t,`profile-history/${T(e)}.json`)||[]:[]}function xt(e,t){let n=$e(e);if(!n)return;vt();let o=kt(e);o.unshift(t);try{M(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${T(e)}: ${s.message}`)}}function je(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Oe(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function At(e,t){if(!e)return[];let n=[];for(let o of Ct){let s=e[o],i=t[o];je(s)||je(i)||Oe(s)!==Oe(i)&&n.push(o)}return n}function Et(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function N(){return L||(Fe(),L=$(Q,"people.json")||{},L)}function Z(e){Fe(),L=e;try{M(Q,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${S.resolve(Q)}`)}}function Ne(e,t={}){if(!e)return null;let n=N(),o=bt(),s=new Date().toISOString(),i=Me(n,e,t.name),r=n[i];if(r){let u=At(r,t);u.length>0&&(xt(i,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:u,snapshot:Et(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=o,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let f of _t)if(t[f]!=null){if(Array.isArray(t[f])&&t[f].length===0&&Array.isArray(r[f])&&r[f].length>0)continue;r[f]=t[f]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else n[i]={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:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Z(n),n[i]}import"dotenv/config";import*as U from"fs";import*as E from"path";import{fileURLToPath as Tt}from"url";var Dt=Tt(import.meta.url),It=E.dirname(E.dirname(Dt)),ee=process.env.DATA_DIR?E.resolve(process.env.DATA_DIR,"collected-profiles"):E.join(It,"collected-profiles"),qe=E.join(ee,"connect-queue.json"),Rt=1,te=300,Pt=["queued","approved","sent","skipped","failed"],jt=["high","normal","low"];function Ot(){U.existsSync(ee)||U.mkdirSync(ee,{recursive:!0})}function ne(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=te?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:jt.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:Pt.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function Ue(){let e=$(qe,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(ne).filter(n=>n.url):[]}function Be(e){Ot(),M(qe,{version:Rt,entries:e.map(ne)})}function q(e){return T(e)||(e||"").trim().toLowerCase()}function oe(e,t){let n=q(t);return e.find(o=>q(o.url)===n)||null}function He(e,t,n={}){let{tag:o="untagged",priority:s="normal",alreadyEngaged:i=()=>!1,nowIso:r}=n,u={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},f=new Set(e.map(l=>q(l.url)));for(let l of t){let m=l?.url;if(!m){u.skippedNoUrl++;continue}let c=q(m);if(f.has(c)){u.skippedDup++;continue}if(i(m)){u.skippedEngaged++;continue}let d=typeof l.note=="string"?l.note.trim():"";d.length>te&&u.notesTooLong++;let a=d.length>0&&d.length<=te;e.push(ne({url:m,tag:l.tag||o,priority:l.priority||s,withNote:a,note:a?d:null,status:"queued",addedAt:r||null})),f.add(c),u.added++}return u}var Lt={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};function Je(e){if(!e)return null;for(let[t,n]of Object.entries(Lt))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}var Ft=process.argv.slice(2),W=e=>Ft.find(t=>t===`--${e}`||t.startsWith(`--${e}=`)),I=(e,t=null)=>{let n=W(e);if(!n)return t;let o=n.indexOf("=");return o<0?!0:n.slice(o+1)},re=I("url",null),H=I("keywords",null),Mt=!!W("2nd"),We=parseInt(I("pages",I("max-pages","5")),10)||5,Ye=!!W("harvest"),D=!!W("dry-run"),$t=(I("category","investor")||"investor").toString(),Ge=(I("priority","normal")||"normal").toString();function Nt(){if(re)return re;if(!H)return null;let e=new URLSearchParams;return e.set("keywords",H),Mt&&e.set("network",'["S"]'),e.set("origin","GLOBAL_SEARCH_HEADER"),"https://www.linkedin.com/search/results/people/?"+e.toString()}var qt=H||(()=>{try{return new URL(re).searchParams.get("keywords")||"url"}catch{return"url"}})(),B=(I("tag",null)||`people-search:${qt.slice(0,40)}`).toString(),J=e=>{let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null},Ut=new Set(["connected","accepted"]),Bt=new Set(["pending","awaiting","sent","requested"]);function Ht(e,t,n){let o=Object.keys(e).find(m=>J(m)===J(n.url)),s=o?e[o]:null,i=oe(t,n.url),r=n.isConnection||s?.connectionDegree==="1st"||Ut.has(s?.connectionStatus),u=Bt.has(s?.connectionStatus)||i&&i.status==="sent",f=!!i&&["queued","approved"].includes(i.status),l="new";return r?l="connected":u?l="pending":f?l="in-queue":s&&(l="known"),{status:l,existing:s}}async function Jt(){let e=Nt();e||(console.error('Usage: ilml linkedin search --url="<people-search URL>" | --keywords="..." [--pages=N] [--harvest] [--dry-run]'),process.exit(1)),console.log(`
|
|
5
|
+
People search harvest`),console.log(` query: ${H||e}`),console.log(` pages: ${We} mode: ${Ye?D?"harvest (DRY-RUN)":"harvest":"view"}
|
|
6
|
+
`);let{browser:t,page:n}=await Ie(),o=[];try{o=await Re(n,e,{maxPages:We,gotoWithReauth:K,delayed:G,onPage:({page:a,total:p,fresh:w})=>console.log(` page ${a}: ${p} on page, ${w} new`)})}finally{await t.close()}let s=N(),i=Ue(),r=o.map(a=>({...a,...Ht(s,i,a)}));console.log(`
|
|
7
|
+
${r.length} people:
|
|
8
|
+
`);let u={connected:"\u2713conn",pending:"\u2026pend","in-queue":"\u22EFqueue",known:"\xB7known",new:"\uFF0Bnew"};for(let a of r)console.log(` ${u[a.status]||a.status} ${a.name}${a.title?" \u2014 "+a.title.slice(0,70):""}`);let f=r.reduce((a,p)=>(a[p.status]=(a[p.status]||0)+1,a),{});if(console.log(`
|
|
9
|
+
breakdown: ${Object.entries(f).map(([a,p])=>`${a}=${p}`).join(" ")}`),!Ye){console.log(`
|
|
10
|
+
(view only \u2014 nothing written. add --harvest to store + queue)
|
|
11
|
+
`);return}let l=[],m=0,c=0;for(let a of r)a.status==="connected"||a.status==="pending"||(D||Ne(a.url,{name:a.name,title:a.title||null,location:a.location||null,connectionDegree:a.degree||null,source:B}),m++,(a.status==="new"||a.status==="known")&&l.push({url:a.url,tag:B,priority:Ge}));if(!D){let a=N();for(let p of r){if(p.status==="connected"||p.status==="pending")continue;let w=Object.keys(a).find(h=>J(h)===J(p.url));if(!w)continue;let b=a[w];b.categorySource!=="manual"&&(b.category=Je(p.title||"")||$t,b.categorySource="people-search",c++)}Z(a)}let d=D?{added:l.filter(a=>!oe(i,a.url)).length}:He(i,l,{tag:B,priority:Ge,alreadyEngaged:()=>!1,nowIso:new Date().toISOString()});D||Be(i),console.log(`
|
|
12
|
+
${D?"WOULD write":"WROTE"}: ${m} people upserted, ${c} categorised, ${d.added} queued (tag=${B})`),console.log(D?` (dry-run \u2014 nothing saved)
|
|
13
|
+
`:" Next: review with `connect list --status=queued`, approve, then `connect run`.\n")}Jt().catch(e=>{console.error("search failed:",e.message),process.exit(1)});
|
package/dist/quota.mjs
CHANGED
|
@@ -1,48 +1,48 @@
|
|
|
1
|
-
var Me=Object.defineProperty;var B=(e,o)=>{for(var n in o)Me(e,n,{get:o[n],enumerable:!0})};import{getPluginConfig as Je}from"@ilivemylife/graph-sdk";var Pe={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},ce=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function Ue(e){return String(e??"").split(/[,\s|]+/).map(o=>o.trim()).filter(Boolean)}function le(e=process.env){let o=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!o)return null;let n=new URLSearchParams;n.set("keywords",o);let t=(e.JOB_SEARCH_LOCATION||"").trim();t&&n.set("location",t);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)),ce(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),ce(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let c=Ue(e.JOB_SEARCH_COMPANY_IDS);c.length&&n.set("f_C",c.join(","));let a=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();a&&n.set("f_TPR",Pe[a]||a),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let l="https://www.linkedin.com/jobs/search/?"+n.toString(),f=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return f&&(l+="&"+f),l}var Be=await Je();for(let[e,o]of Object.entries(Be))process.env[e]===void 0&&(process.env[e]=o);var ae=le(process.env);ae&&(process.env.LINKEDIN_SEARCH_URL=ae);var tn=process.env.LINKEDIN_NAME,T=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),rn=Object.freeze(new Set([T.DRAFT,T.CONFIRMED,T.NEEDS_REVIEW])),sn=Object.freeze(new Set([T.DRAFT,T.CONFIRMED,T.REJECTED,T.NEEDS_REVIEW]));import"dotenv/config";import*as d from"fs";import*as h from"path";import{fileURLToPath as qe}from"url";var Ve=qe(import.meta.url),We=h.dirname(h.dirname(Ve)),j=process.env.DATA_DIR?h.resolve(process.env.DATA_DIR,"collected-profiles"):h.join(We,"collected-profiles"),Ge=h.join(j,"people.json"),fn=h.join(j,"jobs.json"),He=h.join(j,"quota.json"),pn=h.join(j,"conversations.json"),dn=h.join(j,"sync-state.json"),hn=h.join(j,"application-questions.json"),mn=h.join(j,"profile-history"),pe=(e,o)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:o},ue=pe(process.env.CONNECT_MAX_DAILY,20),fe=pe(process.env.CONNECT_MAX_WEEKLY,100),M=null,Ye=null,C=null,Ke=null,ze=null,Qe=null;function de(){M=null,Ye=null,C=null,Ke=null,ze=null,Qe=null}function he(){d.existsSync(j)||d.mkdirSync(j,{recursive:!0})}function me(e,o){if(!d.existsSync(e))return null;try{let n=JSON.parse(d.readFileSync(e,"utf-8"));try{d.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${o} is corrupted: ${n.message}`),console.error(` File: ${h.resolve(e)}`);let t=e+".backup";if(d.existsSync(t))try{let r=JSON.parse(d.readFileSync(t,"utf-8"));console.error(` Restored from ${t}`);try{d.copyFileSync(t,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{d.copyFileSync(e,e+".corrupted")}catch{}return null}}function Xe(){return new Date().toISOString().split("T")[0]}function H(e){if(!e)return null;let o=e.match(/\/in\/([^/?#]+)/);return o?o[1].toLowerCase():null}function ge(){return M||(he(),M=me(Ge,"people.json")||{},M)}function Y(){return C||(he(),C=me(He,"quota.json"),(!C||!C.connections)&&(C={connections:[]}),C)}function Ze(){let e=Y(),o=new Date;o.setDate(o.getDate()-7);let n=o.toISOString().split("T")[0];return e.connections.filter(t=>t.date>=n)}function ye(){let e=Ze(),o=Xe(),n=e.filter(r=>r.date===o).length,t=e.length;return{daily:{sent:n,max:ue,remaining:ue-n},weekly:{sent:t,max:fe,remaining:fe-t}}}import"dotenv/config";import*as i from"fs";import*as ne from"os";import*as u from"path";import{fileURLToPath as To}from"url";var Q={};B(Q,{NAME:()=>oo,VERSION:()=>eo,up:()=>ro});import*as S from"fs";import*as q from"path";var eo=1,oo="normalize-jobs-and-questions",no=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],to=50;function K(e){return S.existsSync(e)?JSON.parse(S.readFileSync(e,"utf-8")):null}function z(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{S.writeFileSync(t,n)}catch(r){try{S.unlinkSync(t)}catch{}throw r}try{S.renameSync(t,e)}catch(r){try{S.unlinkSync(t)}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 ro(e,o){let n=q.join(e,"jobs.json"),t=q.join(o,"scouted-jobs.json"),r=q.join(e,"application-questions.json"),s=K(n)||{},c=K(t)||{},a=0,l=[];for(let p of Object.keys(s)){if(!c[p])continue;let v=c[p],m=s[p];for(let I of no)v[I]!=null&&m[I]==null&&(m[I]=v[I]);l.push(p),a++}a>0?(z(n,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=K(r);if(f&&Array.isArray(f.applications)){let p={},v=0;for(let m of f.applications){let I=m.jobId||"unknown";p[I]||(p[I]={applications:[]});let ie=(m.questions||[]).map(A=>{let L={type:A.type||"input",question:A.question||"",answer:A.answer||""};return A.options&&(A.options.length<=to?L.options=A.options:(L.optionsOmitted=!0,v++)),A.page&&(L.page=A.page),A.wasPreFilled&&(L.wasPreFilled=!0),A.wasRetry&&(L.wasRetry=!0),L});p[I].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||ie.length,questions:ie})}z(r,p),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),v>0&&console.log(` Phase 2: Stripped bloated options from ${v} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let p of l)delete c[p];z(t,c),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(c).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var X={};B(X,{NAME:()=>io,VERSION:()=>so,up:()=>ao});import*as b from"fs";import*as Se from"path";var so=2,io="reset-unread-flags";function co(e){return b.existsSync(e)?JSON.parse(b.readFileSync(e,"utf-8")):null}function lo(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{b.writeFileSync(t,n)}catch(r){try{b.unlinkSync(t)}catch{}throw r}try{b.renameSync(t,e)}catch(r){try{b.unlinkSync(t)}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 ao(e){let o=Se.join(e,"conversations.json"),n=co(o);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let t=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,t++);if(t===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}lo(o,n),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Z={};B(Z,{NAME:()=>fo,VERSION:()=>uo,up:()=>yo});import*as w from"fs";import*as be from"path";var uo=3,fo="recompute-last-message-by",po=new Set(["draft","confirmed","rejected","needs_review"]);function ho(e){return w.existsSync(e)?JSON.parse(w.readFileSync(e,"utf-8")):null}function mo(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{w.writeFileSync(t,n)}catch(r){try{w.unlinkSync(t)}catch{}throw r}try{w.renameSync(t,e)}catch(r){try{w.unlinkSync(t)}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 go(e,o){if(!e||e.length===0)return"them";let n=e.filter(s=>!po.has(s.status));if(n.length===0)return"them";let t=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,c)=>c.t-s.t).map(s=>s.m),r=t.length>0?t:[...n].reverse();for(let s of r){let c=s.sender;if(c===o)return"me";if(c!=="Unknown"&&c!=="")return"them"}return"them"}async function yo(e){let o=be.join(e,"conversations.json"),n=ho(o);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let t=process.env.LINKEDIN_NAME;if(!t||typeof t!="string"||!t.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,c=0;for(let a of Object.keys(n)){let l=n[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,s++);let f=Array.isArray(l.messages)?l.messages:[],p=go(f,t),v=p==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==p&&c++,l.lastMessageBy=p,l.conversationStatus=v,r++}if(r===0){console.log(" No conversations to recompute.");return}mo(o,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${c} 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 ee={};B(ee,{NAME:()=>bo,VERSION:()=>So,up:()=>Ao});import*as k from"fs";import*as we from"path";var So=4,bo="split-connection-timestamps",wo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ko(e){if(!k.existsSync(e))return null;let o=k.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function vo(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{k.writeFileSync(t,n)}catch(r){try{k.unlinkSync(t)}catch{}throw r}try{k.renameSync(t,e)}catch(r){try{k.unlinkSync(t)}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 Ao(e){let o=we.join(e,"people.json"),n=ko(o);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let t=0,r=0;for(let s of Object.keys(n)){let c=n[s];!c||typeof c!="object"||(r++,wo.has(c.connectionStatus)&&c.connectionDate&&!c.requestedConnectionAt&&(c.requestedConnectionAt=c.connectionDate,c.connectionDate=null,t++))}if(t===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}vo(o,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${t} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as y from"path";import{fileURLToPath as Eo}from"url";var $o=Eo(import.meta.url),jo=y.dirname(y.dirname($o)),P=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"market-research"):y.join(jo,"market-research"),An=y.join(P,"scouted-jobs.json"),En=y.join(P,"discovered-people.json"),$n=y.join(P,"visit-log.json"),jn=y.join(P,"companies.json"),On=y.join(P,"job-decisions.json");function ke(){Oo=null,Io=null,Co=null,_o=null,Ro=null}var Oo=null;var Io=null;var Co=null;var _o=null;var Ro=null;var Do=To(import.meta.url),No=u.dirname(Do),xo=u.dirname(u.dirname(No));function Fo(e){return e&&(e==="~"?ne.homedir():e.startsWith("~/")||e.startsWith("~\\")?u.join(ne.homedir(),e.slice(2)):e)}var E=process.env.DATA_DIR?u.resolve(Fo(process.env.DATA_DIR)):xo,N=u.join(E,"collected-profiles"),x=u.join(E,"market-research"),g=u.join(E,".schema-version"),ve=[u.join(N,".schema-version"),u.join(x,".schema-version")],_=4,O=[{version:1,module:Q},{version:2,module:X},{version:3,module:Z},{version:4,module:ee}];(function(){O.sort((t,r)=>t.version-r.version);let o=new Set;for(let t of O){if(!Number.isInteger(t.version)||t.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(t.version)} (must be positive integer)`);if(o.has(t.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${t.version}`);o.add(t.version);let r=t.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${t.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==t.version)throw new Error(`MIGRATION_REGISTRY: v${t.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=O.length?O[O.length-1].version:0;if(n!==_)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${_}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<O.length;t++){let r=t+1;if(O[t].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${t} but found v${O[t].version}`)}})();function je(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
1
|
+
var Ve=Object.defineProperty;var U=(e,o)=>{for(var n in o)Ve(e,n,{get:o[n],enumerable:!0})};import{getPluginConfig as Ge}from"@ilivemylife/graph-sdk";var qe={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},fe=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function We(e){return String(e??"").split(/[,\s|]+/).map(o=>o.trim()).filter(Boolean)}function pe(e=process.env){let o=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!o)return null;let n=new URLSearchParams;n.set("keywords",o);let t=(e.JOB_SEARCH_LOCATION||"").trim();t&&n.set("location",t);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)),fe(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),fe(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let l=We(e.JOB_SEARCH_COMPANY_IDS);l.length&&n.set("f_C",l.join(","));let u=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();u&&n.set("f_TPR",qe[u]||u),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let i="https://www.linkedin.com/jobs/search/?"+n.toString(),a=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return a&&(i+="&"+a),i}var He=await Ge();for(let[e,o]of Object.entries(He))process.env[e]===void 0&&(process.env[e]=o);var de=pe(process.env);de&&(process.env.LINKEDIN_SEARCH_URL=de);var hn=process.env.LINKEDIN_NAME,D=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),gn=Object.freeze(new Set([D.DRAFT,D.CONFIRMED,D.NEEDS_REVIEW])),yn=Object.freeze(new Set([D.DRAFT,D.CONFIRMED,D.REJECTED,D.NEEDS_REVIEW]));import"dotenv/config";import*as d from"fs";import*as m from"path";import{fileURLToPath as Ye}from"url";var Ke=Ye(import.meta.url),ze=m.dirname(m.dirname(Ke)),O=process.env.DATA_DIR?m.resolve(process.env.DATA_DIR,"collected-profiles"):m.join(ze,"collected-profiles"),Qe=m.join(O,"people.json"),vn=m.join(O,"jobs.json"),Xe=m.join(O,"quota.json"),An=m.join(O,"conversations.json"),En=m.join(O,"sync-state.json"),$n=m.join(O,"application-questions.json"),jn=m.join(O,"profile-history"),ge=(e,o)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:o},me=ge(process.env.CONNECT_MAX_DAILY,20),he=ge(process.env.CONNECT_MAX_WEEKLY,100),J=null,Ze=null,_=null,eo=null,oo=null,no=null;function ye(){J=null,Ze=null,_=null,eo=null,oo=null,no=null}function Se(){d.existsSync(O)||d.mkdirSync(O,{recursive:!0})}function be(e,o){if(!d.existsSync(e))return null;try{let n=JSON.parse(d.readFileSync(e,"utf-8"));try{d.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${o} is corrupted: ${n.message}`),console.error(` File: ${m.resolve(e)}`);let t=e+".backup";if(d.existsSync(t))try{let r=JSON.parse(d.readFileSync(t,"utf-8"));console.error(` Restored from ${t}`);try{d.copyFileSync(t,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{d.copyFileSync(e,e+".corrupted")}catch{}return null}}function to(){return new Date().toISOString().split("T")[0]}function z(e){if(!e)return null;let o=e.match(/\/in\/([^/?#]+)/);return o?o[1].toLowerCase():null}function we(){return J||(Se(),J=be(Qe,"people.json")||{},J)}function Q(){return _||(Se(),_=be(Xe,"quota.json"),(!_||!_.connections)&&(_={connections:[]}),_)}function ro(){let e=Q(),o=new Date;o.setDate(o.getDate()-7);let n=o.toISOString().split("T")[0];return e.connections.filter(t=>t.date>=n)}function ke(){let e=ro(),o=to(),n=e.filter(r=>r.date===o).length,t=e.length;return{daily:{sent:n,max:me,remaining:me-n},weekly:{sent:t,max:he,remaining:he-t}}}import"dotenv/config";import*as c from"fs";import*as ie from"os";import*as p from"path";import{fileURLToPath as Vo}from"url";var ee={};U(ee,{NAME:()=>io,VERSION:()=>so,up:()=>ao});import*as b from"fs";import*as G from"path";var so=1,io="normalize-jobs-and-questions",lo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],co=50;function X(e){return b.existsSync(e)?JSON.parse(b.readFileSync(e,"utf-8")):null}function Z(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{b.writeFileSync(t,n)}catch(r){try{b.unlinkSync(t)}catch{}throw r}try{b.renameSync(t,e)}catch(r){try{b.unlinkSync(t)}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 ao(e,o){let n=G.join(e,"jobs.json"),t=G.join(o,"scouted-jobs.json"),r=G.join(e,"application-questions.json"),s=X(n)||{},l=X(t)||{},u=0,i=[];for(let f of Object.keys(s)){if(!l[f])continue;let g=l[f],h=s[f];for(let C of lo)g[C]!=null&&h[C]==null&&(h[C]=g[C]);i.push(f),u++}u>0?(Z(n,s),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=X(r);if(a&&Array.isArray(a.applications)){let f={},g=0;for(let h of a.applications){let C=h.jobId||"unknown";f[C]||(f[C]={applications:[]});let ue=(h.questions||[]).map(E=>{let P={type:E.type||"input",question:E.question||"",answer:E.answer||""};return E.options&&(E.options.length<=co?P.options=E.options:(P.optionsOmitted=!0,g++)),E.page&&(P.page=E.page),E.wasPreFilled&&(P.wasPreFilled=!0),E.wasRetry&&(P.wasRetry=!0),P});f[C].applications.push({applicationId:h.applicationId,date:h.date,result:h.result||"submitted",formPages:h.formPages||null,duration:h.duration||null,retries:h.retries||0,failedField:h.failedField||null,questionCount:h.questionCount||ue.length,questions:ue})}Z(r,f),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),g>0&&console.log(` Phase 2: Stripped bloated options from ${g} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(i.length>0){for(let f of i)delete l[f];Z(t,l),console.log(` Phase 3: Removed ${i.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var oe={};U(oe,{NAME:()=>fo,VERSION:()=>uo,up:()=>ho});import*as w from"fs";import*as ve from"path";var uo=2,fo="reset-unread-flags";function po(e){return w.existsSync(e)?JSON.parse(w.readFileSync(e,"utf-8")):null}function mo(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{w.writeFileSync(t,n)}catch(r){try{w.unlinkSync(t)}catch{}throw r}try{w.renameSync(t,e)}catch(r){try{w.unlinkSync(t)}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 ho(e){let o=ve.join(e,"conversations.json"),n=po(o);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let t=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,t++);if(t===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}mo(o,n),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var ne={};U(ne,{NAME:()=>yo,VERSION:()=>go,up:()=>vo});import*as k from"fs";import*as Ae from"path";var go=3,yo="recompute-last-message-by",So=new Set(["draft","confirmed","rejected","needs_review"]);function bo(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function wo(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{k.writeFileSync(t,n)}catch(r){try{k.unlinkSync(t)}catch{}throw r}try{k.renameSync(t,e)}catch(r){try{k.unlinkSync(t)}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 ko(e,o){if(!e||e.length===0)return"them";let n=e.filter(s=>!So.has(s.status));if(n.length===0)return"them";let t=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,l)=>l.t-s.t).map(s=>s.m),r=t.length>0?t:[...n].reverse();for(let s of r){let l=s.sender;if(l===o)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function vo(e){let o=Ae.join(e,"conversations.json"),n=bo(o);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let t=process.env.LINKEDIN_NAME;if(!t||typeof t!="string"||!t.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,l=0;for(let u of Object.keys(n)){let i=n[u];if(!i||typeof i!="object")continue;Object.prototype.hasOwnProperty.call(i,"_cardSynced")&&(delete i._cardSynced,s++);let a=Array.isArray(i.messages)?i.messages:[],f=ko(a,t),g=f==="me"?"awaiting_reply":"unanswered_by_us";i.lastMessageBy!==f&&l++,i.lastMessageBy=f,i.conversationStatus=g,r++}if(r===0){console.log(" No conversations to recompute.");return}wo(o,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${l} 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 te={};U(te,{NAME:()=>Eo,VERSION:()=>Ao,up:()=>Io});import*as v from"fs";import*as Ee from"path";var Ao=4,Eo="split-connection-timestamps",$o=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function jo(e){if(!v.existsSync(e))return null;let o=v.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Oo(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{v.writeFileSync(t,n)}catch(r){try{v.unlinkSync(t)}catch{}throw r}try{v.renameSync(t,e)}catch(r){try{v.unlinkSync(t)}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 Io(e){let o=Ee.join(e,"people.json"),n=jo(o);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let t=0,r=0;for(let s of Object.keys(n)){let l=n[s];!l||typeof l!="object"||(r++,$o.has(l.connectionStatus)&&l.connectionDate&&!l.requestedConnectionAt&&(l.requestedConnectionAt=l.connectionDate,l.connectionDate=null,t++))}if(t===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Oo(o,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${t} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var re={};U(re,{NAME:()=>_o,VERSION:()=>Co,up:()=>No});import*as A from"fs";import*as $e from"path";var Co=5,_o="rename-headline-to-title",N=/[·•]\s*(1st|2nd|3rd)\+?/i,Ro=e=>(e||"").replace(/\s+/g," ").trim(),B=e=>Ro(e).replace(/^[+·•\s]+/,"").replace(/[·•\s]+$/,"");function To(e){if(!A.existsSync(e))return null;let o=A.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Do(e,o){let n=JSON.stringify(o),t=e+".tmp";try{A.writeFileSync(t,n)}catch(r){try{A.unlinkSync(t)}catch{}throw r}try{A.renameSync(t,e)}catch(r){try{A.unlinkSync(t)}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 No(e,o){let n=$e.join(o,"discovered-people.json"),t=To(n);if(!t||typeof t!="object"){console.log(" discovered-people.json not found \u2014 nothing to migrate.");return}let r=Array.isArray(t)?t:Object.values(t),s=0,l=0,u=0;for(let i of r)if(!(!i||typeof i!="object")){if(s++,i.name&&N.test(i.name)){let a=B(String(i.name).split(N)[0]),f=String(i.name).match(/[·•]\s*(?:1st|2nd|3rd)\+?\s*(.+)$/i),g=f?B(f[1]):"";a&&(i.name=a,l++),g&&(!i.headline||N.test(String(i.headline))||!B(i.headline))&&(i.headline=g)}if(Object.prototype.hasOwnProperty.call(i,"headline")){let a=B(i.headline||"");N.test(a)&&(a=""),(!i.title||N.test(String(i.title)))&&(i.title=a||(i.title&&!N.test(String(i.title))?i.title:null)||null),delete i.headline,u++}else if(typeof i.title=="string"){let a=B(i.title);a&&!N.test(a)&&a!==i.title&&(i.title=a)}}if(u===0&&l===0){console.log(` Scanned ${s} discovered people \u2014 already unified (no headline field, clean names).`);return}Do(n,t),console.log(` discovered-people.json: scanned ${s}, de-glued ${l} names, moved ${u} headline\u2192title.`),console.log(" Every record now carries a single `title` field (matches people.json).")}import"dotenv/config";import*as S from"path";import{fileURLToPath as xo}from"url";var Fo=xo(import.meta.url),Lo=S.dirname(S.dirname(Fo)),V=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"market-research"):S.join(Lo,"market-research"),Nn=S.join(V,"scouted-jobs.json"),xn=S.join(V,"discovered-people.json"),Fn=S.join(V,"visit-log.json"),Ln=S.join(V,"companies.json"),Mn=S.join(V,"job-decisions.json");function je(){Mo=null,Po=null,Uo=null,Jo=null,Bo=null}var Mo=null;var Po=null;var Uo=null;var Jo=null;var Bo=null;var qo=Vo(import.meta.url),Wo=p.dirname(qo),Go=p.dirname(p.dirname(Wo));function Ho(e){return e&&(e==="~"?ie.homedir():e.startsWith("~/")||e.startsWith("~\\")?p.join(ie.homedir(),e.slice(2)):e)}var $=process.env.DATA_DIR?p.resolve(Ho(process.env.DATA_DIR)):Go,F=p.join($,"collected-profiles"),L=p.join($,"market-research"),y=p.join($,".schema-version"),Oe=[p.join(F,".schema-version"),p.join(L,".schema-version")],R=5,I=[{version:1,module:ee},{version:2,module:oe},{version:3,module:ne},{version:4,module:te},{version:5,module:re}];(function(){I.sort((t,r)=>t.version-r.version);let o=new Set;for(let t of I){if(!Number.isInteger(t.version)||t.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(t.version)} (must be positive integer)`);if(o.has(t.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${t.version}`);o.add(t.version);let r=t.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${t.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==t.version)throw new Error(`MIGRATION_REGISTRY: v${t.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=I.length?I[I.length-1].version:0;if(n!==R)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${R}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<I.length;t++){let r=t+1;if(I[t].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${t} but found v${I[t].version}`)}})();function Re(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
2
2
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
3
|
-
`),process.exit(1));try{
|
|
4
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
5
|
-
`),process.exit(1))}let e;try{e=
|
|
6
|
-
[FATAL] DATA_DIR (${
|
|
3
|
+
`),process.exit(1));try{c.mkdirSync($,{recursive:!0})}catch(o){o.code!=="EEXIST"&&(console.error(`
|
|
4
|
+
[FATAL] Cannot create DATA_DIR (${$}): ${o.message}`),console.error(` Fix the path or permissions and try again.
|
|
5
|
+
`),process.exit(1))}let e;try{e=c.statSync($)}catch(o){console.error(`
|
|
6
|
+
[FATAL] DATA_DIR (${$}) is not accessible: ${o.message}
|
|
7
7
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
8
|
-
[FATAL] DATA_DIR (${
|
|
9
|
-
`),process.exit(1));for(let o of[
|
|
8
|
+
[FATAL] DATA_DIR (${$}) 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.
|
|
9
|
+
`),process.exit(1));for(let o of[F,L]){let n;try{n=c.lstatSync(o)}catch(t){if(t.code==="ENOENT")continue;throw t}n.isSymbolicLink()&&(console.error(`
|
|
10
10
|
[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.
|
|
11
|
-
`),process.exit(1))}}var
|
|
12
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${o.pid}`),console.error(` Started at: ${o.startedAt||"(unknown)"}`),console.error(` Lock file: ${
|
|
11
|
+
`),process.exit(1))}}var x=p.join($,".migration-lock");function Yo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return c.writeFileSync(x,e,{flag:"wx"}),!0}catch(t){if(t.code!=="EEXIST")throw t}let o;try{o=JSON.parse(c.readFileSync(x,"utf-8"))}catch{o=null}if(o&&Number.isInteger(o.pid)){let t=!1;try{process.kill(o.pid,0),t=!0}catch(l){l.code==="EPERM"&&(t=!0)}let r=24*60*60*1e3,s=1/0;if(o.startedAt){let l=Date.parse(o.startedAt);Number.isNaN(l)||(s=Date.now()-l)}t&&s<r&&(console.error(`
|
|
12
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${o.pid}`),console.error(` Started at: ${o.startedAt||"(unknown)"}`),console.error(` Lock file: ${x}
|
|
13
13
|
`),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.
|
|
14
|
-
`),process.exit(1)),t&&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 n=
|
|
14
|
+
`),process.exit(1)),t&&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 n=x+".tmp";try{return c.writeFileSync(n,e),c.renameSync(n,x),!0}catch(t){try{c.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${t.message}`)}}function le(){try{if(JSON.parse(c.readFileSync(x,"utf-8")).pid!==process.pid)return;c.unlinkSync(x)}catch{}}var Ie=!1;function Ko(){if(Ie)return;Ie=!0;let e=()=>{try{le()}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 Oe)if(c.existsSync(s))try{e.push({file:s,schema:H(s)})}catch(l){o.push({file:s,err:l.message})}if(o.length>0){console.error(`
|
|
15
15
|
[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(`
|
|
16
16
|
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.
|
|
17
17
|
`),process.exit(1)}if(e.length===0)return;let n=e.map(s=>s.schema.version);if(new Set(n).size>1){console.error(`
|
|
18
18
|
[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.
|
|
19
|
-
`),process.exit(1)}let t=e[0].schema,r=
|
|
20
|
-
[FATAL] ${
|
|
21
|
-
`),process.exit(1)}let o=
|
|
22
|
-
[FATAL] ${
|
|
23
|
-
`),process.exit(1)),o}function
|
|
24
|
-
[FATAL] Your data schema is at v${o}, but this plugin build only understands up to v${
|
|
25
|
-
`),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${
|
|
19
|
+
`),process.exit(1)}let t=e[0].schema,r=y+".tmp";try{c.writeFileSync(r,JSON.stringify(t,null,2)),c.renameSync(r,y)}catch(s){try{c.unlinkSync(r)}catch{}throw s}for(let s of Oe)if(c.existsSync(s))try{c.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${y}`)}function Qo(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 H(e){let o=c.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Ce(){if(zo(),!c.existsSync(y))return{version:0,migrations:[]};let e;try{e=H(y)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
20
|
+
[FATAL] ${y} 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.
|
|
21
|
+
`),process.exit(1)}let o=Qo(e);return o===null&&(console.error(`
|
|
22
|
+
[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.
|
|
23
|
+
`),process.exit(1)),o}function Te(e){try{c.chmodSync(e,384)}catch{}}function Xo(e){if(Re(),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(n){if(n.message?.includes("symbolic link"))throw n}let o=y+".tmp";try{c.writeFileSync(o,JSON.stringify(e,null,2)),Te(o),c.renameSync(o,y)}catch(n){try{c.unlinkSync(o)}catch{}throw n}}function _e(e,o){if(!c.existsSync(e))return;let n=`.pre-v${String(o).padStart(3,"0")}.backup`,t=c.readdirSync(e).filter(u=>{let i=u.toLowerCase();if(i.includes(".backup")||i===".schema-version"||i.endsWith(".tmp"))return!1;try{return c.statSync(p.join(e,u)).isFile()}catch{return!1}}),r=0,s=0,l=[];for(let u of t){let i=p.join(e,u),a=p.join(e,u+n);if(c.existsSync(a)){s++;continue}try{Ne(i,a),r++}catch(f){l.push({file:u,err:f.message})}}if(l.length>0){let u=new Error(`Failed to back up ${l.length} file(s) in ${p.basename(e)}/: `+l.map(i=>`${i.file} (${i.err})`).join(", "));throw u.code="BACKUP_INCOMPLETE",u}if(r>0||s>0){let u=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${p.basename(e)}/ (${n})${u}`)}}var se=!1;async function De(){if(se)return;Re(),tn();let o=Ce().version;if(o===R){se=!0;return}Ko(),Yo(),process.on("exit",le),o>R&&(console.error(`
|
|
24
|
+
[FATAL] Your data schema is at v${o}, but this plugin build only understands up to v${R}.`),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.
|
|
25
|
+
`),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${R}.
|
|
26
26
|
`),process.exit(1)),console.log(`
|
|
27
|
-
\u{1F4E6} Schema migration: v${o} \u2192 v${
|
|
27
|
+
\u{1F4E6} Schema migration: v${o} \u2192 v${R}`);let n=rn();if(!n.ok){console.error(`
|
|
28
28
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
|
|
29
29
|
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'.
|
|
30
|
-
`),process.exit(1)}let t=
|
|
31
|
-
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,
|
|
32
|
-
[FATAL] Pre-migration backup failed for ${s}: ${
|
|
33
|
-
`),process.exit(1)}let
|
|
34
|
-
[FATAL] Migration ${s} failed: ${
|
|
35
|
-
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${
|
|
36
|
-
`))}catch(
|
|
37
|
-
`)}process.exit(1)}try{let
|
|
38
|
-
[FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${
|
|
39
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{
|
|
40
|
-
\u2713 Schema is now at v${
|
|
41
|
-
`)}var
|
|
30
|
+
`),process.exit(1)}let t=I.filter(r=>r.version>o);for(let r of t){console.log(`
|
|
31
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,l=`.pre-${s}.backup`;try{_e(F,r.version),_e(L,r.version)}catch(i){console.error(`
|
|
32
|
+
[FATAL] Pre-migration backup failed for ${s}: ${i.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
33
|
+
`),process.exit(1)}let u=r.module;try{await u.up(F,L)}catch(i){console.error(`
|
|
34
|
+
[FATAL] Migration ${s} failed: ${i.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let a=sn(l);a.ok?(console.error(` \u2713 Auto-rollback restored ${a.restored} files. Schema stays at v${o}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
35
|
+
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
36
|
+
`))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
37
|
+
`)}process.exit(1)}try{let i=new Date().toISOString(),a={version:r.version,name:u.NAME||s,appliedAt:i},f=Ce();f.version=r.version,f.migratedAt=i,f.migrations=f.migrations||[],f.migrations.push(a),Xo(f)}catch(i){console.error(`
|
|
38
|
+
[FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${i.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.
|
|
39
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{ye()}catch{}try{je()}catch{}se=!0,le(),console.log(`
|
|
40
|
+
\u2713 Schema is now at v${R}
|
|
41
|
+
`)}var Zo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function en(e){let o=e.toLowerCase();return Zo.some(n=>n.test(o))}var on=6e4;function nn(){let e=Date.now(),o=[];for(let n of[$,F,L]){if(!c.existsSync(n))continue;let t;try{t=c.readdirSync(n)}catch{continue}for(let r of t){if(!en(r))continue;let s=p.join(n,r);try{let l=c.statSync(s);if(!l.isFile()||e-l.mtimeMs<on)continue;o.push({dir:n,file:r,fullPath:s})}catch{}}}return o}function tn({verbose:e=!1}={}){let o=nn();if(o.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let t of o)try{c.unlinkSync(t.fullPath),n++,e&&console.log(` Removed orphan: ${p.basename(t.dir)}/${t.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${t.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function rn(){let e=[];for(let o of[F,L]){if(!c.existsSync(o))continue;let n=c.readdirSync(o).filter(t=>{let r=t.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let t of n){let r=p.join(o,t);try{H(r)}catch(s){e.push({dir:p.basename(o),file:t,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function sn(e){let o=[],n=[];for(let s of[F,L]){if(!c.existsSync(s))continue;let l=c.readdirSync(s).filter(u=>u.endsWith(e));for(let u of l){let i=p.join(s,u),a=u.slice(0,-e.length),f=p.join(s,a);try{a.toLowerCase().endsWith(".json")?H(i):c.accessSync(i,c.constants.R_OK),o.push({backupPath:i,originalPath:f,fileName:u,dir:s})}catch(g){n.push(`${p.basename(s)}/${u}: ${g.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let t=0,r=[];for(let{backupPath:s,originalPath:l,fileName:u,dir:i}of o)try{Ne(s,l),t++}catch(a){r.push(`${p.basename(i)}/${u}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:t}:{ok:!0,restored:t}}function Ne(e,o){let n=o+".tmp";try{c.copyFileSync(e,n),Te(n)}catch(t){try{c.unlinkSync(n)}catch{}throw t}try{c.renameSync(n,o)}catch(t){try{c.unlinkSync(n)}catch{}if(t.code==="EPERM"||t.code==="EBUSY"){let r=new Error(`File locked: ${o} (${t.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=t.code,r}throw t}}var Me=process.argv.includes("--json"),Pe=new Set(["connected"]),Ue=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]),ce=["founder","investor","hiring_manager","peer"],ln=new Date().toISOString().split("T")[0];function Je(e){if(!e)return 1/0;let o=new Date(e+"T00:00:00Z").getTime(),n=new Date(ln+"T00:00:00Z").getTime();return Math.round((n-o)/864e5)}function cn(e,o,n=20){return o?"\u2588".repeat(Math.max(0,Math.round(e/o*n))):""}Me||await De();var an=Q(),K=an.connections||[],j=ke(),ae=we(),q=new Map;for(let[e,o]of Object.entries(ae)){let n=z(o.profileUrl||e);n&&!q.has(n)&&q.set(n,o)}for(let e of Object.values(ae))for(let o of e.aliases||[])o&&!q.has(o)&&q.set(o,e);var un=K.filter(e=>Je(e.date)<=7),T={},Y={};for(let e of un){T[e.date]=(T[e.date]||0)+1;let o=e.source||"unknown";Y[o]=(Y[o]||0)+1}var M={},xe=new Set;for(let e of K){let o=e.source||"unknown",n=z(e.profileUrl),t=`${o}|${n}`;if(n&&xe.has(t))continue;n&&xe.add(t),M[o]||={sent:0,accepted:0,awaiting:0,stale:0,unknown:0};let r=M[o];r.sent++;let l=(n?q.get(n):null)?.connectionStatus;Pe.has(l)?r.accepted++:Ue.has(l)?(r.awaiting++,Je(e.date)>14&&r.stale++):r.unknown++}var W={};for(let e of ce)W[e]=0;for(let e of Object.values(ae)){let o=e.category;if(!ce.includes(o))continue;let n=e.connectionStatus;Pe.has(n)||Ue.has(n)||e.connectionDegree!=="1st"&&W[o]++}var Be=Object.values(W).reduce((e,o)=>e+o,0);Me&&(console.log(JSON.stringify({state:j,byDay:T,bySource7d:Y,acceptance:M,feederPool:{...W,total:Be},totalLogged:K.length},null,2)),process.exit(0));var Fe=(e,o)=>o?`${Math.round(e/o*100)}%`:"\u2014";console.log(`
|
|
42
42
|
=== LinkedIn Connection Quota ===
|
|
43
|
-
`);console.log("State");console.log(` Today: ${
|
|
44
|
-
`);if(Object.keys(
|
|
43
|
+
`);console.log("State");console.log(` Today: ${j.daily.sent} / ${j.daily.max} (${j.daily.remaining} left)`);console.log(` Week: ${j.weekly.sent} / ${j.weekly.max} (${j.weekly.remaining} left) \u2014 rolling 7 days`);console.log(` Log: ${K.length} requests recorded all-time
|
|
44
|
+
`);if(Object.keys(T).length){let e=Math.max(...Object.values(T));console.log("Last 7 days");for(let o of Object.keys(T).sort())console.log(` ${o} ${cn(T[o],e).padEnd(20)} ${T[o]}`);console.log(""),console.log(" by source (7d): "+Object.entries(Y).map(([o,n])=>`${o}=${n}`).join(", ")+`
|
|
45
45
|
`)}else console.log(`Last 7 days: no connection requests sent.
|
|
46
|
-
`);var
|
|
47
|
-
`)
|
|
46
|
+
`);var Le=Object.keys(M).sort((e,o)=>M[o].sent-M[e].sent);if(Le.length){console.log("Acceptance (all-time, unique profiles)"),console.log(" "+"Source".padEnd(24)+"Sent".padStart(6)+"Accept".padStart(8)+"Rate".padStart(7)+"Await".padStart(7)+"Stale>14d".padStart(11));let e={sent:0,accepted:0,awaiting:0,stale:0};for(let o of Le){let n=M[o];e.sent+=n.sent,e.accepted+=n.accepted,e.awaiting+=n.awaiting,e.stale+=n.stale,console.log(" "+o.padEnd(24)+String(n.sent).padStart(6)+String(n.accepted).padStart(8)+Fe(n.accepted,n.sent).padStart(7)+String(n.awaiting).padStart(7)+String(n.stale).padStart(11))}console.log(" "+"\u2500".repeat(63)),console.log(" "+"TOTAL".padEnd(24)+String(e.sent).padStart(6)+String(e.accepted).padStart(8)+Fe(e.accepted,e.sent).padStart(7)+String(e.awaiting).padStart(7)+String(e.stale).padStart(11)),console.log(" (Accept = they connected \xB7 Await = request still open \xB7 Stale>14d = open >2wk, likely won't)"),console.log(" Acceptance is read from your last `sync` \u2014 run `ilml linkedin sync` to refresh accepted status.\n")}console.log("Feeder pool \u2014 high-value people not yet connected");for(let e of ce)console.log(` ${e.padEnd(16)} ${W[e]}`);console.log(` ${"TOTAL".padEnd(16)} ${Be}`);console.log(` \u2192 these could absorb idle daily quota once the category feeder is wired.
|
|
47
|
+
`);j.daily.sent===0&&j.daily.remaining>0&&(console.log(`\u26A0 Today's quota is idle (0/${j.daily.max}). Recruiter auto-connect is off and no`),console.log(` other feeder is wired yet \u2014 run the funnel manually or build the category feeder.
|
|
48
48
|
`));
|