@night-slayer18/leetcode-cli 2.1.1 → 2.2.1

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/README.md CHANGED
@@ -74,6 +74,7 @@ leetcode submit 1
74
74
  | `today` | Show daily progress & challenge |
75
75
  | `list` | List problems with filters |
76
76
  | `show <id>` | Display problem description |
77
+ | `hint <id>` | Show hints for a problem |
77
78
  | `pick <id>` | Generate solution file |
78
79
  | `pick-batch <ids>` | Pick multiple problems |
79
80
  | `bookmark <action>` | Manage problem bookmarks |
@@ -122,6 +123,17 @@ leetcode show 1
122
123
  leetcode show two-sum
123
124
  ```
124
125
 
126
+ ### Get Hints
127
+
128
+ ```bash
129
+ # Show hints one at a time (press Enter for next)
130
+ leetcode hint 1
131
+ leetcode hint two-sum
132
+
133
+ # Show all hints at once
134
+ leetcode hint 1 --all
135
+ ```
136
+
125
137
  ### Pick Problem
126
138
 
127
139
  ```bash
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {Command}from'commander';import l from'chalk';import oo from'inquirer';import Ue from'ora';import wn from'got';import {z}from'zod';import Sn from'conf';import {homedir}from'os';import {join,dirname,basename,extname,resolve,sep}from'path';import We from'cli-table3';import {mkdir,writeFile,readFile,readdir}from'fs/promises';import {existsSync,writeFileSync,readFileSync,unlinkSync,mkdirSync}from'fs';import {execSync,spawn}from'child_process';import In from'open';import {createClient}from'@supabase/supabase-js';import {diffLines}from'diff';import {fileURLToPath}from'url';var yn=z.object({name:z.string(),slug:z.string()}),hn=z.object({name:z.string(),slug:z.string()}),bn=z.object({lang:z.string(),langSlug:z.string(),code:z.string()}),De=z.object({questionId:z.string(),questionFrontendId:z.string(),title:z.string(),titleSlug:z.string(),difficulty:z.enum(["Easy","Medium","Hard"]),isPaidOnly:z.boolean(),acRate:z.number().optional().default(0),topicTags:z.array(yn),status:z.enum(["ac","notac"]).nullable()}),lo=De.extend({content:z.string().nullable(),codeSnippets:z.array(bn).nullable(),sampleTestCase:z.string(),exampleTestcases:z.string(),hints:z.array(z.string()),companyTags:z.array(hn).nullable(),stats:z.string()}),co=z.object({date:z.string(),link:z.string(),question:De}),go=z.object({id:z.string(),statusDisplay:z.string(),lang:z.string(),runtime:z.string(),timestamp:z.string(),memory:z.string()}),mo=z.object({code:z.string(),lang:z.object({name:z.string()})}),uo=z.object({status_code:z.number(),status_msg:z.string(),state:z.string(),run_success:z.boolean(),code_answer:z.array(z.string()).optional(),expected_code_answer:z.array(z.string()).optional(),correct_answer:z.boolean().optional(),std_output_list:z.array(z.string()).optional(),compile_error:z.string().optional(),runtime_error:z.string().optional()}),po=z.object({status_code:z.number(),status_msg:z.string(),state:z.string(),run_success:z.boolean(),total_correct:z.number(),total_testcases:z.number(),status_runtime:z.string(),status_memory:z.string(),runtime_percentile:z.number(),memory_percentile:z.number(),code_output:z.string().optional(),std_output:z.string().optional(),expected_output:z.string().optional(),compile_error:z.string().optional(),runtime_error:z.string().optional(),last_testcase:z.string().optional()}),fo=z.object({username:z.string(),profile:z.object({realName:z.string(),ranking:z.number()}),submitStatsGlobal:z.object({acSubmissionNum:z.array(z.object({difficulty:z.string(),count:z.number()}))}),userCalendar:z.object({streak:z.number(),totalActiveDays:z.number(),submissionCalendar:z.string().optional()})}),yo=z.object({isSignedIn:z.boolean(),username:z.string().nullable()});var ho=`
2
+ import {Command}from'commander';import l from'chalk';import to from'inquirer';import Ue from'ora';import kn from'got';import {z}from'zod';import vn from'conf';import {homedir}from'os';import {join,dirname,basename,extname,resolve,sep}from'path';import We from'cli-table3';import En from'striptags';import {mkdir,writeFile,readFile,readdir}from'fs/promises';import {existsSync,writeFileSync,readFileSync,unlinkSync,mkdirSync}from'fs';import {execSync,spawn}from'child_process';import zn from'open';import {createClient}from'@supabase/supabase-js';import {diffLines}from'diff';import {fileURLToPath}from'url';var wn=z.object({name:z.string(),slug:z.string()}),Sn=z.object({name:z.string(),slug:z.string()}),$n=z.object({lang:z.string(),langSlug:z.string(),code:z.string()}),xe=z.object({questionId:z.string(),questionFrontendId:z.string(),title:z.string(),titleSlug:z.string(),difficulty:z.enum(["Easy","Medium","Hard"]),isPaidOnly:z.boolean(),acRate:z.number().optional().default(0),topicTags:z.array(wn),status:z.enum(["ac","notac"]).nullable()}),co=xe.extend({content:z.string().nullable(),codeSnippets:z.array($n).nullable(),sampleTestCase:z.string(),exampleTestcases:z.string(),hints:z.array(z.string()),companyTags:z.array(Sn).nullable(),stats:z.string()}),go=z.object({date:z.string(),link:z.string(),question:xe}),mo=z.object({id:z.string(),statusDisplay:z.string(),lang:z.string(),runtime:z.string(),timestamp:z.string(),memory:z.string()}),uo=z.object({code:z.string(),lang:z.object({name:z.string()})}),po=z.object({status_code:z.number(),status_msg:z.string(),state:z.string(),run_success:z.boolean(),code_answer:z.array(z.string()).optional(),expected_code_answer:z.array(z.string()).optional(),correct_answer:z.boolean().optional(),std_output_list:z.array(z.string()).optional(),compile_error:z.string().optional(),runtime_error:z.string().optional()}),fo=z.object({status_code:z.number(),status_msg:z.string(),state:z.string(),run_success:z.boolean(),total_correct:z.number(),total_testcases:z.number(),status_runtime:z.string(),status_memory:z.string(),runtime_percentile:z.number(),memory_percentile:z.number(),code_output:z.string().optional(),std_output:z.string().optional(),expected_output:z.string().optional(),compile_error:z.string().optional(),runtime_error:z.string().optional(),last_testcase:z.string().optional()}),yo=z.object({username:z.string(),profile:z.object({realName:z.string(),ranking:z.number()}),submitStatsGlobal:z.object({acSubmissionNum:z.array(z.object({difficulty:z.string(),count:z.number()}))}),userCalendar:z.object({streak:z.number(),totalActiveDays:z.number(),submissionCalendar:z.string().optional()})}),ho=z.object({isSignedIn:z.boolean(),username:z.string().nullable()});var bo=`
3
3
  query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) {
4
4
  problemsetQuestionList: questionList(
5
5
  categorySlug: $categorySlug
@@ -24,7 +24,7 @@ import {Command}from'commander';import l from'chalk';import oo from'inquirer';im
24
24
  }
25
25
  }
26
26
  }
27
- `,bo=`
27
+ `,wo=`
28
28
  query questionData($titleSlug: String!) {
29
29
  question(titleSlug: $titleSlug) {
30
30
  questionId
@@ -54,14 +54,14 @@ import {Command}from'commander';import l from'chalk';import oo from'inquirer';im
54
54
  status
55
55
  }
56
56
  }
57
- `,wo=`
57
+ `,So=`
58
58
  query globalData {
59
59
  userStatus {
60
60
  isSignedIn
61
61
  username
62
62
  }
63
63
  }
64
- `,So=`
64
+ `,$o=`
65
65
  query userPublicProfile($username: String!) {
66
66
  matchedUser(username: $username) {
67
67
  username
@@ -82,7 +82,7 @@ import {Command}from'commander';import l from'chalk';import oo from'inquirer';im
82
82
  }
83
83
  }
84
84
  }
85
- `,$o=`
85
+ `,ko=`
86
86
  query skillStats($username: String!) {
87
87
  matchedUser(username: $username) {
88
88
  tagProblemCounts {
@@ -104,7 +104,7 @@ import {Command}from'commander';import l from'chalk';import oo from'inquirer';im
104
104
  }
105
105
  }
106
106
  }
107
- `,ko=`
107
+ `,vo=`
108
108
  query questionOfToday {
109
109
  activeDailyCodingChallengeQuestion {
110
110
  date
@@ -125,7 +125,7 @@ import {Command}from'commander';import l from'chalk';import oo from'inquirer';im
125
125
  }
126
126
  }
127
127
  }
128
- `,vo=`
128
+ `,Co=`
129
129
  query submissionList($questionSlug: String!, $limit: Int, $offset: Int) {
130
130
  questionSubmissionList(
131
131
  questionSlug: $questionSlug
@@ -142,13 +142,13 @@ import {Command}from'commander';import l from'chalk';import oo from'inquirer';im
142
142
  }
143
143
  }
144
144
  }
145
- `,Co=`
145
+ `,Po=`
146
146
  query randomQuestion($categorySlug: String, $filters: QuestionListFilterInput) {
147
147
  randomQuestion(categorySlug: $categorySlug, filters: $filters) {
148
148
  titleSlug
149
149
  }
150
150
  }
151
- `,Po=`
151
+ `,To=`
152
152
  query submissionDetails($submissionId: Int!) {
153
153
  submissionDetails(submissionId: $submissionId) {
154
154
  code
@@ -157,40 +157,43 @@ import {Command}from'commander';import l from'chalk';import oo from'inquirer';im
157
157
  }
158
158
  }
159
159
  }
160
- `;var Ee="https://leetcode.com",qe=class{client;credentials=null;constructor(){this.client=wn.extend({prefixUrl:Ee,headers:{"Content-Type":"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",Origin:Ee,Referer:`${Ee}/`},timeout:{request:3e4},retry:{limit:2}});}setCredentials(o){this.credentials=o,this.client=this.client.extend({headers:{Cookie:`LEETCODE_SESSION=${o.session}; csrftoken=${o.csrfToken}`,"X-CSRFToken":o.csrfToken}});}getCredentials(){return this.credentials}async graphql(o,t={}){let n=await this.client.post("graphql",{json:{query:o,variables:t}}).json();if(n.errors?.length)throw new Error(`GraphQL Error: ${n.errors[0].message}`);return n.data}async checkAuth(){let o=await this.graphql(wo);return yo.parse(o.userStatus)}async getProblems(o={}){let t={categorySlug:"",limit:o.limit??50,skip:o.skip??0,filters:{}};o.difficulty&&(t.filters.difficulty=o.difficulty),o.status&&(t.filters.status=o.status),o.tags?.length&&(t.filters.tags=o.tags),o.searchKeywords&&(t.filters.searchKeywords=o.searchKeywords);let n=await this.graphql(ho,t),s=z.array(De).parse(n.problemsetQuestionList.questions);return {total:n.problemsetQuestionList.total,problems:s}}async getProblem(o){let t=await this.graphql(bo,{titleSlug:o});return lo.parse(t.question)}async getProblemById(o){let{problems:t}=await this.getProblems({searchKeywords:o,limit:10}),n=t.find(s=>s.questionFrontendId===o);if(!n)throw new Error(`Problem #${o} not found`);return this.getProblem(n.titleSlug)}async getDailyChallenge(){let o=await this.graphql(ko);return co.parse(o.activeDailyCodingChallengeQuestion)}async getRandomProblem(o={}){let t={categorySlug:"",filters:{}};o.difficulty&&(t.filters.difficulty=o.difficulty),o.tags?.length&&(t.filters.tags=o.tags);let n=await this.graphql(Co,t);return z.object({titleSlug:z.string()}).parse(n.randomQuestion).titleSlug}async getUserProfile(o){let n=(await this.graphql(So,{username:o})).matchedUser,s=fo.parse(n);return {username:s.username,realName:s.profile.realName,ranking:s.profile.ranking,acSubmissionNum:s.submitStatsGlobal.acSubmissionNum,streak:s.userCalendar.streak,totalActiveDays:s.userCalendar.totalActiveDays,submissionCalendar:n.userCalendar.submissionCalendar}}async getSkillStats(o){return (await this.graphql($o,{username:o})).matchedUser.tagProblemCounts}async getSubmissionList(o,t=20,n=0){let s=await this.graphql(vo,{questionSlug:o,limit:t,offset:n});return z.array(go).parse(s.questionSubmissionList.submissions)}async getSubmissionDetails(o){let t=await this.graphql(Po,{submissionId:o});return mo.parse(t.submissionDetails)}async testSolution(o,t,n,s,r){let i=await this.client.post(`problems/${o}/interpret_solution/`,{json:{data_input:s,lang:n,typed_code:t,question_id:r}}).json();return this.pollSubmission(i.interpret_id,"interpret",uo)}async submitSolution(o,t,n,s){let r=await this.client.post(`problems/${o}/submit/`,{json:{lang:n,typed_code:t,question_id:s}}).json();return this.pollSubmission(r.submission_id.toString(),"submission",po)}async pollSubmission(o,t,n){let s=`submissions/detail/${o}/check/`,r=30,i=1e3;for(let a=0;a<r;a++){let c=await this.client.get(s).json();if(c.state==="SUCCESS"||c.state==="FAILURE")return n.parse(c);await new Promise(g=>setTimeout(g,i));}throw new Error("Submission timeout: Result not available after 30 seconds")}},h=new qe;var ce=new Sn({configName:"credentials",cwd:join(homedir(),".leetcode"),defaults:{}}),K={get(){let e=ce.get("session"),o=ce.get("csrfToken");return !e||!o?null:{session:e,csrfToken:o}},set(e){ce.set("session",e.session),ce.set("csrfToken",e.csrfToken);},clear(){ce.clear();},getPath(){return ce.path}};async function Do(){console.log(),console.log(l.cyan("LeetCode CLI Login")),console.log(l.gray("\u2500".repeat(40))),console.log(),console.log(l.yellow("To login, you need to provide your LeetCode session cookies.")),console.log(l.gray("1. Open https://leetcode.com in your browser")),console.log(l.gray("2. Login to your account")),console.log(l.gray("3. Open DevTools (F12) \u2192 Application \u2192 Cookies \u2192 leetcode.com")),console.log(l.gray("4. Copy the values of LEETCODE_SESSION and csrftoken")),console.log();let e=await oo.prompt([{type:"password",name:"session",message:"LEETCODE_SESSION:",mask:"*",validate:n=>n.length>0||"Session token is required"},{type:"password",name:"csrfToken",message:"csrftoken:",mask:"*",validate:n=>n.length>0||"CSRF token is required"}]),o={session:e.session.trim(),csrfToken:e.csrfToken.trim()},t=Ue("Verifying credentials...").start();try{h.setCredentials(o);let{isSignedIn:n,username:s}=await h.checkAuth();if(!n||!s){t.fail("Invalid credentials"),console.log(l.red("Please check your session cookies and try again."));return}K.set(o),t.succeed(`Logged in as ${l.green(s)}`),console.log(),console.log(l.gray(`Credentials saved to ${K.getPath()}`));}catch(n){t.fail("Authentication failed"),n instanceof Error&&console.log(l.red(n.message));}}async function xo(){K.clear(),console.log(l.green("\u2713 Logged out successfully"));}async function Eo(){let e=K.get();if(!e){console.log(l.yellow('Not logged in. Run "leetcode login" to authenticate.'));return}let o=Ue("Checking session...").start();try{h.setCredentials(e);let{isSignedIn:t,username:n}=await h.checkAuth();if(!t||!n){o.fail("Session expired"),console.log(l.yellow('Please run "leetcode login" to re-authenticate.'));return}o.succeed(`Logged in as ${l.green(n)}`);}catch(t){o.fail("Failed to check session"),t instanceof Error&&console.log(l.red(t.message));}}async function v(){let e=K.get();if(!e)return console.log(l.yellow("\u26A0\uFE0F Please login first: leetcode login")),{authorized:false};try{h.setCredentials(e);let{isSignedIn:o,username:t}=await h.checkAuth();return o?{authorized:!0,username:t??void 0}:(console.log(l.yellow("\u26A0\uFE0F Session expired. Please run: leetcode login")),{authorized:!1})}catch{return console.log(l.yellow("\u26A0\uFE0F Session validation failed. Please run: leetcode login")),{authorized:false}}}var Cn={"Linked List":"linkedlist","Doubly-Linked List":"linkedlist",Tree:"tree","Binary Tree":"tree","Binary Search Tree":"tree",Trie:"tree","Segment Tree":"tree","Binary Indexed Tree":"tree",Graph:"graph",Matrix:"matrix",Array:"array","Hash Table":"array",Stack:"array",Queue:"array","Monotonic Stack":"array","Monotonic Queue":"array","Heap (Priority Queue)":"array",String:"string"};function Pn(e){for(let o of e){let t=Cn[o.name];if(t)return t}return null}function Lo(e){try{return JSON.parse(e)}catch{return e}}function ee(e){return Array.isArray(e)&&e.length>0&&Array.isArray(e[0])}function Ao(e,o){if(!Array.isArray(e)||e.length===0)return String(e);let t=Math.max(...e.map(i=>String(i).length),1),n=Math.max(t,3),s=e.map((i,a)=>`[${a}]`.padStart(n).padEnd(n)).join(" "),r=e.map((i,a)=>{let c=String(i).padStart(n).padEnd(n);return o&&Array.isArray(o)&&o[a]!==i?l.red.bold(c):c}).join(" ");return `${l.gray(s)}
161
- ${r}`}function Ro(e,o){return Array.isArray(e)?e.length===0?l.gray("(empty)"):e.map((n,s)=>{let r=String(n);return o&&Array.isArray(o)&&(s>=o.length||o[s]!==n)?l.red.bold(r):r}).join(l.gray(" \u2192 ")):String(e)}function _o(e){if(!Array.isArray(e)||e.length===0)return l.gray("(empty tree)");let o=[],t=Math.floor(Math.log2(e.length))+1,n=Math.pow(2,t)*3;function s(r,i,a,c){if(i>e.length-1)return;let g=[],u=[],p=Math.floor(n/Math.pow(2,r+1));for(let b=i;b<=a&&b<e.length;b++){let C=e[b],I=C===null?" ":String(C);g.push(I.padStart(p).padEnd(p));let R=2*b+1,q=2*b+2,Z=R<e.length&&e[R]!==null,re=q<e.length&&e[q]!==null;if(Z||re){let H="";Z?H+="/":H+=" ",H+=" ",re?H+="\\":H+=" ",u.push(H.padStart(p).padEnd(p));}}g.length>0&&(o.push(g.join("")),u.length>0&&r<t-1&&o.push(u.join("")));}for(let r=0;r<t;r++){let i=Math.pow(2,r)-1,a=Math.pow(2,r+1)-2;s(r,i,a);}return o.join(`
162
- `)}function Le(e,o){if(!ee(e)||e.length===0)return String(e);let t=e.length,n=e[0].length,s=3,r=[],i=" "+e[0].map((a,c)=>String(c).padStart(s).padEnd(s)).join(" ");r.push(l.gray(i)),r.push(" \u250C"+Array(n).fill("\u2500\u2500\u2500").join("\u252C")+"\u2510");for(let a=0;a<t;a++){let c=e[a].map((g,u)=>{let p=String(g).padStart(2);return o&&ee(o)&&o[a]&&o[a][u]!==g?l.red.bold(p):p}).join(" \u2502 ");r.push(l.gray(` ${a} `)+`\u2502 ${c} \u2502`),a<t-1?r.push(" \u251C"+Array(n).fill("\u2500\u2500\u2500").join("\u253C")+"\u2524"):r.push(" \u2514"+Array(n).fill("\u2500\u2500\u2500").join("\u2534")+"\u2518");}return r.join(`
163
- `)}function Fo(e){return ee(e)?e.map((t,n)=>{let s=Array.isArray(t)?t.join(", "):String(t);return ` ${l.cyan(String(n))} \u2192 [${s}]`}).join(`
164
- `):String(e)}function No(e,o,t){let n=Lo(e),s=Lo(o),r=e===o,i=Pn(t),a,c;if(ee(n)){let g=ee(s)?s:void 0;return a=Le(n,g),c=ee(s)?Le(s):String(o),{outputVis:a,expectedVis:c,matches:r}}if(i===null)return {outputVis:String(e),expectedVis:String(o),matches:r,unsupported:true};switch(i){case "linkedlist":a=Ro(n,s),c=Ro(s);break;case "tree":a=_o(n),c=_o(s);break;case "graph":a=Fo(n),c=Fo(s);break;case "matrix":let g=ee(s)?s:void 0;a=Le(n,g),c=ee(s)?Le(s):String(o);break;case "array":case "string":Array.isArray(n)?(a=Ao(n,s),c=Array.isArray(s)?Ao(s):String(o)):(a=r?String(e):l.red.bold(String(e)),c=String(o));break}return {outputVis:a,expectedVis:c,matches:r}}function Io(e,o){let t=new We({head:[l.cyan("ID"),l.cyan("Title"),l.cyan("Difficulty"),l.cyan("Rate"),l.cyan("Status")],colWidths:[8,45,12,10,10],style:{head:[],border:[]}});for(let n of e){let s=n.title;n.isPaidOnly&&(s=`\u{1F512} ${s}`),t.push([n.questionFrontendId,s.length>42?s.slice(0,39)+"...":s,Ae(n.difficulty),`${n.acRate.toFixed(1)}%`,Tn(n.status)]);}console.log(t.toString()),console.log(l.gray(`
165
- Showing ${e.length} of ${o} problems`));}function Uo(e){console.log();let o=e.isPaidOnly?"\u{1F512} ":"";if(console.log(l.bold.cyan(` ${e.questionFrontendId}. ${o}${e.title}`)),console.log(` ${Ae(e.difficulty)}`),console.log(l.gray(` https://leetcode.com/problems/${e.titleSlug}/`)),console.log(),e.isPaidOnly&&(console.log(l.yellow(" \u26A0\uFE0F Premium Problem")),console.log(l.gray(" This problem requires a LeetCode Premium subscription.")),console.log(l.gray(" Visit the URL above to view on LeetCode.")),console.log()),e.topicTags.length){let n=e.topicTags.map(s=>l.bgBlue.white(` ${s.name} `)).join(" ");console.log(` ${n}`),console.log();}console.log(l.gray("\u2500".repeat(60))),console.log();let t=e.content;if(!t){console.log(l.yellow(" \u{1F512} Premium Content")),console.log(l.gray(" Problem description is not available directly.")),console.log(l.gray(" Please visit the URL above to view on LeetCode.")),console.log();return}t=t.replace(/<sup>(.*?)<\/sup>/gi,"^$1"),t=t.replace(/<strong class="example">Example (\d+):<\/strong>/gi,"\xA7EXAMPLE\xA7$1\xA7"),t=t.replace(/Input:/gi,"\xA7INPUT\xA7"),t=t.replace(/Output:/gi,"\xA7OUTPUT\xA7"),t=t.replace(/Explanation:/gi,"\xA7EXPLAIN\xA7"),t=t.replace(/<strong>Constraints:<\/strong>/gi,"\xA7CONSTRAINTS\xA7"),t=t.replace(/Constraints:/gi,"\xA7CONSTRAINTS\xA7"),t=t.replace(/<strong>Follow-up:/gi,"\xA7FOLLOWUP\xA7"),t=t.replace(/Follow-up:/gi,"\xA7FOLLOWUP\xA7"),t=t.replace(/<li>/gi," \u2022 "),t=t.replace(/<\/li>/gi,`
160
+ `;var qe="https://leetcode.com",Oe=class{client;credentials=null;constructor(){this.client=kn.extend({prefixUrl:qe,headers:{"Content-Type":"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",Origin:qe,Referer:`${qe}/`},timeout:{request:3e4},retry:{limit:2}});}setCredentials(o){this.credentials=o,this.client=this.client.extend({headers:{Cookie:`LEETCODE_SESSION=${o.session}; csrftoken=${o.csrfToken}`,"X-CSRFToken":o.csrfToken}});}getCredentials(){return this.credentials}async graphql(o,t={}){let n=await this.client.post("graphql",{json:{query:o,variables:t}}).json();if(n.errors?.length)throw new Error(`GraphQL Error: ${n.errors[0].message}`);return n.data}async checkAuth(){let o=await this.graphql(So);return ho.parse(o.userStatus)}async getProblems(o={}){let t={categorySlug:"",limit:o.limit??50,skip:o.skip??0,filters:{}};o.difficulty&&(t.filters.difficulty=o.difficulty),o.status&&(t.filters.status=o.status),o.tags?.length&&(t.filters.tags=o.tags),o.searchKeywords&&(t.filters.searchKeywords=o.searchKeywords);let n=await this.graphql(bo,t),s=z.array(xe).parse(n.problemsetQuestionList.questions);return {total:n.problemsetQuestionList.total,problems:s}}async getProblem(o){let t=await this.graphql(wo,{titleSlug:o});return co.parse(t.question)}async getProblemById(o){let{problems:t}=await this.getProblems({searchKeywords:o,limit:10}),n=t.find(s=>s.questionFrontendId===o);if(!n)throw new Error(`Problem #${o} not found`);return this.getProblem(n.titleSlug)}async getDailyChallenge(){let o=await this.graphql(vo);return go.parse(o.activeDailyCodingChallengeQuestion)}async getRandomProblem(o={}){let t={categorySlug:"",filters:{}};o.difficulty&&(t.filters.difficulty=o.difficulty),o.tags?.length&&(t.filters.tags=o.tags);let n=await this.graphql(Po,t);return z.object({titleSlug:z.string()}).parse(n.randomQuestion).titleSlug}async getUserProfile(o){let n=(await this.graphql($o,{username:o})).matchedUser,s=yo.parse(n);return {username:s.username,realName:s.profile.realName,ranking:s.profile.ranking,acSubmissionNum:s.submitStatsGlobal.acSubmissionNum,streak:s.userCalendar.streak,totalActiveDays:s.userCalendar.totalActiveDays,submissionCalendar:n.userCalendar.submissionCalendar}}async getSkillStats(o){return (await this.graphql(ko,{username:o})).matchedUser.tagProblemCounts}async getSubmissionList(o,t=20,n=0){let s=await this.graphql(Co,{questionSlug:o,limit:t,offset:n});return z.array(mo).parse(s.questionSubmissionList.submissions)}async getSubmissionDetails(o){let t=await this.graphql(To,{submissionId:o});return uo.parse(t.submissionDetails)}async testSolution(o,t,n,s,r){let i=await this.client.post(`problems/${o}/interpret_solution/`,{json:{data_input:s,lang:n,typed_code:t,question_id:r}}).json();return this.pollSubmission(i.interpret_id,"interpret",po)}async submitSolution(o,t,n,s){let r=await this.client.post(`problems/${o}/submit/`,{json:{lang:n,typed_code:t,question_id:s}}).json();return this.pollSubmission(r.submission_id.toString(),"submission",fo)}async pollSubmission(o,t,n){let s=`submissions/detail/${o}/check/`,r=12,i=500,a=3e3;for(let g=0;g<r;g++){try{let p=await this.client.get(s).json();if(p.state==="SUCCESS"||p.state==="FAILURE")return n.parse(p)}catch(p){if(g===r-1){let b=t==="interpret"?"Test":"Submission";throw new Error(`${b} check failed: ${p instanceof Error?p.message:"Network error"}`)}}let u=Math.min(i*Math.pow(2,g),a);await new Promise(p=>setTimeout(p,u));}let c=t==="interpret"?"Test":"Submission";throw new Error(`${c} timeout: Result not available after 30 seconds`)}},h=new Oe;var ge=new vn({configName:"credentials",cwd:join(homedir(),".leetcode"),defaults:{}}),X={get(){let e=ge.get("session"),o=ge.get("csrfToken");return !e||!o?null:{session:e,csrfToken:o}},set(e){ge.set("session",e.session),ge.set("csrfToken",e.csrfToken);},clear(){ge.clear();},getPath(){return ge.path}};async function xo(){console.log(),console.log(l.cyan("LeetCode CLI Login")),console.log(l.gray("\u2500".repeat(40))),console.log(),console.log(l.yellow("To login, you need to provide your LeetCode session cookies.")),console.log(l.gray("1. Open https://leetcode.com in your browser")),console.log(l.gray("2. Login to your account")),console.log(l.gray("3. Open DevTools (F12) \u2192 Application \u2192 Cookies \u2192 leetcode.com")),console.log(l.gray("4. Copy the values of LEETCODE_SESSION and csrftoken")),console.log();let e=await to.prompt([{type:"password",name:"session",message:"LEETCODE_SESSION:",mask:"*",validate:n=>n.length>0||"Session token is required"},{type:"password",name:"csrfToken",message:"csrftoken:",mask:"*",validate:n=>n.length>0||"CSRF token is required"}]),o={session:e.session.trim(),csrfToken:e.csrfToken.trim()},t=Ue("Verifying credentials...").start();try{h.setCredentials(o);let{isSignedIn:n,username:s}=await h.checkAuth();if(!n||!s){t.fail("Invalid credentials"),console.log(l.red("Please check your session cookies and try again."));return}X.set(o),t.succeed(`Logged in as ${l.green(s)}`),console.log(),console.log(l.gray(`Credentials saved to ${X.getPath()}`));}catch(n){t.fail("Authentication failed"),n instanceof Error&&console.log(l.red(n.message));}}async function Eo(){X.clear(),console.log(l.green("\u2713 Logged out successfully"));}async function Lo(){let e=X.get();if(!e){console.log(l.yellow('Not logged in. Run "leetcode login" to authenticate.'));return}let o=Ue("Checking session...").start();try{h.setCredentials(e);let{isSignedIn:t,username:n}=await h.checkAuth();if(!t||!n){o.fail("Session expired"),console.log(l.yellow('Please run "leetcode login" to re-authenticate.'));return}o.succeed(`Logged in as ${l.green(n)}`);}catch(t){o.fail("Failed to check session"),t instanceof Error&&console.log(l.red(t.message));}}async function $(){let e=X.get();if(!e)return console.log(l.yellow("\u26A0\uFE0F Please login first: leetcode login")),{authorized:false};try{h.setCredentials(e);let{isSignedIn:o,username:t}=await h.checkAuth();return o?{authorized:!0,username:t??void 0}:(console.log(l.yellow("\u26A0\uFE0F Session expired. Please run: leetcode login")),{authorized:!1})}catch{return console.log(l.yellow("\u26A0\uFE0F Session validation failed. Please run: leetcode login")),{authorized:false}}}var Dn={"Linked List":"linkedlist","Doubly-Linked List":"linkedlist",Tree:"tree","Binary Tree":"tree","Binary Search Tree":"tree",Trie:"tree","Segment Tree":"tree","Binary Indexed Tree":"tree",Graph:"graph",Matrix:"matrix",Array:"array","Hash Table":"array",Stack:"array",Queue:"array","Monotonic Stack":"array","Monotonic Queue":"array","Heap (Priority Queue)":"array",String:"string"};function xn(e){for(let o of e){let t=Dn[o.name];if(t)return t}return null}function Ao(e){try{return JSON.parse(e)}catch{return e}}function oe(e){return Array.isArray(e)&&e.length>0&&Array.isArray(e[0])}function Ro(e,o){if(!Array.isArray(e)||e.length===0)return String(e);let t=Math.max(...e.map(i=>String(i).length),1),n=Math.max(t,3),s=e.map((i,a)=>`[${a}]`.padStart(n).padEnd(n)).join(" "),r=e.map((i,a)=>{let c=String(i).padStart(n).padEnd(n);return o&&Array.isArray(o)&&o[a]!==i?l.red.bold(c):c}).join(" ");return `${l.gray(s)}
161
+ ${r}`}function Fo(e,o){return Array.isArray(e)?e.length===0?l.gray("(empty)"):e.map((n,s)=>{let r=String(n);return o&&Array.isArray(o)&&(s>=o.length||o[s]!==n)?l.red.bold(r):r}).join(l.gray(" \u2192 ")):String(e)}function _o(e){if(!Array.isArray(e)||e.length===0)return l.gray("(empty tree)");let o=[],t=Math.floor(Math.log2(e.length))+1,n=Math.pow(2,t)*3;function s(r,i,a,c){if(i>e.length-1)return;let g=[],u=[],p=Math.floor(n/Math.pow(2,r+1));for(let b=i;b<=a&&b<e.length;b++){let x=e[b],I=x===null?" ":String(x);g.push(I.padStart(p).padEnd(p));let F=2*b+1,q=2*b+2,ee=F<e.length&&e[F]!==null,ie=q<e.length&&e[q]!==null;if(ee||ie){let V="";ee?V+="/":V+=" ",V+=" ",ie?V+="\\":V+=" ",u.push(V.padStart(p).padEnd(p));}}g.length>0&&(o.push(g.join("")),u.length>0&&r<t-1&&o.push(u.join("")));}for(let r=0;r<t;r++){let i=Math.pow(2,r)-1,a=Math.pow(2,r+1)-2;s(r,i,a);}return o.join(`
162
+ `)}function Le(e,o){if(!oe(e)||e.length===0)return String(e);let t=e.length,n=e[0].length,s=3,r=[],i=" "+e[0].map((a,c)=>String(c).padStart(s).padEnd(s)).join(" ");r.push(l.gray(i)),r.push(" \u250C"+Array(n).fill("\u2500\u2500\u2500").join("\u252C")+"\u2510");for(let a=0;a<t;a++){let c=e[a].map((g,u)=>{let p=String(g).padStart(2);return o&&oe(o)&&o[a]&&o[a][u]!==g?l.red.bold(p):p}).join(" \u2502 ");r.push(l.gray(` ${a} `)+`\u2502 ${c} \u2502`),a<t-1?r.push(" \u251C"+Array(n).fill("\u2500\u2500\u2500").join("\u253C")+"\u2524"):r.push(" \u2514"+Array(n).fill("\u2500\u2500\u2500").join("\u2534")+"\u2518");}return r.join(`
163
+ `)}function No(e){return oe(e)?e.map((t,n)=>{let s=Array.isArray(t)?t.join(", "):String(t);return ` ${l.cyan(String(n))} \u2192 [${s}]`}).join(`
164
+ `):String(e)}function Io(e,o,t){let n=Ao(e),s=Ao(o),r=e===o,i=xn(t),a,c;if(oe(n)){let g=oe(s)?s:void 0;return a=Le(n,g),c=oe(s)?Le(s):String(o),{outputVis:a,expectedVis:c,matches:r}}if(i===null)return {outputVis:String(e),expectedVis:String(o),matches:r,unsupported:true};switch(i){case "linkedlist":a=Fo(n,s),c=Fo(s);break;case "tree":a=_o(n),c=_o(s);break;case "graph":a=No(n),c=No(s);break;case "matrix":let g=oe(s)?s:void 0;a=Le(n,g),c=oe(s)?Le(s):String(o);break;case "array":case "string":Array.isArray(n)?(a=Ro(n,s),c=Array.isArray(s)?Ro(s):String(o)):(a=r?String(e):l.red.bold(String(e)),c=String(o));break}return {outputVis:a,expectedVis:c,matches:r}}function Uo(e,o){let t=new We({head:[l.cyan("ID"),l.cyan("Title"),l.cyan("Difficulty"),l.cyan("Rate"),l.cyan("Status")],colWidths:[8,45,12,10,10],style:{head:[],border:[]}});for(let n of e){let s=n.title;n.isPaidOnly&&(s=`\u{1F512} ${s}`),t.push([n.questionFrontendId,s.length>42?s.slice(0,39)+"...":s,Ae(n.difficulty),`${n.acRate.toFixed(1)}%`,Ln(n.status)]);}console.log(t.toString()),console.log(l.gray(`
165
+ Showing ${e.length} of ${o} problems`));}function jo(e){console.log();let o=e.isPaidOnly?"\u{1F512} ":"";if(console.log(l.bold.cyan(` ${e.questionFrontendId}. ${o}${e.title}`)),console.log(` ${Ae(e.difficulty)}`),console.log(l.gray(` https://leetcode.com/problems/${e.titleSlug}/`)),console.log(),e.isPaidOnly&&(console.log(l.yellow(" \u26A0\uFE0F Premium Problem")),console.log(l.gray(" This problem requires a LeetCode Premium subscription.")),console.log(l.gray(" Visit the URL above to view on LeetCode.")),console.log()),e.topicTags.length){let n=e.topicTags.map(s=>l.bgBlue.white(` ${s.name} `)).join(" ");console.log(` ${n}`),console.log();}console.log(l.gray("\u2500".repeat(60))),console.log();let t=e.content;if(!t){console.log(l.yellow(" \u{1F512} Premium Content")),console.log(l.gray(" Problem description is not available directly.")),console.log(l.gray(" Please visit the URL above to view on LeetCode.")),console.log();return}t=t.replace(/<sup>(.*?)<\/sup>/gi,"^$1"),t=t.replace(/<strong class="example">Example (\d+):<\/strong>/gi,"\xA7EXAMPLE\xA7$1\xA7"),t=t.replace(/Input:/gi,"\xA7INPUT\xA7"),t=t.replace(/Output:/gi,"\xA7OUTPUT\xA7"),t=t.replace(/Explanation:/gi,"\xA7EXPLAIN\xA7"),t=t.replace(/<strong>Constraints:<\/strong>/gi,"\xA7CONSTRAINTS\xA7"),t=t.replace(/Constraints:/gi,"\xA7CONSTRAINTS\xA7"),t=t.replace(/<strong>Follow-up:/gi,"\xA7FOLLOWUP\xA7"),t=t.replace(/Follow-up:/gi,"\xA7FOLLOWUP\xA7"),t=t.replace(/<li>/gi," \u2022 "),t=t.replace(/<\/li>/gi,`
166
166
  `),t=t.replace(/<\/p>/gi,`
167
167
 
168
168
  `),t=t.replace(/<br\s*\/?>/gi,`
169
- `),t=t.replace(/<[^>]+>/g,""),t=t.replace(/&nbsp;/g," ").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&le;/g,"\u2264").replace(/&ge;/g,"\u2265").replace(/&#(\d+);/g,(n,s)=>String.fromCharCode(parseInt(s,10))),t=t.replace(/\n{3,}/g,`
169
+ `),t=En(t),t=t.replace(/&nbsp;/g," ").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&le;/g,"\u2264").replace(/&ge;/g,"\u2265").replace(/&#(\d+);/g,(n,s)=>String.fromCharCode(parseInt(s,10))).replace(/&amp;/g,"&"),t=t.replace(/\n{3,}/g,`
170
170
 
171
171
  `).trim(),t=t.replace(/§EXAMPLE§(\d+)§/g,(n,s)=>l.green.bold(`\u{1F4CC} Example ${s}:`)),t=t.replace(/§INPUT§/g,l.yellow("Input:")),t=t.replace(/§OUTPUT§/g,l.yellow("Output:")),t=t.replace(/§EXPLAIN§/g,l.gray("Explanation:")),t=t.replace(/§CONSTRAINTS§/g,l.cyan.bold(`
172
172
  \u{1F4CB} Constraints:`)),t=t.replace(/§FOLLOWUP§/g,l.magenta.bold(`
173
- \u{1F4A1} Follow-up:`)),console.log(t),console.log();}function jo(e,o){if(console.log(),e.compile_error){console.log(l.red.bold("\u274C Compile Error")),console.log(l.red(e.compile_error));return}if(e.runtime_error){console.log(l.red.bold("\u274C Runtime Error")),console.log(l.red(e.runtime_error));return}e.correct_answer?console.log(l.green.bold("\u2713 All test cases passed!")):console.log(l.yellow.bold("\u2717 Some test cases failed"));let t=e.code_answer??[],n=e.expected_code_answer??[];if(o&&t.length>0){console.log(),console.log(l.gray.bold("\u2500".repeat(50)));let r=t.map((i,a)=>({out:i,exp:n[a]??""})).filter(({out:i,exp:a})=>i!==""||a!=="");for(let i=0;i<r.length;i++){let{out:a,exp:c}=r[i],{outputVis:g,expectedVis:u,matches:p,unsupported:b}=No(a,c,o);console.log(),console.log(l.gray(`Test Case ${i+1}:`)),b&&(console.log(l.yellow(" \u26A0 No visualization available for this problem type")),console.log(l.gray(` Tags: ${o.map(C=>C.name).join(", ")}`))),console.log(),console.log(l.cyan(" Your Output:")),g.split(`
174
- `).forEach(C=>console.log(` ${C}`)),console.log(),console.log(l.cyan(" Expected:")),u.split(`
175
- `).forEach(C=>console.log(` ${C}`)),console.log(),console.log(p?l.green(" \u2713 Match"):l.red(" \u2717 Mismatch"));}console.log(l.gray.bold("\u2500".repeat(50)));}else {console.log(),console.log(l.gray("Your Output:"));for(let r of t)console.log(l.white(` ${r}`));console.log(),console.log(l.gray("Expected Output:"));for(let r of n)console.log(l.white(` ${r}`));}let s=(e.std_output_list??[]).filter(r=>r);if(s.length>0){console.log(),console.log(l.gray("Stdout:"));for(let r of s)console.log(l.gray(` ${r}`));}}function Mo(e){if(console.log(),e.compile_error){console.log(l.red.bold("\u274C Compile Error")),console.log(l.red(e.compile_error));return}if(e.runtime_error){console.log(l.red.bold("\u274C Runtime Error")),console.log(l.red(e.runtime_error)),e.last_testcase&&console.log(l.gray("Last testcase:"),e.last_testcase);return}e.status_msg==="Accepted"?(console.log(l.green.bold("\u2713 Accepted!")),console.log(),console.log(l.gray("Runtime:"),l.white(e.status_runtime),l.gray(`(beats ${e.runtime_percentile?.toFixed(1)??"N/A"}%)`)),console.log(l.gray("Memory:"),l.white(e.status_memory),l.gray(`(beats ${e.memory_percentile?.toFixed(1)??"N/A"}%)`))):(console.log(l.red.bold(`\u274C ${e.status_msg}`)),console.log(),console.log(l.gray(`Passed ${e.total_correct}/${e.total_testcases} testcases`)),e.code_output&&console.log(l.gray("Your Output:"),e.code_output),e.expected_output&&console.log(l.gray("Expected:"),e.expected_output),e.last_testcase&&console.log(l.gray("Failed testcase:"),e.last_testcase));}function qo(e,o,t,n,s,r){console.log(),console.log(l.bold.white(`\u{1F464} ${e}`)+(o?l.gray(` (${o})`):"")),console.log(l.gray(`Ranking: #${t.toLocaleString()}`)),console.log();let i=new We({head:[l.cyan("Difficulty"),l.cyan("Solved")],style:{head:[],border:[]}});for(let c of n)c.difficulty!=="All"&&i.push([Ae(c.difficulty),c.count.toString()]);let a=n.find(c=>c.difficulty==="All")?.count??0;i.push([l.white.bold("Total"),l.white.bold(a.toString())]),console.log(i.toString()),console.log(),console.log(l.gray("\u{1F525} Current streak:"),l.hex("#FFA500")(s.toString()),l.gray("days")),console.log(l.gray("\u{1F4C5} Total active days:"),l.white(r.toString()));}function Oo(e,o){if(console.log(),console.log(l.bold.yellow("\u{1F3AF} Daily Challenge"),l.gray(`(${e})`)),console.log(),console.log(l.white(`${o.questionFrontendId}. ${o.title}`)),console.log(Ae(o.difficulty)),console.log(l.gray(`https://leetcode.com/problems/${o.titleSlug}/`)),o.topicTags.length){console.log();let t=o.topicTags.map(n=>l.blue(n.name)).join(" ");console.log(l.gray("Tags:"),t);}}function Ae(e){switch(e.toLowerCase()){case "easy":return l.green(e);case "medium":return l.yellow(e);case "hard":return l.red(e);default:return e}}function Tn(e){switch(e){case "ac":return l.green("\u2713");case "notac":return l.yellow("\u25CB");default:return l.gray("-")}}function He(e){let o=new We({head:[l.cyan("ID"),l.cyan("Status"),l.cyan("Lang"),l.cyan("Runtime"),l.cyan("Memory"),l.cyan("Date")],colWidths:[12,18,15,12,12,25],style:{head:[],border:[]}});for(let t of e){let n=t.statusDisplay==="Accepted",s=new Date(parseInt(t.timestamp)*1e3).toLocaleString();o.push([t.id,n?l.green(t.statusDisplay):l.red(t.statusDisplay),t.lang,t.runtime,t.memory,s]);}console.log(o.toString());}async function Wo(e){let{authorized:o}=await v();if(!o)return;let t=Ue("Fetching problems...").start();try{let n={},s=parseInt(e.limit??"20",10),r=parseInt(e.page??"1",10);if(n.limit=s,n.skip=(r-1)*s,e.difficulty){let c={easy:"EASY",e:"EASY",medium:"MEDIUM",m:"MEDIUM",hard:"HARD",h:"HARD"};n.difficulty=c[e.difficulty.toLowerCase()];}if(e.status){let c={todo:"NOT_STARTED",solved:"AC",ac:"AC",attempted:"TRIED",tried:"TRIED"};n.status=c[e.status.toLowerCase()];}e.tag?.length&&(n.tags=e.tag),e.search&&(n.searchKeywords=e.search);let{total:i,problems:a}=await h.getProblems(n);if(t.stop(),a.length===0){console.log(l.yellow("No problems found matching your criteria."));return}Io(a,i),r*s<i&&console.log(l.gray(`
176
- Page ${r} of ${Math.ceil(i/s)}. Use --page to navigate.`));}catch(n){t.fail("Failed to fetch problems"),n instanceof Error&&console.log(l.red(n.message));}}async function Re(e){let{authorized:o}=await v();if(!o)return;let t=Ue("Fetching problem...").start();try{let n;if(/^\d+$/.test(e)?n=await h.getProblemById(e):n=await h.getProblem(e),!n){t.fail(`Problem "${e}" not found`);return}t.stop(),Uo(n);}catch(n){t.fail("Failed to fetch problem"),n instanceof Error&&console.log(l.red(n.message));}}var Ye=join(homedir(),".leetcode"),Be=join(Ye,"workspaces.json"),_e=join(Ye,"workspaces");function Ne(e){existsSync(e)||mkdirSync(e,{recursive:true});}function ie(){return existsSync(Be)?JSON.parse(readFileSync(Be,"utf-8")):{active:"default",workspaces:[]}}function Fe(e){Ne(Ye),writeFileSync(Be,JSON.stringify(e,null,2));}var $={ensureInitialized(){let e=ie();e.workspaces.length===0&&(this.create("default",{workDir:join(homedir(),"leetcode"),lang:"typescript"}),e.workspaces=["default"],e.active="default",Fe(e));},getActive(){return this.ensureInitialized(),ie().active},setActive(e){let o=ie();return o.workspaces.includes(e)?(o.active=e,Fe(o),true):false},list(){return this.ensureInitialized(),ie().workspaces},exists(e){return this.ensureInitialized(),ie().workspaces.includes(e)},create(e,o){let t=ie();if(t.workspaces.includes(e))return false;let n=join(_e,e);Ne(n),Ne(join(n,"snapshots"));let s=join(n,"config.json");return writeFileSync(s,JSON.stringify(o,null,2)),writeFileSync(join(n,"timer.json"),JSON.stringify({solveTimes:{},activeTimer:null},null,2)),writeFileSync(join(n,"collab.json"),JSON.stringify({session:null},null,2)),t.workspaces.push(e),Fe(t),true},delete(e){if(e==="default")return false;let o=ie();return o.workspaces.includes(e)?(o.workspaces=o.workspaces.filter(t=>t!==e),o.active===e&&(o.active="default"),Fe(o),true):false},getWorkspaceDir(e){let o=e??this.getActive();return join(_e,o)},getConfig(e){let o=e??this.getActive(),t=join(_e,o,"config.json");return existsSync(t)?JSON.parse(readFileSync(t,"utf-8")):{workDir:join(homedir(),"leetcode"),lang:"typescript"}},setConfig(e,o){let t=o??this.getActive(),n=join(_e,t);Ne(n);let r={...this.getConfig(t),...e};writeFileSync(join(n,"config.json"),JSON.stringify(r,null,2));},getSnapshotsDir(){return join(this.getWorkspaceDir(),"snapshots")},getTimerPath(){return join(this.getWorkspaceDir(),"timer.json")},getCollabPath(){return join(this.getWorkspaceDir(),"collab.json")}};var w={getConfig(){let e=$.getConfig();return {language:e.lang,editor:e.editor,workDir:e.workDir,repo:e.syncRepo}},setLanguage(e){$.setConfig({lang:e});},setEditor(e){$.setConfig({editor:e});},setWorkDir(e){$.setConfig({workDir:e});},setRepo(e){$.setConfig({syncRepo:e});},deleteRepo(){let e=$.getConfig();delete e.syncRepo,$.setConfig(e);},getLanguage(){return $.getConfig().lang},getEditor(){return $.getConfig().editor},getWorkDir(){return $.getConfig().workDir},getRepo(){return $.getConfig().syncRepo},getPath(){return join($.getWorkspaceDir(),"config.json")},getActiveWorkspace(){return $.getActive()}};var ge={typescript:"ts",javascript:"js",python3:"py",java:"java",cpp:"cpp",c:"c",csharp:"cs",go:"go",rust:"rs",kotlin:"kt",swift:"swift"},Se={typescript:"typescript",javascript:"javascript",python3:"python3",python:"python3",java:"java","c++":"cpp",cpp:"cpp",c:"c","c#":"csharp",csharp:"csharp",go:"go",golang:"go",rust:"rust",kotlin:"kotlin",swift:"swift"};function Vo(e,o){let t=e.find(n=>Se[n.langSlug.toLowerCase()]===o);return t||(e[0]??null)}function zo(e,o,t,n,s,r,i){let a=Rn(r);return `${Fn(a,e,t,n,o,i)}
173
+ \u{1F4A1} Follow-up:`)),console.log(t),console.log();}function Mo(e,o){if(console.log(),e.compile_error){console.log(l.red.bold("\u274C Compile Error")),console.log(l.red(e.compile_error));return}if(e.runtime_error){console.log(l.red.bold("\u274C Runtime Error")),console.log(l.red(e.runtime_error));return}e.correct_answer?console.log(l.green.bold("\u2713 All test cases passed!")):console.log(l.yellow.bold("\u2717 Some test cases failed"));let t=e.code_answer??[],n=e.expected_code_answer??[];if(o&&t.length>0){console.log(),console.log(l.gray.bold("\u2500".repeat(50)));let r=t.map((i,a)=>({out:i,exp:n[a]??""})).filter(({out:i,exp:a})=>i!==""||a!=="");for(let i=0;i<r.length;i++){let{out:a,exp:c}=r[i],{outputVis:g,expectedVis:u,matches:p,unsupported:b}=Io(a,c,o);console.log(),console.log(l.gray(`Test Case ${i+1}:`)),b&&(console.log(l.yellow(" \u26A0 No visualization available for this problem type")),console.log(l.gray(` Tags: ${o.map(x=>x.name).join(", ")}`))),console.log(),console.log(l.cyan(" Your Output:")),g.split(`
174
+ `).forEach(x=>console.log(` ${x}`)),console.log(),console.log(l.cyan(" Expected:")),u.split(`
175
+ `).forEach(x=>console.log(` ${x}`)),console.log(),console.log(p?l.green(" \u2713 Match"):l.red(" \u2717 Mismatch"));}console.log(l.gray.bold("\u2500".repeat(50)));}else {console.log(),console.log(l.gray("Your Output:"));for(let r of t)console.log(l.white(` ${r}`));console.log(),console.log(l.gray("Expected Output:"));for(let r of n)console.log(l.white(` ${r}`));}let s=(e.std_output_list??[]).filter(r=>r);if(s.length>0){console.log(),console.log(l.gray("Stdout:"));for(let r of s)console.log(l.gray(` ${r}`));}}function qo(e){if(console.log(),e.compile_error){console.log(l.red.bold("\u274C Compile Error")),console.log(l.red(e.compile_error));return}if(e.runtime_error){console.log(l.red.bold("\u274C Runtime Error")),console.log(l.red(e.runtime_error)),e.last_testcase&&console.log(l.gray("Last testcase:"),e.last_testcase);return}e.status_msg==="Accepted"?(console.log(l.green.bold("\u2713 Accepted!")),console.log(),console.log(l.gray("Runtime:"),l.white(e.status_runtime),l.gray(`(beats ${e.runtime_percentile?.toFixed(1)??"N/A"}%)`)),console.log(l.gray("Memory:"),l.white(e.status_memory),l.gray(`(beats ${e.memory_percentile?.toFixed(1)??"N/A"}%)`))):(console.log(l.red.bold(`\u274C ${e.status_msg}`)),console.log(),console.log(l.gray(`Passed ${e.total_correct}/${e.total_testcases} testcases`)),e.code_output&&console.log(l.gray("Your Output:"),e.code_output),e.expected_output&&console.log(l.gray("Expected:"),e.expected_output),e.last_testcase&&console.log(l.gray("Failed testcase:"),e.last_testcase));}function Oo(e,o,t,n,s,r){console.log(),console.log(l.bold.white(`\u{1F464} ${e}`)+(o?l.gray(` (${o})`):"")),console.log(l.gray(`Ranking: #${t.toLocaleString()}`)),console.log();let i=new We({head:[l.cyan("Difficulty"),l.cyan("Solved")],style:{head:[],border:[]}});for(let c of n)c.difficulty!=="All"&&i.push([Ae(c.difficulty),c.count.toString()]);let a=n.find(c=>c.difficulty==="All")?.count??0;i.push([l.white.bold("Total"),l.white.bold(a.toString())]),console.log(i.toString()),console.log(),console.log(l.gray("\u{1F525} Current streak:"),l.hex("#FFA500")(s.toString()),l.gray("days")),console.log(l.gray("\u{1F4C5} Total active days:"),l.white(r.toString()));}function Ho(e,o){if(console.log(),console.log(l.bold.yellow("\u{1F3AF} Daily Challenge"),l.gray(`(${e})`)),console.log(),console.log(l.white(`${o.questionFrontendId}. ${o.title}`)),console.log(Ae(o.difficulty)),console.log(l.gray(`https://leetcode.com/problems/${o.titleSlug}/`)),o.topicTags.length){console.log();let t=o.topicTags.map(n=>l.blue(n.name)).join(" ");console.log(l.gray("Tags:"),t);}}function Ae(e){switch(e.toLowerCase()){case "easy":return l.green(e);case "medium":return l.yellow(e);case "hard":return l.red(e);default:return e}}function Ln(e){switch(e){case "ac":return l.green("\u2713");case "notac":return l.yellow("\u25CB");default:return l.gray("-")}}function Ve(e){let o=new We({head:[l.cyan("ID"),l.cyan("Status"),l.cyan("Lang"),l.cyan("Runtime"),l.cyan("Memory"),l.cyan("Date")],colWidths:[12,18,15,12,12,25],style:{head:[],border:[]}});for(let t of e){let n=t.statusDisplay==="Accepted",s=new Date(parseInt(t.timestamp)*1e3).toLocaleString();o.push([t.id,n?l.green(t.statusDisplay):l.red(t.statusDisplay),t.lang,t.runtime,t.memory,s]);}console.log(o.toString());}async function Wo(e){let{authorized:o}=await $();if(!o)return;let t=Ue("Fetching problems...").start();try{let n={},s=parseInt(e.limit??"20",10),r=parseInt(e.page??"1",10);if(n.limit=s,n.skip=(r-1)*s,e.difficulty){let c={easy:"EASY",e:"EASY",medium:"MEDIUM",m:"MEDIUM",hard:"HARD",h:"HARD"};n.difficulty=c[e.difficulty.toLowerCase()];}if(e.status){let c={todo:"NOT_STARTED",solved:"AC",ac:"AC",attempted:"TRIED",tried:"TRIED"};n.status=c[e.status.toLowerCase()];}e.tag?.length&&(n.tags=e.tag),e.search&&(n.searchKeywords=e.search);let{total:i,problems:a}=await h.getProblems(n);if(t.stop(),a.length===0){console.log(l.yellow("No problems found matching your criteria."));return}Uo(a,i),r*s<i&&console.log(l.gray(`
176
+ Page ${r} of ${Math.ceil(i/s)}. Use --page to navigate.`));}catch(n){t.fail("Failed to fetch problems"),n instanceof Error&&console.log(l.red(n.message));}}async function Re(e){let{authorized:o}=await $();if(!o)return;let t=Ue("Fetching problem...").start();try{let n;if(/^\d+$/.test(e)?n=await h.getProblemById(e):n=await h.getProblem(e),!n){t.fail(`Problem "${e}" not found`);return}t.stop(),jo(n);}catch(n){t.fail("Failed to fetch problem"),n instanceof Error&&console.log(l.red(n.message));}}async function Vo(e,o){let{authorized:t}=await $();if(!t)return;let n=Ue("Fetching problem hints...").start();try{let s;if(/^\d+$/.test(e)?s=await h.getProblemById(e):s=await h.getProblem(e),!s){n.fail(`Problem "${e}" not found`);return}n.stop(),console.log(),console.log(l.bold.cyan(`${s.questionFrontendId}. ${s.title}`)),console.log();let r=s.hints||[];if(r.length===0){console.log(l.yellow("\u26A0 No hints available for this problem.")),console.log(l.gray("Try working through the problem description and examples first!"));return}o.all?r.forEach((i,a)=>{zo(i,a+1,r.length);}):await Un(r);}catch(s){n.fail("Failed to fetch problem hints"),s instanceof Error&&console.log(l.red(s.message));}}function zo(e,o,t){let n=In(e);console.log(l.bold.yellow(`\u{1F4A1} Hint ${o}/${t}`)),console.log(l.white(n)),console.log();}function In(e){let o=e.replace(/<code>/g,l.cyan("`")).replace(/<\/code>/g,l.cyan("`")).replace(/<b>/g,l.bold("")).replace(/<\/b>/g,"").replace(/<i>/g,l.italic("")).replace(/<\/i>/g,"").replace(/<br\s*\/?>/g,`
177
+ `).replace(/<p>/g,"").replace(/<\/p>/g,`
178
+ `);return (En(o)??"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&nbsp;/g," ").replace(/&quot;/g,'"').replace(/&amp;/g,"&").trim()}async function Un(e){let t=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),n=s=>new Promise(r=>{if(s>=e.length){console.log(l.green("\u2713 All hints revealed! Good luck solving the problem!")),t.close(),r();return}zo(e[s],s+1,e.length),s<e.length-1?t.question(l.gray(`Press Enter for next hint (${e.length-s-1} remaining), or 'q' to quit: `),i=>{i.toLowerCase()==="q"?(console.log(l.gray(`
179
+ Good luck! You can always run this command again for more hints.`)),t.close(),r()):r(n(s+1));}):(console.log(l.green("\u2713 All hints revealed! Good luck solving the problem!")),t.close(),r());});await n(0);}var Qe=join(homedir(),".leetcode"),Ge=join(Qe,"workspaces.json"),Fe=join(Qe,"workspaces");function Ne(e){existsSync(e)||mkdirSync(e,{recursive:true});}function ae(){return existsSync(Ge)?JSON.parse(readFileSync(Ge,"utf-8")):{active:"default",workspaces:[]}}function _e(e){Ne(Qe),writeFileSync(Ge,JSON.stringify(e,null,2));}var k={ensureInitialized(){let e=ae();e.workspaces.length===0&&(this.create("default",{workDir:join(homedir(),"leetcode"),lang:"typescript"}),e.workspaces=["default"],e.active="default",_e(e));},getActive(){return this.ensureInitialized(),ae().active},setActive(e){let o=ae();return o.workspaces.includes(e)?(o.active=e,_e(o),true):false},list(){return this.ensureInitialized(),ae().workspaces},exists(e){return this.ensureInitialized(),ae().workspaces.includes(e)},create(e,o){let t=ae();if(t.workspaces.includes(e))return false;let n=join(Fe,e);Ne(n),Ne(join(n,"snapshots"));let s=join(n,"config.json");return writeFileSync(s,JSON.stringify(o,null,2)),writeFileSync(join(n,"timer.json"),JSON.stringify({solveTimes:{},activeTimer:null},null,2)),writeFileSync(join(n,"collab.json"),JSON.stringify({session:null},null,2)),t.workspaces.push(e),_e(t),true},delete(e){if(e==="default")return false;let o=ae();return o.workspaces.includes(e)?(o.workspaces=o.workspaces.filter(t=>t!==e),o.active===e&&(o.active="default"),_e(o),true):false},getWorkspaceDir(e){let o=e??this.getActive();return join(Fe,o)},getConfig(e){let o=e??this.getActive(),t=join(Fe,o,"config.json");return existsSync(t)?JSON.parse(readFileSync(t,"utf-8")):{workDir:join(homedir(),"leetcode"),lang:"typescript"}},setConfig(e,o){let t=o??this.getActive(),n=join(Fe,t);Ne(n);let r={...this.getConfig(t),...e};writeFileSync(join(n,"config.json"),JSON.stringify(r,null,2));},getSnapshotsDir(){return join(this.getWorkspaceDir(),"snapshots")},getTimerPath(){return join(this.getWorkspaceDir(),"timer.json")},getCollabPath(){return join(this.getWorkspaceDir(),"collab.json")}};var w={getConfig(){let e=k.getConfig();return {language:e.lang,editor:e.editor,workDir:e.workDir,repo:e.syncRepo}},setLanguage(e){k.setConfig({lang:e});},setEditor(e){k.setConfig({editor:e});},setWorkDir(e){k.setConfig({workDir:e});},setRepo(e){k.setConfig({syncRepo:e});},deleteRepo(){let e=k.getConfig();delete e.syncRepo,k.setConfig(e);},getLanguage(){return k.getConfig().lang},getEditor(){return k.getConfig().editor},getWorkDir(){return k.getConfig().workDir},getRepo(){return k.getConfig().syncRepo},getPath(){return join(k.getWorkspaceDir(),"config.json")},getActiveWorkspace(){return k.getActive()}};var me={typescript:"ts",javascript:"js",python3:"py",java:"java",cpp:"cpp",c:"c",csharp:"cs",go:"go",rust:"rs",kotlin:"kt",swift:"swift"},$e={typescript:"typescript",javascript:"javascript",python3:"python3",python:"python3",java:"java","c++":"cpp",cpp:"cpp",c:"c","c#":"csharp",csharp:"csharp",go:"go",golang:"go",rust:"rust",kotlin:"kotlin",swift:"swift"};function Go(e,o){let t=e.find(n=>$e[n.langSlug.toLowerCase()]===o);return t||(e[0]??null)}function Yo(e,o,t,n,s,r,i){let a=On(r);return `${Wn(a,e,t,n,o,i)}
177
180
 
178
181
  ${s}
179
- `}function Rn(e){return e==="python3"?{single:"#",blockStart:'"""',blockEnd:'"""',linePrefix:""}:{single:"//",blockStart:"/*",blockEnd:"*/",linePrefix:" * "}}function _n(e){let o=e;return o=o.replace(/<sup>(.*?)<\/sup>/gi,"^$1"),o=o.replace(/<strong class="example">Example (\d+):<\/strong>/gi,`
182
+ `}function On(e){return e==="python3"?{single:"#",blockStart:'"""',blockEnd:'"""',linePrefix:""}:{single:"//",blockStart:"/*",blockEnd:"*/",linePrefix:" * "}}function Hn(e){let o=e;return o=o.replace(/<sup>(.*?)<\/sup>/gi,"^$1"),o=o.replace(/<strong class="example">Example (\d+):<\/strong>/gi,`
180
183
  Example $1:`),o=o.replace(/<li>/gi,"\u2022 "),o=o.replace(/<\/li>/gi,`
181
184
  `),o=o.replace(/<\/p>/gi,`
182
185
 
183
186
  `),o=o.replace(/<br\s*\/?>/gi,`
184
- `),o=o.replace(/<[^>]+>/g,""),o=o.replace(/&nbsp;/g," ").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&le;/g,"<=").replace(/&ge;/g,">=").replace(/&#(\d+);/g,(t,n)=>String.fromCharCode(parseInt(n,10))),o=o.replace(/\n{3,}/g,`
187
+ `),o=En(o)??"",o=o.replace(/&nbsp;/g," ").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&le;/g,"<=").replace(/&ge;/g,">=").replace(/&#(\d+);/g,(t,n)=>String.fromCharCode(parseInt(n,10))).replace(/&amp;/g,"&"),o=o.replace(/\n{3,}/g,`
185
188
 
186
- `).trim(),o}function Fn(e,o,t,n,s,r){let i=e.linePrefix,a=[e.blockStart,`${i}${o}. ${t}`,`${i}Difficulty: ${n}`,`${i}https://leetcode.com/problems/${s}/`];if(r){a.push(`${i}`),a.push(`${i}${"\u2500".repeat(50)}`),a.push(`${i}`);let g=_n(r).split(`
187
- `);for(let u of g)if(u.length>70){let p=u.split(" "),b="";for(let C of p)(b+" "+C).length>70?(a.push(`${i}${b.trim()}`),b=C):b+=" "+C;b.trim()&&a.push(`${i}${b.trim()}`);}else a.push(`${i}${u}`);}return a.push(e.blockEnd),a.join(`
188
- `)}function Bo(e,o,t){let n=ge[t];return `${e}.${o}.${n}`}var jn=["vim","nvim","vi","nano","emacs","micro","helix"],Mn=["code","code-insiders","cursor","codium","vscodium"];async function $e(e,o){let t=w.getEditor()??process.env.EDITOR??"code",n=w.getWorkDir();if(jn.includes(t)){console.log(),console.log(l.gray(`Open with: ${t} ${e}`));return}try{if(Mn.includes(t)){spawn(t,["-r",n,"-g",e],{detached:!0,stdio:"ignore"}).unref();return}await In(e,{app:{name:t}});}catch{}}async function Y(e,o){let{authorized:t}=await v();if(!t)return false;let n=Ue({text:"Fetching problem details...",spinner:"dots"}).start();try{let s;if(/^\d+$/.test(e)?s=await h.getProblemById(e):s=await h.getProblem(e),!s)return n.fail(`Problem "${e}" not found`),!1;n.text="Generating solution file...";let r=o.lang?.toLowerCase()??w.getLanguage(),i=Se[r]??r,a=s.codeSnippets??[],c=Vo(a,i),g;if(a.length===0)n.warn(l.yellow("Premium Problem (No code snippets available)")),console.log(l.gray("Generating placeholder file with problem info...")),g=`// \u{1F512} Premium Problem - ${s.title}
189
- // Solution stub not available - visit LeetCode to view`;else if(c)g=c.code;else return n.fail(`No code template available for ${i}`),console.log(l.gray(`Available languages: ${a.map(Z=>Z.langSlug).join(", ")}`)),!1;let u=zo(s.questionFrontendId,s.titleSlug,s.title,s.difficulty,g,i,s.content??void 0),p=w.getWorkDir(),b=s.difficulty,C=s.topicTags.length>0?s.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",I=join(p,b,C);existsSync(I)||await mkdir(I,{recursive:!0});let R=Bo(s.questionFrontendId,s.titleSlug,i),q=join(I,R);return existsSync(q)?(n.warn(`File already exists: ${R}`),console.log(l.gray(`Path: ${q}`)),o.open!==!1&&await $e(q),!0):(await writeFile(q,u,"utf-8"),n.succeed(`Created ${l.green(R)}`),console.log(l.gray(`Path: ${q}`)),console.log(),console.log(l.cyan(`${s.questionFrontendId}. ${s.title}`)),console.log(l.gray(`Difficulty: ${s.difficulty} | Category: ${C}`)),o.open!==!1&&await $e(q),!0)}catch(s){if(n.fail("Failed to fetch problem"),s instanceof Error)if(s.message.includes("expected object, received null"))console.log(l.red(`Problem "${e}" not found`));else try{let r=JSON.parse(s.message);Array.isArray(r)?console.log(l.red("API Response Validation Failed")):console.log(l.red(s.message));}catch{console.log(l.red(s.message));}return false}}async function Qo(e,o){if(e.length===0){console.log(l.yellow("Please provide at least one problem ID"));return}let{authorized:t}=await v();if(!t)return;console.log(l.cyan(`\u{1F4E6} Picking ${e.length} problem${e.length!==1?"s":""}...`)),console.log(),console.log();let n=0,s=0;for(let r of e)await Y(r,{...o,open:false})?n++:s++,console.log();console.log(l.gray("\u2500".repeat(50))),console.log(l.bold(`Done! ${l.green(`${n} succeeded`)}${s>0?`, ${l.red(`${s} failed`)}`:""}`));}var Zo=5;async function O(e,o,t=0){if(!existsSync(e)||t>=Zo)return null;let n=await readdir(e,{withFileTypes:true});for(let s of n){if(s.name.startsWith("."))continue;let r=join(e,s.name);if(s.isDirectory()){let i=await O(r,o,t+1);if(i)return i}else if(s.name.startsWith(`${o}.`)){let i=s.name.split(".").pop()?.toLowerCase();if(i&&i in Hn)return r}}return null}async function ke(e,o,t=0){if(!existsSync(e)||t>=Zo)return null;let n=await readdir(e,{withFileTypes:true});for(let s of n){let r=join(e,s.name);if(s.isDirectory()){let i=await ke(r,o,t+1);if(i)return i}else if(s.name===o)return r}return null}var Hn={ts:"typescript",js:"javascript",py:"python3",java:"java",cpp:"cpp",c:"c",cs:"csharp",go:"go",rs:"rust",kt:"kotlin",swift:"swift"};function ae(e){return {ts:"typescript",js:"javascript",py:"python3",java:"java",cpp:"cpp",c:"c",cs:"csharp",go:"golang",rs:"rust",kt:"kotlin",swift:"swift"}[e.toLowerCase()]??null}function oe(e){return /^\d+$/.test(e)}function Ie(e){return !e.includes("/")&&!e.includes("\\")&&e.includes(".")}function me(e,o){let t=resolve(e),n=resolve(o),s=n.endsWith(sep)?n:n+sep;return t===n||t.startsWith(s)}async function tt(e,o){let{authorized:t}=await v();if(!t)return;let n=e,s=w.getWorkDir();if(oe(e)){let i=await O(s,e);if(!i){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.gray(`Looking in: ${s}`)),console.log(l.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}n=i,console.log(l.gray(`Found: ${n}`));}else if(Ie(e)){let i=await ke(s,e);if(!i){console.log(l.red(`File not found: ${e}`)),console.log(l.gray(`Looking in: ${s}`));return}n=i,console.log(l.gray(`Found: ${n}`));}if(!existsSync(n)){console.log(l.red(`File not found: ${n}`));return}if(!me(n,s)){console.log(l.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(l.gray(`File: ${n}`)),console.log(l.gray(`Workspace: ${s}`)),console.log(l.yellow(`
190
- For security reasons, you can only test files from within your workspace.`)),console.log(l.gray('Use "leetcode config workdir <path>" to change your workspace.'));return}let r=Ue({text:"Reading solution file...",spinner:"dots"}).start();try{let i=basename(n),a=i.match(/^(\d+)\.([^.]+)\./);if(!a){r.fail("Invalid filename format"),console.log(l.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(l.gray("Example: 1.two-sum.ts"));return}let[,c,g]=a,u=i.split(".").pop(),p=ae(u);if(!p){r.fail(`Unsupported file extension: .${u}`);return}let b=await readFile(n,"utf-8");r.text="Fetching problem details...";let C=await h.getProblem(g),I=o.testcase??C.exampleTestcases??C.sampleTestCase;r.text="Running tests...";let R=await h.testSolution(g,b,p,I,C.questionId);r.stop(),jo(R,o.visualize?C.topicTags:void 0);}catch(i){r.fail("Test failed"),i instanceof Error&&console.log(l.red(i.message));}}function st(){return $.getTimerPath()}function le(){let e=st();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{solveTimes:{},activeTimer:null}}function Qe(e){let o=st(),t=dirname(o);existsSync(t)||mkdirSync(t,{recursive:true}),writeFileSync(o,JSON.stringify(e,null,2));}var B={startTimer(e,o,t,n){let s=le();s.activeTimer={problemId:e,title:o,difficulty:t,startedAt:new Date().toISOString(),durationMinutes:n},Qe(s);},getActiveTimer(){return le().activeTimer},stopTimer(){let e=le(),o=e.activeTimer;if(!o)return null;let t=new Date(o.startedAt),s=Math.floor((new Date().getTime()-t.getTime())/1e3);return e.activeTimer=null,Qe(e),{durationSeconds:s}},recordSolveTime(e,o,t,n,s){let r=le();r.solveTimes[e]||(r.solveTimes[e]=[]),r.solveTimes[e].push({problemId:e,title:o,difficulty:t,solvedAt:new Date().toISOString(),durationSeconds:n,timerMinutes:s}),Qe(r);},getSolveTimes(e){return le().solveTimes[e]??[]},getAllSolveTimes(){return le().solveTimes??{}},getStats(){let e=le().solveTimes??{},o=0,t=0;for(let n of Object.values(e)){o+=n.length;for(let s of n)t+=s.durationSeconds;}return {totalProblems:o,totalTime:t,avgTime:o>0?Math.floor(t/o):0}}};async function rt(e){let{authorized:o}=await v();if(!o)return;let t=e,n=w.getWorkDir();if(oe(e)){let r=await O(n,e);if(!r){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.gray(`Looking in: ${n}`)),console.log(l.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}t=r,console.log(l.gray(`Found: ${t}`));}else if(Ie(e)){let r=await ke(n,e);if(!r){console.log(l.red(`File not found: ${e}`)),console.log(l.gray(`Looking in: ${n}`));return}t=r,console.log(l.gray(`Found: ${t}`));}if(!existsSync(t)){console.log(l.red(`File not found: ${t}`));return}if(!me(t,n)){console.log(l.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(l.gray(`File: ${t}`)),console.log(l.gray(`Workspace: ${n}`)),console.log(l.yellow(`
191
- For security reasons, you can only submit files from within your workspace.`)),console.log(l.gray('Use "leetcode config workdir <path>" to change your workspace.'));return}let s=Ue({text:"Reading solution file...",spinner:"dots"}).start();try{let r=basename(t),i=r.match(/^(\d+)\.([^.]+)\./);if(!i){s.fail("Invalid filename format"),console.log(l.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(l.gray("Example: 1.two-sum.ts"));return}let[,a,c]=i,g=r.split(".").pop(),u=ae(g);if(!u){s.fail(`Unsupported file extension: .${g}`);return}let p=await readFile(t,"utf-8");s.text="Fetching problem details...";let b=await h.getProblem(c);s.text="Submitting solution...";let C=await h.submitSolution(c,p,u,b.questionId);if(s.stop(),Mo(C),C.status_msg==="Accepted"){let I=B.getActiveTimer();if(I&&I.problemId===a){let R=B.stopTimer();if(R){B.recordSolveTime(a,b.title,b.difficulty,R.durationSeconds,I.durationMinutes);let q=Math.floor(R.durationSeconds/60),Z=R.durationSeconds%60,re=`${q}m ${Z}s`,H=R.durationSeconds<=I.durationMinutes*60;console.log(),console.log(l.bold("\u23F1\uFE0F Timer Result:")),console.log(` Solved in ${H?l.green(re):l.yellow(re)} (limit: ${I.durationMinutes}m)`),console.log(H?l.green(" \u2713 Within time limit!"):l.yellow(" \u26A0 Exceeded time limit"));}}}}catch(r){s.fail("Submission failed"),r instanceof Error&&console.log(l.red(r.message));}}var it=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function at(e){let o=JSON.parse(e),t=new Date,n=[];for(let i=11;i>=0;i--){let a=new Date(t);a.setDate(a.getDate()-i*7-a.getDay());let c=0,g=0;for(let p=0;p<7;p++){let b=new Date(a);if(b.setDate(b.getDate()+p),b>t)break;let C=new Date(Date.UTC(b.getFullYear(),b.getMonth(),b.getDate())),I=Math.floor(C.getTime()/1e3).toString(),R=o[I]||0;c+=R,R>0&&g++;}let u=new Date(a);u.setDate(u.getDate()+6),n.push({start:`${it[a.getMonth()]} ${a.getDate()}`,end:`${it[u.getMonth()]} ${u.getDate()}`,count:c,days:g});}let s=n.reduce((i,a)=>i+a.count,0),r=n.reduce((i,a)=>i+a.days,0);console.log(),console.log(l.bold("\u{1F4C5} Activity (Last 12 Weeks)")),console.log(l.gray("How many problems you submitted and days you practiced.")),console.log(l.gray("\u2500".repeat(50))),console.log();for(let i of n){let a=`${i.start} - ${i.end}`.padEnd(18),c=i.count>0?l.green("\u2588".repeat(Math.min(i.count,10))).padEnd(10):l.gray("\xB7").padEnd(10),g=i.count>0?`${i.count} subs`.padEnd(10):"".padEnd(10),u=i.days>0?`${i.days}d active`:"";console.log(` ${l.white(a)} ${c} ${l.cyan(g)} ${l.yellow(u)}`);}console.log(l.gray("\u2500".repeat(50))),console.log(` ${l.bold.white("Total:")} ${l.cyan.bold(s+" submissions")}, ${l.yellow.bold(r+" days active")}`),console.log();}function lt(e,o,t){console.log(),console.log(l.bold("\u{1F3AF} Skill Breakdown")),console.log(l.gray("\u2500".repeat(45)));let n=(s,r,i)=>{if(r.length===0)return;console.log(),console.log(i.bold(` ${s}`));let a=[...r].sort((c,g)=>g.problemsSolved-c.problemsSolved);for(let c of a.slice(0,8)){let g=c.tagName.padEnd(22),u=i("\u2588".repeat(Math.min(c.problemsSolved,15)));console.log(` ${l.white(g)} ${u} ${l.white(c.problemsSolved)}`);}};n("Fundamental",e,l.green),n("Intermediate",o,l.yellow),n("Advanced",t,l.red),console.log();}function ct(e){let o=JSON.parse(e),t=new Date,n=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=[];for(let c=6;c>=0;c--){let g=new Date(t);g.setDate(g.getDate()-c);let u=new Date(Date.UTC(g.getFullYear(),g.getMonth(),g.getDate())),p=Math.floor(u.getTime()/1e3).toString();s.push({label:n[g.getDay()],count:o[p]||0});}let r=Math.max(...s.map(c=>c.count),1),i=6;console.log(),console.log(l.bold("\u{1F4C8} Submission Trend (Last 7 Days)")),console.log(l.gray("\u2500".repeat(35))),console.log();for(let c=i;c>=1;c--){let g=` ${c===i?r.toString().padStart(2):" "} \u2502`;for(let u of s)Math.round(u.count/r*i)>=c?g+=l.green(" \u2588\u2588 "):g+=" ";console.log(g);}console.log(` 0 \u2514${"\u2500\u2500\u2500\u2500".repeat(7)}`),console.log(` ${s.map(c=>c.label.padEnd(4)).join("")}`),console.log(l.gray(` ${s.map(c=>c.count.toString().padEnd(4)).join("")}`));let a=s.reduce((c,g)=>c+g.count,0);console.log(),console.log(l.white(` Total: ${a} submissions this week`)),console.log();}async function gt(e,o={}){let{authorized:t,username:n}=await v();if(!t)return;let s=Ue("Fetching statistics...").start();try{let r=e||n;if(!r){s.fail("No username found");return}let i=await h.getUserProfile(r);if(s.stop(),!o.calendar&&!o.skills&&!o.trend){qo(i.username,i.realName,i.ranking,i.acSubmissionNum,i.streak,i.totalActiveDays);return}if(o.calendar&&(i.submissionCalendar?at(i.submissionCalendar):console.log(l.yellow("Calendar data not available."))),o.trend&&(i.submissionCalendar?ct(i.submissionCalendar):console.log(l.yellow("Calendar data not available."))),o.skills){s.start("Fetching skill stats...");let a=await h.getSkillStats(r);s.stop(),lt(a.fundamental,a.intermediate,a.advanced);}}catch(r){s.fail("Failed to fetch statistics"),r instanceof Error&&console.log(l.red(r.message));}}async function mt(){let{authorized:e}=await v();if(!e)return;let o=Ue("Fetching daily challenge...").start();try{let t=await h.getDailyChallenge();o.stop(),Oo(t.date,t.question),console.log(),console.log(l.gray("Run the following to start working on this problem:")),console.log(l.cyan(` leetcode pick ${t.question.titleSlug}`));}catch(t){o.fail("Failed to fetch daily challenge"),t instanceof Error&&console.log(l.red(t.message));}}async function dt(e){let{authorized:o}=await v();if(!o)return;let t=Ue("Fetching random problem...").start();try{let n={};if(e.difficulty){let i={easy:"EASY",e:"EASY",medium:"MEDIUM",m:"MEDIUM",hard:"HARD",h:"HARD"}[e.difficulty.toLowerCase()];if(i)n.difficulty=i;else {t.fail(`Invalid difficulty: ${e.difficulty}`);return}}e.tag&&(n.tags=[e.tag]);let s=await h.getRandomProblem(n);t.succeed("Found random problem!"),console.log(),e.pick?await Y(s,{open:e.open??!0}):(await Re(s),console.log(l.gray("Run following to start solving:")),console.log(l.cyan(` leetcode pick ${s}`)));}catch(n){t.fail("Failed to fetch random problem"),n instanceof Error&&console.log(l.red(n.message));}}async function ft(e,o){let{authorized:t}=await v();if(!t)return;let n=Ue("Fetching problem info...").start();try{let s;if(/^\d+$/.test(e)?s=await h.getProblemById(e):s=await h.getProblem(e),!s){n.fail(`Problem "${e}" not found`);return}let r=s.titleSlug;n.text="Fetching submissions...";let i=o.limit?parseInt(o.limit,10):20,a=await h.getSubmissionList(r,i);if(n.stop(),a.length===0){console.log(l.yellow("No submissions found."));return}if(o.last){let c=a.find(g=>g.statusDisplay==="Accepted");c?(console.log(l.bold("Last Accepted Submission:")),He([c])):console.log(l.yellow("No accepted submissions found in recent history."));}else He(a);if(o.download){let c=Ue("Downloading submission...").start(),g=a.find(fn=>fn.statusDisplay==="Accepted");if(!g){c.fail("No accepted submission found to download.");return}let u=parseInt(g.id,10);if(isNaN(u)){c.fail("Invalid submission ID format");return}let p=await h.getSubmissionDetails(u),b=w.getWorkDir(),C=s.difficulty,I=s.topicTags.length>0?s.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",R=join(b,C,I);existsSync(R)||await mkdir(R,{recursive:!0});let q=p.lang.name,Z=Se[q]??"txt",re=ge[Z]??q,H=`${s.questionFrontendId}.${s.titleSlug}.submission-${g.id}.${re}`,ao=join(R,H);await writeFile(ao,p.code,"utf-8"),c.succeed(`Downloaded to ${l.green(H)}`),console.log(l.gray(`Path: ${ao}`));}}catch(s){n.fail("Failed to fetch submissions"),s instanceof Error&&console.log(l.red(s.message));}}var Ze=["typescript","javascript","python3","java","cpp","c","csharp","go","rust","kotlin","swift"];async function yt(e){if(!e.lang&&!e.editor&&!e.workdir){bt();return}if(e.lang){let o=e.lang.toLowerCase();if(!Ze.includes(o)){console.log(l.red(`Unsupported language: ${e.lang}`)),console.log(l.gray(`Supported: ${Ze.join(", ")}`));return}let t=o;w.setLanguage(t),console.log(l.green(`\u2713 Default language set to ${t}`));}e.editor&&(w.setEditor(e.editor),console.log(l.green(`\u2713 Editor set to ${e.editor}`))),e.workdir&&(w.setWorkDir(e.workdir),console.log(l.green(`\u2713 Work directory set to ${e.workdir}`))),e.repo!==void 0&&(e.repo.trim()===""?(w.deleteRepo(),console.log(l.green("\u2713 Repository URL cleared"))):(w.setRepo(e.repo),console.log(l.green(`\u2713 Repository URL set to ${e.repo}`))));}async function ht(){let e=w.getConfig(),o=w.getActiveWorkspace();console.log(),console.log(l.bold.cyan(`\u{1F4C1} Configuring workspace: ${o}`)),console.log(l.gray("\u2500".repeat(40)));let t=await oo.prompt([{type:"list",name:"language",message:"Default programming language:",choices:Ze,default:e.language},{type:"input",name:"editor",message:"Editor command (e.g., code, vim, nvim):",default:e.editor??"code"},{type:"input",name:"workDir",message:"Working directory for solution files:",default:e.workDir},{type:"input",name:"repo",message:"Git repository URL (optional):",default:e.repo}]);w.setLanguage(t.language),w.setEditor(t.editor),w.setWorkDir(t.workDir),t.repo?w.setRepo(t.repo):w.deleteRepo(),console.log(),console.log(l.green("\u2713 Configuration saved")),bt();}function bt(){let e=w.getConfig(),o=K.get(),t=w.getActiveWorkspace();console.log(),console.log(l.bold.cyan(`\u{1F4C1} Workspace: ${t}`)),console.log(l.gray("\u2500".repeat(40))),console.log(),console.log(l.gray("Config file:"),w.getPath()),console.log(),console.log(l.gray("Language: "),l.white(e.language)),console.log(l.gray("Editor: "),l.white(e.editor??"(not set)")),console.log(l.gray("Work Dir: "),l.white(e.workDir)),console.log(l.gray("Repo URL: "),l.white(e.repo??"(not set)")),console.log(l.gray("Logged in: "),o?l.green("Yes"):l.yellow("No"));}var te=new Sn({projectName:"leetcode-cli-bookmarks",defaults:{bookmarks:[]}}),ue={add(e){let o=te.get("bookmarks");return o.includes(e)?false:(te.set("bookmarks",[...o,e]),true)},remove(e){let o=te.get("bookmarks");return o.includes(e)?(te.set("bookmarks",o.filter(t=>t!==e)),true):false},list(){return te.get("bookmarks")},has(e){return te.get("bookmarks").includes(e)},count(){return te.get("bookmarks").length},clear(){te.set("bookmarks",[]);}};async function wt(e,o){if(!["add","remove","list","clear"].includes(e)){console.log(l.red(`Invalid action: ${e}`)),console.log(l.gray("Valid actions: add, remove, list, clear"));return}switch(e){case "add":if(!o){console.log(l.red("Please provide a problem ID to bookmark"));return}if(!oe(o)){console.log(l.red(`Invalid problem ID: ${o}`)),console.log(l.gray("Problem ID must be a positive integer"));return}ue.add(o)?console.log(l.green(`\u2713 Bookmarked problem ${o}`)):console.log(l.yellow(`Problem ${o} is already bookmarked`));break;case "remove":if(!o){console.log(l.red("Please provide a problem ID to remove"));return}ue.remove(o)?console.log(l.green(`\u2713 Removed bookmark for problem ${o}`)):console.log(l.yellow(`Problem ${o} is not bookmarked`));break;case "list":await ds();break;case "clear":let n=ue.count();n===0?console.log(l.yellow("No bookmarks to clear")):(ue.clear(),console.log(l.green(`\u2713 Cleared ${n} bookmark${n!==1?"s":""}`)));break}}async function ds(){let e=ue.list();if(e.length===0){console.log(l.yellow("\u{1F4CC} No bookmarked problems")),console.log(l.gray('Use "leetcode bookmark add <id>" to bookmark a problem'));return}console.log(),console.log(l.bold.cyan(`\u{1F4CC} Bookmarked Problems (${e.length})`)),console.log();let{authorized:o}=await v();if(o){let t=Ue({text:"Fetching problem details...",spinner:"dots"}).start();try{let n=new We({head:[l.cyan("ID"),l.cyan("Title"),l.cyan("Difficulty"),l.cyan("Status")],colWidths:[8,45,12,10],style:{head:[],border:[]}});for(let s of e)try{let r=await h.getProblemById(s);r?n.push([r.questionFrontendId,r.title.length>42?r.title.slice(0,39)+"...":r.title,us(r.difficulty),r.status==="ac"?l.green("\u2713"):l.gray("-")]):n.push([s,l.gray("(not found)"),"-","-"]);}catch{n.push([s,l.gray("(error fetching)"),"-","-"]);}t.stop(),console.log(n.toString());}catch{t.stop(),console.log(l.gray("IDs: ")+e.join(", "));}}else console.log(l.gray("IDs: ")+e.join(", ")),console.log(),console.log(l.gray("Login to see problem details"));}function us(e){switch(e.toLowerCase()){case "easy":return l.green(e);case "medium":return l.yellow(e);case "hard":return l.red(e);default:return e}}async function $t(e,o){if(!oe(e)){console.log(l.red(`Invalid problem ID: ${e}`)),console.log(l.gray("Problem ID must be a positive integer"));return}let t=o==="view"?"view":"edit",n=join(w.getWorkDir(),".notes"),s=join(n,`${e}.md`);existsSync(n)||await mkdir(n,{recursive:true}),t==="view"?await hs(s,e):await bs(s,e);}async function hs(e,o){if(!existsSync(e)){console.log(l.yellow(`No notes found for problem ${o}`)),console.log(l.gray(`Use "leetcode note ${o} edit" to create notes`));return}try{let t=await readFile(e,"utf-8");console.log(),console.log(l.bold.cyan(`\u{1F4DD} Notes for Problem ${o}`)),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(t);}catch(t){console.log(l.red("Failed to read notes")),t instanceof Error&&console.log(l.gray(t.message));}}async function bs(e,o){if(!existsSync(e)){let t=await ws(o);await writeFile(e,t,"utf-8"),console.log(l.green(`\u2713 Created notes file for problem ${o}`));}console.log(l.gray(`Opening: ${e}`)),await $e(e);}async function ws(e){let o=`# Problem ${e} Notes
189
+ `).trim(),o}function Wn(e,o,t,n,s,r){let i=e.linePrefix,a=[e.blockStart,`${i}${o}. ${t}`,`${i}Difficulty: ${n}`,`${i}https://leetcode.com/problems/${s}/`];if(r){a.push(`${i}`),a.push(`${i}${"\u2500".repeat(50)}`),a.push(`${i}`);let g=Hn(r).split(`
190
+ `);for(let u of g)if(u.length>70){let p=u.split(" "),b="";for(let x of p)(b+" "+x).length>70?(a.push(`${i}${b.trim()}`),b=x):b+=" "+x;b.trim()&&a.push(`${i}${b.trim()}`);}else a.push(`${i}${u}`);}return a.push(e.blockEnd),a.join(`
191
+ `)}function Qo(e,o,t){let n=me[t];return `${e}.${o}.${n}`}var Gn=["vim","nvim","vi","nano","emacs","micro","helix"],Yn=["code","code-insiders","cursor","codium","vscodium"];async function ke(e,o){let t=w.getEditor()??process.env.EDITOR??"code",n=w.getWorkDir();if(Gn.includes(t)){console.log(),console.log(l.gray(`Open with: ${t} ${e}`));return}try{if(Yn.includes(t)){spawn(t,["-r",n,"-g",e],{detached:!0,stdio:"ignore"}).unref();return}await zn(e,{app:{name:t}});}catch{}}async function Q(e,o){let{authorized:t}=await $();if(!t)return false;let n=Ue({text:"Fetching problem details...",spinner:"dots"}).start();try{let s;if(/^\d+$/.test(e)?s=await h.getProblemById(e):s=await h.getProblem(e),!s)return n.fail(`Problem "${e}" not found`),!1;n.text="Generating solution file...";let r=o.lang?.toLowerCase()??w.getLanguage(),i=$e[r]??r,a=s.codeSnippets??[],c=Go(a,i),g;if(a.length===0)n.warn(l.yellow("Premium Problem (No code snippets available)")),console.log(l.gray("Generating placeholder file with problem info...")),g=`// \u{1F512} Premium Problem - ${s.title}
192
+ // Solution stub not available - visit LeetCode to view`;else if(c)g=c.code;else return n.fail(`No code template available for ${i}`),console.log(l.gray(`Available languages: ${a.map(ee=>ee.langSlug).join(", ")}`)),!1;let u=Yo(s.questionFrontendId,s.titleSlug,s.title,s.difficulty,g,i,s.content??void 0),p=w.getWorkDir(),b=s.difficulty,x=s.topicTags.length>0?s.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",I=join(p,b,x);existsSync(I)||await mkdir(I,{recursive:!0});let F=Qo(s.questionFrontendId,s.titleSlug,i),q=join(I,F);return existsSync(q)?(n.warn(`File already exists: ${F}`),console.log(l.gray(`Path: ${q}`)),o.open!==!1&&await ke(q),!0):(await writeFile(q,u,"utf-8"),n.succeed(`Created ${l.green(F)}`),console.log(l.gray(`Path: ${q}`)),console.log(),console.log(l.cyan(`${s.questionFrontendId}. ${s.title}`)),console.log(l.gray(`Difficulty: ${s.difficulty} | Category: ${x}`)),o.open!==!1&&await ke(q),!0)}catch(s){if(n.fail("Failed to fetch problem"),s instanceof Error)if(s.message.includes("expected object, received null"))console.log(l.red(`Problem "${e}" not found`));else try{let r=JSON.parse(s.message);Array.isArray(r)?console.log(l.red("API Response Validation Failed")):console.log(l.red(s.message));}catch{console.log(l.red(s.message));}return false}}async function Xo(e,o){if(e.length===0){console.log(l.yellow("Please provide at least one problem ID"));return}let{authorized:t}=await $();if(!t)return;console.log(l.cyan(`\u{1F4E6} Picking ${e.length} problem${e.length!==1?"s":""}...`)),console.log(),console.log();let n=0,s=0;for(let r of e)await Q(r,{...o,open:false})?n++:s++,console.log();console.log(l.gray("\u2500".repeat(50))),console.log(l.bold(`Done! ${l.green(`${n} succeeded`)}${s>0?`, ${l.red(`${s} failed`)}`:""}`));}var tt=5;async function H(e,o,t=0){if(!existsSync(e)||t>=tt)return null;let n=await readdir(e,{withFileTypes:true});for(let s of n){if(s.name.startsWith("."))continue;let r=join(e,s.name);if(s.isDirectory()){let i=await H(r,o,t+1);if(i)return i}else if(s.name.startsWith(`${o}.`)){let i=s.name.split(".").pop()?.toLowerCase();if(i&&i in Xn)return r}}return null}async function ve(e,o,t=0){if(!existsSync(e)||t>=tt)return null;let n=await readdir(e,{withFileTypes:true});for(let s of n){let r=join(e,s.name);if(s.isDirectory()){let i=await ve(r,o,t+1);if(i)return i}else if(s.name===o)return r}return null}var Xn={ts:"typescript",js:"javascript",py:"python3",java:"java",cpp:"cpp",c:"c",cs:"csharp",go:"go",rs:"rust",kt:"kotlin",swift:"swift"};function le(e){return {ts:"typescript",js:"javascript",py:"python3",java:"java",cpp:"cpp",c:"c",cs:"csharp",go:"golang",rs:"rust",kt:"kotlin",swift:"swift"}[e.toLowerCase()]??null}function te(e){return /^\d+$/.test(e)}function Ie(e){return !e.includes("/")&&!e.includes("\\")&&e.includes(".")}function de(e,o){let t=resolve(e),n=resolve(o),s=n.endsWith(sep)?n:n+sep;return t===n||t.startsWith(s)}async function rt(e,o){let{authorized:t}=await $();if(!t)return;let n=e,s=w.getWorkDir();if(te(e)){let i=await H(s,e);if(!i){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.gray(`Looking in: ${s}`)),console.log(l.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}n=i,console.log(l.gray(`Found: ${n}`));}else if(Ie(e)){let i=await ve(s,e);if(!i){console.log(l.red(`File not found: ${e}`)),console.log(l.gray(`Looking in: ${s}`));return}n=i,console.log(l.gray(`Found: ${n}`));}if(!existsSync(n)){console.log(l.red(`File not found: ${n}`));return}if(!de(n,s)){console.log(l.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(l.gray(`File: ${n}`)),console.log(l.gray(`Workspace: ${s}`)),console.log(l.yellow(`
193
+ For security reasons, you can only test files from within your workspace.`)),console.log(l.gray('Use "leetcode config workdir <path>" to change your workspace.'));return}let r=Ue({text:"Reading solution file...",spinner:"dots"}).start();try{let i=basename(n),a=i.match(/^(\d+)\.([^.]+)\./);if(!a){r.fail("Invalid filename format"),console.log(l.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(l.gray("Example: 1.two-sum.ts"));return}let c=a[2],g=i.split(".").pop(),u=le(g);if(!u){r.fail(`Unsupported file extension: .${g}`);return}let p=await readFile(n,"utf-8");r.text="Fetching problem details...";let b=await h.getProblem(c),x=o.testcase??b.exampleTestcases??b.sampleTestCase;r.text="Running tests...";let I=await h.testSolution(c,p,u,x,b.questionId);r.stop(),Mo(I,o.visualize?b.topicTags:void 0);}catch(i){r.fail("Test failed"),i instanceof Error&&console.log(l.red(i.message));}}function at(){return k.getTimerPath()}function ce(){let e=at();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{solveTimes:{},activeTimer:null}}function Je(e){let o=at(),t=dirname(o);existsSync(t)||mkdirSync(t,{recursive:true}),writeFileSync(o,JSON.stringify(e,null,2));}var G={startTimer(e,o,t,n){let s=ce();s.activeTimer={problemId:e,title:o,difficulty:t,startedAt:new Date().toISOString(),durationMinutes:n},Je(s);},getActiveTimer(){return ce().activeTimer},stopTimer(){let e=ce(),o=e.activeTimer;if(!o)return null;let t=new Date(o.startedAt),s=Math.floor((new Date().getTime()-t.getTime())/1e3);return e.activeTimer=null,Je(e),{durationSeconds:s}},recordSolveTime(e,o,t,n,s){let r=ce();r.solveTimes[e]||(r.solveTimes[e]=[]),r.solveTimes[e].push({problemId:e,title:o,difficulty:t,solvedAt:new Date().toISOString(),durationSeconds:n,timerMinutes:s}),Je(r);},getSolveTimes(e){return ce().solveTimes[e]??[]},getAllSolveTimes(){return ce().solveTimes??{}},getStats(){let e=ce().solveTimes??{},o=0,t=0;for(let n of Object.values(e)){o+=n.length;for(let s of n)t+=s.durationSeconds;}return {totalProblems:o,totalTime:t,avgTime:o>0?Math.floor(t/o):0}}};async function lt(e){let{authorized:o}=await $();if(!o)return;let t=e,n=w.getWorkDir();if(te(e)){let r=await H(n,e);if(!r){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.gray(`Looking in: ${n}`)),console.log(l.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}t=r,console.log(l.gray(`Found: ${t}`));}else if(Ie(e)){let r=await ve(n,e);if(!r){console.log(l.red(`File not found: ${e}`)),console.log(l.gray(`Looking in: ${n}`));return}t=r,console.log(l.gray(`Found: ${t}`));}if(!existsSync(t)){console.log(l.red(`File not found: ${t}`));return}if(!de(t,n)){console.log(l.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(l.gray(`File: ${t}`)),console.log(l.gray(`Workspace: ${n}`)),console.log(l.yellow(`
194
+ For security reasons, you can only submit files from within your workspace.`)),console.log(l.gray('Use "leetcode config workdir <path>" to change your workspace.'));return}let s=Ue({text:"Reading solution file...",spinner:"dots"}).start();try{let r=basename(t),i=r.match(/^(\d+)\.([^.]+)\./);if(!i){s.fail("Invalid filename format"),console.log(l.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(l.gray("Example: 1.two-sum.ts"));return}let[,a,c]=i,g=r.split(".").pop(),u=le(g);if(!u){s.fail(`Unsupported file extension: .${g}`);return}let p=await readFile(t,"utf-8");s.text="Fetching problem details...";let b=await h.getProblem(c);s.text="Submitting solution...";let x=await h.submitSolution(c,p,u,b.questionId);if(s.stop(),qo(x),x.status_msg==="Accepted"){let I=G.getActiveTimer();if(I&&I.problemId===a){let F=G.stopTimer();if(F){G.recordSolveTime(a,b.title,b.difficulty,F.durationSeconds,I.durationMinutes);let q=Math.floor(F.durationSeconds/60),ee=F.durationSeconds%60,ie=`${q}m ${ee}s`,V=F.durationSeconds<=I.durationMinutes*60;console.log(),console.log(l.bold("\u23F1\uFE0F Timer Result:")),console.log(` Solved in ${V?l.green(ie):l.yellow(ie)} (limit: ${I.durationMinutes}m)`),console.log(V?l.green(" \u2713 Within time limit!"):l.yellow(" \u26A0 Exceeded time limit"));}}}}catch(r){s.fail("Submission failed"),r instanceof Error&&console.log(l.red(r.message));}}var ct=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function gt(e){let o=JSON.parse(e),t=new Date,n=[];for(let i=11;i>=0;i--){let a=new Date(t);a.setDate(a.getDate()-i*7-a.getDay());let c=0,g=0;for(let p=0;p<7;p++){let b=new Date(a);if(b.setDate(b.getDate()+p),b>t)break;let x=new Date(Date.UTC(b.getFullYear(),b.getMonth(),b.getDate())),I=Math.floor(x.getTime()/1e3).toString(),F=o[I]||0;c+=F,F>0&&g++;}let u=new Date(a);u.setDate(u.getDate()+6),n.push({start:`${ct[a.getMonth()]} ${a.getDate()}`,end:`${ct[u.getMonth()]} ${u.getDate()}`,count:c,days:g});}let s=n.reduce((i,a)=>i+a.count,0),r=n.reduce((i,a)=>i+a.days,0);console.log(),console.log(l.bold("\u{1F4C5} Activity (Last 12 Weeks)")),console.log(l.gray("How many problems you submitted and days you practiced.")),console.log(l.gray("\u2500".repeat(50))),console.log();for(let i of n){let a=`${i.start} - ${i.end}`.padEnd(18),c=i.count>0?l.green("\u2588".repeat(Math.min(i.count,10))).padEnd(10):l.gray("\xB7").padEnd(10),g=i.count>0?`${i.count} subs`.padEnd(10):"".padEnd(10),u=i.days>0?`${i.days}d active`:"";console.log(` ${l.white(a)} ${c} ${l.cyan(g)} ${l.yellow(u)}`);}console.log(l.gray("\u2500".repeat(50))),console.log(` ${l.bold.white("Total:")} ${l.cyan.bold(s+" submissions")}, ${l.yellow.bold(r+" days active")}`),console.log();}function mt(e,o,t){console.log(),console.log(l.bold("\u{1F3AF} Skill Breakdown")),console.log(l.gray("\u2500".repeat(45)));let n=(s,r,i)=>{if(r.length===0)return;console.log(),console.log(i.bold(` ${s}`));let a=[...r].sort((c,g)=>g.problemsSolved-c.problemsSolved);for(let c of a.slice(0,8)){let g=c.tagName.padEnd(22),u=i("\u2588".repeat(Math.min(c.problemsSolved,15)));console.log(` ${l.white(g)} ${u} ${l.white(c.problemsSolved)}`);}};n("Fundamental",e,l.green),n("Intermediate",o,l.yellow),n("Advanced",t,l.red),console.log();}function dt(e){let o=JSON.parse(e),t=new Date,n=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=[];for(let c=6;c>=0;c--){let g=new Date(t);g.setDate(g.getDate()-c);let u=new Date(Date.UTC(g.getFullYear(),g.getMonth(),g.getDate())),p=Math.floor(u.getTime()/1e3).toString();s.push({label:n[g.getDay()],count:o[p]||0});}let r=Math.max(...s.map(c=>c.count),1),i=6;console.log(),console.log(l.bold("\u{1F4C8} Submission Trend (Last 7 Days)")),console.log(l.gray("\u2500".repeat(35))),console.log();for(let c=i;c>=1;c--){let g=` ${c===i?r.toString().padStart(2):" "} \u2502`;for(let u of s)Math.round(u.count/r*i)>=c?g+=l.green(" \u2588\u2588 "):g+=" ";console.log(g);}console.log(` 0 \u2514${"\u2500\u2500\u2500\u2500".repeat(7)}`),console.log(` ${s.map(c=>c.label.padEnd(4)).join("")}`),console.log(l.gray(` ${s.map(c=>c.count.toString().padEnd(4)).join("")}`));let a=s.reduce((c,g)=>c+g.count,0);console.log(),console.log(l.white(` Total: ${a} submissions this week`)),console.log();}async function ut(e,o={}){let{authorized:t,username:n}=await $();if(!t)return;let s=Ue("Fetching statistics...").start();try{let r=e||n;if(!r){s.fail("No username found");return}let i=await h.getUserProfile(r);if(s.stop(),!o.calendar&&!o.skills&&!o.trend){Oo(i.username,i.realName,i.ranking,i.acSubmissionNum,i.streak,i.totalActiveDays);return}if(o.calendar&&(i.submissionCalendar?gt(i.submissionCalendar):console.log(l.yellow("Calendar data not available."))),o.trend&&(i.submissionCalendar?dt(i.submissionCalendar):console.log(l.yellow("Calendar data not available."))),o.skills){s.start("Fetching skill stats...");let a=await h.getSkillStats(r);s.stop(),mt(a.fundamental,a.intermediate,a.advanced);}}catch(r){s.fail("Failed to fetch statistics"),r instanceof Error&&console.log(l.red(r.message));}}async function pt(){let{authorized:e}=await $();if(!e)return;let o=Ue("Fetching daily challenge...").start();try{let t=await h.getDailyChallenge();o.stop(),Ho(t.date,t.question),console.log(),console.log(l.gray("Run the following to start working on this problem:")),console.log(l.cyan(` leetcode pick ${t.question.titleSlug}`));}catch(t){o.fail("Failed to fetch daily challenge"),t instanceof Error&&console.log(l.red(t.message));}}async function ft(e){let{authorized:o}=await $();if(!o)return;let t=Ue("Fetching random problem...").start();try{let n={};if(e.difficulty){let i={easy:"EASY",e:"EASY",medium:"MEDIUM",m:"MEDIUM",hard:"HARD",h:"HARD"}[e.difficulty.toLowerCase()];if(i)n.difficulty=i;else {t.fail(`Invalid difficulty: ${e.difficulty}`);return}}e.tag&&(n.tags=[e.tag]);let s=await h.getRandomProblem(n);t.succeed("Found random problem!"),console.log(),e.pick?await Q(s,{open:e.open??!0}):(await Re(s),console.log(l.gray("Run following to start solving:")),console.log(l.cyan(` leetcode pick ${s}`)));}catch(n){t.fail("Failed to fetch random problem"),n instanceof Error&&console.log(l.red(n.message));}}async function bt(e,o){let{authorized:t}=await $();if(!t)return;let n=Ue("Fetching problem info...").start();try{let s;if(/^\d+$/.test(e)?s=await h.getProblemById(e):s=await h.getProblem(e),!s){n.fail(`Problem "${e}" not found`);return}let r=s.titleSlug;n.text="Fetching submissions...";let i=o.limit?parseInt(o.limit,10):20,a=await h.getSubmissionList(r,i);if(n.stop(),a.length===0){console.log(l.yellow("No submissions found."));return}if(o.last){let c=a.find(g=>g.statusDisplay==="Accepted");c?(console.log(l.bold("Last Accepted Submission:")),Ve([c])):console.log(l.yellow("No accepted submissions found in recent history."));}else Ve(a);if(o.download){let c=Ue("Downloading submission...").start(),g=a.find(bn=>bn.statusDisplay==="Accepted");if(!g){c.fail("No accepted submission found to download.");return}let u=parseInt(g.id,10);if(isNaN(u)){c.fail("Invalid submission ID format");return}let p=await h.getSubmissionDetails(u),b=w.getWorkDir(),x=s.difficulty,I=s.topicTags.length>0?s.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",F=join(b,x,I);existsSync(F)||await mkdir(F,{recursive:!0});let q=p.lang.name,ee=$e[q]??"txt",ie=me[ee]??q,V=`${s.questionFrontendId}.${s.titleSlug}.submission-${g.id}.${ie}`,lo=join(F,V);await writeFile(lo,p.code,"utf-8"),c.succeed(`Downloaded to ${l.green(V)}`),console.log(l.gray(`Path: ${lo}`));}}catch(s){n.fail("Failed to fetch submissions"),s instanceof Error&&console.log(l.red(s.message));}}var eo=["typescript","javascript","python3","java","cpp","c","csharp","go","rust","kotlin","swift"];async function wt(e){if(!e.lang&&!e.editor&&!e.workdir){$t();return}if(e.lang){let o=e.lang.toLowerCase();if(!eo.includes(o)){console.log(l.red(`Unsupported language: ${e.lang}`)),console.log(l.gray(`Supported: ${eo.join(", ")}`));return}let t=o;w.setLanguage(t),console.log(l.green(`\u2713 Default language set to ${t}`));}e.editor&&(w.setEditor(e.editor),console.log(l.green(`\u2713 Editor set to ${e.editor}`))),e.workdir&&(w.setWorkDir(e.workdir),console.log(l.green(`\u2713 Work directory set to ${e.workdir}`))),e.repo!==void 0&&(e.repo.trim()===""?(w.deleteRepo(),console.log(l.green("\u2713 Repository URL cleared"))):(w.setRepo(e.repo),console.log(l.green(`\u2713 Repository URL set to ${e.repo}`))));}async function St(){let e=w.getConfig(),o=w.getActiveWorkspace();console.log(),console.log(l.bold.cyan(`\u{1F4C1} Configuring workspace: ${o}`)),console.log(l.gray("\u2500".repeat(40)));let t=await to.prompt([{type:"list",name:"language",message:"Default programming language:",choices:eo,default:e.language},{type:"input",name:"editor",message:"Editor command (e.g., code, vim, nvim):",default:e.editor??"code"},{type:"input",name:"workDir",message:"Working directory for solution files:",default:e.workDir},{type:"input",name:"repo",message:"Git repository URL (optional):",default:e.repo}]);w.setLanguage(t.language),w.setEditor(t.editor),w.setWorkDir(t.workDir),t.repo?w.setRepo(t.repo):w.deleteRepo(),console.log(),console.log(l.green("\u2713 Configuration saved")),$t();}function $t(){let e=w.getConfig(),o=X.get(),t=w.getActiveWorkspace();console.log(),console.log(l.bold.cyan(`\u{1F4C1} Workspace: ${t}`)),console.log(l.gray("\u2500".repeat(40))),console.log(),console.log(l.gray("Config file:"),w.getPath()),console.log(),console.log(l.gray("Language: "),l.white(e.language)),console.log(l.gray("Editor: "),l.white(e.editor??"(not set)")),console.log(l.gray("Work Dir: "),l.white(e.workDir)),console.log(l.gray("Repo URL: "),l.white(e.repo??"(not set)")),console.log(l.gray("Logged in: "),o?l.green("Yes"):l.yellow("No"));}var ne=new vn({projectName:"leetcode-cli-bookmarks",defaults:{bookmarks:[]}}),pe={add(e){let o=ne.get("bookmarks");return o.includes(e)?false:(ne.set("bookmarks",[...o,e]),true)},remove(e){let o=ne.get("bookmarks");return o.includes(e)?(ne.set("bookmarks",o.filter(t=>t!==e)),true):false},list(){return ne.get("bookmarks")},has(e){return ne.get("bookmarks").includes(e)},count(){return ne.get("bookmarks").length},clear(){ne.set("bookmarks",[]);}};async function kt(e,o){if(!["add","remove","list","clear"].includes(e)){console.log(l.red(`Invalid action: ${e}`)),console.log(l.gray("Valid actions: add, remove, list, clear"));return}switch(e){case "add":if(!o){console.log(l.red("Please provide a problem ID to bookmark"));return}if(!te(o)){console.log(l.red(`Invalid problem ID: ${o}`)),console.log(l.gray("Problem ID must be a positive integer"));return}pe.add(o)?console.log(l.green(`\u2713 Bookmarked problem ${o}`)):console.log(l.yellow(`Problem ${o} is already bookmarked`));break;case "remove":if(!o){console.log(l.red("Please provide a problem ID to remove"));return}pe.remove(o)?console.log(l.green(`\u2713 Removed bookmark for problem ${o}`)):console.log(l.yellow(`Problem ${o} is not bookmarked`));break;case "list":await $s();break;case "clear":let n=pe.count();n===0?console.log(l.yellow("No bookmarks to clear")):(pe.clear(),console.log(l.green(`\u2713 Cleared ${n} bookmark${n!==1?"s":""}`)));break}}async function $s(){let e=pe.list();if(e.length===0){console.log(l.yellow("\u{1F4CC} No bookmarked problems")),console.log(l.gray('Use "leetcode bookmark add <id>" to bookmark a problem'));return}console.log(),console.log(l.bold.cyan(`\u{1F4CC} Bookmarked Problems (${e.length})`)),console.log();let{authorized:o}=await $();if(o){let t=Ue({text:"Fetching problem details...",spinner:"dots"}).start();try{let n=new We({head:[l.cyan("ID"),l.cyan("Title"),l.cyan("Difficulty"),l.cyan("Status")],colWidths:[8,45,12,10],style:{head:[],border:[]}});for(let s of e)try{let r=await h.getProblemById(s);r?n.push([r.questionFrontendId,r.title.length>42?r.title.slice(0,39)+"...":r.title,ks(r.difficulty),r.status==="ac"?l.green("\u2713"):l.gray("-")]):n.push([s,l.gray("(not found)"),"-","-"]);}catch{n.push([s,l.gray("(error fetching)"),"-","-"]);}t.stop(),console.log(n.toString());}catch{t.stop(),console.log(l.gray("IDs: ")+e.join(", "));}}else console.log(l.gray("IDs: ")+e.join(", ")),console.log(),console.log(l.gray("Login to see problem details"));}function ks(e){switch(e.toLowerCase()){case "easy":return l.green(e);case "medium":return l.yellow(e);case "hard":return l.red(e);default:return e}}async function Ct(e,o){if(!te(e)){console.log(l.red(`Invalid problem ID: ${e}`)),console.log(l.gray("Problem ID must be a positive integer"));return}let t=o==="view"?"view":"edit",n=join(w.getWorkDir(),".notes"),s=join(n,`${e}.md`);existsSync(n)||await mkdir(n,{recursive:true}),t==="view"?await Ts(s,e):await Ds(s,e);}async function Ts(e,o){if(!existsSync(e)){console.log(l.yellow(`No notes found for problem ${o}`)),console.log(l.gray(`Use "leetcode note ${o} edit" to create notes`));return}try{let t=await readFile(e,"utf-8");console.log(),console.log(l.bold.cyan(`\u{1F4DD} Notes for Problem ${o}`)),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(t);}catch(t){console.log(l.red("Failed to read notes")),t instanceof Error&&console.log(l.gray(t.message));}}async function Ds(e,o){if(!existsSync(e)){let t=await xs(o);await writeFile(e,t,"utf-8"),console.log(l.green(`\u2713 Created notes file for problem ${o}`));}console.log(l.gray(`Opening: ${e}`)),await ke(e);}async function xs(e){let o=`# Problem ${e} Notes
192
195
 
193
- `,{authorized:t}=await v();if(t)try{let n=await h.getProblemById(e);n&&(o=`# ${e}. ${n.title}
196
+ `,{authorized:t}=await $();if(t)try{let n=await h.getProblemById(e);n&&(o=`# ${e}. ${n.title}
194
197
 
195
198
  `,o+=`**Difficulty:** ${n.difficulty}
196
199
  `,o+=`**URL:** https://leetcode.com/problems/${n.titleSlug}/
@@ -223,22 +226,22 @@ For security reasons, you can only submit files from within your workspace.`)),c
223
226
 
224
227
  <!-- What did you learn from this problem? -->
225
228
 
226
- `}async function kt(){let{authorized:e,username:o}=await v();if(!e||!o)return;let t=Ue({text:"Fetching your progress...",spinner:"dots"}).start();try{let[n,s]=await Promise.all([h.getUserProfile(o),h.getDailyChallenge()]);t.stop(),console.log(),console.log(l.bold.cyan("\u{1F4CA} Today's Summary"),l.gray(`- ${o}`)),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(l.yellow(`\u{1F525} Current Streak: ${n.streak} day${n.streak!==1?"s":""}`)),console.log(l.gray(` Total Active Days: ${n.totalActiveDays}`)),console.log();let r=n.acSubmissionNum.find(u=>u.difficulty==="All"),i=n.acSubmissionNum.find(u=>u.difficulty==="Easy"),a=n.acSubmissionNum.find(u=>u.difficulty==="Medium"),c=n.acSubmissionNum.find(u=>u.difficulty==="Hard");console.log(l.white("\u{1F4C8} Problems Solved:")),console.log(` ${l.green("Easy")}: ${i?.count??0} | ${l.yellow("Medium")}: ${a?.count??0} | ${l.red("Hard")}: ${c?.count??0}`),console.log(` ${l.bold("Total")}: ${r?.count??0}`),console.log(),console.log(l.bold.yellow("\u{1F3AF} Today's Challenge:")),console.log(` ${s.question.questionFrontendId}. ${s.question.title}`),console.log(` ${$s(s.question.difficulty)}`);let g=s.question.status;console.log(g==="ac"?l.green(" \u2713 Completed!"):g==="notac"?l.yellow(" \u25CB Attempted"):l.gray(" - Not started")),console.log(),console.log(l.gray(` leetcode pick ${s.question.questionFrontendId} # Start working on it`));}catch(n){t.fail("Failed to fetch progress"),n instanceof Error&&console.log(l.red(n.message));}}function $s(e){switch(e.toLowerCase()){case "easy":return l.green(e);case "medium":return l.yellow(e);case "hard":return l.red(e);default:return e}}function vs(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-").replace(/--+/g,"-")}function Cs(e){let o=/^https:\/\/[\w.-]+\/[\w./-]+$/,t=/^git@[\w.-]+:[\w./-]+$/;return o.test(e)||t.test(e)}function Ps(e){return `'${e.replace(/'/g,"'\\''")}'`}function Ts(){try{return execSync("git --version",{stdio:"ignore"}),!0}catch{return false}}function Ds(e){try{return execSync("git rev-parse --is-inside-work-tree",{cwd:e,stdio:"ignore"}),!0}catch{return false}}function xs(){try{return execSync("gh --version",{stdio:"ignore"}),!0}catch{return false}}function vt(e){try{return execSync("git config --get remote.origin.url",{cwd:e,encoding:"utf-8"}).trim()}catch{return null}}async function Es(e){let{init:o}=await oo.prompt([{type:"confirm",name:"init",message:"Work directory is not a git repository. Initialize?",default:true}]);if(!o)return console.log(l.yellow("Skipping basic git initialization.")),false;let t=Ue("Initializing git repository...").start();try{return execSync("git init",{cwd:e}),t.succeed("Initialized git repository"),!0}catch(n){throw t.fail("Failed to initialize git repository"),n}}async function Ls(e){let o=Ue(),t=w.getRepo();if(!t){if(xs()){let{createGh:s}=await oo.prompt([{type:"confirm",name:"createGh",message:"Create a new private GitHub repository?",default:true}]);if(s){o.start("Creating GitHub repository...");try{let r=e.split("/").pop()||"leetcode-solutions",i=vs(r);return execSync(`gh repo create ${i} --private --source=. --remote=origin`,{cwd:e}),o.succeed("Created and linked GitHub repository"),t=vt(e)||"",t&&w.setRepo(t),t}catch(r){o.fail("Failed to create GitHub repository"),console.log(l.red(r));}}}if(!t){console.log(l.yellow(`
227
- Please create a new repository on your Git provider and copy the URL.`));let{url:s}=await oo.prompt([{type:"input",name:"url",message:"Enter remote repository URL:",validate:r=>r.length>0?true:"URL cannot be empty"}]);t=s;}}if(t&&!Cs(t))return console.log(l.red("Invalid repository URL format.")),console.log(l.gray("Expected: https://github.com/user/repo or git@github.com:user/repo")),"";if(t&&w.setRepo(t),!vt(e)&&t)try{execSync(`git remote add origin ${t}`,{cwd:e}),console.log(l.green("\u2713 Added remote origin"));}catch{console.log(l.red("Failed to add remote origin"));}return t||""}async function Ct(){let e=w.getWorkDir();if(!existsSync(e)){console.log(l.red(`Work directory does not exist: ${e}`));return}if(!Ts()){console.log(l.red("Git is not installed. Please install Git to use command."));return}if(!Ds(e)&&!await Es(e))return;await Ls(e);let o=Ue("Syncing solutions...").start();try{let t=execSync("git status --porcelain",{cwd:e,encoding:"utf-8"});if(!t){o.info("No changes to sync");return}execSync("git add .",{cwd:e});let s=t.trim().split(`
228
- `).length,r=new Date().toISOString().replace("T"," ").substring(0,19),i=`Sync: ${s} solutions - ${r}`;execSync(`git commit -m ${Ps(i)}`,{cwd:e});try{execSync("git push -u origin main",{cwd:e,stdio:"ignore"});}catch{try{execSync("git push -u origin master",{cwd:e,stdio:"ignore"});}catch{throw new Error("Failed to push to remote. Please check your git credentials and branch status.")}}o.succeed("Successfully synced solutions to remote");}catch(t){o.fail("Sync failed"),t.message&&console.log(l.red(t.message));}}var Rs={Easy:20,Medium:40,Hard:60};function pe(e){if(e<60)return `${e}s`;if(e<3600){let o=Math.floor(e/60),t=e%60;return t>0?`${o}m ${t}s`:`${o}m`}else {let o=Math.floor(e/3600),t=Math.floor(e%3600/60);return t>0?`${o}h ${t}m`:`${o}h`}}async function Pt(e,o){if(o.stats){await Fs(e);return}if(o.stop){await _s();return}if(!e){console.log(l.yellow("Please provide a problem ID to start the timer.")),console.log(l.gray("Usage: leetcode timer <id>")),console.log(l.gray(" leetcode timer --stats")),console.log(l.gray(" leetcode timer --stop"));return}let{authorized:t}=await v();if(!t)return;let n=B.getActiveTimer();if(n){let r=new Date(n.startedAt),i=Math.floor((Date.now()-r.getTime())/1e3);console.log(l.yellow("\u26A0\uFE0F You have an active timer running:")),console.log(l.white(` Problem: ${n.title}`)),console.log(l.white(` Elapsed: ${pe(i)}`)),console.log(),console.log(l.gray("Use `leetcode timer --stop` to stop it first."));return}let s=Ue("Fetching problem...").start();try{let r;if(/^\d+$/.test(e)?r=await h.getProblemById(e):r=await h.getProblem(e),!r){s.fail(`Problem "${e}" not found`);return}s.stop();let i=o.minutes??Rs[r.difficulty]??30;B.startTimer(r.questionFrontendId,r.title,r.difficulty,i),console.log(),console.log(l.bold.cyan("\u23F1\uFE0F Interview Mode Started!")),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(l.white(`Problem: ${r.questionFrontendId}. ${r.title}`)),console.log(l.white(`Difficulty: ${l.bold(r.difficulty)}`)),console.log(l.white(`Time Limit: ${l.bold.yellow(i+" minutes")}`)),console.log(),console.log(l.gray("\u2500".repeat(50))),console.log(l.green("\u2713 Timer is running in background")),console.log(l.gray(" When you submit successfully, your time will be recorded.")),console.log(l.gray(" Use `leetcode timer --stop` to cancel.")),console.log(),await Y(e,{open:!0});}catch(r){s.fail("Failed to start timer"),r instanceof Error&&console.log(l.red(r.message));}}async function _s(){let e=B.stopTimer();if(!e){console.log(l.yellow("No active timer to stop."));return}console.log(l.green("\u23F1\uFE0F Timer stopped.")),console.log(l.gray(`Elapsed time: ${pe(e.durationSeconds)}`)),console.log(l.gray("(Time not recorded since problem was not submitted)"));}async function Fs(e){if(e&&/^\d+$/.test(e)){let o=B.getSolveTimes(e);if(o.length===0){console.log(l.yellow(`No solve times recorded for problem ${e}`));return}console.log(),console.log(l.bold(`\u23F1\uFE0F Solve Times for Problem ${e}`)),console.log(l.gray("\u2500".repeat(40)));for(let t of o){let n=new Date(t.solvedAt).toLocaleDateString(),s=pe(t.durationSeconds),r=t.timerMinutes,i=t.durationSeconds<=r*60;console.log(` ${n} ${i?l.green(s):l.red(s)} (limit: ${r}m)`);}}else {let o=B.getStats(),t=B.getAllSolveTimes();console.log(),console.log(l.bold("\u23F1\uFE0F Timer Statistics")),console.log(l.gray("\u2500".repeat(40))),console.log(),console.log(` Problems timed: ${l.cyan(o.totalProblems)}`),console.log(` Total time: ${l.cyan(pe(o.totalTime))}`),console.log(` Average time: ${l.cyan(pe(o.avgTime))}`),console.log();let n=[];for(let[s,r]of Object.entries(t))for(let i of r)n.push({problemId:s,title:i.title,duration:i.durationSeconds,date:i.solvedAt});if(n.length>0){n.sort((s,r)=>new Date(r.date).getTime()-new Date(s.date).getTime()),console.log(l.bold(" Recent Solves:"));for(let s of n.slice(0,5)){let r=new Date(s.date).toLocaleDateString();console.log(l.gray(` ${r} `)+l.white(`${s.problemId}. ${s.title.substring(0,25)}`)+l.gray(" ")+l.cyan(pe(s.duration)));}}console.log();}}var Is="https://abagrmwdpvnfyuqizyym.supabase.co",Us="sb_publishable_indrKu8VJmASdyLp7w8Hog_OyqT17cV",ne=createClient(Is,Us);function no(){return $.getCollabPath()}function Ws(){let e=no();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{session:null}}function Hs(e){let o=no(),t=dirname(o);existsSync(t)||mkdirSync(t,{recursive:true}),writeFileSync(o,JSON.stringify(e,null,2));}var X={getSession(){return Ws().session},setSession(e){Hs({session:e});},getPath(){return no()}};function Vs(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",o="";for(let t=0;t<6;t++)o+=e.charAt(Math.floor(Math.random()*e.length));return o}var G={getSession(){return X.getSession()},async createRoom(e,o){let t=Vs(),{error:n}=await ne.from("collab_rooms").insert({room_code:t,problem_id:e,host_username:o,host_code:"",guest_username:null,guest_code:null});return n?{error:n.message}:(X.setSession({roomCode:t,problemId:e,isHost:true,username:o}),{roomCode:t})},async joinRoom(e,o){let{data:t,error:n}=await ne.from("collab_rooms").select("*").eq("room_code",e.toUpperCase()).single();if(n||!t)return {error:"Room not found"};let{error:s}=await ne.from("collab_rooms").update({guest_username:o}).eq("room_code",e.toUpperCase());return s?{error:s.message}:(X.setSession({roomCode:e.toUpperCase(),problemId:t.problem_id,isHost:false,username:o}),{problemId:t.problem_id})},async syncCode(e){let o=X.getSession();if(!o)return {success:false,error:"No active session"};let t=o.isHost?"host_code":"guest_code",{error:n}=await ne.from("collab_rooms").update({[t]:e}).eq("room_code",o.roomCode);return n?{success:false,error:n.message}:{success:true}},async getPartnerCode(){let e=X.getSession();if(!e)return {error:"No active session"};let{data:o,error:t}=await ne.from("collab_rooms").select("*").eq("room_code",e.roomCode).single();return t||!o?{error:"Room not found"}:e.isHost?{code:o.guest_code||"",username:o.guest_username||"Partner"}:{code:o.host_code||"",username:o.host_username||"Host"}},async getRoomStatus(){let e=X.getSession();if(!e)return {error:"No active session"};let{data:o,error:t}=await ne.from("collab_rooms").select("*").eq("room_code",e.roomCode).single();return t||!o?{error:"Room not found"}:{host:o.host_username,guest:o.guest_username,hasHostCode:!!o.host_code,hasGuestCode:!!o.guest_code}},async leaveRoom(){let e=X.getSession();e&&e.isHost&&await ne.from("collab_rooms").delete().eq("room_code",e.roomCode),X.setSession(null);}};async function xt(e){let{authorized:o,username:t}=await v();if(!o||!t)return;let n=Ue("Creating collaboration room...").start();try{let s=await G.createRoom(e,t);if("error"in s){n.fail(s.error);return}n.succeed("Room created!"),console.log(),console.log(l.bold.cyan("\u{1F465} Collaborative Coding Session")),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(l.white(`Room Code: ${l.bold.green(s.roomCode)}`)),console.log(l.white(`Problem: ${e}`)),console.log(),console.log(l.gray("Share this code with your partner:")),console.log(l.yellow(` leetcode collab join ${s.roomCode}`)),console.log(),console.log(l.gray("\u2500".repeat(50))),console.log(l.gray("After solving, sync and compare:")),console.log(l.gray(" leetcode collab sync - Upload your solution")),console.log(l.gray(" leetcode collab compare - See both solutions")),console.log(l.gray(" leetcode collab status - Check room status")),console.log(l.gray(" leetcode collab leave - End session")),console.log(),await Y(e,{open:!0});}catch(s){n.fail("Failed to create room"),s instanceof Error&&console.log(l.red(s.message));}}async function Et(e){let{authorized:o,username:t}=await v();if(!o||!t)return;let n=Ue(`Joining room ${e}...`).start();try{let s=await G.joinRoom(e.toUpperCase(),t);if("error"in s){n.fail(s.error);return}n.succeed("Joined room!"),console.log(),console.log(l.bold.cyan("\u{1F465} Collaborative Coding Session")),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(l.white(`Room Code: ${l.bold.green(e.toUpperCase())}`)),console.log(l.white(`Problem: ${s.problemId}`)),console.log(),console.log(l.gray("\u2500".repeat(50))),console.log(l.gray("After solving, sync and compare:")),console.log(l.gray(" leetcode collab sync - Upload your solution")),console.log(l.gray(" leetcode collab compare - See both solutions")),console.log(l.gray(" leetcode collab status - Check room status")),console.log(l.gray(" leetcode collab leave - End session")),console.log(),await Y(s.problemId,{open:!0});}catch(s){n.fail("Failed to join room"),s instanceof Error&&console.log(l.red(s.message));}}async function Lt(){let e=G.getSession();if(!e){console.log(l.yellow("No active collaboration session.")),console.log(l.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` first."));return}let o=Ue("Syncing your code...").start(),t=w.getWorkDir(),n=await O(t,e.problemId);if(!n){o.fail(`No solution file found for problem ${e.problemId}`);return}let s=await readFile(n,"utf-8"),r=await G.syncCode(s);r.success?(o.succeed("Code synced successfully!"),console.log(l.gray(`Uploaded ${s.split(`
229
- `).length} lines from ${n}`))):o.fail(r.error||"Sync failed");}async function At(){let e=G.getSession();if(!e){console.log(l.yellow("No active collaboration session.")),console.log(l.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` first."));return}let o=Ue("Fetching solutions...").start(),t=w.getWorkDir(),n=await O(t,e.problemId);if(!n){o.fail(`No solution file found for problem ${e.problemId}`);return}let s=await readFile(n,"utf-8"),r=await G.getPartnerCode();if("error"in r){o.fail(r.error);return}if(o.stop(),!r.code){console.log(l.yellow("Partner has not synced their code yet.")),console.log(l.gray("Ask them to run `leetcode collab sync`."));return}console.log(),console.log(l.bold.cyan("\u{1F4CA} Solution Comparison")),console.log(l.gray("\u2500".repeat(60))),console.log(),console.log(l.bold.green(`\u25B8 Your Solution (${e.username})`)),console.log(l.gray("\u2500".repeat(60)));let i=s.split(`
229
+ `}async function Pt(){let{authorized:e,username:o}=await $();if(!e||!o)return;let t=Ue({text:"Fetching your progress...",spinner:"dots"}).start();try{let[n,s]=await Promise.all([h.getUserProfile(o),h.getDailyChallenge()]);t.stop(),console.log(),console.log(l.bold.cyan("\u{1F4CA} Today's Summary"),l.gray(`- ${o}`)),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(l.yellow(`\u{1F525} Current Streak: ${n.streak} day${n.streak!==1?"s":""}`)),console.log(l.gray(` Total Active Days: ${n.totalActiveDays}`)),console.log();let r=n.acSubmissionNum.find(u=>u.difficulty==="All"),i=n.acSubmissionNum.find(u=>u.difficulty==="Easy"),a=n.acSubmissionNum.find(u=>u.difficulty==="Medium"),c=n.acSubmissionNum.find(u=>u.difficulty==="Hard");console.log(l.white("\u{1F4C8} Problems Solved:")),console.log(` ${l.green("Easy")}: ${i?.count??0} | ${l.yellow("Medium")}: ${a?.count??0} | ${l.red("Hard")}: ${c?.count??0}`),console.log(` ${l.bold("Total")}: ${r?.count??0}`),console.log(),console.log(l.bold.yellow("\u{1F3AF} Today's Challenge:")),console.log(` ${s.question.questionFrontendId}. ${s.question.title}`),console.log(` ${Ls(s.question.difficulty)}`);let g=s.question.status;console.log(g==="ac"?l.green(" \u2713 Completed!"):g==="notac"?l.yellow(" \u25CB Attempted"):l.gray(" - Not started")),console.log(),console.log(l.gray(` leetcode pick ${s.question.questionFrontendId} # Start working on it`));}catch(n){t.fail("Failed to fetch progress"),n instanceof Error&&console.log(l.red(n.message));}}function Ls(e){switch(e.toLowerCase()){case "easy":return l.green(e);case "medium":return l.yellow(e);case "hard":return l.red(e);default:return e}}function Rs(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-").replace(/--+/g,"-")}function Fs(e){let o=/^https:\/\/[\w.-]+\/[\w./-]+$/,t=/^git@[\w.-]+:[\w./-]+$/;return o.test(e)||t.test(e)}function _s(e){return `'${e.replace(/'/g,"'\\''")}'`}function Ns(){try{return execSync("git --version",{stdio:"ignore"}),!0}catch{return false}}function Is(e){try{return execSync("git rev-parse --is-inside-work-tree",{cwd:e,stdio:"ignore"}),!0}catch{return false}}function Us(){try{return execSync("gh --version",{stdio:"ignore"}),!0}catch{return false}}function Tt(e){try{return execSync("git config --get remote.origin.url",{cwd:e,encoding:"utf-8"}).trim()}catch{return null}}async function js(e){let{init:o}=await to.prompt([{type:"confirm",name:"init",message:"Work directory is not a git repository. Initialize?",default:true}]);if(!o)return console.log(l.yellow("Skipping basic git initialization.")),false;let t=Ue("Initializing git repository...").start();try{return execSync("git init",{cwd:e}),t.succeed("Initialized git repository"),!0}catch(n){throw t.fail("Failed to initialize git repository"),n}}async function Ms(e){let o=Ue(),t=w.getRepo();if(!t){if(Us()){let{createGh:s}=await to.prompt([{type:"confirm",name:"createGh",message:"Create a new private GitHub repository?",default:true}]);if(s){o.start("Creating GitHub repository...");try{let r=e.split("/").pop()||"leetcode-solutions",i=Rs(r);return execSync(`gh repo create ${i} --private --source=. --remote=origin`,{cwd:e}),o.succeed("Created and linked GitHub repository"),t=Tt(e)||"",t&&w.setRepo(t),t}catch(r){o.fail("Failed to create GitHub repository"),console.log(l.red(r));}}}if(!t){console.log(l.yellow(`
230
+ Please create a new repository on your Git provider and copy the URL.`));let{url:s}=await to.prompt([{type:"input",name:"url",message:"Enter remote repository URL:",validate:r=>r.length>0?true:"URL cannot be empty"}]);t=s;}}if(t&&!Fs(t))return console.log(l.red("Invalid repository URL format.")),console.log(l.gray("Expected: https://github.com/user/repo or git@github.com:user/repo")),"";if(t&&w.setRepo(t),!Tt(e)&&t)try{execSync(`git remote add origin ${t}`,{cwd:e}),console.log(l.green("\u2713 Added remote origin"));}catch{console.log(l.red("Failed to add remote origin"));}return t||""}async function Dt(){let e=w.getWorkDir();if(!existsSync(e)){console.log(l.red(`Work directory does not exist: ${e}`));return}if(!Ns()){console.log(l.red("Git is not installed. Please install Git to use command."));return}if(!Is(e)&&!await js(e))return;await Ms(e);let o=Ue("Syncing solutions...").start();try{let t=execSync("git status --porcelain",{cwd:e,encoding:"utf-8"});if(!t){o.info("No changes to sync");return}execSync("git add .",{cwd:e});let s=t.trim().split(`
231
+ `).length,r=new Date().toISOString().replace("T"," ").substring(0,19),i=`Sync: ${s} solutions - ${r}`;execSync(`git commit -m ${_s(i)}`,{cwd:e});try{execSync("git push -u origin main",{cwd:e,stdio:"ignore"});}catch{try{execSync("git push -u origin master",{cwd:e,stdio:"ignore"});}catch{throw new Error("Failed to push to remote. Please check your git credentials and branch status.")}}o.succeed("Successfully synced solutions to remote");}catch(t){o.fail("Sync failed"),t instanceof Error&&t.message&&console.log(l.red(t.message));}}var Os={Easy:20,Medium:40,Hard:60};function fe(e){if(e<60)return `${e}s`;if(e<3600){let o=Math.floor(e/60),t=e%60;return t>0?`${o}m ${t}s`:`${o}m`}else {let o=Math.floor(e/3600),t=Math.floor(e%3600/60);return t>0?`${o}h ${t}m`:`${o}h`}}async function xt(e,o){if(o.stats){await Ws(e);return}if(o.stop){await Hs();return}if(!e){console.log(l.yellow("Please provide a problem ID to start the timer.")),console.log(l.gray("Usage: leetcode timer <id>")),console.log(l.gray(" leetcode timer --stats")),console.log(l.gray(" leetcode timer --stop"));return}let{authorized:t}=await $();if(!t)return;let n=G.getActiveTimer();if(n){let r=new Date(n.startedAt),i=Math.floor((Date.now()-r.getTime())/1e3);console.log(l.yellow("\u26A0\uFE0F You have an active timer running:")),console.log(l.white(` Problem: ${n.title}`)),console.log(l.white(` Elapsed: ${fe(i)}`)),console.log(),console.log(l.gray("Use `leetcode timer --stop` to stop it first."));return}let s=Ue("Fetching problem...").start();try{let r;if(/^\d+$/.test(e)?r=await h.getProblemById(e):r=await h.getProblem(e),!r){s.fail(`Problem "${e}" not found`);return}s.stop();let i=o.minutes??Os[r.difficulty]??30;G.startTimer(r.questionFrontendId,r.title,r.difficulty,i),console.log(),console.log(l.bold.cyan("\u23F1\uFE0F Interview Mode Started!")),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(l.white(`Problem: ${r.questionFrontendId}. ${r.title}`)),console.log(l.white(`Difficulty: ${l.bold(r.difficulty)}`)),console.log(l.white(`Time Limit: ${l.bold.yellow(i+" minutes")}`)),console.log(),console.log(l.gray("\u2500".repeat(50))),console.log(l.green("\u2713 Timer is running in background")),console.log(l.gray(" When you submit successfully, your time will be recorded.")),console.log(l.gray(" Use `leetcode timer --stop` to cancel.")),console.log(),await Q(e,{open:!0});}catch(r){s.fail("Failed to start timer"),r instanceof Error&&console.log(l.red(r.message));}}async function Hs(){let e=G.stopTimer();if(!e){console.log(l.yellow("No active timer to stop."));return}console.log(l.green("\u23F1\uFE0F Timer stopped.")),console.log(l.gray(`Elapsed time: ${fe(e.durationSeconds)}`)),console.log(l.gray("(Time not recorded since problem was not submitted)"));}async function Ws(e){if(e&&/^\d+$/.test(e)){let o=G.getSolveTimes(e);if(o.length===0){console.log(l.yellow(`No solve times recorded for problem ${e}`));return}console.log(),console.log(l.bold(`\u23F1\uFE0F Solve Times for Problem ${e}`)),console.log(l.gray("\u2500".repeat(40)));for(let t of o){let n=new Date(t.solvedAt).toLocaleDateString(),s=fe(t.durationSeconds),r=t.timerMinutes,i=t.durationSeconds<=r*60;console.log(` ${n} ${i?l.green(s):l.red(s)} (limit: ${r}m)`);}}else {let o=G.getStats(),t=G.getAllSolveTimes();console.log(),console.log(l.bold("\u23F1\uFE0F Timer Statistics")),console.log(l.gray("\u2500".repeat(40))),console.log(),console.log(` Problems timed: ${l.cyan(o.totalProblems)}`),console.log(` Total time: ${l.cyan(fe(o.totalTime))}`),console.log(` Average time: ${l.cyan(fe(o.avgTime))}`),console.log();let n=[];for(let[s,r]of Object.entries(t))for(let i of r)n.push({problemId:s,title:i.title,duration:i.durationSeconds,date:i.solvedAt});if(n.length>0){n.sort((s,r)=>new Date(r.date).getTime()-new Date(s.date).getTime()),console.log(l.bold(" Recent Solves:"));for(let s of n.slice(0,5)){let r=new Date(s.date).toLocaleDateString();console.log(l.gray(` ${r} `)+l.white(`${s.problemId}. ${s.title.substring(0,25)}`)+l.gray(" ")+l.cyan(fe(s.duration)));}}console.log();}}var zs="https://abagrmwdpvnfyuqizyym.supabase.co",Bs="sb_publishable_indrKu8VJmASdyLp7w8Hog_OyqT17cV",se=createClient(zs,Bs);function so(){return k.getCollabPath()}function Ks(){let e=so();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{session:null}}function Xs(e){let o=so(),t=dirname(o);existsSync(t)||mkdirSync(t,{recursive:true}),writeFileSync(o,JSON.stringify(e,null,2));}var Z={getSession(){return Ks().session},setSession(e){Xs({session:e});},getPath(){return so()}};function Zs(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",o="";for(let t=0;t<6;t++)o+=e.charAt(Math.floor(Math.random()*e.length));return o}var Y={getSession(){return Z.getSession()},async createRoom(e,o){let t=Zs(),{error:n}=await se.from("collab_rooms").insert({room_code:t,problem_id:e,host_username:o,host_code:"",guest_username:null,guest_code:null});return n?{error:n.message}:(Z.setSession({roomCode:t,problemId:e,isHost:true,username:o}),{roomCode:t})},async joinRoom(e,o){let{data:t,error:n}=await se.from("collab_rooms").select("*").eq("room_code",e.toUpperCase()).single();if(n||!t)return {error:"Room not found"};let{error:s}=await se.from("collab_rooms").update({guest_username:o}).eq("room_code",e.toUpperCase());return s?{error:s.message}:(Z.setSession({roomCode:e.toUpperCase(),problemId:t.problem_id,isHost:false,username:o}),{problemId:t.problem_id})},async syncCode(e){let o=Z.getSession();if(!o)return {success:false,error:"No active session"};let t=o.isHost?"host_code":"guest_code",{error:n}=await se.from("collab_rooms").update({[t]:e}).eq("room_code",o.roomCode);return n?{success:false,error:n.message}:{success:true}},async getPartnerCode(){let e=Z.getSession();if(!e)return {error:"No active session"};let{data:o,error:t}=await se.from("collab_rooms").select("*").eq("room_code",e.roomCode).single();return t||!o?{error:"Room not found"}:e.isHost?{code:o.guest_code||"",username:o.guest_username||"Partner"}:{code:o.host_code||"",username:o.host_username||"Host"}},async getRoomStatus(){let e=Z.getSession();if(!e)return {error:"No active session"};let{data:o,error:t}=await se.from("collab_rooms").select("*").eq("room_code",e.roomCode).single();return t||!o?{error:"Room not found"}:{host:o.host_username,guest:o.guest_username,hasHostCode:!!o.host_code,hasGuestCode:!!o.guest_code}},async leaveRoom(){let e=Z.getSession();e&&e.isHost&&await se.from("collab_rooms").delete().eq("room_code",e.roomCode),Z.setSession(null);}};async function At(e){let{authorized:o,username:t}=await $();if(!o||!t)return;let n=Ue("Creating collaboration room...").start();try{let s=await Y.createRoom(e,t);if("error"in s){n.fail(s.error);return}n.succeed("Room created!"),console.log(),console.log(l.bold.cyan("\u{1F465} Collaborative Coding Session")),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(l.white(`Room Code: ${l.bold.green(s.roomCode)}`)),console.log(l.white(`Problem: ${e}`)),console.log(),console.log(l.gray("Share this code with your partner:")),console.log(l.yellow(` leetcode collab join ${s.roomCode}`)),console.log(),console.log(l.gray("\u2500".repeat(50))),console.log(l.gray("After solving, sync and compare:")),console.log(l.gray(" leetcode collab sync - Upload your solution")),console.log(l.gray(" leetcode collab compare - See both solutions")),console.log(l.gray(" leetcode collab status - Check room status")),console.log(l.gray(" leetcode collab leave - End session")),console.log(),await Q(e,{open:!0});}catch(s){n.fail("Failed to create room"),s instanceof Error&&console.log(l.red(s.message));}}async function Rt(e){let{authorized:o,username:t}=await $();if(!o||!t)return;let n=Ue(`Joining room ${e}...`).start();try{let s=await Y.joinRoom(e.toUpperCase(),t);if("error"in s){n.fail(s.error);return}n.succeed("Joined room!"),console.log(),console.log(l.bold.cyan("\u{1F465} Collaborative Coding Session")),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(l.white(`Room Code: ${l.bold.green(e.toUpperCase())}`)),console.log(l.white(`Problem: ${s.problemId}`)),console.log(),console.log(l.gray("\u2500".repeat(50))),console.log(l.gray("After solving, sync and compare:")),console.log(l.gray(" leetcode collab sync - Upload your solution")),console.log(l.gray(" leetcode collab compare - See both solutions")),console.log(l.gray(" leetcode collab status - Check room status")),console.log(l.gray(" leetcode collab leave - End session")),console.log(),await Q(s.problemId,{open:!0});}catch(s){n.fail("Failed to join room"),s instanceof Error&&console.log(l.red(s.message));}}async function Ft(){let e=Y.getSession();if(!e){console.log(l.yellow("No active collaboration session.")),console.log(l.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` first."));return}let o=Ue("Syncing your code...").start(),t=w.getWorkDir(),n=await H(t,e.problemId);if(!n){o.fail(`No solution file found for problem ${e.problemId}`);return}let s=await readFile(n,"utf-8"),r=await Y.syncCode(s);r.success?(o.succeed("Code synced successfully!"),console.log(l.gray(`Uploaded ${s.split(`
232
+ `).length} lines from ${n}`))):o.fail(r.error||"Sync failed");}async function _t(){let e=Y.getSession();if(!e){console.log(l.yellow("No active collaboration session.")),console.log(l.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` first."));return}let o=Ue("Fetching solutions...").start(),t=w.getWorkDir(),n=await H(t,e.problemId);if(!n){o.fail(`No solution file found for problem ${e.problemId}`);return}let s=await readFile(n,"utf-8"),r=await Y.getPartnerCode();if("error"in r){o.fail(r.error);return}if(o.stop(),!r.code){console.log(l.yellow("Partner has not synced their code yet.")),console.log(l.gray("Ask them to run `leetcode collab sync`."));return}console.log(),console.log(l.bold.cyan("\u{1F4CA} Solution Comparison")),console.log(l.gray("\u2500".repeat(60))),console.log(),console.log(l.bold.green(`\u25B8 Your Solution (${e.username})`)),console.log(l.gray("\u2500".repeat(60)));let i=s.split(`
230
233
  `);for(let c=0;c<i.length;c++){let g=String(c+1).padStart(3," ");console.log(`${l.gray(g)} ${i[c]}`);}console.log(),console.log(l.bold.blue(`\u25B8 ${r.username}'s Solution`)),console.log(l.gray("\u2500".repeat(60)));let a=r.code.split(`
231
- `);for(let c=0;c<a.length;c++){let g=String(c+1).padStart(3," ");console.log(`${l.gray(g)} ${a[c]}`);}console.log(),console.log(l.gray("\u2500".repeat(60))),console.log(l.gray(`Your code: ${i.length} lines | Partner: ${a.length} lines`)),console.log();}async function Rt(){if(!G.getSession()){console.log(l.yellow("No active collaboration session."));return}await G.leaveRoom(),console.log(l.green("\u2713 Left the collaboration session."));}async function _t(){let e=G.getSession();if(!e){console.log(l.yellow("No active collaboration session.")),console.log(l.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` to start."));return}let o=await G.getRoomStatus();if("error"in o){console.log(l.red(o.error));return}console.log(),console.log(l.bold.cyan("\u{1F465} Collaboration Status")),console.log(l.gray("\u2500".repeat(40))),console.log(` Room: ${l.green(e.roomCode)}`),console.log(` Problem: ${e.problemId}`),console.log(` Role: ${e.isHost?"Host":"Guest"}`),console.log(),console.log(l.bold(" Participants:")),console.log(` Host: ${o.host} ${o.hasHostCode?l.green("\u2713 synced"):l.gray("pending")}`),console.log(` Guest: ${o.guest||l.gray("(waiting...)")} ${o.hasGuestCode?l.green("\u2713 synced"):l.gray("pending")}`),console.log();}function Gs(){return $.getSnapshotsDir()}function Ut(e){return join(Gs(),e)}function jt(e){return join(Ut(e),"meta.json")}function je(e){return join(Ut(e),"files")}function Mt(e){let o=je(e);existsSync(o)||mkdirSync(o,{recursive:true});}function ve(e){let o=jt(e);return existsSync(o)?JSON.parse(readFileSync(o,"utf-8")):{problemId:e,problemTitle:"",snapshots:[]}}function Ft(e,o){Mt(e),writeFileSync(jt(e),JSON.stringify(o,null,2));}var W={save(e,o,t,n,s){Mt(e);let r=ve(e);o&&(r.problemTitle=o);let i=r.snapshots.length>0?Math.max(...r.snapshots.map(C=>C.id))+1:1,a=s||`snapshot-${i}`,c=r.snapshots.find(C=>C.name===a);if(c)return {error:`Snapshot with name "${a}" already exists (ID: ${c.id})`};let g=ge[n]||n,u=`${i}_${a}.${g}`,p=join(je(e),u);writeFileSync(p,t,"utf-8");let b={id:i,name:a,fileName:u,language:n,lines:t.split(`
232
- `).length,createdAt:new Date().toISOString()};return r.snapshots.push(b),Ft(e,r),b},list(e){return ve(e).snapshots},getMeta(e){return ve(e)},get(e,o){let t=ve(e),n=t.snapshots.find(r=>r.id===parseInt(o,10));return n||t.snapshots.find(r=>r.name===o)||null},getCode(e,o){let t=join(je(e),o.fileName);if(!existsSync(t))throw new Error(`Snapshot file not found: ${o.fileName}`);return readFileSync(t,"utf-8")},delete(e,o){let t=ve(e),n=this.get(e,o);if(!n)return false;let s=join(je(e),n.fileName);return existsSync(s)&&unlinkSync(s),t.snapshots=t.snapshots.filter(r=>r.id!==n.id),Ft(e,t),true},hasSnapshots(e){return this.list(e).length>0}};function Ks(e){let o=new Date(e),n=new Date().getTime()-o.getTime(),s=Math.floor(n/6e4),r=Math.floor(s/60),i=Math.floor(r/24);return s<1?"just now":s<60?`${s}m ago`:r<24?`${r}h ago`:`${i}d ago`}async function Wt(e,o){let t=w.getWorkDir();try{let n=await O(t,e);if(!n){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.gray("Run `leetcode pick "+e+"` first to create a solution file."));return}let s=await readFile(n,"utf-8"),r=extname(n).slice(1),i=ae(r)||r,c=basename(n).match(/^\d+\.(.+)\.\w+$/),g=c?c[1]:"",u=W.save(e,g,s,i,o);if("error"in u){console.log(l.red("\u2717 "+u.error));return}let p=u;console.log(l.green("\u2713 Snapshot saved!")),console.log(),console.log(` ID: ${l.cyan(p.id)}`),console.log(` Name: ${l.white(p.name)}`),console.log(` Lines: ${l.gray(p.lines)}`),console.log(` File: ${l.gray(n)}`);}catch(n){console.log(l.red("Failed to save snapshot")),n instanceof Error&&console.log(l.gray(n.message));}}async function Ht(e){let o=W.list(e);if(o.length===0){console.log(l.yellow(`No snapshots found for problem ${e}`)),console.log(l.gray("Use `leetcode snapshot save "+e+"` to create one."));return}let t=W.getMeta(e);console.log(),console.log(l.bold(`\u{1F4F8} Snapshots for Problem ${e}`)),t.problemTitle&&console.log(l.gray(` ${t.problemTitle}`)),console.log(l.gray("\u2500".repeat(50))),console.log();for(let n of o){let s=Ks(n.createdAt);console.log(` ${l.cyan(n.id.toString().padStart(2))}. ${l.white(n.name.padEnd(25))} ${l.gray(n.lines+" lines")} ${l.gray("\xB7")} ${l.gray(s)}`);}console.log(),console.log(l.gray("Commands:")),console.log(l.gray(` restore: leetcode snapshot restore ${e} <id|name>`)),console.log(l.gray(` diff: leetcode snapshot diff ${e} <id1> <id2>`)),console.log(l.gray(` delete: leetcode snapshot delete ${e} <id|name>`));}async function Vt(e,o){let t=w.getWorkDir();try{let n=W.get(e,o);if(!n){console.log(l.red(`Snapshot "${o}" not found for problem ${e}`)),console.log(l.gray("Run `leetcode snapshot list "+e+"` to see available snapshots."));return}let s=await O(t,e);if(!s){console.log(l.red(`No solution file found for problem ${e}`));return}let r=await readFile(s,"utf-8"),i=`backup-before-restore-${Date.now()}`,a=extname(s).slice(1),c=ae(a)||a;W.save(e,"",r,c,i);let g=W.getCode(e,n);await writeFile(s,g,"utf-8"),console.log(l.green("\u2713 Snapshot restored!")),console.log(),console.log(` Restored: ${l.cyan(n.name)} (${n.lines} lines)`),console.log(` File: ${l.gray(s)}`),console.log(` Backup: ${l.gray(i)}`);}catch(n){console.log(l.red("Failed to restore snapshot")),n instanceof Error&&console.log(l.gray(n.message));}}async function zt(e,o,t){try{let n=W.get(e,o),s=W.get(e,t);if(!n){console.log(l.red(`Snapshot "${o}" not found`));return}if(!s){console.log(l.red(`Snapshot "${t}" not found`));return}let r=W.getCode(e,n),i=W.getCode(e,s);console.log(),console.log(l.bold(`\u{1F4CA} Diff: ${n.name} \u2192 ${s.name}`)),console.log(l.gray("\u2500".repeat(50))),console.log();let a=diffLines(r,i),c=0,g=0;for(let u of a){let p=u.value.split(`
233
- `).filter(b=>b!=="");if(u.added){c+=p.length;for(let b of p)console.log(l.green("+ "+b));}else if(u.removed){g+=p.length;for(let b of p)console.log(l.red("- "+b));}else if(p.length<=4)for(let b of p)console.log(l.gray(" "+b));else console.log(l.gray(" "+p[0])),console.log(l.gray(" "+p[1])),console.log(l.gray(` ... (${p.length-4} more lines)`)),console.log(l.gray(" "+p[p.length-2])),console.log(l.gray(" "+p[p.length-1]));}console.log(),console.log(l.gray("\u2500".repeat(50))),console.log(`${l.green("+"+c+" added")} ${l.gray("\xB7")} ${l.red("-"+g+" removed")} ${l.gray("\xB7")} ${l.gray(n.lines+" \u2192 "+s.lines+" lines")}`);}catch(n){console.log(l.red("Failed to diff snapshots")),n instanceof Error&&console.log(l.gray(n.message));}}async function Bt(e,o){let t=W.get(e,o);if(!t){console.log(l.red(`Snapshot "${o}" not found for problem ${e}`));return}let n=W.delete(e,o);console.log(n?l.green(`\u2713 Deleted snapshot: ${t.name}`):l.red("Failed to delete snapshot"));}function Yt(e,o){let t=e.split(`
234
- `),n=t.length;console.log(),console.log(l.bold.cyan(`=== ${o} (${n} lines) ===`)),console.log(l.gray("\u2500".repeat(60))),t.forEach((s,r)=>{let i=(r+1).toString().padStart(3);console.log(l.gray(i+" \u2502 ")+s);});}function er(e,o,t,n){let s=e.split(`
234
+ `);for(let c=0;c<a.length;c++){let g=String(c+1).padStart(3," ");console.log(`${l.gray(g)} ${a[c]}`);}console.log(),console.log(l.gray("\u2500".repeat(60))),console.log(l.gray(`Your code: ${i.length} lines | Partner: ${a.length} lines`)),console.log();}async function Nt(){if(!Y.getSession()){console.log(l.yellow("No active collaboration session."));return}await Y.leaveRoom(),console.log(l.green("\u2713 Left the collaboration session."));}async function It(){let e=Y.getSession();if(!e){console.log(l.yellow("No active collaboration session.")),console.log(l.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` to start."));return}let o=await Y.getRoomStatus();if("error"in o){console.log(l.red(o.error));return}console.log(),console.log(l.bold.cyan("\u{1F465} Collaboration Status")),console.log(l.gray("\u2500".repeat(40))),console.log(` Room: ${l.green(e.roomCode)}`),console.log(` Problem: ${e.problemId}`),console.log(` Role: ${e.isHost?"Host":"Guest"}`),console.log(),console.log(l.bold(" Participants:")),console.log(` Host: ${o.host} ${o.hasHostCode?l.green("\u2713 synced"):l.gray("pending")}`),console.log(` Guest: ${o.guest||l.gray("(waiting...)")} ${o.hasGuestCode?l.green("\u2713 synced"):l.gray("pending")}`),console.log();}function tr(){return k.getSnapshotsDir()}function qt(e){return join(tr(),e)}function Ot(e){return join(qt(e),"meta.json")}function je(e){return join(qt(e),"files")}function Ht(e){let o=je(e);existsSync(o)||mkdirSync(o,{recursive:true});}function Ce(e){let o=Ot(e);return existsSync(o)?JSON.parse(readFileSync(o,"utf-8")):{problemId:e,problemTitle:"",snapshots:[]}}function Ut(e,o){Ht(e),writeFileSync(Ot(e),JSON.stringify(o,null,2));}var W={save(e,o,t,n,s){Ht(e);let r=Ce(e);o&&(r.problemTitle=o);let i=r.snapshots.length>0?Math.max(...r.snapshots.map(x=>x.id))+1:1,a=s||`snapshot-${i}`,c=r.snapshots.find(x=>x.name===a);if(c)return {error:`Snapshot with name "${a}" already exists (ID: ${c.id})`};let g=me[n]||n,u=`${i}_${a}.${g}`,p=join(je(e),u);writeFileSync(p,t,"utf-8");let b={id:i,name:a,fileName:u,language:n,lines:t.split(`
235
+ `).length,createdAt:new Date().toISOString()};return r.snapshots.push(b),Ut(e,r),b},list(e){return Ce(e).snapshots},getMeta(e){return Ce(e)},get(e,o){let t=Ce(e),n=t.snapshots.find(r=>r.id===parseInt(o,10));return n||t.snapshots.find(r=>r.name===o)||null},getCode(e,o){let t=join(je(e),o.fileName);if(!existsSync(t))throw new Error(`Snapshot file not found: ${o.fileName}`);return readFileSync(t,"utf-8")},delete(e,o){let t=Ce(e),n=this.get(e,o);if(!n)return false;let s=join(je(e),n.fileName);return existsSync(s)&&unlinkSync(s),t.snapshots=t.snapshots.filter(r=>r.id!==n.id),Ut(e,t),true},hasSnapshots(e){return this.list(e).length>0}};function ir(e){let o=new Date(e),n=new Date().getTime()-o.getTime(),s=Math.floor(n/6e4),r=Math.floor(s/60),i=Math.floor(r/24);return s<1?"just now":s<60?`${s}m ago`:r<24?`${r}h ago`:`${i}d ago`}async function zt(e,o){let t=w.getWorkDir();try{let n=await H(t,e);if(!n){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.gray("Run `leetcode pick "+e+"` first to create a solution file."));return}let s=await readFile(n,"utf-8"),r=extname(n).slice(1),i=le(r)||r,c=basename(n).match(/^\d+\.(.+)\.\w+$/),g=c?c[1]:"",u=W.save(e,g,s,i,o);if("error"in u){console.log(l.red("\u2717 "+u.error));return}let p=u;console.log(l.green("\u2713 Snapshot saved!")),console.log(),console.log(` ID: ${l.cyan(p.id)}`),console.log(` Name: ${l.white(p.name)}`),console.log(` Lines: ${l.gray(p.lines)}`),console.log(` File: ${l.gray(n)}`);}catch(n){console.log(l.red("Failed to save snapshot")),n instanceof Error&&console.log(l.gray(n.message));}}async function Bt(e){let o=W.list(e);if(o.length===0){console.log(l.yellow(`No snapshots found for problem ${e}`)),console.log(l.gray("Use `leetcode snapshot save "+e+"` to create one."));return}let t=W.getMeta(e);console.log(),console.log(l.bold(`\u{1F4F8} Snapshots for Problem ${e}`)),t.problemTitle&&console.log(l.gray(` ${t.problemTitle}`)),console.log(l.gray("\u2500".repeat(50))),console.log();for(let n of o){let s=ir(n.createdAt);console.log(` ${l.cyan(n.id.toString().padStart(2))}. ${l.white(n.name.padEnd(25))} ${l.gray(n.lines+" lines")} ${l.gray("\xB7")} ${l.gray(s)}`);}console.log(),console.log(l.gray("Commands:")),console.log(l.gray(` restore: leetcode snapshot restore ${e} <id|name>`)),console.log(l.gray(` diff: leetcode snapshot diff ${e} <id1> <id2>`)),console.log(l.gray(` delete: leetcode snapshot delete ${e} <id|name>`));}async function Gt(e,o){let t=w.getWorkDir();try{let n=W.get(e,o);if(!n){console.log(l.red(`Snapshot "${o}" not found for problem ${e}`)),console.log(l.gray("Run `leetcode snapshot list "+e+"` to see available snapshots."));return}let s=await H(t,e);if(!s){console.log(l.red(`No solution file found for problem ${e}`));return}let r=await readFile(s,"utf-8"),i=`backup-before-restore-${Date.now()}`,a=extname(s).slice(1),c=le(a)||a;W.save(e,"",r,c,i);let g=W.getCode(e,n);await writeFile(s,g,"utf-8"),console.log(l.green("\u2713 Snapshot restored!")),console.log(),console.log(` Restored: ${l.cyan(n.name)} (${n.lines} lines)`),console.log(` File: ${l.gray(s)}`),console.log(` Backup: ${l.gray(i)}`);}catch(n){console.log(l.red("Failed to restore snapshot")),n instanceof Error&&console.log(l.gray(n.message));}}async function Yt(e,o,t){try{let n=W.get(e,o),s=W.get(e,t);if(!n){console.log(l.red(`Snapshot "${o}" not found`));return}if(!s){console.log(l.red(`Snapshot "${t}" not found`));return}let r=W.getCode(e,n),i=W.getCode(e,s);console.log(),console.log(l.bold(`\u{1F4CA} Diff: ${n.name} \u2192 ${s.name}`)),console.log(l.gray("\u2500".repeat(50))),console.log();let a=diffLines(r,i),c=0,g=0;for(let u of a){let p=u.value.split(`
236
+ `).filter(b=>b!=="");if(u.added){c+=p.length;for(let b of p)console.log(l.green("+ "+b));}else if(u.removed){g+=p.length;for(let b of p)console.log(l.red("- "+b));}else if(p.length<=4)for(let b of p)console.log(l.gray(" "+b));else console.log(l.gray(" "+p[0])),console.log(l.gray(" "+p[1])),console.log(l.gray(` ... (${p.length-4} more lines)`)),console.log(l.gray(" "+p[p.length-2])),console.log(l.gray(" "+p[p.length-1]));}console.log(),console.log(l.gray("\u2500".repeat(50))),console.log(`${l.green("+"+c+" added")} ${l.gray("\xB7")} ${l.red("-"+g+" removed")} ${l.gray("\xB7")} ${l.gray(n.lines+" \u2192 "+s.lines+" lines")}`);}catch(n){console.log(l.red("Failed to diff snapshots")),n instanceof Error&&console.log(l.gray(n.message));}}async function Qt(e,o){let t=W.get(e,o);if(!t){console.log(l.red(`Snapshot "${o}" not found for problem ${e}`));return}let n=W.delete(e,o);console.log(n?l.green(`\u2713 Deleted snapshot: ${t.name}`):l.red("Failed to delete snapshot"));}function Kt(e,o){let t=e.split(`
237
+ `),n=t.length;console.log(),console.log(l.bold.cyan(`=== ${o} (${n} lines) ===`)),console.log(l.gray("\u2500".repeat(60))),t.forEach((s,r)=>{let i=(r+1).toString().padStart(3);console.log(l.gray(i+" \u2502 ")+s);});}function cr(e,o,t,n){let s=e.split(`
235
238
  `).length,r=o.split(`
236
239
  `).length;console.log(),console.log(l.bold(`\u{1F4CA} Unified Diff: ${t} \u2192 ${n}`)),console.log(l.gray("\u2500".repeat(60))),console.log();let i=diffLines(e,o),a=0,c=0;for(let g of i){let u=g.value.split(`
237
- `).filter(p=>p!=="");if(g.added){a+=u.length;for(let p of u)console.log(l.green("+ "+p));}else if(g.removed){c+=u.length;for(let p of u)console.log(l.red("- "+p));}else if(u.length<=6)for(let p of u)console.log(l.gray(" "+p));else console.log(l.gray(" "+u[0])),console.log(l.gray(" "+u[1])),console.log(l.dim(` ... (${u.length-4} unchanged lines)`)),console.log(l.gray(" "+u[u.length-2])),console.log(l.gray(" "+u[u.length-1]));}console.log(),console.log(l.gray("\u2500".repeat(60))),console.log(`${l.green("+"+a+" added")} ${l.gray("\xB7")} ${l.red("-"+c+" removed")} ${l.gray("\xB7")} ${l.gray(s+" \u2192 "+r+" lines")}`);}function so(e,o,t,n,s){if(s)er(e,o,t,n);else {Yt(e,t),Yt(o,n);let r=diffLines(e,o),i=0,a=0;for(let c of r){let g=c.value.split(`
238
- `).filter(u=>u!=="");c.added?i+=g.length:c.removed&&(a+=g.length);}console.log(),console.log(l.gray("\u2500".repeat(60))),console.log(`${l.bold("Summary:")} ${l.green("+"+i+" added")} ${l.gray("\xB7")} ${l.red("-"+a+" removed")}`),console.log(l.gray("Tip: Use --unified for line-by-line diff"));}}async function Jt(e,o){let{authorized:t}=await v();if(!t)return;let n=w.getWorkDir(),s=Ue("Finding solution file...").start();try{let r=await O(n,e);if(!r){s.fail(`No solution file found for problem ${e}`),console.log(l.gray("Run `leetcode pick "+e+"` first to create a solution file."));return}let i=await readFile(r,"utf-8");if(s.text="Fetching comparison target...",o.file){if(s.stop(),!existsSync(o.file)){console.log(l.red(`File not found: ${o.file}`));return}if(!me(o.file,n)){console.log(l.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(l.gray(`File: ${o.file}`)),console.log(l.gray(`Workspace: ${n}`)),console.log(l.yellow(`
239
- For security reasons, you can only diff files from within your workspace.`));return}let p=await readFile(o.file,"utf-8");so(i,p,"Your Solution",o.file,o.unified??!1);return}let a=await h.getProblemById(e);if(!a){s.fail(`Problem ${e} not found`);return}if(o.submission){let p=parseInt(o.submission,10),b=await h.getSubmissionDetails(p);s.stop(),so(i,b.code,"Your Solution",`Submission #${p}`,o.unified??!1);return}let g=(await h.getSubmissionList(a.titleSlug,50)).find(p=>p.statusDisplay==="Accepted");if(!g){s.fail("No accepted submissions found for this problem"),console.log(l.gray("Tip: Use --file to compare with a local file instead"));return}let u=await h.getSubmissionDetails(parseInt(g.id,10));s.stop(),so(i,u.code,"Your Solution","Last Accepted",o.unified??!1);}catch(r){s.fail("Failed to diff"),r instanceof Error&&console.log(l.red(r.message));}}async function Kt(){let e=$.getActive(),o=$.getConfig(e);console.log(),console.log(l.bold.cyan(`\u{1F4C1} Active Workspace: ${e}`)),console.log(l.gray("\u2500".repeat(40))),console.log(` workDir: ${l.white(o.workDir)}`),console.log(` lang: ${l.white(o.lang)}`),o.editor&&console.log(` editor: ${l.white(o.editor)}`),o.syncRepo&&console.log(` syncRepo: ${l.white(o.syncRepo)}`),console.log();}async function Xt(){let e=$.list(),o=$.getActive();console.log(),console.log(l.bold("Workspaces:")),console.log();for(let t of e){let n=$.getConfig(t),s=t===o?l.green("\u25B8 "):" ",r=t===o?l.green.bold(t):t;console.log(`${s}${r}`),console.log(` ${l.gray(n.workDir)}`);}console.log();}async function Zt(e,o){if($.exists(e)){console.log(l.red(`Workspace "${e}" already exists`));return}let t=o.workdir??join(homedir(),"leetcode",e),n={workDir:t,lang:"typescript"};$.create(e,n)?(console.log(l.green(`\u2713 Created workspace "${e}"`)),console.log(` workDir: ${l.gray(t)}`),console.log(),console.log(l.gray(`Switch to it: leetcode workspace use ${e}`))):console.log(l.red("Failed to create workspace"));}async function en(e){if(!$.exists(e)){console.log(l.red(`Workspace "${e}" not found`)),console.log(l.gray("Use `leetcode workspace list` to see available workspaces"));return}if($.setActive(e)){let t=$.getConfig(e);console.log(l.green(`\u2713 Switched to workspace "${e}"`)),console.log(` workDir: ${l.gray(t.workDir)}`);}else console.log(l.red("Failed to switch workspace"));}async function on(e){if(e==="default"){console.log(l.red("Cannot delete the default workspace"));return}if(!$.exists(e)){console.log(l.red(`Workspace "${e}" not found`));return}let{confirmed:o}=await oo.prompt([{type:"confirm",name:"confirmed",message:`Delete workspace "${e}"? (files in workDir will NOT be deleted)`,default:false}]);if(!o){console.log(l.gray("Cancelled"));return}let t=$.delete(e);console.log(t?l.green(`\u2713 Deleted workspace "${e}"`):l.red("Failed to delete workspace"));}var ro=join(homedir(),".leetcode"),Ce=join(ro,"version-cache.json"),cr=1440*60*1e3;function gr(){existsSync(ro)||mkdirSync(ro,{recursive:true});}function tn(){if(existsSync(Ce))try{return JSON.parse(readFileSync(Ce,"utf-8"))}catch{return null}return null}function mr(e){gr(),writeFileSync(Ce,JSON.stringify(e,null,2));}var se={shouldCheck(){let e=tn();return e?Date.now()-e.lastCheck>cr:true},getCached(){return tn()},updateCache(e,o){mr({lastCheck:Date.now(),latestVersion:e,hasBreakingChanges:o});},clearCache(){existsSync(Ce)&&unlinkSync(Ce);}};function ye(e,o){let t=e.replace("v","").split(".").map(Number),n=o.replace("v","").split(".").map(Number);for(let s=0;s<3;s++){let r=t[s]||0,i=n[s]||0;if(r>i)return true;if(r<i)return false}return false}function sn(e,o){let t=parseInt(e.replace("v","").split(".")[0])||0;return (parseInt(o.replace("v","").split(".")[0])||0)>t}var hr=fileURLToPath(import.meta.url),an=dirname(hr),br="https://registry.npmjs.org/@night-slayer18/leetcode-cli/latest",wr="@night-slayer18/leetcode-cli";function he(){let e=[join(an,"../package.json"),join(an,"../../package.json")];for(let o of e)try{let t=JSON.parse(readFileSync(o,"utf-8"));if(t.version)return t.version}catch{continue}throw new Error("Could not read package.json version. Ensure you are running from a valid installation.")}async function cn(){let o=(await wn(br,{timeout:{request:1e4},retry:{limit:2}}).json()).version,t=he(),n=sn(t,o);return {version:o,hasBreakingChanges:n}}function Sr(e,o,t){console.log();let n=60,s="\u256D"+"\u2500".repeat(n-2)+"\u256E",r="\u2570"+"\u2500".repeat(n-2)+"\u256F";console.log(l.cyan(s));let i=` \u{1F680} Update available: ${l.gray(e)} \u2192 ${l.green(o)}`;if(console.log(l.cyan("\u2502")+i.padEnd(n+18)+l.cyan("\u2502")),t){console.log(l.cyan("\u2502")+"".padEnd(n-2)+l.cyan("\u2502"));let c=` ${l.yellow("\u26A0\uFE0F This update contains breaking changes!")}`;console.log(l.cyan("\u2502")+c.padEnd(n+20)+l.cyan("\u2502"));let g=` ${l.gray("Run:")} leetcode changelog ${l.gray("to review changes")}`;console.log(l.cyan("\u2502")+g.padEnd(n+16)+l.cyan("\u2502"));}console.log(l.cyan("\u2502")+"".padEnd(n-2)+l.cyan("\u2502"));let a=` ${l.gray("Run:")} npm update -g ${wr}`;console.log(l.cyan("\u2502")+a.padEnd(n+8)+l.cyan("\u2502")),console.log(l.cyan(r)),console.log();}async function gn(e){let o=he();e.force&&se.clearCache();let t=se.getCached(),n,s;if(t&&!se.shouldCheck()&&!e.force)n=t.latestVersion,s=t.hasBreakingChanges;else {let r=Ue("Checking for updates...").start();try{let i=await cn();n=i.version,s=i.hasBreakingChanges,se.updateCache(n,s),r.stop();}catch(i){r.fail("Failed to check for updates"),process.env.DEBUG&&console.log(l.gray(` Debug: ${i instanceof Error?i.message:String(i)}`)),console.log(l.gray(" Could not reach npm registry. Check your internet connection."));return}}ye(o,n)?(Sr(o,n,s),e.checkOnly||s&&(console.log(l.yellow("\u{1F4A1} Tip: Review the changelog before updating to check for breaking changes.")),console.log(l.gray(` Run: leetcode changelog
240
- `)))):(console.log(),console.log(l.green("\u2713")+` You're on the latest version (${l.cyan(o)})`),console.log());}async function mn(){if(!se.shouldCheck()){let e=se.getCached();e&&ye(he(),e.latestVersion)&&ln(he(),e.latestVersion,e.hasBreakingChanges);return}try{let e=await cn();se.updateCache(e.version,e.hasBreakingChanges),ye(he(),e.version)&&ln(he(),e.version,e.hasBreakingChanges);}catch{}}function ln(e,o,t){console.log(),t?(console.log(l.yellow(`\u26A0\uFE0F Update ${e} \u2192 ${o} available (breaking changes!)`)),console.log(l.gray(" Run: leetcode changelog && leetcode update"))):(console.log(l.cyan(`\u{1F680} Update available: ${e} \u2192 ${o}`)),console.log(l.gray(" Run: leetcode update"))),console.log();}var Tr=fileURLToPath(import.meta.url),un=dirname(Tr),Dr="https://raw.githubusercontent.com/night-slayer18/leetcode-cli/main/docs/releases.md";function xr(){let e=[join(un,"../package.json"),join(un,"../../package.json")];for(let o of e)try{let t=JSON.parse(readFileSync(o,"utf-8"));if(t.version)return t.version}catch{continue}throw new Error("Could not read package.json version. Ensure you are running from a valid installation.")}async function Er(){return await wn(Dr,{timeout:{request:1e4},retry:{limit:2}}).text()}function Lr(e){let o=[],t=/^## v?([\d.]+)/gm,n=[...e.matchAll(t)];for(let s=0;s<n.length;s++){let r=n[s],i=`v${r[1]}`,a=r.index+r[0].length,c=s+1<n.length?n[s+1].index:e.length,g=e.slice(a,c).trim(),u=g.includes("\u26A0\uFE0F Breaking Change");o.push({version:i,content:g,hasBreakingChanges:u});}return o}function Ar(e,o,t){let n=t?l.bgRed.white.bold(` ${e} `)+l.red(" \u26A0\uFE0F BREAKING CHANGES"):l.bgCyan.black.bold(` ${e} `);console.log(n),console.log();let s=o.split(`
241
- `),r=false;for(let i of s)if(!(i.trim()===""&&!r)){if(i.startsWith("> **Release Date**")){let a=i.replace("> **Release Date**: ","").trim();console.log(l.gray(` \u{1F4C5} ${a}`));continue}if(i.startsWith("> **Focus**")){let a=i.replace("> **Focus**: ","").trim();console.log(l.gray(` \u{1F3AF} ${a}`)),console.log();continue}if(i.startsWith("### ")){let a=i.replace("### ","").trim();if(console.log(),/^[\u{1F300}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/u.test(a))console.log(l.bold.yellow(` ${a}`));else {let g="\u{1F4CC}";a.includes("Breaking")?g="\u26A0\uFE0F":a.includes("Feature")||a.includes("New")?g="\u{1F680}":a.includes("Fix")||a.includes("Bug")?g="\u{1F41B}":a.includes("Security")?g="\u{1F512}":a.includes("Improvement")?g="\u2728":a.includes("Architecture")?g="\u{1F3D7}\uFE0F":a.includes("Testing")?g="\u{1F9EA}":a.includes("Config")&&(g="\u2699\uFE0F"),console.log(l.bold.yellow(` ${g} ${a}`));}r=true;continue}if(i.startsWith("#### ")){let a=i.replace("#### ","").trim();console.log(l.bold.white(` ${a}`));continue}if(i.startsWith("- **")){let a=i.match(/^- \*\*(.+?)\*\*:?\s*(.*)/);console.log(a?l.cyan(` \u2022 ${l.bold(a[1])}`)+(a[2]?l.white(`: ${a[2]}`):""):l.cyan(` \u2022 ${i.replace("- ","")}`));continue}if(i.startsWith("- ")){let a=i.replace("- ","").trim();console.log(l.white(` \u2022 ${a}`));continue}i.startsWith("---")||i.trim()===">"||i.trim()&&console.log(l.gray(` ${i.trim()}`));}}async function pn(e,o={}){let t=Ue("Fetching changelog...").start();try{let n=await Er();t.stop();let s=Lr(n);if(s.length===0){console.log(l.yellow("No release entries found."));return}let r=xr(),i=s;if(e){let a=e.startsWith("v")?e:`v${e}`;if(i=s.filter(c=>c.version===a),i.length===0){console.log(l.red(`Version ${e} not found in changelog.`)),console.log(l.gray("Available versions: "+s.map(c=>c.version).join(", ")));return}}else if(o.latest)i=s.slice(0,1);else if(o.breaking){if(i=s.filter(a=>a.hasBreakingChanges),i.length===0){console.log(l.green("\u2713 No breaking changes in any release."));return}}else if(o.all)i=s;else {if(i=s.filter(a=>ye(a.version,r)),i.length===0){console.log(l.green(`\u2713 You're on the latest version (${r})`)),console.log(l.gray("Use --all to see the full changelog."));return}console.log(l.gray(`Showing changes since your version (${r})`)),console.log(l.gray("Use --all to see the full changelog."));}console.log(),console.log(l.bold.cyan("\u{1F4CB} LeetCode CLI Release Notes")),console.log(l.gray("\u2500".repeat(50))),console.log();for(let a of i)Ar(a.version,a.content,a.hasBreakingChanges),console.log(l.gray("\u2500".repeat(60))),console.log();if(!e&&!o.latest){let a=s.filter(c=>c.hasBreakingChanges).length;console.log(l.gray(`Showing ${i.length} of ${s.length} releases`)),a>0&&!o.breaking&&console.log(l.yellow(`${a} release(s) contain breaking changes. Use --breaking to filter.`));}}catch{t.fail("Failed to fetch changelog"),console.log(l.gray(" Could not fetch release notes from GitHub.")),console.log(l.gray(" Visit: https://github.com/night-slayer18/leetcode-cli/blob/main/docs/releases.md"));}}var T=new Command;T.configureHelp({sortSubcommands:true,subcommandTerm:e=>{let o=e.name(),t=e.alias(),n=t?`${o}|${t}`:o;return l.cyan(n.padEnd(16))},subcommandDescription:e=>l.white(e.description()),optionTerm:e=>l.yellow(e.flags),optionDescription:e=>l.white(e.description)});T.name("leetcode").usage("[command] [options]").description(l.bold.cyan("\u{1F525} A modern LeetCode CLI built with TypeScript")).version("2.1.1","-v, --version","Output the version number").helpOption("-h, --help","Display help for command").addHelpText("after",`
240
+ `).filter(p=>p!=="");if(g.added){a+=u.length;for(let p of u)console.log(l.green("+ "+p));}else if(g.removed){c+=u.length;for(let p of u)console.log(l.red("- "+p));}else if(u.length<=6)for(let p of u)console.log(l.gray(" "+p));else console.log(l.gray(" "+u[0])),console.log(l.gray(" "+u[1])),console.log(l.dim(` ... (${u.length-4} unchanged lines)`)),console.log(l.gray(" "+u[u.length-2])),console.log(l.gray(" "+u[u.length-1]));}console.log(),console.log(l.gray("\u2500".repeat(60))),console.log(`${l.green("+"+a+" added")} ${l.gray("\xB7")} ${l.red("-"+c+" removed")} ${l.gray("\xB7")} ${l.gray(s+" \u2192 "+r+" lines")}`);}function ro(e,o,t,n,s){if(s)cr(e,o,t,n);else {Kt(e,t),Kt(o,n);let r=diffLines(e,o),i=0,a=0;for(let c of r){let g=c.value.split(`
241
+ `).filter(u=>u!=="");c.added?i+=g.length:c.removed&&(a+=g.length);}console.log(),console.log(l.gray("\u2500".repeat(60))),console.log(`${l.bold("Summary:")} ${l.green("+"+i+" added")} ${l.gray("\xB7")} ${l.red("-"+a+" removed")}`),console.log(l.gray("Tip: Use --unified for line-by-line diff"));}}async function Zt(e,o){let{authorized:t}=await $();if(!t)return;let n=w.getWorkDir(),s=Ue("Finding solution file...").start();try{let r=await H(n,e);if(!r){s.fail(`No solution file found for problem ${e}`),console.log(l.gray("Run `leetcode pick "+e+"` first to create a solution file."));return}let i=await readFile(r,"utf-8");if(s.text="Fetching comparison target...",o.file){if(s.stop(),!existsSync(o.file)){console.log(l.red(`File not found: ${o.file}`));return}if(!de(o.file,n)){console.log(l.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(l.gray(`File: ${o.file}`)),console.log(l.gray(`Workspace: ${n}`)),console.log(l.yellow(`
242
+ For security reasons, you can only diff files from within your workspace.`));return}let p=await readFile(o.file,"utf-8");ro(i,p,"Your Solution",o.file,o.unified??!1);return}let a=await h.getProblemById(e);if(!a){s.fail(`Problem ${e} not found`);return}if(o.submission){let p=parseInt(o.submission,10),b=await h.getSubmissionDetails(p);s.stop(),ro(i,b.code,"Your Solution",`Submission #${p}`,o.unified??!1);return}let g=(await h.getSubmissionList(a.titleSlug,50)).find(p=>p.statusDisplay==="Accepted");if(!g){s.fail("No accepted submissions found for this problem"),console.log(l.gray("Tip: Use --file to compare with a local file instead"));return}let u=await h.getSubmissionDetails(parseInt(g.id,10));s.stop(),ro(i,u.code,"Your Solution","Last Accepted",o.unified??!1);}catch(r){s.fail("Failed to diff"),r instanceof Error&&console.log(l.red(r.message));}}async function en(){let e=k.getActive(),o=k.getConfig(e);console.log(),console.log(l.bold.cyan(`\u{1F4C1} Active Workspace: ${e}`)),console.log(l.gray("\u2500".repeat(40))),console.log(` workDir: ${l.white(o.workDir)}`),console.log(` lang: ${l.white(o.lang)}`),o.editor&&console.log(` editor: ${l.white(o.editor)}`),o.syncRepo&&console.log(` syncRepo: ${l.white(o.syncRepo)}`),console.log();}async function on(){let e=k.list(),o=k.getActive();console.log(),console.log(l.bold("Workspaces:")),console.log();for(let t of e){let n=k.getConfig(t),s=t===o?l.green("\u25B8 "):" ",r=t===o?l.green.bold(t):t;console.log(`${s}${r}`),console.log(` ${l.gray(n.workDir)}`);}console.log();}async function tn(e,o){if(k.exists(e)){console.log(l.red(`Workspace "${e}" already exists`));return}let t=o.workdir??join(homedir(),"leetcode",e),n={workDir:t,lang:"typescript"};k.create(e,n)?(console.log(l.green(`\u2713 Created workspace "${e}"`)),console.log(` workDir: ${l.gray(t)}`),console.log(),console.log(l.gray(`Switch to it: leetcode workspace use ${e}`))):console.log(l.red("Failed to create workspace"));}async function nn(e){if(!k.exists(e)){console.log(l.red(`Workspace "${e}" not found`)),console.log(l.gray("Use `leetcode workspace list` to see available workspaces"));return}if(k.setActive(e)){let t=k.getConfig(e);console.log(l.green(`\u2713 Switched to workspace "${e}"`)),console.log(` workDir: ${l.gray(t.workDir)}`);}else console.log(l.red("Failed to switch workspace"));}async function sn(e){if(e==="default"){console.log(l.red("Cannot delete the default workspace"));return}if(!k.exists(e)){console.log(l.red(`Workspace "${e}" not found`));return}let{confirmed:o}=await to.prompt([{type:"confirm",name:"confirmed",message:`Delete workspace "${e}"? (files in workDir will NOT be deleted)`,default:false}]);if(!o){console.log(l.gray("Cancelled"));return}let t=k.delete(e);console.log(t?l.green(`\u2713 Deleted workspace "${e}"`):l.red("Failed to delete workspace"));}var io=join(homedir(),".leetcode"),Pe=join(io,"version-cache.json"),br=1440*60*1e3;function wr(){existsSync(io)||mkdirSync(io,{recursive:true});}function rn(){if(existsSync(Pe))try{return JSON.parse(readFileSync(Pe,"utf-8"))}catch{return null}return null}function Sr(e){wr(),writeFileSync(Pe,JSON.stringify(e,null,2));}var re={shouldCheck(){let e=rn();return e?Date.now()-e.lastCheck>br:true},getCached(){return rn()},updateCache(e,o){Sr({lastCheck:Date.now(),latestVersion:e,hasBreakingChanges:o});},clearCache(){existsSync(Pe)&&unlinkSync(Pe);}};function he(e,o){let t=e.replace("v","").split(".").map(Number),n=o.replace("v","").split(".").map(Number);for(let s=0;s<3;s++){let r=t[s]||0,i=n[s]||0;if(r>i)return true;if(r<i)return false}return false}function ln(e,o){let t=parseInt(e.replace("v","").split(".")[0])||0;return (parseInt(o.replace("v","").split(".")[0])||0)>t}var Tr=fileURLToPath(import.meta.url),gn=dirname(Tr),Dr="https://registry.npmjs.org/@night-slayer18/leetcode-cli/latest",xr="@night-slayer18/leetcode-cli";function be(){let e=[join(gn,"../package.json"),join(gn,"../../package.json")];for(let o of e)try{let t=JSON.parse(readFileSync(o,"utf-8"));if(t.version)return t.version}catch{continue}throw new Error("Could not read package.json version. Ensure you are running from a valid installation.")}async function dn(){let o=(await kn(Dr,{timeout:{request:1e4},retry:{limit:2}}).json()).version,t=be(),n=ln(t,o);return {version:o,hasBreakingChanges:n}}function Er(e,o,t){console.log();let n=60,s="\u256D"+"\u2500".repeat(n-2)+"\u256E",r="\u2570"+"\u2500".repeat(n-2)+"\u256F";console.log(l.cyan(s));let i=` \u{1F680} Update available: ${l.gray(e)} \u2192 ${l.green(o)}`;if(console.log(l.cyan("\u2502")+i.padEnd(n+18)+l.cyan("\u2502")),t){console.log(l.cyan("\u2502")+"".padEnd(n-2)+l.cyan("\u2502"));let c=` ${l.yellow("\u26A0\uFE0F This update contains breaking changes!")}`;console.log(l.cyan("\u2502")+c.padEnd(n+20)+l.cyan("\u2502"));let g=` ${l.gray("Run:")} leetcode changelog ${l.gray("to review changes")}`;console.log(l.cyan("\u2502")+g.padEnd(n+16)+l.cyan("\u2502"));}console.log(l.cyan("\u2502")+"".padEnd(n-2)+l.cyan("\u2502"));let a=` ${l.gray("Run:")} npm update -g ${xr}`;console.log(l.cyan("\u2502")+a.padEnd(n+8)+l.cyan("\u2502")),console.log(l.cyan(r)),console.log();}async function un(e){let o=be();e.force&&re.clearCache();let t=re.getCached(),n,s;if(t&&!re.shouldCheck()&&!e.force)n=t.latestVersion,s=t.hasBreakingChanges;else {let r=Ue("Checking for updates...").start();try{let i=await dn();n=i.version,s=i.hasBreakingChanges,re.updateCache(n,s),r.stop();}catch(i){r.fail("Failed to check for updates"),process.env.DEBUG&&console.log(l.gray(` Debug: ${i instanceof Error?i.message:String(i)}`)),console.log(l.gray(" Could not reach npm registry. Check your internet connection."));return}}he(o,n)?(Er(o,n,s),e.checkOnly||s&&(console.log(l.yellow("\u{1F4A1} Tip: Review the changelog before updating to check for breaking changes.")),console.log(l.gray(` Run: leetcode changelog
243
+ `)))):(console.log(),console.log(l.green("\u2713")+` You're on the latest version (${l.cyan(o)})`),console.log());}async function pn(){if(!re.shouldCheck()){let e=re.getCached();e&&he(be(),e.latestVersion)&&mn(be(),e.latestVersion,e.hasBreakingChanges);return}try{let e=await dn();re.updateCache(e.version,e.hasBreakingChanges),he(be(),e.version)&&mn(be(),e.version,e.hasBreakingChanges);}catch{}}function mn(e,o,t){console.log(),t?(console.log(l.yellow(`\u26A0\uFE0F Update ${e} \u2192 ${o} available (breaking changes!)`)),console.log(l.gray(" Run: leetcode changelog && leetcode update"))):(console.log(l.cyan(`\u{1F680} Update available: ${e} \u2192 ${o}`)),console.log(l.gray(" Run: leetcode update"))),console.log();}var Nr=fileURLToPath(import.meta.url),yn=dirname(Nr),Ir="https://raw.githubusercontent.com/night-slayer18/leetcode-cli/main/docs/releases.md";function Ur(){let e=[join(yn,"../package.json"),join(yn,"../../package.json")];for(let o of e)try{let t=JSON.parse(readFileSync(o,"utf-8"));if(t.version)return t.version}catch{continue}throw new Error("Could not read package.json version. Ensure you are running from a valid installation.")}async function jr(){return await kn(Ir,{timeout:{request:1e4},retry:{limit:2}}).text()}function Mr(e){let o=[],t=/^## v?([\d.]+)/gm,n=[...e.matchAll(t)];for(let s=0;s<n.length;s++){let r=n[s],i=`v${r[1]}`,a=r.index+r[0].length,c=s+1<n.length?n[s+1].index:e.length,g=e.slice(a,c).trim(),u=g.includes("\u26A0\uFE0F Breaking Change");o.push({version:i,content:g,hasBreakingChanges:u});}return o}function qr(e,o,t){let n=t?l.bgRed.white.bold(` ${e} `)+l.red(" \u26A0\uFE0F BREAKING CHANGES"):l.bgCyan.black.bold(` ${e} `);console.log(n),console.log();let s=o.split(`
244
+ `),r=false;for(let i of s)if(!(i.trim()===""&&!r)){if(i.startsWith("> **Release Date**")){let a=i.replace("> **Release Date**: ","").trim();console.log(l.gray(` \u{1F4C5} ${a}`));continue}if(i.startsWith("> **Focus**")){let a=i.replace("> **Focus**: ","").trim();console.log(l.gray(` \u{1F3AF} ${a}`)),console.log();continue}if(i.startsWith("### ")){let a=i.replace("### ","").trim();if(console.log(),/^[\u{1F300}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/u.test(a))console.log(l.bold.yellow(` ${a}`));else {let g="\u{1F4CC}";a.includes("Breaking")?g="\u26A0\uFE0F":a.includes("Feature")||a.includes("New")?g="\u{1F680}":a.includes("Fix")||a.includes("Bug")?g="\u{1F41B}":a.includes("Security")?g="\u{1F512}":a.includes("Improvement")?g="\u2728":a.includes("Architecture")?g="\u{1F3D7}\uFE0F":a.includes("Testing")?g="\u{1F9EA}":a.includes("Config")&&(g="\u2699\uFE0F"),console.log(l.bold.yellow(` ${g} ${a}`));}r=true;continue}if(i.startsWith("#### ")){let a=i.replace("#### ","").trim();console.log(l.bold.white(` ${a}`));continue}if(i.startsWith("- **")){let a=i.match(/^- \*\*(.+?)\*\*:?\s*(.*)/);console.log(a?l.cyan(` \u2022 ${l.bold(a[1])}`)+(a[2]?l.white(`: ${a[2]}`):""):l.cyan(` \u2022 ${i.replace("- ","")}`));continue}if(i.startsWith("- ")){let a=i.replace("- ","").trim();console.log(l.white(` \u2022 ${a}`));continue}i.startsWith("---")||i.trim()===">"||i.trim()&&console.log(l.gray(` ${i.trim()}`));}}async function hn(e,o={}){let t=Ue("Fetching changelog...").start();try{let n=await jr();t.stop();let s=Mr(n);if(s.length===0){console.log(l.yellow("No release entries found."));return}let r=Ur(),i=s;if(e){let a=e.startsWith("v")?e:`v${e}`;if(i=s.filter(c=>c.version===a),i.length===0){console.log(l.red(`Version ${e} not found in changelog.`)),console.log(l.gray("Available versions: "+s.map(c=>c.version).join(", ")));return}}else if(o.latest)i=s.slice(0,1);else if(o.breaking){if(i=s.filter(a=>a.hasBreakingChanges),i.length===0){console.log(l.green("\u2713 No breaking changes in any release."));return}}else if(o.all)i=s;else {if(i=s.filter(a=>he(a.version,r)),i.length===0){console.log(l.green(`\u2713 You're on the latest version (${r})`)),console.log(l.gray("Use --all to see the full changelog."));return}console.log(l.gray(`Showing changes since your version (${r})`)),console.log(l.gray("Use --all to see the full changelog."));}console.log(),console.log(l.bold.cyan("\u{1F4CB} LeetCode CLI Release Notes")),console.log(l.gray("\u2500".repeat(50))),console.log();for(let a of i)qr(a.version,a.content,a.hasBreakingChanges),console.log(l.gray("\u2500".repeat(60))),console.log();if(!e&&!o.latest){let a=s.filter(c=>c.hasBreakingChanges).length;console.log(l.gray(`Showing ${i.length} of ${s.length} releases`)),a>0&&!o.breaking&&console.log(l.yellow(`${a} release(s) contain breaking changes. Use --breaking to filter.`));}}catch{t.fail("Failed to fetch changelog"),console.log(l.gray(" Could not fetch release notes from GitHub.")),console.log(l.gray(" Visit: https://github.com/night-slayer18/leetcode-cli/blob/main/docs/releases.md"));}}var C=new Command;C.configureHelp({sortSubcommands:true,subcommandTerm:e=>{let o=e.name(),t=e.alias(),n=t?`${o}|${t}`:o;return l.cyan(n.padEnd(16))},subcommandDescription:e=>l.white(e.description()),optionTerm:e=>l.yellow(e.flags),optionDescription:e=>l.white(e.description)});C.name("leetcode").usage("[command] [options]").description(l.bold.cyan("\u{1F525} A modern LeetCode CLI built with TypeScript")).version("2.2.1","-v, --version","Output the version number").helpOption("-h, --help","Display help for command").addHelpText("after",`
242
245
  ${l.yellow("Examples:")}
243
246
  ${l.cyan("$ leetcode login")} Login to LeetCode
244
247
  ${l.cyan("$ leetcode list -d easy")} List easy problems
@@ -246,14 +249,14 @@ ${l.yellow("Examples:")}
246
249
  ${l.cyan("$ leetcode pick 1")} Start solving "Two Sum"
247
250
  ${l.cyan("$ leetcode test 1")} Test your solution
248
251
  ${l.cyan("$ leetcode submit 1")} Submit your solution
249
- `);T.command("login").description("Login to LeetCode with browser cookies").addHelpText("after",`
252
+ `);C.command("login").description("Login to LeetCode with browser cookies").addHelpText("after",`
250
253
  ${l.yellow("How to login:")}
251
254
  1. Open ${l.cyan("https://leetcode.com")} in your browser
252
255
  2. Login to your account
253
256
  3. Open Developer Tools (F12) \u2192 Application \u2192 Cookies
254
257
  4. Copy values of ${l.green("LEETCODE_SESSION")} and ${l.green("csrftoken")}
255
258
  5. Paste when prompted by this command
256
- `).action(Do);T.command("logout").description("Clear stored credentials").action(xo);T.command("whoami").description("Check current login status").action(Eo);T.command("list").alias("l").description("List LeetCode problems").option("-d, --difficulty <level>","Filter by difficulty (easy/medium/hard)").option("-s, --status <status>","Filter by status (todo/solved/attempted)").option("-t, --tag <tags...>","Filter by topic tags").option("-q, --search <keywords>","Search by keywords").option("-n, --limit <number>","Number of problems to show","20").option("-p, --page <number>","Page number","1").addHelpText("after",`
259
+ `).action(xo);C.command("logout").description("Clear stored credentials").action(Eo);C.command("whoami").description("Check current login status").action(Lo);C.command("list").alias("l").description("List LeetCode problems").option("-d, --difficulty <level>","Filter by difficulty (easy/medium/hard)").option("-s, --status <status>","Filter by status (todo/solved/attempted)").option("-t, --tag <tags...>","Filter by topic tags").option("-q, --search <keywords>","Search by keywords").option("-n, --limit <number>","Number of problems to show","20").option("-p, --page <number>","Page number","1").addHelpText("after",`
257
260
  ${l.yellow("Examples:")}
258
261
  ${l.cyan("$ leetcode list")} List first 20 problems
259
262
  ${l.cyan("$ leetcode list -d easy")} List easy problems only
@@ -261,23 +264,31 @@ ${l.yellow("Examples:")}
261
264
  ${l.cyan("$ leetcode list -t array -t string")} Filter by multiple tags
262
265
  ${l.cyan('$ leetcode list -q "two sum"')} Search by keywords
263
266
  ${l.cyan("$ leetcode list -n 50 -p 2")} Show 50 problems, page 2
264
- `).action(Wo);T.command("show <id>").alias("s").description("Show problem description").addHelpText("after",`
267
+ `).action(Wo);C.command("show <id>").alias("s").description("Show problem description").addHelpText("after",`
265
268
  ${l.yellow("Examples:")}
266
269
  ${l.cyan("$ leetcode show 1")} Show by problem ID
267
270
  ${l.cyan("$ leetcode show two-sum")} Show by problem slug
268
271
  ${l.cyan("$ leetcode s 412")} Short alias
269
- `).action(Re);T.command("daily").alias("d").description("Show today's daily challenge").addHelpText("after",`
272
+ `).action(Re);C.command("hint <id>").alias("h").description("Show hints for a problem").option("-a, --all","Show all hints at once").addHelpText("after",`
273
+ ${l.yellow("Examples:")}
274
+ ${l.cyan("$ leetcode hint 1")} Show hints for problem 1
275
+ ${l.cyan("$ leetcode hint two-sum")} Show hints by slug
276
+ ${l.cyan("$ leetcode hint 1 --all")} Show all hints at once
277
+ ${l.cyan("$ leetcode h 412")} Short alias
278
+
279
+ ${l.gray("Hints are revealed one at a time. Press Enter to see more.")}
280
+ `).action(Vo);C.command("daily").alias("d").description("Show today's daily challenge").addHelpText("after",`
270
281
  ${l.yellow("Examples:")}
271
282
  ${l.cyan("$ leetcode daily")} Show today's challenge
272
283
  ${l.cyan("$ leetcode d")} Short alias
273
- `).action(mt);T.command("random").alias("r").description("Get a random problem").option("-d, --difficulty <level>","Filter by difficulty (easy/medium/hard)").option("-t, --tag <tag>","Filter by topic tag").option("--pick","Auto-generate solution file").option("--no-open","Do not open file in editor").addHelpText("after",`
284
+ `).action(pt);C.command("random").alias("r").description("Get a random problem").option("-d, --difficulty <level>","Filter by difficulty (easy/medium/hard)").option("-t, --tag <tag>","Filter by topic tag").option("--pick","Auto-generate solution file").option("--no-open","Do not open file in editor").addHelpText("after",`
274
285
  ${l.yellow("Examples:")}
275
286
  ${l.cyan("$ leetcode random")} Get any random problem
276
287
  ${l.cyan("$ leetcode random -d medium")} Random medium problem
277
288
  ${l.cyan("$ leetcode random -t array")} Random array problem
278
289
  ${l.cyan("$ leetcode random --pick")} Random + create file
279
290
  ${l.cyan("$ leetcode r -d easy --pick")} Random easy + file
280
- `).action(dt);T.command("pick <id>").alias("p").description("Generate solution file for a problem").option("-l, --lang <language>","Programming language for the solution").option("--no-open","Do not open file in editor").addHelpText("after",`
291
+ `).action(ft);C.command("pick <id>").alias("p").description("Generate solution file for a problem").option("-l, --lang <language>","Programming language for the solution").option("--no-open","Do not open file in editor").addHelpText("after",`
281
292
  ${l.yellow("Examples:")}
282
293
  ${l.cyan("$ leetcode pick 1")} Pick by problem ID
283
294
  ${l.cyan("$ leetcode pick two-sum")} Pick by problem slug
@@ -286,11 +297,11 @@ ${l.yellow("Examples:")}
286
297
  ${l.cyan("$ leetcode p 412")} Short alias
287
298
 
288
299
  ${l.gray("Files are organized by: workDir/Difficulty/Category/")}
289
- `).action(async(e,o)=>{await Y(e,o);});T.command("pick-batch <ids...>").description("Generate solution files for multiple problems").option("-l, --lang <language>","Programming language for the solutions").addHelpText("after",`
300
+ `).action(async(e,o)=>{await Q(e,o);});C.command("pick-batch <ids...>").description("Generate solution files for multiple problems").option("-l, --lang <language>","Programming language for the solutions").addHelpText("after",`
290
301
  ${l.yellow("Examples:")}
291
302
  ${l.cyan("$ leetcode pick-batch 1 2 3")} Pick problems 1, 2, and 3
292
303
  ${l.cyan("$ leetcode pick-batch 1 2 3 -l py")} Pick with Python
293
- `).action(Qo);T.command("test <file>").alias("t").description("Test solution against sample test cases").option("-c, --testcase <testcase>","Custom test case").option("-V, --visualize","Visual output for data structures (arrays, trees, etc.)").addHelpText("after",`
304
+ `).action(Xo);C.command("test <file>").alias("t").description("Test solution against sample test cases").option("-c, --testcase <testcase>","Custom test case").option("-V, --visualize","Visual output for data structures (arrays, trees, etc.)").addHelpText("after",`
294
305
  ${l.yellow("Examples:")}
295
306
  ${l.cyan("$ leetcode test 1")} Test by problem ID
296
307
  ${l.cyan("$ leetcode test two-sum")} Test by problem slug
@@ -300,25 +311,25 @@ ${l.yellow("Examples:")}
300
311
  ${l.cyan("$ leetcode t 412")} Short alias
301
312
 
302
313
  ${l.gray("Testcases use \\n to separate multiple inputs.")}
303
- `).action(tt);T.command("submit <file>").alias("x").description("Submit solution to LeetCode").addHelpText("after",`
314
+ `).action(rt);C.command("submit <file>").alias("x").description("Submit solution to LeetCode").addHelpText("after",`
304
315
  ${l.yellow("Examples:")}
305
316
  ${l.cyan("$ leetcode submit 1")} Submit by problem ID
306
317
  ${l.cyan("$ leetcode submit two-sum")} Submit by problem slug
307
318
  ${l.cyan("$ leetcode submit ./path/to/file.py")} Submit by file path
308
319
  ${l.cyan("$ leetcode x 412")} Short alias
309
- `).action(rt);T.command("diff <id>").description("Compare solution with past submissions").option("-s, --submission <id>","Compare with specific submission ID").option("-f, --file <path>","Compare with a local file").option("-u, --unified","Show unified diff (line-by-line changes)").addHelpText("after",`
320
+ `).action(lt);C.command("diff <id>").description("Compare solution with past submissions").option("-s, --submission <id>","Compare with specific submission ID").option("-f, --file <path>","Compare with a local file").option("-u, --unified","Show unified diff (line-by-line changes)").addHelpText("after",`
310
321
  ${l.yellow("Examples:")}
311
322
  ${l.cyan("$ leetcode diff 1")} Compare with last accepted
312
323
  ${l.cyan("$ leetcode diff 1 -u")} Show unified diff
313
324
  ${l.cyan("$ leetcode diff 1 -s 12345")} Compare with specific submission
314
325
  ${l.cyan("$ leetcode diff 1 -f other.py")} Compare with local file
315
- `).action(Jt);T.command("submissions <id>").description("View past submissions").option("-n, --limit <number>","Number of submissions to show","20").option("--last","Show details of the last accepted submission").option("--download","Download the last accepted submission code").addHelpText("after",`
326
+ `).action(Zt);C.command("submissions <id>").description("View past submissions").option("-n, --limit <number>","Number of submissions to show","20").option("--last","Show details of the last accepted submission").option("--download","Download the last accepted submission code").addHelpText("after",`
316
327
  ${l.yellow("Examples:")}
317
328
  ${l.cyan("$ leetcode submissions 1")} View submissions for problem
318
329
  ${l.cyan("$ leetcode submissions 1 -n 5")} Show last 5 submissions
319
330
  ${l.cyan("$ leetcode submissions 1 --last")} Show last accepted submission
320
331
  ${l.cyan("$ leetcode submissions 1 --download")} Download last accepted code
321
- `).action(ft);T.command("stat [username]").description("Show user statistics and analytics").option("-c, --calendar","Weekly activity summary (submissions & active days for last 12 weeks)").option("-s, --skills","Skill breakdown (problems solved grouped by topic tags)").option("-t, --trend","Daily trend chart (bar graph of submissions for last 7 days)").addHelpText("after",`
332
+ `).action(bt);C.command("stat [username]").description("Show user statistics and analytics").option("-c, --calendar","Weekly activity summary (submissions & active days for last 12 weeks)").option("-s, --skills","Skill breakdown (problems solved grouped by topic tags)").option("-t, --trend","Daily trend chart (bar graph of submissions for last 7 days)").addHelpText("after",`
322
333
  ${l.yellow("Options Explained:")}
323
334
  ${l.cyan("-c, --calendar")} Shows a table of your weekly submissions and active days
324
335
  for the past 12 weeks. Useful for tracking consistency.
@@ -336,10 +347,10 @@ ${l.yellow("Examples:")}
336
347
  ${l.cyan("$ leetcode stat -c")} Weekly activity table
337
348
  ${l.cyan("$ leetcode stat -s")} Topic-wise breakdown
338
349
  ${l.cyan("$ leetcode stat -t")} 7-day trend chart
339
- `).action((e,o)=>gt(e,o));T.command("today").description("Show today's progress summary").addHelpText("after",`
350
+ `).action((e,o)=>ut(e,o));C.command("today").description("Show today's progress summary").addHelpText("after",`
340
351
  ${l.yellow("Examples:")}
341
352
  ${l.cyan("$ leetcode today")} Show streak, solved, and daily challenge
342
- `).action(kt);T.command("bookmark <action> [id]").description("Manage problem bookmarks").addHelpText("after",`
353
+ `).action(Pt);C.command("bookmark <action> [id]").description("Manage problem bookmarks").addHelpText("after",`
343
354
  ${l.yellow("Actions:")}
344
355
  ${l.cyan("add <id>")} Bookmark a problem
345
356
  ${l.cyan("remove <id>")} Remove a bookmark
@@ -350,7 +361,7 @@ ${l.yellow("Examples:")}
350
361
  ${l.cyan("$ leetcode bookmark add 1")} Bookmark problem 1
351
362
  ${l.cyan("$ leetcode bookmark remove 1")} Remove bookmark
352
363
  ${l.cyan("$ leetcode bookmark list")} List all bookmarks
353
- `).action(wt);T.command("note <id> [action]").description("View or edit notes for a problem").addHelpText("after",`
364
+ `).action(kt);C.command("note <id> [action]").description("View or edit notes for a problem").addHelpText("after",`
354
365
  ${l.yellow("Actions:")}
355
366
  ${l.cyan("edit")} Open notes in editor (default)
356
367
  ${l.cyan("view")} Display notes in terminal
@@ -359,10 +370,10 @@ ${l.yellow("Examples:")}
359
370
  ${l.cyan("$ leetcode note 1")} Edit notes for problem 1
360
371
  ${l.cyan("$ leetcode note 1 edit")} Edit notes (explicit)
361
372
  ${l.cyan("$ leetcode note 1 view")} View notes in terminal
362
- `).action($t);T.command("sync").description("Sync solutions to Git repository").addHelpText("after",`
373
+ `).action(Ct);C.command("sync").description("Sync solutions to Git repository").addHelpText("after",`
363
374
  ${l.yellow("Examples:")}
364
375
  ${l.cyan("$ leetcode sync")} Sync all solutions to remote
365
- `).action(Ct);T.command("config").description("View or set configuration").option("-l, --lang <language>","Set default programming language").option("-e, --editor <editor>","Set editor command").option("-w, --workdir <path>","Set working directory for solutions").option("-r, --repo <url>","Set Git repository URL").option("-i, --interactive","Interactive configuration").addHelpText("after",`
376
+ `).action(Dt);C.command("config").description("View or set configuration").option("-l, --lang <language>","Set default programming language").option("-e, --editor <editor>","Set editor command").option("-w, --workdir <path>","Set working directory for solutions").option("-r, --repo <url>","Set Git repository URL").option("-i, --interactive","Interactive configuration").addHelpText("after",`
366
377
  ${l.yellow("Examples:")}
367
378
  ${l.cyan("$ leetcode config")} View current config
368
379
  ${l.cyan("$ leetcode config -l python3")} Set language to Python
@@ -372,7 +383,7 @@ ${l.yellow("Examples:")}
372
383
  ${l.cyan("$ leetcode config -i")} Interactive setup
373
384
 
374
385
  ${l.gray("Supported languages: typescript, javascript, python3, java, cpp, c, csharp, go, rust, kotlin, swift")}
375
- `).action(async e=>{e.interactive?await ht():await yt(e);});T.command("timer [id]").description("Start interview mode with timer").option("-m, --minutes <minutes>","Custom time limit in minutes").option("--stats","Show solve time statistics").option("--stop","Stop active timer").addHelpText("after",`
386
+ `).action(async e=>{e.interactive?await St():await wt(e);});C.command("timer [id]").description("Start interview mode with timer").option("-m, --minutes <minutes>","Custom time limit in minutes").option("--stats","Show solve time statistics").option("--stop","Stop active timer").addHelpText("after",`
376
387
  ${l.yellow("How it works:")}
377
388
  Start a problem with a countdown timer to simulate interview conditions.
378
389
  Default time limits: Easy (20 min), Medium (40 min), Hard (60 min).
@@ -383,7 +394,7 @@ ${l.yellow("Examples:")}
383
394
  ${l.cyan("$ leetcode timer 1 -m 30")} Start with 30 minute limit
384
395
  ${l.cyan("$ leetcode timer --stats")} Show your solve time statistics
385
396
  ${l.cyan("$ leetcode timer --stop")} Stop active timer
386
- `).action((e,o)=>Pt(e,o));var Pe=T.command("workspace").description("Manage workspaces for different contexts");Pe.command("current").description("Show current workspace").action(Kt);Pe.command("list").description("List all workspaces").action(Xt);Pe.command("create <name>").description("Create a new workspace").option("-w, --workdir <path>","Set working directory for this workspace").action(Zt);Pe.command("use <name>").description("Switch to a workspace").action(en);Pe.command("delete <name>").description("Delete a workspace").action(on);var be=T.command("collab").description("Collaborative coding with a partner").addHelpText("after",`
397
+ `).action((e,o)=>xt(e,o));var Te=C.command("workspace").description("Manage workspaces for different contexts");Te.command("current").description("Show current workspace").action(en);Te.command("list").description("List all workspaces").action(on);Te.command("create <name>").description("Create a new workspace").option("-w, --workdir <path>","Set working directory for this workspace").action(tn);Te.command("use <name>").description("Switch to a workspace").action(nn);Te.command("delete <name>").description("Delete a workspace").action(sn);var we=C.command("collab").description("Collaborative coding with a partner").addHelpText("after",`
387
398
  ${l.yellow("Subcommands:")}
388
399
  ${l.cyan("host <id>")} Create a room and get a code to share
389
400
  ${l.cyan("join <code>")} Join a room with the shared code
@@ -397,7 +408,7 @@ ${l.yellow("Examples:")}
397
408
  ${l.gray("$ leetcode collab join ABC123")} Join your partner's session
398
409
  ${l.gray("$ leetcode collab sync")} Upload your code after solving
399
410
  ${l.gray("$ leetcode collab compare")} Compare solutions
400
- `);be.command("host <problemId>").description("Host a collaboration session").action(xt);be.command("join <roomCode>").description("Join a collaboration session").action(Et);be.command("sync").description("Sync your code with partner").action(Lt);be.command("compare").description("Compare your solution with partner").action(At);be.command("leave").description("Leave the collaboration session").action(Rt);be.command("status").description("Show collaboration status").action(_t);var Te=T.command("snapshot").description("Save and restore solution versions").addHelpText("after",`
411
+ `);we.command("host <problemId>").description("Host a collaboration session").action(At);we.command("join <roomCode>").description("Join a collaboration session").action(Rt);we.command("sync").description("Sync your code with partner").action(Ft);we.command("compare").description("Compare your solution with partner").action(_t);we.command("leave").description("Leave the collaboration session").action(Nt);we.command("status").description("Show collaboration status").action(It);var De=C.command("snapshot").description("Save and restore solution versions").addHelpText("after",`
401
412
  ${l.yellow("Subcommands:")}
402
413
  ${l.cyan("save <id> [name]")} Save current solution as a snapshot
403
414
  ${l.cyan("list <id>")} List all snapshots for a problem
@@ -410,16 +421,16 @@ ${l.yellow("Examples:")}
410
421
  ${l.gray("$ leetcode snapshot list 1")} List snapshots
411
422
  ${l.gray("$ leetcode snapshot restore 1 2")} Restore snapshot #2
412
423
  ${l.gray("$ leetcode snapshot diff 1 1 2")} Compare snapshots
413
- `);Te.command("save <id> [name]").description("Save current solution as a snapshot").action(Wt);Te.command("list <id>").description("List all snapshots for a problem").action(Ht);Te.command("restore <id> <snapshot>").description("Restore a snapshot").action(Vt);Te.command("diff <id> <snap1> <snap2>").description("Compare two snapshots").action(zt);Te.command("delete <id> <snapshot>").description("Delete a snapshot").action(Bt);T.command("update").description("Check for CLI updates").option("--check-only","Only check for updates, do not show update instructions").option("-f, --force","Force check even if recently checked").addHelpText("after",`
424
+ `);De.command("save <id> [name]").description("Save current solution as a snapshot").action(zt);De.command("list <id>").description("List all snapshots for a problem").action(Bt);De.command("restore <id> <snapshot>").description("Restore a snapshot").action(Gt);De.command("diff <id> <snap1> <snap2>").description("Compare two snapshots").action(Yt);De.command("delete <id> <snapshot>").description("Delete a snapshot").action(Qt);C.command("update").description("Check for CLI updates").option("--check-only","Only check for updates, do not show update instructions").option("-f, --force","Force check even if recently checked").addHelpText("after",`
414
425
  ${l.yellow("Examples:")}
415
426
  ${l.cyan("$ leetcode update")} Check for updates
416
427
  ${l.cyan("$ leetcode update --force")} Force re-check npm registry
417
428
  ${l.cyan("$ leetcode update --check-only")} Just check, minimal output
418
- `).action(gn);T.command("changelog [version]").description("View release notes and changelog").option("--latest","Show only the latest version").option("--breaking","Show only versions with breaking changes").option("-a, --all","Show all versions (default: only newer than installed)").addHelpText("after",`
429
+ `).action(un);C.command("changelog [version]").description("View release notes and changelog").option("--latest","Show only the latest version").option("--breaking","Show only versions with breaking changes").option("-a, --all","Show all versions (default: only newer than installed)").addHelpText("after",`
419
430
  ${l.yellow("Examples:")}
420
431
  ${l.cyan("$ leetcode changelog")} Show what's new since your version
421
432
  ${l.cyan("$ leetcode changelog --all")} View full changelog
422
433
  ${l.cyan("$ leetcode changelog 2.0.0")} Show specific version
423
434
  ${l.cyan("$ leetcode changelog --latest")} Show latest version only
424
435
  ${l.cyan("$ leetcode changelog --breaking")} Filter to breaking changes
425
- `).action((e,o)=>pn(e,o));T.showHelpAfterError("(add --help for additional information)");var _r=process.argv.length>2&&!["update","changelog","--version","-v","--help","-h"].includes(process.argv[2]);_r&&mn().catch(()=>{});T.parse();process.argv.slice(2).length||(console.log(),console.log(l.bold.cyan(" \u{1F525} LeetCode CLI")),console.log(l.gray(" A modern command-line interface for LeetCode")),console.log(),T.outputHelp());
436
+ `).action((e,o)=>hn(e,o));C.showHelpAfterError("(add --help for additional information)");var Hr=process.argv.length>2&&!["update","changelog","--version","-v","--help","-h"].includes(process.argv[2]);Hr&&pn().catch(()=>{});C.parse();process.argv.slice(2).length||(console.log(),console.log(l.bold.cyan(" \u{1F525} LeetCode CLI")),console.log(l.gray(" A modern command-line interface for LeetCode")),console.log(),C.outputHelp());
@@ -0,0 +1,28 @@
1
+ import tseslint from '@typescript-eslint/eslint-plugin';
2
+ import tsParser from '@typescript-eslint/parser';
3
+
4
+ export default [
5
+ {
6
+ files: ['src/**/*.ts'],
7
+ languageOptions: {
8
+ parser: tsParser,
9
+ parserOptions: {
10
+ ecmaVersion: 'latest',
11
+ sourceType: 'module',
12
+ },
13
+ },
14
+ plugins: {
15
+ '@typescript-eslint': tseslint,
16
+ },
17
+ rules: {
18
+ ...tseslint.configs.recommended.rules,
19
+ '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
20
+ '@typescript-eslint/no-explicit-any': 'warn',
21
+ '@typescript-eslint/explicit-function-return-type': 'off',
22
+ 'no-console': 'off',
23
+ },
24
+ },
25
+ {
26
+ ignores: ['dist/**', 'node_modules/**', '**/*.js'],
27
+ },
28
+ ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@night-slayer18/leetcode-cli",
3
- "version": "2.1.1",
3
+ "version": "2.2.1",
4
4
  "description": "A modern LeetCode CLI built with TypeScript",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -49,13 +49,18 @@
49
49
  "marked-terminal": "^7.2.1",
50
50
  "open": "^11.0.0",
51
51
  "ora": "^8.1.1",
52
+ "striptags": "^3.2.0",
52
53
  "zod": "^4.3.5"
53
54
  },
54
55
  "devDependencies": {
55
56
  "@types/diff": "^7.0.2",
56
57
  "@types/inquirer": "^9.0.7",
57
58
  "@types/node": "^22.10.2",
59
+ "@types/striptags": "^0.0.5",
60
+ "@typescript-eslint/eslint-plugin": "^8.53.0",
61
+ "@typescript-eslint/parser": "^8.53.0",
58
62
  "@vitest/coverage-v8": "^4.0.16",
63
+ "eslint": "^9.39.2",
59
64
  "tsup": "^8.3.5",
60
65
  "typescript": "^5.7.2",
61
66
  "vitest": "^4.0.16"