@night-slayer18/leetcode-cli 2.4.1 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -19
- package/dist/index.js +111 -101
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {Command}from'commander';import f from'chalk';import
|
|
2
|
+
import {Command}from'commander';import f from'chalk';import Jn from'inquirer';import nn from'ora';import Zi from'got';import {z}from'zod';import {randomBytes,createCipheriv,scryptSync,createDecipheriv}from'crypto';import {existsSync,writeFileSync,readFileSync,unlinkSync,mkdirSync,chmodSync}from'fs';import Mn from'keytar';import {homedir}from'os';import*as Ae from'path';import Ae__default,{join,dirname,basename,extname,resolve,sep}from'path';import $n from'cli-table3';import ba from'striptags';import*as ve from'fs/promises';import {mkdir,writeFile,readFile,readdir}from'fs/promises';import {execSync,execFileSync,spawn}from'child_process';import Fa from'open';import cl from'conf';import {createClient}from'@supabase/supabase-js';import {diffLines}from'diff';import {fileURLToPath}from'url';import {stdin,stdout}from'process';import Sn from'ansi-escapes';import En from'cli-cursor';var zi=Object.defineProperty;var Yi=(e,t)=>{for(var n in t)zi(e,n,{get:t[n],enumerable:true});};var Qi=z.object({name:z.string(),slug:z.string()}),Ji=z.object({name:z.string(),slug:z.string()}),Xi=z.object({lang:z.string(),langSlug:z.string(),code:z.string()}),Ft=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(Qi),status:z.enum(["ac","notac"]).nullable()}),Do=Ft.extend({content:z.string().nullable(),codeSnippets:z.array(Xi).nullable(),sampleTestCase:z.string(),exampleTestcases:z.string(),hints:z.array(z.string()),companyTags:z.array(Ji).nullable(),stats:z.string()}),Io=z.object({date:z.string(),link:z.string(),question:Ft}),No=z.object({id:z.string(),statusDisplay:z.string(),lang:z.string(),runtime:z.string(),timestamp:z.string(),memory:z.string()}),Fo=z.object({code:z.string(),lang:z.object({name:z.string()})}),Ho=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()}),Bo=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()}),Uo=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()})}),Wo=z.object({isSignedIn:z.boolean(),username:z.string().nullable()});var Go=`
|
|
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 f from'chalk';import $o from'inquirer';im
|
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
|
-
`,
|
|
27
|
+
`,jo=`
|
|
28
28
|
query questionData($titleSlug: String!) {
|
|
29
29
|
question(titleSlug: $titleSlug) {
|
|
30
30
|
questionId
|
|
@@ -54,14 +54,14 @@ import {Command}from'commander';import f from'chalk';import $o from'inquirer';im
|
|
|
54
54
|
status
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
|
-
`,
|
|
57
|
+
`,qo=`
|
|
58
58
|
query globalData {
|
|
59
59
|
userStatus {
|
|
60
60
|
isSignedIn
|
|
61
61
|
username
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
|
-
`,
|
|
64
|
+
`,Ko=`
|
|
65
65
|
query userPublicProfile($username: String!) {
|
|
66
66
|
matchedUser(username: $username) {
|
|
67
67
|
username
|
|
@@ -82,7 +82,7 @@ import {Command}from'commander';import f from'chalk';import $o from'inquirer';im
|
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
|
-
`,
|
|
85
|
+
`,Vo=`
|
|
86
86
|
query skillStats($username: String!) {
|
|
87
87
|
matchedUser(username: $username) {
|
|
88
88
|
tagProblemCounts {
|
|
@@ -104,7 +104,7 @@ import {Command}from'commander';import f from'chalk';import $o from'inquirer';im
|
|
|
104
104
|
}
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
|
-
`,
|
|
107
|
+
`,zo=`
|
|
108
108
|
query questionOfToday {
|
|
109
109
|
activeDailyCodingChallengeQuestion {
|
|
110
110
|
date
|
|
@@ -125,7 +125,7 @@ import {Command}from'commander';import f from'chalk';import $o from'inquirer';im
|
|
|
125
125
|
}
|
|
126
126
|
}
|
|
127
127
|
}
|
|
128
|
-
`,
|
|
128
|
+
`,Yo=`
|
|
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 f from'chalk';import $o from'inquirer';im
|
|
|
142
142
|
}
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
|
-
`,
|
|
145
|
+
`,Qo=`
|
|
146
146
|
query randomQuestion($categorySlug: String, $filters: QuestionListFilterInput) {
|
|
147
147
|
randomQuestion(categorySlug: $categorySlug, filters: $filters) {
|
|
148
148
|
titleSlug
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
|
-
|
|
151
|
+
`,Jo=`
|
|
152
152
|
query submissionDetails($submissionId: Int!) {
|
|
153
153
|
submissionDetails(submissionId: $submissionId) {
|
|
154
154
|
code
|
|
@@ -157,47 +157,54 @@ import {Command}from'commander';import f from'chalk';import $o from'inquirer';im
|
|
|
157
157
|
}
|
|
158
158
|
}
|
|
159
159
|
}
|
|
160
|
-
`;var
|
|
161
|
-
${
|
|
162
|
-
`
|
|
163
|
-
`)}function
|
|
164
|
-
`)
|
|
165
|
-
|
|
160
|
+
`;var Cn="https://leetcode.com",wn=class{client;credentials=null;constructor(){this.client=Zi.extend({prefixUrl:Cn,headers:{"Content-Type":"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",Origin:Cn,Referer:`${Cn}/`},timeout:{request:3e4},retry:{limit:2}});}setCredentials(t){this.credentials=t,this.client=this.client.extend({headers:{Cookie:`LEETCODE_SESSION=${t.session}; csrftoken=${t.csrfToken}`,"X-CSRFToken":t.csrfToken}});}getCredentials(){return this.credentials}async graphql(t,n={}){let o=await this.client.post("graphql",{json:{query:t,variables:n}}).json();if(o.errors?.length)throw new Error(`GraphQL Error: ${o.errors[0].message}`);return o.data}async checkAuth(){let t=await this.graphql(qo);return Wo.parse(t.userStatus)}async getProblems(t={}){let n={categorySlug:"",limit:t.limit??50,skip:t.skip??0,filters:{}};t.difficulty&&(n.filters.difficulty=t.difficulty),t.status&&(n.filters.status=t.status),t.tags?.length&&(n.filters.tags=t.tags),t.searchKeywords&&(n.filters.searchKeywords=t.searchKeywords);let o=await this.graphql(Go,n),r=z.array(Ft).parse(o.problemsetQuestionList.questions);return {total:o.problemsetQuestionList.total,problems:r}}async getProblem(t){let n=await this.graphql(jo,{titleSlug:t});return Do.parse(n.question)}async getProblemById(t){let{problems:n}=await this.getProblems({searchKeywords:t,limit:10}),o=n.find(r=>r.questionFrontendId===t);if(!o)throw new Error(`Problem #${t} not found`);return this.getProblem(o.titleSlug)}async getDailyChallenge(){let t=await this.graphql(zo);return Io.parse(t.activeDailyCodingChallengeQuestion)}async getRandomProblem(t={}){let n={categorySlug:"",filters:{}};t.difficulty&&(n.filters.difficulty=t.difficulty),t.tags?.length&&(n.filters.tags=t.tags);let o=await this.graphql(Qo,n);return z.object({titleSlug:z.string()}).parse(o.randomQuestion).titleSlug}async getUserProfile(t){let o=(await this.graphql(Ko,{username:t})).matchedUser,r=Uo.parse(o);return {username:r.username,realName:r.profile.realName,ranking:r.profile.ranking,acSubmissionNum:r.submitStatsGlobal.acSubmissionNum,streak:r.userCalendar.streak,totalActiveDays:r.userCalendar.totalActiveDays,submissionCalendar:o.userCalendar.submissionCalendar}}async getSkillStats(t){return (await this.graphql(Vo,{username:t})).matchedUser.tagProblemCounts}async getSubmissionList(t,n=20,o=0){let r=await this.graphql(Yo,{questionSlug:t,limit:n,offset:o});return z.array(No).parse(r.questionSubmissionList.submissions)}async getSubmissionDetails(t){let n=await this.graphql(Jo,{submissionId:t});return Fo.parse(n.submissionDetails)}async testSolution(t,n,o,r,s){let i=await this.client.post(`problems/${t}/interpret_solution/`,{json:{data_input:r,lang:o,typed_code:n,question_id:s}}).json();return this.pollSubmission(i.interpret_id,"interpret",Ho)}async submitSolution(t,n,o,r){let s=await this.client.post(`problems/${t}/submit/`,{json:{lang:o,typed_code:n,question_id:r}}).json();return this.pollSubmission(s.submission_id.toString(),"submission",Bo)}async pollSubmission(t,n,o){let r=`submissions/detail/${t}/check/`,s=12,i=500,a=3e3;for(let u=0;u<s;u++){try{let g=await this.client.get(r).json();if(g.state==="SUCCESS"||g.state==="FAILURE")return o.parse(g)}catch(g){if(u===s-1){let m=n==="interpret"?"Test":"Submission";throw new Error(`${m} check failed: ${g instanceof Error?g.message:"Network error"}`)}}let p=Math.min(i*Math.pow(2,u),a);await new Promise(g=>setTimeout(g,p));}let l=n==="interpret"?"Test":"Submission";throw new Error(`${l} timeout: Result not available after 30 seconds`)}},S=new wn;var Ge={};Yi(Ge,{credentials:()=>vn,describeCredentialStatus:()=>ye});var bt=join(homedir(),".leetcode"),kn=join(bt,"credentials.json"),me=join(bt,"credentials.v2.enc.json"),Tn="leetcode-cli",Ln="auth";function er(e){if(!e||typeof e!="object")return false;let t=e;return typeof t.session=="string"&&t.session.length>0&&typeof t.csrfToken=="string"&&t.csrfToken.length>0}function Rn(){let e=process.env.LEETCODE_SESSION,t=process.env.LEETCODE_CSRF_TOKEN;return !e||!t?null:{session:e,csrfToken:t}}function la(){let e=!!process.env.LEETCODE_SESSION,t=!!process.env.LEETCODE_CSRF_TOKEN;return e!==t}function Ut(){return process.env.LEETCODECLI_CREDENTIAL_BACKEND?.trim().toLowerCase()==="file"?"file":"keychain"}function ca(){existsSync(bt)||mkdirSync(bt,{recursive:true});try{chmodSync(bt,448);}catch{}}function ua(e){if(existsSync(e))try{chmodSync(e,384);}catch{}}function tr(e,t){return scryptSync(e,t,32,{N:32768,r:8,p:1,maxmem:128*1024*1024})}function da(e,t){let n=randomBytes(32),o=randomBytes(12),r=tr(t,n),s=createCipheriv("aes-256-gcm",r,o),i=JSON.stringify(e),a=Buffer.concat([s.update(i,"utf8"),s.final()]),l=s.getAuthTag();return {v:2,alg:"aes-256-gcm",kdf:"scrypt",salt:n.toString("hex"),iv:o.toString("hex"),tag:l.toString("hex"),ct:a.toString("hex")}}function pa(e,t){try{let n=Buffer.from(e.salt,"hex"),o=Buffer.from(e.iv,"hex"),r=Buffer.from(e.tag,"hex"),s=Buffer.from(e.ct,"hex"),i=tr(t,n),a=createDecipheriv("aes-256-gcm",i,o);a.setAuthTag(r);let l=Buffer.concat([a.update(s),a.final()]).toString("utf8"),u=JSON.parse(l);return er(u)?u:null}catch{return null}}function ga(e){try{let t=JSON.parse(e);return er(t)?t:null}catch{return null}}function On(e){let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return ["not available","unsupported","cannot autolaunch","dbus","secret service","keychain","credential store"].some(o=>t.includes(o))?"KEYCHAIN_UNAVAILABLE":"KEYCHAIN_ERROR"}function xn(e){switch(e){case "ENV_PARTIAL":return "Both LEETCODE_SESSION and LEETCODE_CSRF_TOKEN must be set together.";case "KEYCHAIN_UNAVAILABLE":return "System keychain is unavailable. In headless environments, use LEETCODE_SESSION and LEETCODE_CSRF_TOKEN.";case "KEYCHAIN_ERROR":return "Failed to access system keychain credentials.";case "FILE_MISSING_MASTER_KEY":return "File backend requires LEETCODECLI_MASTER_KEY to read or write credentials.";case "FILE_DECRYPT_FAILED":return 'Stored encrypted credentials could not be decrypted. Run "leetcode login" again.';case "LEGACY_CREDENTIALS_IGNORED":return 'Legacy plaintext credentials were detected and ignored. Please run "leetcode login" again.'}}function ye(e){if(e.hasCredentials){if(e.source==="env")return "Using environment credentials (read-only mode).";if(e.source==="keychain")return "Using credentials from the system keychain.";if(e.source==="file")return `Using encrypted credentials from ${e.path}.`}return e.reason?xn(e.reason):'No credentials found. Run "leetcode login".'}function Bt(e,t,n,o){return {ok:true,reason:null,mode:e,source:t,path:n,message:o}}function We(e,t,n,o){return {ok:false,reason:t,mode:e,source:null,path:n,message:o}}async function fa(e){try{let t=await Mn.getPassword(Tn,Ln);if(!t)return {status:{mode:"keychain",backend:"keychain",source:null,hasCredentials:!1,readOnly:!1,reason:existsSync(kn)?"LEGACY_CREDENTIALS_IGNORED":e?"ENV_PARTIAL":null,path:null},creds:null};let n=ga(t);return n?{status:{mode:"keychain",backend:"keychain",source:"keychain",hasCredentials:!0,readOnly:!1,reason:null,path:null},creds:n}:{status:{mode:"keychain",backend:"keychain",source:null,hasCredentials:!1,readOnly:!1,reason:"KEYCHAIN_ERROR",path:null},creds:null}}catch(t){return {status:{mode:"keychain",backend:"keychain",source:null,hasCredentials:false,readOnly:false,reason:On(t),path:null},creds:null}}}function ma(e){let t=process.env.LEETCODECLI_MASTER_KEY,n=me;if(!t)return {status:{mode:"file",backend:"file",source:null,hasCredentials:false,readOnly:false,reason:!existsSync(n)&&existsSync(kn)?"LEGACY_CREDENTIALS_IGNORED":"FILE_MISSING_MASTER_KEY",path:n},creds:null};if(!existsSync(n))return {status:{mode:"file",backend:"file",source:null,hasCredentials:false,readOnly:false,reason:existsSync(kn)?"LEGACY_CREDENTIALS_IGNORED":e?"ENV_PARTIAL":null,path:n},creds:null};try{let o=readFileSync(n,"utf8"),r=JSON.parse(o);if(r.v!==2||r.alg!=="aes-256-gcm"||r.kdf!=="scrypt"||typeof r.salt!="string"||typeof r.iv!="string"||typeof r.tag!="string"||typeof r.ct!="string")return {status:{mode:"file",backend:"file",source:null,hasCredentials:!1,readOnly:!1,reason:"FILE_DECRYPT_FAILED",path:n},creds:null};let s=pa(r,t);return s?{status:{mode:"file",backend:"file",source:"file",hasCredentials:!0,readOnly:!1,reason:null,path:n},creds:s}:{status:{mode:"file",backend:"file",source:null,hasCredentials:!1,readOnly:!1,reason:"FILE_DECRYPT_FAILED",path:n},creds:null}}catch{return {status:{mode:"file",backend:"file",source:null,hasCredentials:false,readOnly:false,reason:"FILE_DECRYPT_FAILED",path:n},creds:null}}}async function _n(){let e=Rn();if(e)return {status:{mode:"env-readonly",backend:Ut(),source:"env",hasCredentials:true,readOnly:true,reason:null,path:null},creds:e};let t=la();return Ut()==="file"?ma(t):fa(t)}var vn={async get(){let{creds:e}=await _n();return e},async status(){let{status:e}=await _n();return e},async info(){let{status:e}=await _n();return e},async set(e){if(Rn())return We("env-readonly","ENV_READONLY",null,"Environment credential mode is read-only. Unset LEETCODE_SESSION and LEETCODE_CSRF_TOKEN to store credentials.");if(Ut()==="file"){let o=process.env.LEETCODECLI_MASTER_KEY;if(!o)return We("file","FILE_MISSING_MASTER_KEY",me,"File backend requires LEETCODECLI_MASTER_KEY.");try{ca();let r=da(e,o);return writeFileSync(me,JSON.stringify(r,null,2)+`
|
|
161
|
+
`,{encoding:"utf8",mode:384}),ua(me),Bt("file","file",me,`Credentials encrypted and saved to ${me}.`)}catch{return We("file","FILE_DECRYPT_FAILED",me,"Failed to write encrypted credentials.")}}try{return await Mn.setPassword(Tn,Ln,JSON.stringify(e)),Bt("keychain","keychain",null,"Credentials saved to the system keychain.")}catch(o){let r=On(o);return We("keychain",r,null,xn(r))}},async clear(){if(Rn())return We("env-readonly","ENV_READONLY",null,"Environment credential mode is read-only. Unset LEETCODE_SESSION and LEETCODE_CSRF_TOKEN to log out.");if(Ut()==="file")try{return existsSync(me)&&unlinkSync(me),Bt("file","file",me,"Encrypted credentials removed.")}catch{return We("file","FILE_DECRYPT_FAILED",me,"Failed to remove encrypted credentials file.")}try{return await Mn.deletePassword(Tn,Ln),Bt("keychain","keychain",null,"Credentials removed from the system keychain.")}catch(n){let o=On(n);return We("keychain",o,null,xn(o))}},getPath(){return me}};var{credentials:Qe}=Ge;async function nr(){let e=await Qe.status();if(e.mode==="env-readonly"){let r=await Qe.get();if(!r){console.log(f.yellow("Environment credential mode is active but credentials are unavailable."));return}let s=nn("Validating environment credentials...").start();try{S.setCredentials(r);let{isSignedIn:i,username:a}=await S.checkAuth();if(!i||!a){s.fail("Invalid environment credentials"),console.log(f.red("Please check LEETCODE_SESSION and LEETCODE_CSRF_TOKEN."));return}s.succeed(`Logged in as ${f.green(a)}`),console.log(f.gray("Environment credential mode is read-only. Nothing was written to disk."));return}catch(i){s.fail("Authentication failed"),i instanceof Error&&console.log(f.red(i.message));return}}if(e.mode==="keychain"&&e.reason==="KEYCHAIN_UNAVAILABLE"){let r=typeof ye=="function"?ye(e):"System keychain is unavailable.";console.log(f.yellow(r));return}console.log(),console.log(f.cyan("LeetCode CLI Login")),console.log(f.gray("\u2500".repeat(40))),console.log(),console.log(f.yellow("To login, you need to provide your LeetCode session cookies.")),console.log(f.gray("1. Open https://leetcode.com in your browser")),console.log(f.gray("2. Login to your account")),console.log(f.gray("3. Open DevTools (F12) \u2192 Application \u2192 Cookies \u2192 leetcode.com")),console.log(f.gray("4. Copy the values of LEETCODE_SESSION and csrftoken")),console.log();let t=await Jn.prompt([{type:"password",name:"session",message:"LEETCODE_SESSION:",mask:"*",validate:r=>r.length>0||"Session token is required"},{type:"password",name:"csrfToken",message:"csrftoken:",mask:"*",validate:r=>r.length>0||"CSRF token is required"}]),n={session:t.session.trim(),csrfToken:t.csrfToken.trim()},o=nn("Verifying credentials...").start();try{S.setCredentials(n);let{isSignedIn:r,username:s}=await S.checkAuth();if(!r||!s){o.fail("Invalid credentials"),console.log(f.red("Please check your session cookies and try again."));return}let i=await Qe.set(n);if(!i.ok){o.fail("Authenticated, but failed to save credentials"),console.log(f.red(i.message));return}o.succeed(`Logged in as ${f.green(s)}`),console.log(),i.source==="keychain"?console.log(f.green("\u2713 Credentials saved to system keychain.")):i.source==="file"&&i.path?console.log(f.green("\u2713 Credentials encrypted and saved to ")+f.gray(i.path)):console.log(f.gray(i.message));}catch(r){o.fail("Authentication failed"),r instanceof Error&&console.log(f.red(r.message));}}async function or(){let e=await Qe.clear();if(!e.ok){console.log(f.yellow(e.message));return}console.log(f.green("\u2713 Logged out successfully"));}async function rr(){let e=await Qe.get();if(!e){let n=await Qe.status(),o=typeof ye=="function"?ye(n):'Not logged in. Run "leetcode login" to authenticate.';console.log(f.yellow(o));return}let t=nn("Checking session...").start();try{S.setCredentials(e);let{isSignedIn:n,username:o}=await S.checkAuth();if(!n||!o){t.fail("Session expired"),console.log(f.yellow('Please run "leetcode login" to re-authenticate.'));return}t.succeed(`Logged in as ${f.green(o)}`);}catch(n){t.fail("Failed to check session"),n instanceof Error&&console.log(f.red(n.message));}}var{credentials:sr}=Ge;async function A(){let e=await sr.get();if(!e){try{let t=await sr.status(),n=typeof ye=="function"?ye(t):"Please login first: leetcode login";console.log(f.yellow(`\u26A0\uFE0F ${n}`));}catch{console.log(f.yellow("\u26A0\uFE0F Please login first: leetcode login"));}return {authorized:false}}try{S.setCredentials(e);let{isSignedIn:t,username:n}=await S.checkAuth();return t?{authorized:!0,username:n??void 0}:(console.log(f.yellow("\u26A0\uFE0F Session expired. Please run: leetcode login")),{authorized:!1})}catch{return console.log(f.yellow("\u26A0\uFE0F Session validation failed. Please run: leetcode login")),{authorized:false}}}var ha={"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 Sa(e){for(let t of e){let n=ha[t.name];if(n)return n}return null}function ir(e){try{return JSON.parse(e)}catch{return e}}function De(e){return Array.isArray(e)&&e.length>0&&Array.isArray(e[0])}function ar(e,t){if(!Array.isArray(e)||e.length===0)return String(e);let n=Math.max(...e.map(i=>String(i).length),1),o=Math.max(n,3),r=e.map((i,a)=>`[${a}]`.padStart(o).padEnd(o)).join(" "),s=e.map((i,a)=>{let l=String(i).padStart(o).padEnd(o);return t&&Array.isArray(t)&&t[a]!==i?f.red.bold(l):l}).join(" ");return `${f.gray(r)}
|
|
162
|
+
${s}`}function lr(e,t){return Array.isArray(e)?e.length===0?f.gray("(empty)"):e.map((o,r)=>{let s=String(o);return t&&Array.isArray(t)&&(r>=t.length||t[r]!==o)?f.red.bold(s):s}).join(f.gray(" \u2192 ")):String(e)}function cr(e){if(!Array.isArray(e)||e.length===0)return f.gray("(empty tree)");let t=[],n=Math.floor(Math.log2(e.length))+1,o=Math.pow(2,n)*3;function r(s,i,a,l){if(i>e.length-1)return;let u=[],p=[],g=Math.floor(o/Math.pow(2,s+1));for(let m=i;m<=a&&m<e.length;m++){let b=e[m],_=b===null?" ":String(b);u.push(_.padStart(g).padEnd(g));let C=2*m+1,R=2*m+2,q=C<e.length&&e[C]!==null,K=R<e.length&&e[R]!==null;if(q||K){let Y="";q?Y+="/":Y+=" ",Y+=" ",K?Y+="\\":Y+=" ",p.push(Y.padStart(g).padEnd(g));}}u.length>0&&(t.push(u.join("")),p.length>0&&s<n-1&&t.push(p.join("")));}for(let s=0;s<n;s++){let i=Math.pow(2,s)-1,a=Math.pow(2,s+1)-2;r(s,i,a);}return t.join(`
|
|
163
|
+
`)}function Gt(e,t){if(!De(e)||e.length===0)return String(e);let n=e.length,o=e[0].length,r=3,s=[],i=" "+e[0].map((a,l)=>String(l).padStart(r).padEnd(r)).join(" ");s.push(f.gray(i)),s.push(" \u250C"+Array(o).fill("\u2500\u2500\u2500").join("\u252C")+"\u2510");for(let a=0;a<n;a++){let l=e[a].map((u,p)=>{let g=String(u).padStart(2);return t&&De(t)&&t[a]&&t[a][p]!==u?f.red.bold(g):g}).join(" \u2502 ");s.push(f.gray(` ${a} `)+`\u2502 ${l} \u2502`),a<n-1?s.push(" \u251C"+Array(o).fill("\u2500\u2500\u2500").join("\u253C")+"\u2524"):s.push(" \u2514"+Array(o).fill("\u2500\u2500\u2500").join("\u2534")+"\u2518");}return s.join(`
|
|
164
|
+
`)}function ur(e){return De(e)?e.map((n,o)=>{let r=Array.isArray(n)?n.join(", "):String(n);return ` ${f.cyan(String(o))} \u2192 [${r}]`}).join(`
|
|
165
|
+
`):String(e)}function dr(e,t,n){let o=ir(e),r=ir(t),s=e===t,i=Sa(n),a,l;if(De(o)){let u=De(r)?r:void 0;return a=Gt(o,u),l=De(r)?Gt(r):String(t),{outputVis:a,expectedVis:l,matches:s}}if(i===null)return {outputVis:String(e),expectedVis:String(t),matches:s,unsupported:true};switch(i){case "linkedlist":a=lr(o,r),l=lr(r);break;case "tree":a=cr(o),l=cr(r);break;case "graph":a=ur(o),l=ur(r);break;case "matrix":let u=De(r)?r:void 0;a=Gt(o,u),l=De(r)?Gt(r):String(t);break;case "array":case "string":Array.isArray(o)?(a=ar(o,r),l=Array.isArray(r)?ar(r):String(t)):(a=s?String(e):f.red.bold(String(e)),l=String(t));break}return {outputVis:a,expectedVis:l,matches:s}}function pr(e,t){let n=new $n({head:[f.cyan("ID"),f.cyan("Title"),f.cyan("Difficulty"),f.cyan("Rate"),f.cyan("Status")],colWidths:[8,45,12,10,10],style:{head:[],border:[]}});for(let o of e){let r=o.title;o.isPaidOnly&&(r=`\u{1F512} ${r}`),n.push([o.questionFrontendId,r.length>42?r.slice(0,39)+"...":r,jt(o.difficulty),`${o.acRate.toFixed(1)}%`,Ea(o.status)]);}console.log(n.toString()),console.log(f.gray(`
|
|
166
|
+
Showing ${e.length} of ${t} problems`));}function gr(e){console.log();let t=e.isPaidOnly?"\u{1F512} ":"";if(console.log(f.bold.cyan(` ${e.questionFrontendId}. ${t}${e.title}`)),console.log(` ${jt(e.difficulty)}`),console.log(f.gray(` https://leetcode.com/problems/${e.titleSlug}/`)),console.log(),e.isPaidOnly&&(console.log(f.yellow(" \u26A0\uFE0F Premium Problem")),console.log(f.gray(" This problem requires a LeetCode Premium subscription.")),console.log(f.gray(" Visit the URL above to view on LeetCode.")),console.log()),e.topicTags.length){let o=e.topicTags.map(r=>f.bgBlue.white(` ${r.name} `)).join(" ");console.log(` ${o}`),console.log();}console.log(f.gray("\u2500".repeat(60))),console.log();let n=e.content;if(!n){console.log(f.yellow(" \u{1F512} Premium Content")),console.log(f.gray(" Problem description is not available directly.")),console.log(f.gray(" Please visit the URL above to view on LeetCode.")),console.log();return}console.log(Dn(n)),console.log();}function Dn(e){return e=e.replace(/<sup>(.*?)<\/sup>/gi,"^$1"),e=e.replace(/<strong class="example">Example (\d+):<\/strong>/gi,"\xA7EXAMPLE\xA7$1\xA7"),e=e.replace(/Input:/gi,"\xA7INPUT\xA7"),e=e.replace(/Output:/gi,"\xA7OUTPUT\xA7"),e=e.replace(/Explanation:/gi,"\xA7EXPLAIN\xA7"),e=e.replace(/<strong>Constraints:<\/strong>/gi,"\xA7CONSTRAINTS\xA7"),e=e.replace(/Constraints:/gi,"\xA7CONSTRAINTS\xA7"),e=e.replace(/<strong>Follow-up:/gi,"\xA7FOLLOWUP\xA7"),e=e.replace(/Follow-up:/gi,"\xA7FOLLOWUP\xA7"),e=e.replace(/<li>/gi," \u2022 "),e=e.replace(/<\/li>/gi,`
|
|
166
167
|
`),e=e.replace(/<\/p>/gi,`
|
|
167
168
|
|
|
168
169
|
`),e=e.replace(/<br\s*\/?>/gi,`
|
|
169
|
-
`),e=
|
|
170
|
+
`),e=ba(e),e=e.replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/≤/g,"\u2264").replace(/≥/g,"\u2265").replace(/&#(\d+);/g,(t,n)=>String.fromCharCode(parseInt(n,10))).replace(/&/g,"&"),e=e.replace(/\n{3,}/g,`
|
|
170
171
|
|
|
171
|
-
`).trim(),e=e.replace(/§EXAMPLE§(\d+)§/g,(t,
|
|
172
|
+
`).trim(),e=e.replace(/§EXAMPLE§(\d+)§/g,(t,n)=>f.green.bold(`\u{1F4CC} Example ${n}:`)),e=e.replace(/§INPUT§/g,f.yellow("Input:")),e=e.replace(/§OUTPUT§/g,f.yellow("Output:")),e=e.replace(/§EXPLAIN§/g,f.gray("Explanation:")),e=e.replace(/§CONSTRAINTS§/g,f.cyan.bold(`
|
|
172
173
|
\u{1F4CB} Constraints:`)),e=e.replace(/§FOLLOWUP§/g,f.magenta.bold(`
|
|
173
|
-
\u{1F4A1} Follow-up:`)),e}function
|
|
174
|
-
`).forEach(b=>console.log(` ${b}`)),console.log(),console.log(f.cyan(" Expected:")),
|
|
175
|
-
`).forEach(b=>console.log(` ${b}`)),console.log(),console.log(
|
|
176
|
-
Page ${s} of ${Math.ceil(i/r)}. Use --page to navigate.`));}catch(
|
|
174
|
+
\u{1F4A1} Follow-up:`)),e}function fr(e,t){if(console.log(),e.compile_error){console.log(f.red.bold("\u274C Compile Error")),console.log(f.red(e.compile_error));return}if(e.runtime_error){console.log(f.red.bold("\u274C Runtime Error")),console.log(f.red(e.runtime_error));return}e.correct_answer?console.log(f.green.bold("\u2713 All test cases passed!")):console.log(f.yellow.bold("\u2717 Some test cases failed"));let n=e.code_answer??[],o=e.expected_code_answer??[];if(t&&n.length>0){console.log(),console.log(f.gray.bold("\u2500".repeat(50)));let s=n.map((i,a)=>({out:i,exp:o[a]??""})).filter(({out:i,exp:a})=>i!==""||a!=="");for(let i=0;i<s.length;i++){let{out:a,exp:l}=s[i],{outputVis:u,expectedVis:p,matches:g,unsupported:m}=dr(a,l,t);console.log(),console.log(f.gray(`Test Case ${i+1}:`)),m&&(console.log(f.yellow(" \u26A0 No visualization available for this problem type")),console.log(f.gray(` Tags: ${t.map(b=>b.name).join(", ")}`))),console.log(),console.log(f.cyan(" Your Output:")),u.split(`
|
|
175
|
+
`).forEach(b=>console.log(` ${b}`)),console.log(),console.log(f.cyan(" Expected:")),p.split(`
|
|
176
|
+
`).forEach(b=>console.log(` ${b}`)),console.log(),console.log(g?f.green(" \u2713 Match"):f.red(" \u2717 Mismatch"));}console.log(f.gray.bold("\u2500".repeat(50)));}else {console.log(),console.log(f.gray("Your Output:"));for(let s of n)console.log(f.white(` ${s}`));console.log(),console.log(f.gray("Expected Output:"));for(let s of o)console.log(f.white(` ${s}`));}let r=(e.std_output_list??[]).filter(s=>s);if(r.length>0){console.log(),console.log(f.gray("Stdout:"));for(let s of r)console.log(f.gray(` ${s}`));}}function mr(e){if(console.log(),e.compile_error){console.log(f.red.bold("\u274C Compile Error")),console.log(f.red(e.compile_error));return}if(e.runtime_error){console.log(f.red.bold("\u274C Runtime Error")),console.log(f.red(e.runtime_error)),e.last_testcase&&console.log(f.gray("Last testcase:"),e.last_testcase);return}e.status_msg==="Accepted"?(console.log(f.green.bold("\u2713 Accepted!")),console.log(),console.log(f.gray("Runtime:"),f.white(e.status_runtime),f.gray(`(beats ${e.runtime_percentile?.toFixed(1)??"N/A"}%)`)),console.log(f.gray("Memory:"),f.white(e.status_memory),f.gray(`(beats ${e.memory_percentile?.toFixed(1)??"N/A"}%)`))):(console.log(f.red.bold(`\u274C ${e.status_msg}`)),console.log(),console.log(f.gray(`Passed ${e.total_correct}/${e.total_testcases} testcases`)),e.code_output&&console.log(f.gray("Your Output:"),e.code_output),e.expected_output&&console.log(f.gray("Expected:"),e.expected_output),e.last_testcase&&console.log(f.gray("Failed testcase:"),e.last_testcase));}function yr(e,t,n,o,r,s){console.log(),console.log(f.bold.white(`\u{1F464} ${e}`)+(t?f.gray(` (${t})`):"")),console.log(f.gray(`Ranking: #${n.toLocaleString()}`)),console.log();let i=new $n({head:[f.cyan("Difficulty"),f.cyan("Solved")],style:{head:[],border:[]}});for(let l of o)l.difficulty!=="All"&&i.push([jt(l.difficulty),l.count.toString()]);let a=o.find(l=>l.difficulty==="All")?.count??0;i.push([f.white.bold("Total"),f.white.bold(a.toString())]),console.log(i.toString()),console.log(),console.log(f.gray("\u{1F525} Current streak:"),f.hex("#FFA500")(r.toString()),f.gray("days")),console.log(f.gray("\u{1F4C5} Total active days:"),f.white(s.toString()));}function hr(e,t){if(console.log(),console.log(f.bold.yellow("\u{1F3AF} Daily Challenge"),f.gray(`(${e})`)),console.log(),console.log(f.white(`${t.questionFrontendId}. ${t.title}`)),console.log(jt(t.difficulty)),console.log(f.gray(`https://leetcode.com/problems/${t.titleSlug}/`)),t.topicTags.length){console.log();let n=t.topicTags.map(o=>f.blue(o.name)).join(" ");console.log(f.gray("Tags:"),n);}}function jt(e){switch(e.toLowerCase()){case "easy":return f.green(e);case "medium":return f.yellow(e);case "hard":return f.red(e);default:return e}}function Ea(e){switch(e){case "ac":return f.green("\u2713");case "notac":return f.yellow("\u25CB");default:return f.gray("-")}}function In(e){let t=new $n({head:[f.cyan("ID"),f.cyan("Status"),f.cyan("Lang"),f.cyan("Runtime"),f.cyan("Memory"),f.cyan("Date")],colWidths:[12,18,15,12,12,25],style:{head:[],border:[]}});for(let n of e){let o=n.statusDisplay==="Accepted",r=new Date(parseInt(n.timestamp)*1e3).toLocaleString();t.push([n.id,o?f.green(n.statusDisplay):f.red(n.statusDisplay),n.lang,n.runtime,n.memory,r]);}console.log(t.toString());}async function Sr(e){let{authorized:t}=await A();if(!t)return;let n=nn("Fetching problems...").start();try{let o={},r=parseInt(e.limit??"20",10),s=parseInt(e.page??"1",10);if(o.limit=r,o.skip=(s-1)*r,e.difficulty){let l={easy:"EASY",e:"EASY",medium:"MEDIUM",m:"MEDIUM",hard:"HARD",h:"HARD"};o.difficulty=l[e.difficulty.toLowerCase()];}if(e.status){let l={todo:"NOT_STARTED",solved:"AC",ac:"AC",attempted:"TRIED",tried:"TRIED"};o.status=l[e.status.toLowerCase()];}e.tag?.length&&(o.tags=e.tag),e.search&&(o.searchKeywords=e.search);let{total:i,problems:a}=await S.getProblems(o);if(n.stop(),a.length===0){console.log(f.yellow("No problems found matching your criteria."));return}pr(a,i),s*r<i&&console.log(f.gray(`
|
|
177
|
+
Page ${s} of ${Math.ceil(i/r)}. Use --page to navigate.`));}catch(o){n.fail("Failed to fetch problems"),o instanceof Error&&console.log(f.red(o.message));}}async function qt(e){let{authorized:t}=await A();if(!t)return;let n=nn("Fetching problem...").start();try{let o;if(/^\d+$/.test(e)?o=await S.getProblemById(e):o=await S.getProblem(e),!o){n.fail(`Problem "${e}" not found`);return}n.stop(),gr(o);}catch(o){n.fail("Failed to fetch problem"),o instanceof Error&&console.log(f.red(o.message));}}async function br(e,t){let{authorized:n}=await A();if(!n)return;let o=nn("Fetching problem hints...").start();try{let r;if(/^\d+$/.test(e)?r=await S.getProblemById(e):r=await S.getProblem(e),!r){o.fail(`Problem "${e}" not found`);return}o.stop(),console.log(),console.log(f.bold.cyan(`${r.questionFrontendId}. ${r.title}`)),console.log();let s=r.hints||[];if(s.length===0){console.log(f.yellow("\u26A0 No hints available for this problem.")),console.log(f.gray("Try working through the problem description and examples first!"));return}t.all?s.forEach((i,a)=>{Er(i,a+1,s.length);}):await La(s);}catch(r){o.fail("Failed to fetch problem hints"),r instanceof Error&&console.log(f.red(r.message));}}function Er(e,t,n){let o=Ta(e);console.log(f.bold.yellow(`\u{1F4A1} Hint ${t}/${n}`)),console.log(f.white(o)),console.log();}function Ta(e){let t=e.replace(/<code>/g,f.cyan("`")).replace(/<\/code>/g,f.cyan("`")).replace(/<b>/g,f.bold("")).replace(/<\/b>/g,"").replace(/<i>/g,f.italic("")).replace(/<\/i>/g,"").replace(/<br\s*\/?>/g,`
|
|
177
178
|
`).replace(/<p>/g,"").replace(/<\/p>/g,`
|
|
178
|
-
`);return (
|
|
179
|
-
Good luck! You can always run this command again for more hints.`)),
|
|
180
|
-
|
|
179
|
+
`);return (ba(t)??"").replace(/</g,"<").replace(/>/g,">").replace(/ /g," ").replace(/"/g,'"').replace(/&/g,"&").trim()}async function La(e){let n=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),o=r=>new Promise(s=>{if(r>=e.length){console.log(f.green("\u2713 All hints revealed! Good luck solving the problem!")),n.close(),s();return}Er(e[r],r+1,e.length),r<e.length-1?n.question(f.gray(`Press Enter for next hint (${e.length-r-1} remaining), or 'q' to quit: `),i=>{i.toLowerCase()==="q"?(console.log(f.gray(`
|
|
180
|
+
Good luck! You can always run this command again for more hints.`)),n.close(),s()):s(o(r+1));}):(console.log(f.green("\u2713 All hints revealed! Good luck solving the problem!")),n.close(),s());});await o(0);}function Ie(e){return /^\d+$/.test(e)}function Kt(e){return !e.includes("/")&&!e.includes("\\")&&e.includes(".")}var Ra=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/,Oa=/^[a-zA-Z0-9][a-zA-Z0-9 _-]{0,63}$/;function Je(e){return Ra.test(e.trim())}function _r(e){return Oa.test(e.trim())}function Xe(e,t){let n=resolve(e),o=resolve(t),r=o.endsWith(sep)?o:o+sep;return n===o||n.startsWith(r)}var Un=join(homedir(),".leetcode"),Hn=join(Un,"workspaces.json"),Vt=join(Un,"workspaces");function zt(e){existsSync(e)||mkdirSync(e,{recursive:true});}function je(){return existsSync(Hn)?JSON.parse(readFileSync(Hn,"utf-8")):{active:"default",workspaces:[]}}function Et(e){zt(Un),writeFileSync(Hn,JSON.stringify(e,null,2)+`
|
|
181
|
+
`);}function Le(e){let t=e.trim();return Je(t)?t:null}var T={ensureInitialized(){let e=je(),t=e.workspaces.map(r=>Le(r)).filter(r=>r!==null),n=false;if(t.length!==e.workspaces.length&&(e.workspaces=[...new Set(t)],n=true),e.workspaces.length===0){this.create("default",{workDir:join(homedir(),"leetcode"),lang:"typescript"}),e.workspaces=["default"],e.active="default",Et(e);return}let o=Le(e.active);!o||!e.workspaces.includes(o)?(e.active=e.workspaces[0],n=true):o!==e.active&&(e.active=o,n=true),n&&Et(e);},getActive(){return this.ensureInitialized(),je().active},setActive(e){let t=Le(e);if(!t)return false;let n=je();return n.workspaces.includes(t)?(n.active=t,Et(n),true):false},list(){return this.ensureInitialized(),je().workspaces},exists(e){let t=Le(e);return t?(this.ensureInitialized(),je().workspaces.includes(t)):false},create(e,t){let n=Le(e);if(!n)return false;let o=je();if(o.workspaces.includes(n))return false;let r=join(Vt,n);zt(r),zt(join(r,"snapshots"));let s=join(r,"config.json");return writeFileSync(s,JSON.stringify(t,null,2)+`
|
|
182
|
+
`),writeFileSync(join(r,"timer.json"),JSON.stringify({solveTimes:{},activeTimer:null},null,2)+`
|
|
183
|
+
`),writeFileSync(join(r,"collab.json"),JSON.stringify({session:null},null,2)+`
|
|
184
|
+
`),o.workspaces.push(n),Et(o),true},delete(e){let t=Le(e);if(!t||t==="default")return false;let n=je();return n.workspaces.includes(t)?(n.workspaces=n.workspaces.filter(o=>o!==t),n.active===t&&(n.active="default"),Et(n),true):false},getWorkspaceDir(e){let t=e?Le(e)||"default":this.getActive();return join(Vt,t)},getConfig(e){let t=e?Le(e)||"default":this.getActive(),n=join(Vt,t,"config.json");return existsSync(n)?JSON.parse(readFileSync(n,"utf-8")):{workDir:join(homedir(),"leetcode"),lang:"typescript"}},setConfig(e,t){let n=t?Le(t)||"default":this.getActive(),o=join(Vt,n);zt(o);let s={...this.getConfig(n),...e};writeFileSync(join(o,"config.json"),JSON.stringify(s,null,2)+`
|
|
185
|
+
`);},getSnapshotsDir(){return join(this.getWorkspaceDir(),"snapshots")},getTimerPath(){return join(this.getWorkspaceDir(),"timer.json")},getCollabPath(){return join(this.getWorkspaceDir(),"collab.json")}};var M={getConfig(){let e=T.getConfig();return {language:e.lang,editor:e.editor,workDir:e.workDir,repo:e.syncRepo}},setLanguage(e){T.setConfig({lang:e});},setEditor(e){T.setConfig({editor:e});},setWorkDir(e){T.setConfig({workDir:e});},setRepo(e){T.setConfig({syncRepo:e});},deleteRepo(){let e=T.getConfig();delete e.syncRepo,T.setConfig(e);},getLanguage(){return T.getConfig().lang},getEditor(){return T.getConfig().editor},getWorkDir(){return T.getConfig().workDir},getRepo(){return T.getConfig().syncRepo},getPath(){return join(T.getWorkspaceDir(),"config.json")},getActiveWorkspace(){return T.getActive()}};var Yt=["typescript","javascript","python3","java","cpp","c","csharp","go","rust","kotlin","swift","sql"],Wn={typescript:"typescript",ts:"typescript",javascript:"javascript",js:"javascript",python3:"python3",python:"python3",py:"python3",java:"java","c++":"cpp",cpp:"cpp",c:"c","c#":"csharp",csharp:"csharp",cs:"csharp",go:"go",golang:"go",rust:"rust",rs:"rust",kotlin:"kotlin",kt:"kotlin",swift:"swift",sql:"sql",mysql:"sql",mssql:"sql",postgresql:"sql",postgres:"sql",oracle:"sql"},va={typescript:"typescript",javascript:"javascript",python3:"python3",java:"java",cpp:"cpp",c:"c",csharp:"csharp",go:"golang",rust:"rust",kotlin:"kotlin",swift:"swift",sql:"mysql"},Aa={sql:"mysql",mysql:"mysql",mssql:"mssql","ms sql":"mssql",postgresql:"postgresql",postgres:"postgresql",oracle:"oracle"};function Tr(e){return e.trim().toLowerCase()}function kr(e){let t=Tr(e).replace(/[-_]+/g," ");return Aa[t]??null}function qe(e){return Wn[Tr(e)]??null}function Lr(e){return qe(e)}function $a(e){if(!e||e.length===0)return "mysql";let t=new Set;for(let n of e){let o=kr(n.langSlug);if(o){t.add(o);continue}let r=kr(n.lang);r&&t.add(r);}return t.has("mysql")?"mysql":t.has("mssql")?"mssql":t.has("postgresql")?"postgresql":t.has("oracle")?"oracle":"mysql"}function Qt(e,t){return e==="sql"?$a(t):va[e]}function Rr(){return Yt.join(", ")}var Ze={typescript:"ts",javascript:"js",python3:"py",java:"java",cpp:"cpp",c:"c",csharp:"cs",go:"go",rust:"rs",kotlin:"kt",swift:"swift",sql:"sql"},Or={...Wn};function Jt(e,t){let n=e.find(o=>Lr(o.langSlug)===t);return n||(e[0]??null)}function Xt(e,t){let n=xr(e);return `${n.single} Premium Problem - ${t}
|
|
186
|
+
${n.single} Solution stub not available - visit LeetCode to view`}function Zt(e,t,n,o,r,s,i){let a=xr(s);return `${Na(a,e,n,o,t,i)}
|
|
181
187
|
|
|
182
188
|
${r}
|
|
183
|
-
`}function
|
|
189
|
+
`}function xr(e){switch(e){case "python3":return {single:"#",blockStart:'"""',blockEnd:'"""',linePrefix:""};case "sql":return {single:"--",blockStart:"/*",blockEnd:"*/",linePrefix:" * "};default:return {single:"//",blockStart:"/*",blockEnd:"*/",linePrefix:" * "}}}function Ia(e){let t=e;return t=t.replace(/<sup>(.*?)<\/sup>/gi,"^$1"),t=t.replace(/<strong class="example">Example (\d+):<\/strong>/gi,`
|
|
184
190
|
Example $1:`),t=t.replace(/<li>/gi,"\u2022 "),t=t.replace(/<\/li>/gi,`
|
|
185
191
|
`),t=t.replace(/<\/p>/gi,`
|
|
186
192
|
|
|
187
193
|
`),t=t.replace(/<br\s*\/?>/gi,`
|
|
188
|
-
`),t=
|
|
194
|
+
`),t=ba(t)??"",t=t.replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/≤/g,"<=").replace(/≥/g,">=").replace(/&#(\d+);/g,(n,o)=>String.fromCharCode(parseInt(o,10))).replace(/&/g,"&"),t=t.replace(/\n{3,}/g,`
|
|
189
195
|
|
|
190
|
-
`).trim(),t}function
|
|
191
|
-
`);for(let
|
|
192
|
-
`)}function
|
|
193
|
-
For security reasons, you can only test files from within your workspace.`)),console.log(f.gray('Use "leetcode config workdir <path>" to change your workspace.'));return}let s=
|
|
194
|
-
For security reasons, you can only submit files from within your workspace.`)),console.log(f.gray('Use "leetcode config workdir <path>" to change your workspace.'));return}let r=Vt({text:"Reading solution file...",spinner:"dots"}).start();try{let s=basename(o),i=s.match(/^(\d+)\.([^.]+)\./);if(!i){r.fail("Invalid filename format"),console.log(f.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(f.gray("Example: 1.two-sum.ts"));return}let[,a,l]=i,u=s.split(".").pop(),g=await readFile(o,"utf-8");r.text="Fetching problem details...";let d=await S.getProblem(l),m=qt(u,d.codeSnippets);if(!m){r.fail(`Unsupported file extension: .${u}`);return}r.text="Submitting solution...";let b=await S.submitSolution(l,g,m,d.questionId);if(r.stop(),Kn(b),b.status_msg==="Accepted"){let M=be.getActiveTimer();if(M&&M.problemId===a){let E=be.stopTimer();if(E){be.recordSolveTime(a,d.title,d.difficulty,E.durationSeconds,M.durationMinutes);let x=Math.floor(E.durationSeconds/60),G=E.durationSeconds%60,q=`${x}m ${G}s`,z=E.durationSeconds<=M.durationMinutes*60;console.log(),console.log(f.bold("\u23F1\uFE0F Timer Result:")),console.log(` Solved in ${z?f.green(q):f.yellow(q)} (limit: ${M.durationMinutes}m)`),console.log(z?f.green(" \u2713 Within time limit!"):f.yellow(" \u26A0 Exceeded time limit"));}}}}catch(s){r.fail("Submission failed"),s instanceof Error&&console.log(f.red(s.message));}}var Cr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Er(e){let t=JSON.parse(e),o=new Date,n=[];for(let i=11;i>=0;i--){let a=new Date(o);a.setDate(a.getDate()-i*7-a.getDay());let l=0,u=0;for(let d=0;d<7;d++){let m=new Date(a);if(m.setDate(m.getDate()+d),m>o)break;let b=new Date(Date.UTC(m.getFullYear(),m.getMonth(),m.getDate())),M=Math.floor(b.getTime()/1e3).toString(),E=t[M]||0;l+=E,E>0&&u++;}let g=new Date(a);g.setDate(g.getDate()+6),n.push({start:`${Cr[a.getMonth()]} ${a.getDate()}`,end:`${Cr[g.getMonth()]} ${g.getDate()}`,count:l,days:u});}let r=n.reduce((i,a)=>i+a.count,0),s=n.reduce((i,a)=>i+a.days,0);console.log(),console.log(f.bold("\u{1F4C5} Activity (Last 12 Weeks)")),console.log(f.gray("How many problems you submitted and days you practiced.")),console.log(f.gray("\u2500".repeat(50))),console.log();for(let i of n){let a=`${i.start} - ${i.end}`.padEnd(18),l=i.count>0?f.green("\u2588".repeat(Math.min(i.count,10))).padEnd(10):f.gray("\xB7").padEnd(10),u=i.count>0?`${i.count} subs`.padEnd(10):"".padEnd(10),g=i.days>0?`${i.days}d active`:"";console.log(` ${f.white(a)} ${l} ${f.cyan(u)} ${f.yellow(g)}`);}console.log(f.gray("\u2500".repeat(50))),console.log(` ${f.bold.white("Total:")} ${f.cyan.bold(r+" submissions")}, ${f.yellow.bold(s+" days active")}`),console.log();}function wr(e,t,o){console.log(),console.log(f.bold("\u{1F3AF} Skill Breakdown")),console.log(f.gray("\u2500".repeat(45)));let n=(r,s,i)=>{if(s.length===0)return;console.log(),console.log(i.bold(` ${r}`));let a=[...s].sort((l,u)=>u.problemsSolved-l.problemsSolved);for(let l of a.slice(0,8)){let u=l.tagName.padEnd(22),g=i("\u2588".repeat(Math.min(l.problemsSolved,15)));console.log(` ${f.white(u)} ${g} ${f.white(l.problemsSolved)}`);}};n("Fundamental",e,f.green),n("Intermediate",t,f.yellow),n("Advanced",o,f.red),console.log();}function Mr(e){let t=JSON.parse(e),o=new Date,n=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],r=[];for(let l=6;l>=0;l--){let u=new Date(o);u.setDate(u.getDate()-l);let g=new Date(Date.UTC(u.getFullYear(),u.getMonth(),u.getDate())),d=Math.floor(g.getTime()/1e3).toString();r.push({label:n[u.getDay()],count:t[d]||0});}let s=Math.max(...r.map(l=>l.count),1),i=6;console.log(),console.log(f.bold("\u{1F4C8} Submission Trend (Last 7 Days)")),console.log(f.gray("\u2500".repeat(35))),console.log();for(let l=i;l>=1;l--){let u=` ${l===i?s.toString().padStart(2):" "} \u2502`;for(let g of r)Math.round(g.count/s*i)>=l?u+=f.green(" \u2588\u2588 "):u+=" ";console.log(u);}console.log(` 0 \u2514${"\u2500\u2500\u2500\u2500".repeat(7)}`),console.log(` ${r.map(l=>l.label.padEnd(4)).join("")}`),console.log(f.gray(` ${r.map(l=>l.count.toString().padEnd(4)).join("")}`));let a=r.reduce((l,u)=>l+u.count,0);console.log(),console.log(f.white(` Total: ${a} submissions this week`)),console.log();}async function _r(e,t={}){let{authorized:o,username:n}=await v();if(!o)return;let r=Vt("Fetching statistics...").start();try{let s=e||n;if(!s){r.fail("No username found");return}let i=await S.getUserProfile(s);if(r.stop(),!t.calendar&&!t.skills&&!t.trend){Vn(i.username,i.realName,i.ranking,i.acSubmissionNum,i.streak,i.totalActiveDays);return}if(t.calendar&&(i.submissionCalendar?Er(i.submissionCalendar):console.log(f.yellow("Calendar data not available."))),t.trend&&(i.submissionCalendar?Mr(i.submissionCalendar):console.log(f.yellow("Calendar data not available."))),t.skills){r.start("Fetching skill stats...");let a=await S.getSkillStats(s);r.stop(),wr(a.fundamental,a.intermediate,a.advanced);}}catch(s){r.fail("Failed to fetch statistics"),s instanceof Error&&console.log(f.red(s.message));}}async function kr(){let{authorized:e}=await v();if(!e)return;let t=Vt("Fetching daily challenge...").start();try{let o=await S.getDailyChallenge();t.stop(),zn(o.date,o.question),console.log(),console.log(f.gray("Run the following to start working on this problem:")),console.log(f.cyan(` leetcode pick ${o.question.titleSlug}`));}catch(o){t.fail("Failed to fetch daily challenge"),o instanceof Error&&console.log(f.red(o.message));}}async function Tr(e){let{authorized:t}=await v();if(!t)return;let o=Vt("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 {o.fail(`Invalid difficulty: ${e.difficulty}`);return}}e.tag&&(n.tags=[e.tag]);let r=await S.getRandomProblem(n);o.succeed("Found random problem!"),console.log(),e.pick?await Me(r,{open:e.open??!0}):(await It(r),console.log(f.gray("Run following to start solving:")),console.log(f.cyan(` leetcode pick ${r}`)));}catch(n){o.fail("Failed to fetch random problem"),n instanceof Error&&console.log(f.red(n.message));}}async function Rr(e,t){let{authorized:o}=await v();if(!o)return;let n=Vt("Fetching problem info...").start();try{let r;if(/^\d+$/.test(e)?r=await S.getProblemById(e):r=await S.getProblem(e),!r){n.fail(`Problem "${e}" not found`);return}let s=r.titleSlug;n.text="Fetching submissions...";let i=t.limit?parseInt(t.limit,10):20,a=await S.getSubmissionList(s,i);if(n.stop(),a.length===0){console.log(f.yellow("No submissions found."));return}if(t.last){let l=a.find(u=>u.statusDisplay==="Accepted");l?(console.log(f.bold("Last Accepted Submission:")),ho([l])):console.log(f.yellow("No accepted submissions found in recent history."));}else ho(a);if(t.download){let l=Vt("Downloading submission...").start(),u=a.find(Ot=>Ot.statusDisplay==="Accepted");if(!u){l.fail("No accepted submission found to download.");return}let g=parseInt(u.id,10);if(isNaN(g)){l.fail("Invalid submission ID format");return}let d=await S.getSubmissionDetails(g),m=_.getWorkDir(),b=r.difficulty,M=r.topicTags.length>0?r.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",E=join(m,b,M);existsSync(E)||await mkdir(E,{recursive:!0});let x=d.lang.name.toLowerCase(),G=ir[x]??"txt",q=ze[G]??x,z=`${r.questionFrontendId}.${r.titleSlug}.submission-${u.id}.${q}`,Pt=join(E,z);await writeFile(Pt,d.code,"utf-8"),l.succeed(`Downloaded to ${f.green(z)}`),console.log(f.gray(`Path: ${Pt}`));}}catch(r){n.fail("Failed to fetch submissions"),r instanceof Error&&console.log(f.red(r.message));}}async function Pr(e){let t=e.repo!==void 0;if(!e.lang&&!e.editor&&!e.workdir&&!t){$r();return}if(e.lang){let o=Be(e.lang);if(!o){console.log(f.red(`Unsupported language: ${e.lang}`)),console.log(f.gray(`Supported: ${Ut.join(", ")}`));return}_.setLanguage(o),console.log(f.green(`\u2713 Default language set to ${o}`));}e.editor&&(_.setEditor(e.editor),console.log(f.green(`\u2713 Editor set to ${e.editor}`))),e.workdir&&(_.setWorkDir(e.workdir),console.log(f.green(`\u2713 Work directory set to ${e.workdir}`))),t&&(e.repo===true||typeof e.repo=="string"&&e.repo.trim()===""?(_.deleteRepo(),console.log(f.green("\u2713 Repository URL cleared"))):typeof e.repo=="string"&&(_.setRepo(e.repo),console.log(f.green(`\u2713 Repository URL set to ${e.repo}`))));}async function Or(){let e=_.getConfig(),t=_.getActiveWorkspace();console.log(),console.log(f.bold.cyan(`\u{1F4C1} Configuring workspace: ${t}`)),console.log(f.gray("\u2500".repeat(40)));let o=await $o.prompt([{type:"list",name:"language",message:"Default programming language:",choices:Ut,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}]);_.setLanguage(o.language),_.setEditor(o.editor),_.setWorkDir(o.workDir),o.repo?_.setRepo(o.repo):_.deleteRepo(),console.log(),console.log(f.green("\u2713 Configuration saved")),$r();}function $r(){let e=_.getConfig(),t=ae.get(),o=_.getActiveWorkspace();console.log(),console.log(f.bold.cyan(`\u{1F4C1} Workspace: ${o}`)),console.log(f.gray("\u2500".repeat(40))),console.log(),console.log(f.gray("Config file:"),_.getPath()),console.log(),console.log(f.gray("Language: "),f.white(e.language)),console.log(f.gray("Editor: "),f.white(e.editor??"(not set)")),console.log(f.gray("Work Dir: "),f.white(e.workDir)),console.log(f.gray("Repo URL: "),f.white(e.repo??"(not set)")),console.log(f.gray("Logged in: "),t?f.green("Yes"):f.yellow("No"));}var De=new Ri({projectName:"leetcode-cli-bookmarks",defaults:{bookmarks:[]}}),de={add(e){let t=De.get("bookmarks");return t.includes(e)?false:(De.set("bookmarks",[...t,e]),true)},remove(e){let t=De.get("bookmarks");return t.includes(e)?(De.set("bookmarks",t.filter(o=>o!==e)),true):false},list(){return De.get("bookmarks")},has(e){return De.get("bookmarks").includes(e)},count(){return De.get("bookmarks").length},clear(){De.set("bookmarks",[]);}};async function vr(e,t){if(!["add","remove","list","clear"].includes(e)){console.log(f.red(`Invalid action: ${e}`)),console.log(f.gray("Valid actions: add, remove, list, clear"));return}switch(e){case "add":if(!t){console.log(f.red("Please provide a problem ID to bookmark"));return}if(!Ae(t)){console.log(f.red(`Invalid problem ID: ${t}`)),console.log(f.gray("Problem ID must be a positive integer"));return}de.add(t)?console.log(f.green(`\u2713 Bookmarked problem ${t}`)):console.log(f.yellow(`Problem ${t} is already bookmarked`));break;case "remove":if(!t){console.log(f.red("Please provide a problem ID to remove"));return}de.remove(t)?console.log(f.green(`\u2713 Removed bookmark for problem ${t}`)):console.log(f.yellow(`Problem ${t} is not bookmarked`));break;case "list":await xa();break;case "clear":let n=de.count();n===0?console.log(f.yellow("No bookmarks to clear")):(de.clear(),console.log(f.green(`\u2713 Cleared ${n} bookmark${n!==1?"s":""}`)));break}}async function xa(){let e=de.list();if(e.length===0){console.log(f.yellow("\u{1F4CC} No bookmarked problems")),console.log(f.gray('Use "leetcode bookmark add <id>" to bookmark a problem'));return}console.log(),console.log(f.bold.cyan(`\u{1F4CC} Bookmarked Problems (${e.length})`)),console.log();let{authorized:t}=await v();if(t){let o=Vt({text:"Fetching problem details...",spinner:"dots"}).start();try{let n=new mo({head:[f.cyan("ID"),f.cyan("Title"),f.cyan("Difficulty"),f.cyan("Status")],colWidths:[8,45,12,10],style:{head:[],border:[]}});for(let r of e)try{let s=await S.getProblemById(r);s?n.push([s.questionFrontendId,s.title.length>42?s.title.slice(0,39)+"...":s.title,Ra(s.difficulty),s.status==="ac"?f.green("\u2713"):f.gray("-")]):n.push([r,f.gray("(not found)"),"-","-"]);}catch{n.push([r,f.gray("(error fetching)"),"-","-"]);}o.stop(),console.log(n.toString());}catch{o.stop(),console.log(f.gray("IDs: ")+e.join(", "));}}else console.log(f.gray("IDs: ")+e.join(", ")),console.log(),console.log(f.gray("Login to see problem details"));}function Ra(e){switch(e.toLowerCase()){case "easy":return f.green(e);case "medium":return f.yellow(e);case "hard":return f.red(e);default:return e}}async function Kt(e,t,o={}){if(!Ae(e)){o.silent||(console.log(f.red(`Invalid problem ID: ${e}`)),console.log(f.gray("Problem ID must be a positive integer")));return}let n=t==="view"?"view":"edit",r=join(_.getWorkDir(),".notes"),s=join(r,`${e}.md`);existsSync(r)||await mkdir(r,{recursive:true}),n==="view"?await va(s,e):await Aa(s,e,o);}async function va(e,t){if(!existsSync(e)){console.log(f.yellow(`No notes found for problem ${t}`)),console.log(f.gray(`Use "leetcode note ${t} edit" to create notes`));return}try{let o=await readFile(e,"utf-8");console.log(),console.log(f.bold.cyan(`\u{1F4DD} Notes for Problem ${t}`)),console.log(f.gray("\u2500".repeat(50))),console.log(),console.log(o);}catch(o){console.log(f.red("Failed to read notes")),o instanceof Error&&console.log(f.gray(o.message));}}async function Aa(e,t,o={}){if(!existsSync(e)){let n=await Da(t);await writeFile(e,n,"utf-8"),o.silent||console.log(f.green(`\u2713 Created notes file for problem ${t}`));}o.silent||console.log(f.gray(`Opening: ${e}`)),await yt(e);}async function Da(e){let t=`# Problem ${e} Notes
|
|
196
|
+
`).trim(),t}function Na(e,t,n,o,r,s){let i=e.linePrefix,a=[e.blockStart,`${i}${t}. ${n}`,`${i}Difficulty: ${o}`,`${i}https://leetcode.com/problems/${r}/`];if(s){a.push(`${i}`),a.push(`${i}${"\u2500".repeat(50)}`),a.push(`${i}`);let u=Ia(s).split(`
|
|
197
|
+
`);for(let p of u)if(p.length>70){let g=p.split(" "),m="";for(let b of g)(m+" "+b).length>70?(a.push(`${i}${m.trim()}`),m=b):m+=" "+b;m.trim()&&a.push(`${i}${m.trim()}`);}else a.push(`${i}${p}`);}return a.push(e.blockEnd),a.join(`
|
|
198
|
+
`)}function et(e,t,n){let o=Ze[n];return `${e}.${t}.${o}`}var Ha=["vim","nvim","vi","nano","emacs","micro","helix"],Ba=["code","code-insiders","cursor","codium","vscodium"];async function wt(e,t){let n=M.getEditor()??process.env.EDITOR??"code",o=M.getWorkDir();if(Ha.includes(n)){let r=spawn(n,[e],{stdio:"inherit"});return new Promise((s,i)=>{r.on("exit",a=>{a===0?s():i(new Error(`Editor exited with code ${a}`));}),r.on("error",a=>{i(new Error(`Failed to start editor: ${a.message}`));});})}try{if(Ba.includes(n)){spawn(n,["-r",o,"-g",e],{detached:!0,stdio:"ignore"}).unref();return}await Fa(e,{app:{name:n}});}catch{throw new Error(`Failed to open editor '${n}'. Make sure it is installed and in your PATH.`)}}async function Me(e,t){let{authorized:n}=await A();if(!n)return false;let o=nn({text:"Fetching problem details...",spinner:"dots"}).start();try{let r;if(/^\d+$/.test(e)?r=await S.getProblemById(e):r=await S.getProblem(e),!r)return o.fail(`Problem "${e}" not found`),!1;o.text="Generating solution file...";let s=t.lang??M.getLanguage(),i=qe(s);if(!i)return o.fail(`Unsupported language: ${s}`),!1;let a=r.codeSnippets??[],l=Jt(a,i),u;if(a.length===0)o.warn(f.yellow("Premium Problem (No code snippets available)")),console.log(f.gray("Generating placeholder file with problem info...")),u=Xt(i,r.title);else if(l)u=l.code;else return o.fail(`No code template available for ${i}`),console.log(f.gray(`Available languages: ${a.map(q=>q.langSlug).join(", ")}`)),!1;let p=Zt(r.questionFrontendId,r.titleSlug,r.title,r.difficulty,u,i,r.content??void 0),g=M.getWorkDir(),m=r.difficulty,b=r.topicTags.length>0?r.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",_=join(g,m,b);existsSync(_)||await mkdir(_,{recursive:!0});let C=et(r.questionFrontendId,r.titleSlug,i),R=join(_,C);return existsSync(R)?(o.warn(`File already exists: ${C}`),console.log(f.gray(`Path: ${R}`)),t.open!==!1&&await wt(R),!0):(await writeFile(R,p,"utf-8"),o.succeed(`Created ${f.green(C)}`),console.log(f.gray(`Path: ${R}`)),console.log(),console.log(f.cyan(`${r.questionFrontendId}. ${r.title}`)),console.log(f.gray(`Difficulty: ${r.difficulty} | Category: ${b}`)),t.open!==!1&&await wt(R),!0)}catch(r){if(o.fail("Failed to fetch problem"),r instanceof Error)if(r.message.includes("expected object, received null"))console.log(f.red(`Problem "${e}" not found`));else try{let s=JSON.parse(r.message);Array.isArray(s)?console.log(f.red("API Response Validation Failed")):console.log(f.red(r.message));}catch{console.log(f.red(r.message));}return false}}async function $r(e,t){if(e.length===0){console.log(f.yellow("Please provide at least one problem ID"));return}let{authorized:n}=await A();if(!n)return;console.log(f.cyan(`\u{1F4E6} Picking ${e.length} problem${e.length!==1?"s":""}...`)),console.log(),console.log();let o=0,r=0;for(let s of e)await Me(s,{...t,open:false})?o++:r++,console.log();console.log(f.gray("\u2500".repeat(50))),console.log(f.bold(`Done! ${f.green(`${o} succeeded`)}${r>0?`, ${f.red(`${r} failed`)}`:""}`));}var Fr=5;async function de(e,t,n=0){if(!existsSync(e)||n>=Fr)return null;let o=await readdir(e,{withFileTypes:true});for(let r of o){if(r.name.startsWith("."))continue;let s=join(e,r.name);if(r.isDirectory()){let i=await de(s,t,n+1);if(i)return i}else if(r.name.startsWith(`${t}.`)){let i=r.name.split(".").pop()?.toLowerCase();if(i&&i in Gn)return s}}return null}async function _t(e,t,n=0){if(!existsSync(e)||n>=Fr)return null;let o=await readdir(e,{withFileTypes:true});for(let r of o){let s=join(e,r.name);if(r.isDirectory()){let i=await _t(s,t,n+1);if(i)return i}else if(r.name===t)return s}return null}var Gn={ts:"typescript",js:"javascript",py:"python3",java:"java",cpp:"cpp",c:"c",cs:"csharp",go:"go",rs:"rust",kt:"kotlin",swift:"swift",sql:"sql"};function jn(e){let t=e.split(".").pop()?.toLowerCase();return t?Gn[t]??null:null}function en(e,t){let n=Gn[e.toLowerCase()];return n?Qt(n,t):null}async function Hr(e,t){let{authorized:n}=await A();if(!n)return;let o=e,r=M.getWorkDir();if(Ie(e)){let i=await de(r,e);if(!i){console.log(f.red(`No solution file found for problem ${e}`)),console.log(f.gray(`Looking in: ${r}`)),console.log(f.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}o=i,console.log(f.gray(`Found: ${o}`));}else if(Kt(e)){let i=await _t(r,e);if(!i){console.log(f.red(`File not found: ${e}`)),console.log(f.gray(`Looking in: ${r}`));return}o=i,console.log(f.gray(`Found: ${o}`));}if(!existsSync(o)){console.log(f.red(`File not found: ${o}`));return}if(!Xe(o,r)){console.log(f.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(f.gray(`File: ${o}`)),console.log(f.gray(`Workspace: ${r}`)),console.log(f.yellow(`
|
|
199
|
+
For security reasons, you can only test files from within your workspace.`)),console.log(f.gray('Use "leetcode config workdir <path>" to change your workspace.'));return}let s=nn({text:"Reading solution file...",spinner:"dots"}).start();try{let i=basename(o),a=i.match(/^(\d+)\.([^.]+)\./);if(!a){s.fail("Invalid filename format"),console.log(f.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(f.gray("Example: 1.two-sum.ts"));return}let l=a[2],u=i.split(".").pop(),p=await readFile(o,"utf-8");s.text="Fetching problem details...";let g=await S.getProblem(l),m=en(u,g.codeSnippets);if(!m){s.fail(`Unsupported file extension: .${u}`);return}let b=t.testcase??g.exampleTestcases??g.sampleTestCase;s.text="Running tests...";let _=await S.testSolution(l,p,m,b,g.questionId);s.stop(),fr(_,t.visualize?g.topicTags:void 0);}catch(i){s.fail("Test failed"),o.toLowerCase().endsWith(".sql")&&console.log(f.yellow("SQL interpret mode may be unavailable for this problem on LeetCode. Try `leetcode submit <file>`.")),i instanceof Error&&console.log(f.red(i.message));}}function Ur(){return T.getTimerPath()}function Ke(){let e=Ur();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{solveTimes:{},activeTimer:null}}function qn(e){let t=Ur(),n=dirname(t);existsSync(n)||mkdirSync(n,{recursive:true}),writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
200
|
+
`);}var Ee={startTimer(e,t,n,o){let r=Ke();r.activeTimer={problemId:e,title:t,difficulty:n,startedAt:new Date().toISOString(),durationMinutes:o},qn(r);},getActiveTimer(){return Ke().activeTimer},stopTimer(){let e=Ke(),t=e.activeTimer;if(!t)return null;let n=new Date(t.startedAt),r=Math.floor((new Date().getTime()-n.getTime())/1e3);return e.activeTimer=null,qn(e),{durationSeconds:r}},recordSolveTime(e,t,n,o,r){let s=Ke();s.solveTimes[e]||(s.solveTimes[e]=[]),s.solveTimes[e].push({problemId:e,title:t,difficulty:n,solvedAt:new Date().toISOString(),durationSeconds:o,timerMinutes:r}),qn(s);},getSolveTimes(e){return Ke().solveTimes[e]??[]},getAllSolveTimes(){return Ke().solveTimes??{}},getStats(){let e=Ke().solveTimes??{},t=0,n=0;for(let o of Object.values(e)){t+=o.length;for(let r of o)n+=r.durationSeconds;}return {totalProblems:t,totalTime:n,avgTime:t>0?Math.floor(n/t):0}}};async function Wr(e){let{authorized:t}=await A();if(!t)return;let n=e,o=M.getWorkDir();if(Ie(e)){let s=await de(o,e);if(!s){console.log(f.red(`No solution file found for problem ${e}`)),console.log(f.gray(`Looking in: ${o}`)),console.log(f.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}n=s,console.log(f.gray(`Found: ${n}`));}else if(Kt(e)){let s=await _t(o,e);if(!s){console.log(f.red(`File not found: ${e}`)),console.log(f.gray(`Looking in: ${o}`));return}n=s,console.log(f.gray(`Found: ${n}`));}if(!existsSync(n)){console.log(f.red(`File not found: ${n}`));return}if(!Xe(n,o)){console.log(f.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(f.gray(`File: ${n}`)),console.log(f.gray(`Workspace: ${o}`)),console.log(f.yellow(`
|
|
201
|
+
For security reasons, you can only submit files from within your workspace.`)),console.log(f.gray('Use "leetcode config workdir <path>" to change your workspace.'));return}let r=nn({text:"Reading solution file...",spinner:"dots"}).start();try{let s=basename(n),i=s.match(/^(\d+)\.([^.]+)\./);if(!i){r.fail("Invalid filename format"),console.log(f.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(f.gray("Example: 1.two-sum.ts"));return}let[,a,l]=i,u=s.split(".").pop(),p=await readFile(n,"utf-8");r.text="Fetching problem details...";let g=await S.getProblem(l),m=en(u,g.codeSnippets);if(!m){r.fail(`Unsupported file extension: .${u}`);return}r.text="Submitting solution...";let b=await S.submitSolution(l,p,m,g.questionId);if(r.stop(),mr(b),b.status_msg==="Accepted"){let _=Ee.getActiveTimer();if(_&&_.problemId===a){let C=Ee.stopTimer();if(C){Ee.recordSolveTime(a,g.title,g.difficulty,C.durationSeconds,_.durationMinutes);let R=Math.floor(C.durationSeconds/60),q=C.durationSeconds%60,K=`${R}m ${q}s`,Y=C.durationSeconds<=_.durationMinutes*60;console.log(),console.log(f.bold("\u23F1\uFE0F Timer Result:")),console.log(` Solved in ${Y?f.green(K):f.yellow(K)} (limit: ${_.durationMinutes}m)`),console.log(Y?f.green(" \u2713 Within time limit!"):f.yellow(" \u26A0 Exceeded time limit"));}}}}catch(s){r.fail("Submission failed"),s instanceof Error&&console.log(f.red(s.message));}}var Gr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function jr(e){let t=JSON.parse(e),n=new Date,o=[];for(let i=11;i>=0;i--){let a=new Date(n);a.setDate(a.getDate()-i*7-a.getDay());let l=0,u=0;for(let g=0;g<7;g++){let m=new Date(a);if(m.setDate(m.getDate()+g),m>n)break;let b=new Date(Date.UTC(m.getFullYear(),m.getMonth(),m.getDate())),_=Math.floor(b.getTime()/1e3).toString(),C=t[_]||0;l+=C,C>0&&u++;}let p=new Date(a);p.setDate(p.getDate()+6),o.push({start:`${Gr[a.getMonth()]} ${a.getDate()}`,end:`${Gr[p.getMonth()]} ${p.getDate()}`,count:l,days:u});}let r=o.reduce((i,a)=>i+a.count,0),s=o.reduce((i,a)=>i+a.days,0);console.log(),console.log(f.bold("\u{1F4C5} Activity (Last 12 Weeks)")),console.log(f.gray("How many problems you submitted and days you practiced.")),console.log(f.gray("\u2500".repeat(50))),console.log();for(let i of o){let a=`${i.start} - ${i.end}`.padEnd(18),l=i.count>0?f.green("\u2588".repeat(Math.min(i.count,10))).padEnd(10):f.gray("\xB7").padEnd(10),u=i.count>0?`${i.count} subs`.padEnd(10):"".padEnd(10),p=i.days>0?`${i.days}d active`:"";console.log(` ${f.white(a)} ${l} ${f.cyan(u)} ${f.yellow(p)}`);}console.log(f.gray("\u2500".repeat(50))),console.log(` ${f.bold.white("Total:")} ${f.cyan.bold(r+" submissions")}, ${f.yellow.bold(s+" days active")}`),console.log();}function qr(e,t,n){console.log(),console.log(f.bold("\u{1F3AF} Skill Breakdown")),console.log(f.gray("\u2500".repeat(45)));let o=(r,s,i)=>{if(s.length===0)return;console.log(),console.log(i.bold(` ${r}`));let a=[...s].sort((l,u)=>u.problemsSolved-l.problemsSolved);for(let l of a.slice(0,8)){let u=l.tagName.padEnd(22),p=i("\u2588".repeat(Math.min(l.problemsSolved,15)));console.log(` ${f.white(u)} ${p} ${f.white(l.problemsSolved)}`);}};o("Fundamental",e,f.green),o("Intermediate",t,f.yellow),o("Advanced",n,f.red),console.log();}function Kr(e){let t=JSON.parse(e),n=new Date,o=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],r=[];for(let l=6;l>=0;l--){let u=new Date(n);u.setDate(u.getDate()-l);let p=new Date(Date.UTC(u.getFullYear(),u.getMonth(),u.getDate())),g=Math.floor(p.getTime()/1e3).toString();r.push({label:o[u.getDay()],count:t[g]||0});}let s=Math.max(...r.map(l=>l.count),1),i=6;console.log(),console.log(f.bold("\u{1F4C8} Submission Trend (Last 7 Days)")),console.log(f.gray("\u2500".repeat(35))),console.log();for(let l=i;l>=1;l--){let u=` ${l===i?s.toString().padStart(2):" "} \u2502`;for(let p of r)Math.round(p.count/s*i)>=l?u+=f.green(" \u2588\u2588 "):u+=" ";console.log(u);}console.log(` 0 \u2514${"\u2500\u2500\u2500\u2500".repeat(7)}`),console.log(` ${r.map(l=>l.label.padEnd(4)).join("")}`),console.log(f.gray(` ${r.map(l=>l.count.toString().padEnd(4)).join("")}`));let a=r.reduce((l,u)=>l+u.count,0);console.log(),console.log(f.white(` Total: ${a} submissions this week`)),console.log();}async function Vr(e,t={}){let{authorized:n,username:o}=await A();if(!n)return;let r=nn("Fetching statistics...").start();try{let s=e||o;if(!s){r.fail("No username found");return}let i=await S.getUserProfile(s);if(r.stop(),!t.calendar&&!t.skills&&!t.trend){yr(i.username,i.realName,i.ranking,i.acSubmissionNum,i.streak,i.totalActiveDays);return}if(t.calendar&&(i.submissionCalendar?jr(i.submissionCalendar):console.log(f.yellow("Calendar data not available."))),t.trend&&(i.submissionCalendar?Kr(i.submissionCalendar):console.log(f.yellow("Calendar data not available."))),t.skills){r.start("Fetching skill stats...");let a=await S.getSkillStats(s);r.stop(),qr(a.fundamental,a.intermediate,a.advanced);}}catch(s){r.fail("Failed to fetch statistics"),s instanceof Error&&console.log(f.red(s.message));}}async function zr(){let{authorized:e}=await A();if(!e)return;let t=nn("Fetching daily challenge...").start();try{let n=await S.getDailyChallenge();t.stop(),hr(n.date,n.question),console.log(),console.log(f.gray("Run the following to start working on this problem:")),console.log(f.cyan(` leetcode pick ${n.question.titleSlug}`));}catch(n){t.fail("Failed to fetch daily challenge"),n instanceof Error&&console.log(f.red(n.message));}}async function Yr(e){let{authorized:t}=await A();if(!t)return;let n=nn("Fetching random problem...").start();try{let o={};if(e.difficulty){let i={easy:"EASY",e:"EASY",medium:"MEDIUM",m:"MEDIUM",hard:"HARD",h:"HARD"}[e.difficulty.toLowerCase()];if(i)o.difficulty=i;else {n.fail(`Invalid difficulty: ${e.difficulty}`);return}}e.tag&&(o.tags=[e.tag]);let r=await S.getRandomProblem(o);n.succeed("Found random problem!"),console.log(),e.pick?await Me(r,{open:e.open??!0}):(await qt(r),console.log(f.gray("Run following to start solving:")),console.log(f.cyan(` leetcode pick ${r}`)));}catch(o){n.fail("Failed to fetch random problem"),o instanceof Error&&console.log(f.red(o.message));}}async function Xr(e,t){let{authorized:n}=await A();if(!n)return;let o=nn("Fetching problem info...").start();try{let r;if(/^\d+$/.test(e)?r=await S.getProblemById(e):r=await S.getProblem(e),!r){o.fail(`Problem "${e}" not found`);return}let s=r.titleSlug;o.text="Fetching submissions...";let i=t.limit?parseInt(t.limit,10):20,a=await S.getSubmissionList(s,i);if(o.stop(),a.length===0){console.log(f.yellow("No submissions found."));return}if(t.last){let l=a.find(u=>u.statusDisplay==="Accepted");l?(console.log(f.bold("Last Accepted Submission:")),In([l])):console.log(f.yellow("No accepted submissions found in recent history."));}else In(a);if(t.download){let l=nn("Downloading submission...").start(),u=a.find(Nt=>Nt.statusDisplay==="Accepted");if(!u){l.fail("No accepted submission found to download.");return}let p=parseInt(u.id,10);if(isNaN(p)){l.fail("Invalid submission ID format");return}let g=await S.getSubmissionDetails(p),m=M.getWorkDir(),b=r.difficulty,_=r.topicTags.length>0?r.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",C=join(m,b,_);existsSync(C)||await mkdir(C,{recursive:!0});let R=g.lang.name.toLowerCase(),q=Or[R]??"txt",K=Ze[q]??R,Y=`${r.questionFrontendId}.${r.titleSlug}.submission-${u.id}.${K}`,It=join(C,Y);await writeFile(It,g.code,"utf-8"),l.succeed(`Downloaded to ${f.green(Y)}`),console.log(f.gray(`Path: ${It}`));}}catch(r){o.fail("Failed to fetch submissions"),r instanceof Error&&console.log(f.red(r.message));}}async function Zr(e){let t=e.repo!==void 0;if(!e.lang&&!e.editor&&!e.workdir&&!t){await ts();return}if(e.lang){let n=qe(e.lang);if(!n){console.log(f.red(`Unsupported language: ${e.lang}`)),console.log(f.gray(`Supported: ${Yt.join(", ")}`));return}M.setLanguage(n),console.log(f.green(`\u2713 Default language set to ${n}`));}e.editor&&(M.setEditor(e.editor),console.log(f.green(`\u2713 Editor set to ${e.editor}`))),e.workdir&&(M.setWorkDir(e.workdir),console.log(f.green(`\u2713 Work directory set to ${e.workdir}`))),t&&(e.repo===true||typeof e.repo=="string"&&e.repo.trim()===""?(M.deleteRepo(),console.log(f.green("\u2713 Repository URL cleared"))):typeof e.repo=="string"&&(M.setRepo(e.repo),console.log(f.green(`\u2713 Repository URL set to ${e.repo}`))));}async function es(){let e=M.getConfig(),t=M.getActiveWorkspace();console.log(),console.log(f.bold.cyan(`\u{1F4C1} Configuring workspace: ${t}`)),console.log(f.gray("\u2500".repeat(40)));let n=await Jn.prompt([{type:"list",name:"language",message:"Default programming language:",choices:Yt,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}]);M.setLanguage(n.language),M.setEditor(n.editor),M.setWorkDir(n.workDir),n.repo?M.setRepo(n.repo):M.deleteRepo(),console.log(),console.log(f.green("\u2713 Configuration saved")),await ts();}async function ts(){let e=M.getConfig(),t=await vn.get(),n=M.getActiveWorkspace();console.log(),console.log(f.bold.cyan(`\u{1F4C1} Workspace: ${n}`)),console.log(f.gray("\u2500".repeat(40))),console.log(),console.log(f.gray("Config file:"),M.getPath()),console.log(),console.log(f.gray("Language: "),f.white(e.language)),console.log(f.gray("Editor: "),f.white(e.editor??"(not set)")),console.log(f.gray("Work Dir: "),f.white(e.workDir)),console.log(f.gray("Repo URL: "),f.white(e.repo??"(not set)")),console.log(f.gray("Logged in: "),t?f.green("Yes"):f.yellow("No"));}var Ne=new cl({projectName:"leetcode-cli-bookmarks",defaults:{bookmarks:[]}}),pe={add(e){let t=Ne.get("bookmarks");return t.includes(e)?false:(Ne.set("bookmarks",[...t,e]),true)},remove(e){let t=Ne.get("bookmarks");return t.includes(e)?(Ne.set("bookmarks",t.filter(n=>n!==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 ns(e,t){if(!["add","remove","list","clear"].includes(e)){console.log(f.red(`Invalid action: ${e}`)),console.log(f.gray("Valid actions: add, remove, list, clear"));return}switch(e){case "add":if(!t){console.log(f.red("Please provide a problem ID to bookmark"));return}if(!Ie(t)){console.log(f.red(`Invalid problem ID: ${t}`)),console.log(f.gray("Problem ID must be a positive integer"));return}pe.add(t)?console.log(f.green(`\u2713 Bookmarked problem ${t}`)):console.log(f.yellow(`Problem ${t} is already bookmarked`));break;case "remove":if(!t){console.log(f.red("Please provide a problem ID to remove"));return}pe.remove(t)?console.log(f.green(`\u2713 Removed bookmark for problem ${t}`)):console.log(f.yellow(`Problem ${t} is not bookmarked`));break;case "list":await pl();break;case "clear":let o=pe.count();o===0?console.log(f.yellow("No bookmarks to clear")):(pe.clear(),console.log(f.green(`\u2713 Cleared ${o} bookmark${o!==1?"s":""}`)));break}}async function pl(){let e=pe.list();if(e.length===0){console.log(f.yellow("\u{1F4CC} No bookmarked problems")),console.log(f.gray('Use "leetcode bookmark add <id>" to bookmark a problem'));return}console.log(),console.log(f.bold.cyan(`\u{1F4CC} Bookmarked Problems (${e.length})`)),console.log();let{authorized:t}=await A();if(t){let n=nn({text:"Fetching problem details...",spinner:"dots"}).start();try{let o=new $n({head:[f.cyan("ID"),f.cyan("Title"),f.cyan("Difficulty"),f.cyan("Status")],colWidths:[8,45,12,10],style:{head:[],border:[]}});for(let r of e)try{let s=await S.getProblemById(r);s?o.push([s.questionFrontendId,s.title.length>42?s.title.slice(0,39)+"...":s.title,gl(s.difficulty),s.status==="ac"?f.green("\u2713"):f.gray("-")]):o.push([r,f.gray("(not found)"),"-","-"]);}catch{o.push([r,f.gray("(error fetching)"),"-","-"]);}n.stop(),console.log(o.toString());}catch{n.stop(),console.log(f.gray("IDs: ")+e.join(", "));}}else console.log(f.gray("IDs: ")+e.join(", ")),console.log(),console.log(f.gray("Login to see problem details"));}function gl(e){switch(e.toLowerCase()){case "easy":return f.green(e);case "medium":return f.yellow(e);case "hard":return f.red(e);default:return e}}async function tn(e,t,n={}){if(!Ie(e)){n.silent||(console.log(f.red(`Invalid problem ID: ${e}`)),console.log(f.gray("Problem ID must be a positive integer")));return}let o=t==="view"?"view":"edit",r=join(M.getWorkDir(),".notes"),s=join(r,`${e}.md`);existsSync(r)||await mkdir(r,{recursive:true}),o==="view"?await hl(s,e):await Sl(s,e,n);}async function hl(e,t){if(!existsSync(e)){console.log(f.yellow(`No notes found for problem ${t}`)),console.log(f.gray(`Use "leetcode note ${t} edit" to create notes`));return}try{let n=await readFile(e,"utf-8");console.log(),console.log(f.bold.cyan(`\u{1F4DD} Notes for Problem ${t}`)),console.log(f.gray("\u2500".repeat(50))),console.log(),console.log(n);}catch(n){console.log(f.red("Failed to read notes")),n instanceof Error&&console.log(f.gray(n.message));}}async function Sl(e,t,n={}){if(!existsSync(e)){let o=await bl(t);await writeFile(e,o,"utf-8"),n.silent||console.log(f.green(`\u2713 Created notes file for problem ${t}`));}n.silent||console.log(f.gray(`Opening: ${e}`)),await wt(e);}async function bl(e){let t=`# Problem ${e} Notes
|
|
195
202
|
|
|
196
|
-
`,{authorized:
|
|
203
|
+
`,{authorized:n}=await A();if(n)try{let o=await S.getProblemById(e);o&&(t=`# ${e}. ${o.title}
|
|
197
204
|
|
|
198
|
-
`,t+=`**Difficulty:** ${
|
|
199
|
-
`,t+=`**URL:** https://leetcode.com/problems/${
|
|
200
|
-
`,
|
|
205
|
+
`,t+=`**Difficulty:** ${o.difficulty}
|
|
206
|
+
`,t+=`**URL:** https://leetcode.com/problems/${o.titleSlug}/
|
|
207
|
+
`,o.topicTags.length>0&&(t+=`**Topics:** ${o.topicTags.map(r=>r.name).join(", ")}
|
|
201
208
|
`),t+=`
|
|
202
209
|
---
|
|
203
210
|
|
|
@@ -226,51 +233,54 @@ For security reasons, you can only submit files from within your workspace.`)),c
|
|
|
226
233
|
|
|
227
234
|
<!-- What did you learn from this problem? -->
|
|
228
235
|
|
|
229
|
-
`}async function
|
|
230
|
-
Please create a new repository on your Git provider and copy the URL.`));let{url:r}=await
|
|
231
|
-
`).length,i=new Date().toISOString().replace("T"," ").substring(0,19),a=`Sync: ${s} solutions - ${i}`;execFileSync("git",["commit","-m",a],{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.")}}
|
|
232
|
-
`).
|
|
236
|
+
`}async function rs(){let{authorized:e,username:t}=await A();if(!e||!t)return;let n=nn({text:"Fetching your progress...",spinner:"dots"}).start();try{let[o,r]=await Promise.all([S.getUserProfile(t),S.getDailyChallenge()]);n.stop(),console.log(),console.log(f.bold.cyan("\u{1F4CA} Today's Summary"),f.gray(`- ${t}`)),console.log(f.gray("\u2500".repeat(50))),console.log(),console.log(f.yellow(`\u{1F525} Current Streak: ${o.streak} day${o.streak!==1?"s":""}`)),console.log(f.gray(` Total Active Days: ${o.totalActiveDays}`)),console.log();let s=o.acSubmissionNum.find(p=>p.difficulty==="All"),i=o.acSubmissionNum.find(p=>p.difficulty==="Easy"),a=o.acSubmissionNum.find(p=>p.difficulty==="Medium"),l=o.acSubmissionNum.find(p=>p.difficulty==="Hard");console.log(f.white("\u{1F4C8} Problems Solved:")),console.log(` ${f.green("Easy")}: ${i?.count??0} | ${f.yellow("Medium")}: ${a?.count??0} | ${f.red("Hard")}: ${l?.count??0}`),console.log(` ${f.bold("Total")}: ${s?.count??0}`),console.log(),console.log(f.bold.yellow("\u{1F3AF} Today's Challenge:")),console.log(` ${r.question.questionFrontendId}. ${r.question.title}`),console.log(` ${Cl(r.question.difficulty)}`);let u=r.question.status;console.log(u==="ac"?f.green(" \u2713 Completed!"):u==="notac"?f.yellow(" \u25CB Attempted"):f.gray(" - Not started")),console.log(),console.log(f.gray(` leetcode pick ${r.question.questionFrontendId} # Start working on it`));}catch(o){n.fail("Failed to fetch progress"),o instanceof Error&&console.log(f.red(o.message));}}function Cl(e){switch(e.toLowerCase()){case "easy":return f.green(e);case "medium":return f.yellow(e);case "hard":return f.red(e);default:return e}}function Ml(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-").replace(/--+/g,"-")}function kl(e){let t=/^https:\/\/[\w.-]+\/[\w./-]+$/,n=/^git@[\w.-]+:[\w./-]+$/;return t.test(e)||n.test(e)}function Tl(){try{return execSync("git --version",{stdio:"ignore"}),!0}catch{return false}}function Ll(e){try{return execSync("git rev-parse --is-inside-work-tree",{cwd:e,stdio:"ignore"}),!0}catch{return false}}function Rl(){try{return execSync("gh --version",{stdio:"ignore"}),!0}catch{return false}}function Xn(e){try{return execSync("git config --get remote.origin.url",{cwd:e,encoding:"utf-8"}).trim()}catch{return null}}async function Ol(e){let{init:t}=await Jn.prompt([{type:"confirm",name:"init",message:"Work directory is not a git repository. Initialize?",default:true}]);if(!t)return console.log(f.yellow("Skipping basic git initialization.")),false;let n=nn("Initializing git repository...").start();try{return execSync("git init",{cwd:e}),n.succeed("Initialized git repository"),!0}catch(o){throw n.fail("Failed to initialize git repository"),o}}async function xl(e){let t=nn(),n=M.getRepo();if(!n){if(Rl()){let{createGh:r}=await Jn.prompt([{type:"confirm",name:"createGh",message:"Create a new private GitHub repository?",default:true}]);if(r){t.start("Creating GitHub repository...");try{let s=Ae__default.basename(e)||"leetcode-solutions",i=Ml(s);return execFileSync("gh",["repo","create",i,"--private","--source=.","--remote=origin"],{cwd:e}),t.succeed("Created and linked GitHub repository"),n=Xn(e)||"",n&&M.setRepo(n),n}catch(s){t.fail("Failed to create GitHub repository"),console.log(f.red(s));}}}if(!n){console.log(f.yellow(`
|
|
237
|
+
Please create a new repository on your Git provider and copy the URL.`));let{url:r}=await Jn.prompt([{type:"input",name:"url",message:"Enter remote repository URL:",validate:s=>s.length>0?true:"URL cannot be empty"}]);n=r;}}if(n&&!kl(n))return console.log(f.red("Invalid repository URL format.")),console.log(f.gray("Expected: https://github.com/user/repo or git@github.com:user/repo")),"";if(n&&M.setRepo(n),!Xn(e)&&n)try{execFileSync("git",["remote","add","origin",n],{cwd:e}),console.log(f.green("\u2713 Added remote origin"));}catch{return console.log(f.red("Failed to add remote origin")),""}return n||""}async function ss(){let e=M.getWorkDir();if(!existsSync(e)){console.log(f.red(`Work directory does not exist: ${e}`));return}if(!Tl()){console.log(f.red("Git is not installed. Please install Git to use command."));return}if(!Ll(e)&&!await Ol(e))return;if(!await xl(e)&&!Xn(e)){console.log(f.red("No valid remote repository configured. Sync aborted."));return}let n=nn("Syncing solutions...").start();try{let o=execSync("git status --porcelain",{cwd:e,encoding:"utf-8"});if(!o){n.info("No changes to sync");return}execSync("git add .",{cwd:e});let s=o.trim().split(`
|
|
238
|
+
`).length,i=new Date().toISOString().replace("T"," ").substring(0,19),a=`Sync: ${s} solutions - ${i}`;execFileSync("git",["commit","-m",a],{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.")}}n.succeed("Successfully synced solutions to remote");}catch(o){n.fail("Sync failed"),o instanceof Error&&o.message&&console.log(f.red(o.message));}}var vl={Easy:20,Medium:40,Hard:60};function nt(e){if(e<60)return `${e}s`;if(e<3600){let t=Math.floor(e/60),n=e%60;return n>0?`${t}m ${n}s`:`${t}m`}else {let t=Math.floor(e/3600),n=Math.floor(e%3600/60);return n>0?`${t}h ${n}m`:`${t}h`}}async function is(e,t){if(t.stats){await $l(e);return}if(t.stop){await Al();return}if(!e){console.log(f.yellow("Please provide a problem ID to start the timer.")),console.log(f.gray("Usage: leetcode timer <id>")),console.log(f.gray(" leetcode timer --stats")),console.log(f.gray(" leetcode timer --stop"));return}let{authorized:n}=await A();if(!n)return;let o=Ee.getActiveTimer();if(o){let s=new Date(o.startedAt),i=Math.floor((Date.now()-s.getTime())/1e3);console.log(f.yellow("\u26A0\uFE0F You have an active timer running:")),console.log(f.white(` Problem: ${o.title}`)),console.log(f.white(` Elapsed: ${nt(i)}`)),console.log(),console.log(f.gray("Use `leetcode timer --stop` to stop it first."));return}let r=nn("Fetching problem...").start();try{let s;if(/^\d+$/.test(e)?s=await S.getProblemById(e):s=await S.getProblem(e),!s){r.fail(`Problem "${e}" not found`);return}r.stop();let i=t.minutes??vl[s.difficulty]??30;Ee.startTimer(s.questionFrontendId,s.title,s.difficulty,i),console.log(),console.log(f.bold.cyan("\u23F1\uFE0F Interview Mode Started!")),console.log(f.gray("\u2500".repeat(50))),console.log(),console.log(f.white(`Problem: ${s.questionFrontendId}. ${s.title}`)),console.log(f.white(`Difficulty: ${f.bold(s.difficulty)}`)),console.log(f.white(`Time Limit: ${f.bold.yellow(i+" minutes")}`)),console.log(),console.log(f.gray("\u2500".repeat(50))),console.log(f.green("\u2713 Timer is running in background")),console.log(f.gray(" When you submit successfully, your time will be recorded.")),console.log(f.gray(" Use `leetcode timer --stop` to cancel.")),console.log(),await Me(e,{open:!0});}catch(s){r.fail("Failed to start timer"),s instanceof Error&&console.log(f.red(s.message));}}async function Al(){let e=Ee.stopTimer();if(!e){console.log(f.yellow("No active timer to stop."));return}console.log(f.green("\u23F1\uFE0F Timer stopped.")),console.log(f.gray(`Elapsed time: ${nt(e.durationSeconds)}`)),console.log(f.gray("(Time not recorded since problem was not submitted)"));}async function $l(e){if(e&&/^\d+$/.test(e)){let t=Ee.getSolveTimes(e);if(t.length===0){console.log(f.yellow(`No solve times recorded for problem ${e}`));return}console.log(),console.log(f.bold(`\u23F1\uFE0F Solve Times for Problem ${e}`)),console.log(f.gray("\u2500".repeat(40)));for(let n of t){let o=new Date(n.solvedAt).toLocaleDateString(),r=nt(n.durationSeconds),s=n.timerMinutes,i=n.durationSeconds<=s*60;console.log(` ${o} ${i?f.green(r):f.red(r)} (limit: ${s}m)`);}}else {let t=Ee.getStats(),n=Ee.getAllSolveTimes();console.log(),console.log(f.bold("\u23F1\uFE0F Timer Statistics")),console.log(f.gray("\u2500".repeat(40))),console.log(),console.log(` Problems timed: ${f.cyan(t.totalProblems)}`),console.log(` Total time: ${f.cyan(nt(t.totalTime))}`),console.log(` Average time: ${f.cyan(nt(t.avgTime))}`),console.log();let o=[];for(let[r,s]of Object.entries(n))for(let i of s)o.push({problemId:r,title:i.title,duration:i.durationSeconds,date:i.solvedAt});if(o.length>0){o.sort((r,s)=>new Date(s.date).getTime()-new Date(r.date).getTime()),console.log(f.bold(" Recent Solves:"));for(let r of o.slice(0,5)){let s=new Date(r.date).toLocaleDateString();console.log(f.gray(` ${s} `)+f.white(`${r.problemId}. ${r.title.substring(0,25)}`)+f.gray(" ")+f.cyan(nt(r.duration)));}}console.log();}}var Il="https://abagrmwdpvnfyuqizyym.supabase.co",Nl="sb_publishable_indrKu8VJmASdyLp7w8Hog_OyqT17cV",Fe=createClient(Il,Nl);function eo(){return T.getCollabPath()}function Wl(){let e=eo();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{session:null}}function Gl(e){let t=eo(),n=dirname(t);existsSync(n)||mkdirSync(n,{recursive:true}),writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
239
|
+
`);}var Oe={getSession(){return Wl().session},setSession(e){Gl({session:e});},getPath(){return eo()}};function jl(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<6;n++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}var we={getSession(){return Oe.getSession()},async createRoom(e,t){let n=jl(),{error:o}=await Fe.from("collab_rooms").insert({room_code:n,problem_id:e,host_username:t,host_code:"",guest_username:null,guest_code:null});return o?{error:o.message}:(Oe.setSession({roomCode:n,problemId:e,isHost:true,username:t}),{roomCode:n})},async joinRoom(e,t){let{data:n,error:o}=await Fe.from("collab_rooms").select("*").eq("room_code",e.toUpperCase()).single();if(o||!n)return {error:"Room not found"};if(n.guest_username&&n.guest_username!==t)return {error:"Room already has a guest"};let{error:r}=await Fe.from("collab_rooms").update({guest_username:t}).eq("room_code",e.toUpperCase());return r?{error:r.message}:(Oe.setSession({roomCode:e.toUpperCase(),problemId:n.problem_id,isHost:false,username:t}),{problemId:n.problem_id})},async syncCode(e){let t=Oe.getSession();if(!t)return {success:false,error:"No active session"};let n=t.isHost?"host_code":"guest_code",{error:o}=await Fe.from("collab_rooms").update({[n]:e}).eq("room_code",t.roomCode);return o?{success:false,error:o.message}:{success:true}},async getPartnerCode(){let e=Oe.getSession();if(!e)return {error:"No active session"};let{data:t,error:n}=await Fe.from("collab_rooms").select("*").eq("room_code",e.roomCode).single();return n||!t?{error:"Room not found"}:e.isHost?{code:t.guest_code||"",username:t.guest_username||"Partner"}:{code:t.host_code||"",username:t.host_username||"Host"}},async getRoomStatus(){let e=Oe.getSession();if(!e)return {error:"No active session"};let{data:t,error:n}=await Fe.from("collab_rooms").select("*").eq("room_code",e.roomCode).single();return n||!t?{error:"Room not found"}:{host:t.host_username,guest:t.guest_username,hasHostCode:!!t.host_code,hasGuestCode:!!t.guest_code}},async leaveRoom(){let e=Oe.getSession();e&&e.isHost&&await Fe.from("collab_rooms").delete().eq("room_code",e.roomCode),Oe.setSession(null);}};async function cs(e){let{authorized:t,username:n}=await A();if(!t||!n)return;let o=nn("Creating collaboration room...").start();try{let r=await we.createRoom(e,n);if("error"in r){o.fail(r.error);return}o.succeed("Room created!"),console.log(),console.log(f.bold.cyan("\u{1F465} Collaborative Coding Session")),console.log(f.gray("\u2500".repeat(50))),console.log(),console.log(f.white(`Room Code: ${f.bold.green(r.roomCode)}`)),console.log(f.white(`Problem: ${e}`)),console.log(),console.log(f.gray("Share this code with your partner:")),console.log(f.yellow(` leetcode collab join ${r.roomCode}`)),console.log(),console.log(f.gray("\u2500".repeat(50))),console.log(f.gray("After solving, sync and compare:")),console.log(f.gray(" leetcode collab sync - Upload your solution")),console.log(f.gray(" leetcode collab compare - See both solutions")),console.log(f.gray(" leetcode collab status - Check room status")),console.log(f.gray(" leetcode collab leave - End session")),console.log(),await Me(e,{open:!0});}catch(r){o.fail("Failed to create room"),r instanceof Error&&console.log(f.red(r.message));}}async function us(e){let{authorized:t,username:n}=await A();if(!t||!n)return;let o=nn(`Joining room ${e}...`).start();try{let r=await we.joinRoom(e.toUpperCase(),n);if("error"in r){o.fail(r.error);return}o.succeed("Joined room!"),console.log(),console.log(f.bold.cyan("\u{1F465} Collaborative Coding Session")),console.log(f.gray("\u2500".repeat(50))),console.log(),console.log(f.white(`Room Code: ${f.bold.green(e.toUpperCase())}`)),console.log(f.white(`Problem: ${r.problemId}`)),console.log(),console.log(f.gray("\u2500".repeat(50))),console.log(f.gray("After solving, sync and compare:")),console.log(f.gray(" leetcode collab sync - Upload your solution")),console.log(f.gray(" leetcode collab compare - See both solutions")),console.log(f.gray(" leetcode collab status - Check room status")),console.log(f.gray(" leetcode collab leave - End session")),console.log(),await Me(r.problemId,{open:!0});}catch(r){o.fail("Failed to join room"),r instanceof Error&&console.log(f.red(r.message));}}async function ds(){let e=we.getSession();if(!e){console.log(f.yellow("No active collaboration session.")),console.log(f.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` first."));return}let t=nn("Syncing your code...").start();try{let n=M.getWorkDir(),o=await de(n,e.problemId);if(!o){t.fail(`No solution file found for problem ${e.problemId}`);return}let r=await readFile(o,"utf-8"),s=await we.syncCode(r);s.success?(t.succeed("Code synced successfully!"),console.log(f.gray(`Uploaded ${r.split(`
|
|
240
|
+
`).length} lines from ${o}`))):t.fail(s.error||"Sync failed");}catch(n){t.fail("Sync failed"),n instanceof Error&&console.log(f.red(n.message));}}async function ps(){let e=we.getSession();if(!e){console.log(f.yellow("No active collaboration session.")),console.log(f.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` first."));return}let t=nn("Fetching solutions...").start();try{let n=M.getWorkDir(),o=await de(n,e.problemId);if(!o){t.fail(`No solution file found for problem ${e.problemId}`);return}let r=await readFile(o,"utf-8"),s=await we.getPartnerCode();if("error"in s){t.fail(s.error);return}if(t.stop(),!s.code){console.log(f.yellow("Partner has not synced their code yet.")),console.log(f.gray("Ask them to run `leetcode collab sync`."));return}console.log(),console.log(f.bold.cyan("\u{1F4CA} Solution Comparison")),console.log(f.gray("\u2500".repeat(60))),console.log(),console.log(f.bold.green(`\u25B8 Your Solution (${e.username})`)),console.log(f.gray("\u2500".repeat(60)));let i=r.split(`
|
|
233
241
|
`);for(let l=0;l<i.length;l++){let u=String(l+1).padStart(3," ");console.log(`${f.gray(u)} ${i[l]}`);}console.log(),console.log(f.bold.blue(`\u25B8 ${s.username}'s Solution`)),console.log(f.gray("\u2500".repeat(60)));let a=s.code.split(`
|
|
234
|
-
`);for(let l=0;l<a.length;l++){let u=String(l+1).padStart(3," ");console.log(`${f.gray(u)} ${a[l]}`);}console.log(),console.log(f.gray("\u2500".repeat(60))),console.log(f.gray(`Your code: ${i.length} lines | Partner: ${a.length} lines`)),console.log();}catch(
|
|
235
|
-
`)
|
|
236
|
-
`).
|
|
237
|
-
`)
|
|
242
|
+
`);for(let l=0;l<a.length;l++){let u=String(l+1).padStart(3," ");console.log(`${f.gray(u)} ${a[l]}`);}console.log(),console.log(f.gray("\u2500".repeat(60))),console.log(f.gray(`Your code: ${i.length} lines | Partner: ${a.length} lines`)),console.log();}catch(n){t.fail("Failed to fetch solutions"),n instanceof Error&&console.log(f.red(n.message));}}async function gs(){if(!we.getSession()){console.log(f.yellow("No active collaboration session."));return}await we.leaveRoom(),console.log(f.green("\u2713 Left the collaboration session."));}async function fs(){let e=we.getSession();if(!e){console.log(f.yellow("No active collaboration session.")),console.log(f.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` to start."));return}let t=await we.getRoomStatus();if("error"in t){console.log(f.red(t.error));return}console.log(),console.log(f.bold.cyan("\u{1F465} Collaboration Status")),console.log(f.gray("\u2500".repeat(40))),console.log(` Room: ${f.green(e.roomCode)}`),console.log(` Problem: ${e.problemId}`),console.log(` Role: ${e.isHost?"Host":"Guest"}`),console.log(),console.log(f.bold(" Participants:")),console.log(` Host: ${t.host} ${t.hasHostCode?f.green("\u2713 synced"):f.gray("pending")}`),console.log(` Guest: ${t.guest||f.gray("(waiting...)")} ${t.hasGuestCode?f.green("\u2713 synced"):f.gray("pending")}`),console.log();}function Vl(){return T.getSnapshotsDir()}function Ss(e){return join(Vl(),e)}function bs(e){return join(Ss(e),"meta.json")}function on(e){return join(Ss(e),"files")}function Es(e){let t=on(e);existsSync(t)||mkdirSync(t,{recursive:true});}function Mt(e){let t=bs(e);return existsSync(t)?JSON.parse(readFileSync(t,"utf-8")):{problemId:e,problemTitle:"",snapshots:[]}}function ms(e,t){Es(e),writeFileSync(bs(e),JSON.stringify(t,null,2)+`
|
|
243
|
+
`);}var X={save(e,t,n,o,r){Es(e);let s=Mt(e);t&&(s.problemTitle=t);let i=s.snapshots.length>0?Math.max(...s.snapshots.map(b=>b.id))+1:1,a=(r??`snapshot-${i}`).trim();if(!_r(a))return {error:'Invalid snapshot name. Use 1-64 characters: letters, numbers, spaces, "-" or "_".'};let l=s.snapshots.find(b=>b.name===a);if(l)return {error:`Snapshot with name "${a}" already exists (ID: ${l.id})`};let u=Ze[o]||o,p=`${i}_${a}.${u}`,g=join(on(e),p);writeFileSync(g,n,"utf-8");let m={id:i,name:a,fileName:p,language:o,lines:n.split(`
|
|
244
|
+
`).length,createdAt:new Date().toISOString()};return s.snapshots.push(m),ms(e,s),m},list(e){return Mt(e).snapshots},getMeta(e){return Mt(e)},get(e,t){let n=Mt(e),o=n.snapshots.find(s=>s.id===parseInt(t,10));return o||n.snapshots.find(s=>s.name===t)||null},getCode(e,t){let n=join(on(e),t.fileName);if(!existsSync(n))throw new Error(`Snapshot file not found: ${t.fileName}`);return readFileSync(n,"utf-8")},delete(e,t){let n=Mt(e),o=this.get(e,t);if(!o)return false;let r=join(on(e),o.fileName);return existsSync(r)&&unlinkSync(r),n.snapshots=n.snapshots.filter(s=>s.id!==o.id),ms(e,n),true},hasSnapshots(e){return this.list(e).length>0}};function Jl(e){let t=new Date(e),o=new Date().getTime()-t.getTime(),r=Math.floor(o/6e4),s=Math.floor(r/60),i=Math.floor(s/24);return r<1?"just now":r<60?`${r}m ago`:s<24?`${s}h ago`:`${i}d ago`}async function _s(e,t){let n=M.getWorkDir();try{let o=await de(n,e);if(!o){console.log(f.red(`No solution file found for problem ${e}`)),console.log(f.gray("Run `leetcode pick "+e+"` first to create a solution file."));return}let r=await readFile(o,"utf-8"),s=extname(o).slice(1),i=jn(o)||s,l=basename(o).match(/^\d+\.(.+)\.\w+$/),u=l?l[1]:"",p=X.save(e,u,r,i,t);if("error"in p){console.log(f.red("\u2717 "+p.error));return}let g=p;console.log(f.green("\u2713 Snapshot saved!")),console.log(),console.log(` ID: ${f.cyan(g.id)}`),console.log(` Name: ${f.white(g.name)}`),console.log(` Lines: ${f.gray(g.lines)}`),console.log(` File: ${f.gray(o)}`);}catch(o){console.log(f.red("Failed to save snapshot")),o instanceof Error&&console.log(f.gray(o.message));}}async function Ms(e){let t=X.list(e);if(t.length===0){console.log(f.yellow(`No snapshots found for problem ${e}`)),console.log(f.gray("Use `leetcode snapshot save "+e+"` to create one."));return}let n=X.getMeta(e);console.log(),console.log(f.bold(`\u{1F4F8} Snapshots for Problem ${e}`)),n.problemTitle&&console.log(f.gray(` ${n.problemTitle}`)),console.log(f.gray("\u2500".repeat(50))),console.log();for(let o of t){let r=Jl(o.createdAt);console.log(` ${f.cyan(o.id.toString().padStart(2))}. ${f.white(o.name.padEnd(25))} ${f.gray(o.lines+" lines")} ${f.gray("\xB7")} ${f.gray(r)}`);}console.log(),console.log(f.gray("Commands:")),console.log(f.gray(` restore: leetcode snapshot restore ${e} <id|name>`)),console.log(f.gray(` diff: leetcode snapshot diff ${e} <id1> <id2>`)),console.log(f.gray(` delete: leetcode snapshot delete ${e} <id|name>`));}async function ks(e,t){let n=M.getWorkDir();try{let o=X.get(e,t);if(!o){console.log(f.red(`Snapshot "${t}" not found for problem ${e}`)),console.log(f.gray("Run `leetcode snapshot list "+e+"` to see available snapshots."));return}let r=await de(n,e);if(!r){console.log(f.red(`No solution file found for problem ${e}`));return}let s=await readFile(r,"utf-8"),i=`backup-before-restore-${Date.now()}`,a=extname(r).slice(1),l=jn(r)||a;X.save(e,"",s,l,i);let u=X.getCode(e,o);await writeFile(r,u,"utf-8"),console.log(f.green("\u2713 Snapshot restored!")),console.log(),console.log(` Restored: ${f.cyan(o.name)} (${o.lines} lines)`),console.log(` File: ${f.gray(r)}`),console.log(` Backup: ${f.gray(i)}`);}catch(o){console.log(f.red("Failed to restore snapshot")),o instanceof Error&&console.log(f.gray(o.message));}}async function Ts(e,t,n){try{let o=X.get(e,t),r=X.get(e,n);if(!o){console.log(f.red(`Snapshot "${t}" not found`));return}if(!r){console.log(f.red(`Snapshot "${n}" not found`));return}let s=X.getCode(e,o),i=X.getCode(e,r);console.log(),console.log(f.bold(`\u{1F4CA} Diff: ${o.name} \u2192 ${r.name}`)),console.log(f.gray("\u2500".repeat(50))),console.log();let a=diffLines(s,i),l=0,u=0;for(let p of a){let g=p.value.split(`
|
|
245
|
+
`).filter(m=>m!=="");if(p.added){l+=g.length;for(let m of g)console.log(f.green("+ "+m));}else if(p.removed){u+=g.length;for(let m of g)console.log(f.red("- "+m));}else if(g.length<=4)for(let m of g)console.log(f.gray(" "+m));else console.log(f.gray(" "+g[0])),console.log(f.gray(" "+g[1])),console.log(f.gray(` ... (${g.length-4} more lines)`)),console.log(f.gray(" "+g[g.length-2])),console.log(f.gray(" "+g[g.length-1]));}console.log(),console.log(f.gray("\u2500".repeat(50))),console.log(`${f.green("+"+l+" added")} ${f.gray("\xB7")} ${f.red("-"+u+" removed")} ${f.gray("\xB7")} ${f.gray(o.lines+" \u2192 "+r.lines+" lines")}`);}catch(o){console.log(f.red("Failed to diff snapshots")),o instanceof Error&&console.log(f.gray(o.message));}}async function Ls(e,t){let n=X.get(e,t);if(!n){console.log(f.red(`Snapshot "${t}" not found for problem ${e}`));return}let o=X.delete(e,t);console.log(o?f.green(`\u2713 Deleted snapshot: ${n.name}`):f.red("Failed to delete snapshot"));}function Os(e,t){let n=e.split(`
|
|
246
|
+
`),o=n.length;console.log(),console.log(f.bold.cyan(`=== ${t} (${o} lines) ===`)),console.log(f.gray("\u2500".repeat(60))),n.forEach((r,s)=>{let i=(s+1).toString().padStart(3);console.log(f.gray(i+" \u2502 ")+r);});}function ec(e,t,n,o){let r=e.split(`
|
|
238
247
|
`).length,s=t.split(`
|
|
239
|
-
`).length;console.log(),console.log(f.bold(`\u{1F4CA} Unified Diff: ${
|
|
240
|
-
`).filter(
|
|
241
|
-
`).filter(
|
|
242
|
-
For security reasons, you can only diff files from within your workspace.`));return}let
|
|
243
|
-
`)
|
|
244
|
-
`),s=false;for(let i of r)if(!(i.trim()===""&&!s)){if(i.startsWith("> **Release Date**")){let a=i.replace("> **Release Date**: ","").trim();console.log(f.gray(` \u{1F4C5} ${a}`));continue}if(i.startsWith("> **Focus**")){let a=i.replace("> **Focus**: ","").trim();console.log(f.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(f.bold.yellow(` ${a}`));else {let u="\u{1F4CC}";a.includes("Breaking")?u="\u26A0\uFE0F":a.includes("Feature")||a.includes("New")?u="\u{1F680}":a.includes("Fix")||a.includes("Bug")?u="\u{1F41B}":a.includes("Security")?u="\u{1F512}":a.includes("Improvement")?u="\u2728":a.includes("Architecture")?u="\u{1F3D7}\uFE0F":a.includes("Testing")?u="\u{1F9EA}":a.includes("Config")&&(u="\u2699\uFE0F"),console.log(f.bold.yellow(` ${u} ${a}`));}s=true;continue}if(i.startsWith("#### ")){let a=i.replace("#### ","").trim();console.log(f.bold.white(` ${a}`));continue}if(i.startsWith("- **")){let a=i.match(/^- \*\*(.+?)\*\*:?\s*(.*)/);console.log(a?f.cyan(` \u2022 ${f.bold(a[1])}`)+(a[2]?f.white(`: ${a[2]}`):""):f.cyan(` \u2022 ${i.replace("- ","")}`));continue}if(i.startsWith("- ")){let a=i.replace("- ","").trim();console.log(f.white(` \u2022 ${a}`));continue}i.startsWith("---")||i.trim()===">"||i.trim()&&console.log(f.gray(` ${i.trim()}`));}}async function ks(e,t={}){let o=Vt("Fetching changelog...").start();try{let n=await ql();o.stop();let r=Kl(n);if(r.length===0){console.log(f.yellow("No release entries found."));return}let s=Gl(),i=r;if(e){let a=e.startsWith("v")?e:`v${e}`;if(i=r.filter(l=>l.version===a),i.length===0){console.log(f.red(`Version ${e} not found in changelog.`)),console.log(f.gray("Available versions: "+r.map(l=>l.version).join(", ")));return}}else if(t.latest)i=r.slice(0,1);else if(t.breaking){if(i=r.filter(a=>a.hasBreakingChanges),i.length===0){console.log(f.green("\u2713 No breaking changes in any release."));return}}else if(t.all)i=r;else {if(i=r.filter(a=>Ze(a.version,s)),i.length===0){console.log(f.green(`\u2713 You're on the latest version (${s})`)),console.log(f.gray("Use --all to see the full changelog."));return}console.log(f.gray(`Showing changes since your version (${s})`)),console.log(f.gray("Use --all to see the full changelog."));}console.log(),console.log(f.bold.cyan("\u{1F4CB} LeetCode CLI Release Notes")),console.log(f.gray("\u2500".repeat(50))),console.log();for(let a of i)Vl(a.version,a.content,a.hasBreakingChanges),console.log(f.gray("\u2500".repeat(60))),console.log();if(!e&&!t.latest){let a=r.filter(l=>l.hasBreakingChanges).length;console.log(f.gray(`Showing ${i.length} of ${r.length} releases`)),a>0&&!t.breaking&&console.log(f.yellow(`${a} release(s) contain breaking changes. Use --breaking to filter.`));}}catch{o.fail("Failed to fetch changelog"),console.log(f.gray(" Could not fetch release notes from GitHub.")),console.log(f.gray(" Visit: https://github.com/night-slayer18/leetcode-cli/blob/main/docs/releases.md"));}}var c={none:()=>({type:"CMD_NONE"}),batch:(...e)=>({type:"CMD_BATCH",commands:e}),fetchProblems:(e,t=false)=>({type:"CMD_FETCH_PROBLEMS",filters:e,append:t}),fetchProblemDetail:e=>({type:"CMD_FETCH_PROBLEM_DETAIL",slug:e}),fetchStats:()=>({type:"CMD_FETCH_STATS"}),fetchDaily:()=>({type:"CMD_FETCH_DAILY"}),fetchRandom:()=>({type:"CMD_FETCH_RANDOM"}),checkAuth:()=>({type:"CMD_CHECK_AUTH"}),pickProblem:(e,t)=>({type:"CMD_PICK_PROBLEM",slug:e,lang:t}),testSolution:e=>({type:"CMD_TEST_SOLUTION",slug:e}),submitSolution:e=>({type:"CMD_SUBMIT_SOLUTION",slug:e}),startTimer:(e=1e3)=>({type:"CMD_START_TIMER_SUBSCRIPTION",intervalMs:e}),stopTimer:()=>({type:"CMD_STOP_TIMER_SUBSCRIPTION"}),saveConfig:(e,t)=>({type:"CMD_SAVE_CONFIG",key:e,value:t}),openEditor:e=>({type:"CMD_OPEN_EDITOR",id:e}),fetchSubmissions:e=>({type:"CMD_FETCH_SUBMISSIONS",slug:e}),exit:()=>({type:"CMD_EXIT"}),loadNote:e=>({type:"CMD_LOAD_NOTE",problemId:e}),diffSnapshot:(e,t)=>({type:"CMD_DIFF_SNAPSHOT",slug:e,snapshotId:t}),restoreSnapshot:(e,t)=>({type:"CMD_RESTORE_SNAPSHOT",slug:e,snapshotId:t}),loadWorkspaces:()=>({type:"CMD_LOAD_WORKSPACES"}),createWorkspace:e=>({type:"CMD_CREATE_WORKSPACE",name:e}),deleteWorkspace:e=>({type:"CMD_DELETE_WORKSPACE",name:e}),switchWorkspace:e=>({type:"CMD_SWITCH_WORKSPACE",name:e}),fetchChangelog:()=>({type:"CMD_FETCH_CHANGELOG"}),logout:()=>({type:"CMD_LOGOUT"}),login:(e,t)=>({type:"CMD_LOGIN",session:e,csrf:t})};function Ts(e){return {screenState:{screen:"home",model:{menuIndex:0}},history:[],user:e?{username:e,isLoggedIn:true}:null,isCheckingAuth:true,globalError:null,terminalWidth:process.stdout.columns||80,terminalHeight:process.stdout.rows||24,needsRender:true}}var Qt=50;function zl(){return {problems:[],total:0,cursor:0,scrollOffset:0,page:0,loading:true,loadingMore:false,error:null,searchQuery:"",searchMode:false,searchBuffer:"",difficultyFilter:null,statusFilter:null,bookmarkFilter:false}}function Ho(){let e=zl(),t={limit:Qt,skip:0};return [e,c.fetchProblems(t,false)]}function Uo(e,t,o){let n=Math.max(3,o-13);switch(e.type){case "LIST_CURSOR_DOWN":{if(t.problems.length===0)return [t,c.none()];let r=Math.min(t.cursor+1,t.problems.length-1),s=t.scrollOffset;if(r>=t.scrollOffset+n&&(s=r-n+1),r>=t.problems.length-5&&t.problems.length<t.total&&!t.loadingMore&&!t.loading){let a=tt(t,t.page+1);return [{...t,cursor:r,scrollOffset:s,loadingMore:true},c.fetchProblems(a,true)]}return [{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_CURSOR_UP":{if(t.problems.length===0)return [t,c.none()];let r=Math.max(t.cursor-1,0),s=t.scrollOffset;return r<t.scrollOffset&&(s=r),[{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_PAGE_DOWN":{let r=Math.min(t.cursor+n,t.problems.length-1),s=Math.min(t.scrollOffset+n,Math.max(0,t.problems.length-n));return [{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_PAGE_UP":{let r=Math.max(t.cursor-n,0),s=Math.max(t.scrollOffset-n,0);return [{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_GO_TOP":return [{...t,cursor:0,scrollOffset:0},c.none()];case "LIST_GO_BOTTOM":{let r=Math.max(0,t.problems.length-1),s=Math.max(0,t.problems.length-n);return [{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_SELECT":return [t,c.none()];case "LIST_SEARCH_START":return [{...t,searchMode:true,searchBuffer:t.searchQuery},c.none()];case "LIST_SEARCH_INPUT":return [{...t,searchBuffer:t.searchBuffer+e.char},c.none()];case "LIST_SEARCH_BACKSPACE":return [{...t,searchBuffer:t.searchBuffer.slice(0,-1)},c.none()];case "LIST_SEARCH_SUBMIT":{let r=tt({...t,searchQuery:t.searchBuffer},0);return [{...t,searchMode:false,searchQuery:t.searchBuffer,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(r,false)]}case "LIST_SEARCH_CANCEL":return [{...t,searchMode:false,searchBuffer:""},c.none()];case "LIST_FILTER_DIFFICULTY":{let r=e.difficulty,s=tt({...t,difficultyFilter:r},0);return [{...t,difficultyFilter:r,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(s,false)]}case "LIST_FILTER_STATUS":{let r=e.status,s=tt({...t,statusFilter:r},0);return [{...t,statusFilter:r,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(s,false)]}case "LIST_FILTER_BOOKMARKS":{let r=!t.bookmarkFilter,s=tt({...t},0);return [{...t,bookmarkFilter:r,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(s,false)]}case "LIST_CLEAR_FILTERS":{let r={limit:Qt,skip:0};return [{...t,difficultyFilter:null,statusFilter:null,searchQuery:"",bookmarkFilter:false,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(r,false)]}case "LIST_REFRESH":{let r=tt(t,0);return [{...t,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(r,false)]}case "LIST_FETCH_START":return [{...t,loading:true,error:null},c.none()];case "LIST_FETCH_SUCCESS":{let r=e.append?[...t.problems,...e.problems]:e.problems;return t.bookmarkFilter&&(r=r.filter(s=>de.has(s.questionFrontendId))),[{...t,problems:r,total:t.bookmarkFilter?r.length:e.total,loading:false,loadingMore:false,page:e.append?t.page+1:0,error:null},c.none()]}case "LIST_FETCH_ERROR":return [{...t,loading:false,loadingMore:false,error:e.error},c.none()];default:return [t,c.none()]}}function tt(e,t){let o={limit:Qt,skip:t*Qt};if(e.difficultyFilter&&(o.difficulty=e.difficultyFilter.toUpperCase()),e.statusFilter){let n={solved:"AC",attempted:"TRIED",todo:"NOT_STARTED"};o.status=n[e.statusFilter];}return e.searchQuery&&(o.searchKeywords=e.searchQuery),o}var Ct=[{key:"l",label:"Problem List",description:"Browse and search problems"},{key:"d",label:"Daily Challenge",description:"Today's daily problem"},{key:"r",label:"Random Problem",description:"Pick a random problem"},{key:"b",label:"Bookmarks",description:"View bookmarked problems"},{key:"t",label:"Timer",description:"Practice timer"},{key:"s",label:"Statistics",description:"View your progress"},{key:"y",label:"Sync",description:"Sync solutions to GitHub"},{key:"w",label:"Workspaces",description:"Manage workspaces"},{key:"c",label:"Config",description:"Settings and preferences"},{key:"v",label:"Changelog",description:"What's new in this version"},{key:"L",label:"Logout",description:"Sign out of LeetCode"},{key:"?",label:"Help",description:"Keyboard shortcuts and help"}];function Jt(e,t){switch(e.type){case "HOME_MENU_UP":{let o=Math.max(0,t.menuIndex-1);return [{...t,menuIndex:o},c.none()]}case "HOME_MENU_DOWN":{let o=Math.min(Ct.length-1,t.menuIndex+1);return [{...t,menuIndex:o},c.none()]}case "HOME_MENU_SELECT":return [t,c.none()];default:return [t,c.none()]}}function Xt(e,t){switch(e.type){case "TIMER_START":return t.status==="running"?[t,c.none()]:[{...t,status:"running"},c.startTimer(1e3)];case "TIMER_PAUSE":return t.status!=="running"?[t,c.none()]:[{...t,status:"paused"},c.stopTimer()];case "TIMER_RESET":return [{...t,remainingSeconds:t.totalSeconds,status:"idle"},c.stopTimer()];case "TIMER_TICK":return t.status!=="running"?[t,c.none()]:t.remainingSeconds<=1?[{...t,remainingSeconds:0,status:"completed"},c.stopTimer()]:[{...t,remainingSeconds:t.remainingSeconds-1},c.none()];case "TIMER_COMPLETE":return [{...t,status:"completed"},c.stopTimer()];case "TIMER_SWITCH_VIEW":return [{...t,viewMode:e.view},c.none()];default:return [t,c.none()]}}function Xl(){return {loading:true,error:null,stats:null,dailyChallenge:null,skillStats:null}}function Ls(){return [Xl(),c.fetchStats()]}function Bo(e,t){switch(e.type){case "STATS_FETCH_START":return [{...t,loading:true,error:null},c.none()];case "STATS_FETCH_SUCCESS":return [{...t,loading:false,stats:e.stats,dailyChallenge:e.daily,skillStats:e.skills},c.none()];case "STATS_FETCH_ERROR":return [{...t,loading:false,error:e.error},c.none()];case "STATS_REFRESH":return [{...t,loading:true,error:null},c.fetchStats()];default:return [t,c.none()]}}function ec(e){return [{id:"language",label:"Default Language",description:"Language for new solutions (example: typescript, python3, sql)",value:e.language},{id:"editor",label:"Editor Command",description:"Command used to open files (example: code, vim, nano)",value:e.editor||""},{id:"workdir",label:"Working Directory",description:"Directory where solution files are generated",value:e.workDir},{id:"repo",label:"Sync Repository",description:"Git repository URL used for sync operations",value:e.repo||""}]}function Wo(e){return e.options[e.selectedOption]}function tc(e,t){let o=t.trim();return e.id==="language"&&!o?"Language cannot be empty":e.id==="workdir"&&!o?"Working directory cannot be empty":null}function oc(){let e=_.getConfig(),t=ec(e);return {selectedOption:0,options:t,paneFocus:"list",isEditing:false,draftValue:t[0]?.value??"",validationError:null,isDirty:false,config:e}}function Rs(){return [oc(),c.none()]}function xs(e,t){let o=(t+e.options.length)%e.options.length,n=e.options[o];return {...e,selectedOption:o,draftValue:n.value,isEditing:false,isDirty:false,validationError:null}}function jo(e,t){switch(e.type){case "CONFIG_OPTION_UP":return t.isEditing?[t,c.none()]:[xs(t,t.selectedOption-1),c.none()];case "CONFIG_OPTION_DOWN":return t.isEditing?[t,c.none()]:[xs(t,t.selectedOption+1),c.none()];case "CONFIG_FOCUS_LIST":return [{...t,paneFocus:"list",isEditing:false,isDirty:false},c.none()];case "CONFIG_FOCUS_EDITOR":return [{...t,paneFocus:"editor"},c.none()];case "CONFIG_TOGGLE_FOCUS":return [{...t,paneFocus:t.paneFocus==="list"?"editor":"list"},c.none()];case "CONFIG_EDIT_START":{let o=Wo(t);return [{...t,paneFocus:"editor",isEditing:true,draftValue:o.value,validationError:null,isDirty:false},c.none()]}case "CONFIG_EDIT_INPUT":return t.isEditing?[{...t,draftValue:t.draftValue+e.char,validationError:null,isDirty:true},c.none()]:[t,c.none()];case "CONFIG_EDIT_BACKSPACE":return t.isEditing?[{...t,draftValue:t.draftValue.slice(0,-1),validationError:null,isDirty:true},c.none()]:[t,c.none()];case "CONFIG_EDIT_CANCEL":{let o=Wo(t);return [{...t,isEditing:false,isDirty:false,draftValue:o.value,validationError:null},c.none()]}case "CONFIG_EDIT_SAVE":{if(!t.isEditing)return [t,c.none()];let o=Wo(t),n=tc(o,t.draftValue);if(n)return [{...t,validationError:n},c.none()];let r=[...t.options];return r[t.selectedOption]={...o,value:t.draftValue},[{...t,options:r,isEditing:false,isDirty:false,validationError:null},c.saveConfig(o.id,t.draftValue)]}default:return [t,c.none()]}}var p={primary:"#00B8D4",success:"#00E676",warning:"#FFEA00",error:"#FF1744",info:"#2979FF",text:"#FFFFFF",textMuted:"#90A4AE",textDim:"#546E7A",border:"#37474F",textBright:"#FFFFFF",bgHighlight:"#263238",cyan:"#00E5FF"},Y={check:"\u2714",cross:"\u2716",star:"\u2605",gear:"\u2699",folder:"\u{1F4C2}",target:"\u{1F3AF}",fire:"\u{1F525}",arrow:"\u2192",code:"\u{1F4DD}"},j={topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502",leftT:"\u251C",rightT:"\u2524",topT:"\u252C",bottomT:"\u2534",cross:"\u253C",roundTopLeft:"\u256D",roundTopRight:"\u256E",roundBottomLeft:"\u2570",roundBottomRight:"\u256F",heavyHorizontal:"\u2501",heavyVertical:"\u2503"},Zt={tableColumns:{selector:2,status:3,id:6,difficulty:10,acceptance:8,premium:2}};var Go={filled:"\u2588",empty:"\u2591"};var rc=/\x1B\[[0-9;]*[a-zA-Z]/g;function O(e){return e.replace(rc,"")}function Et(e){return O(e).length}function A(e,t){if(t<=0)return "";if(t===1)return "\u2026";if(Et(e)<=t)return e;let o=t-1,n="",r=0;for(let s=0;s<e.length&&r<o;){if(e[s]==="\x1B"){let i=e.slice(s).match(/^\x1B\[[0-9;]*[a-zA-Z]/);if(i){n+=i[0],s+=i[0].length;continue}}n+=e[s],s+=1,r+=1;}return e.includes("\x1B[")?`${n}\u2026\x1B[0m`:`${n}\u2026`}function ue(e,t){let o=O(e),n=t-o.length;return n>0?e+" ".repeat(n):e}function Ko(e,t){let o=O(e),n=t-o.length;return n>0?" ".repeat(n)+e:e}function $(e,t){if(t<=0)return "";let n=O(e).length;if(n>=t)return e;let r=Math.floor((t-n)/2),s=t-n-r;return " ".repeat(r)+e+" ".repeat(s)}var qo={light:j,round:j,heavy:{horizontal:"\u2501",vertical:"\u2503",topLeft:"\u250F",topRight:"\u2513",bottomLeft:"\u2517",bottomRight:"\u251B"},double:{horizontal:"\u2550",vertical:"\u2551",topLeft:"\u2554",topRight:"\u2557",bottomLeft:"\u255A",bottomRight:"\u255D"}};function ye(e,t,o={}){let n=typeof o=="string"?{title:o}:o,{title:r,borderColor:s=p.textMuted,padding:i=0,borderStyle:a="round"}=n,l=qo[a]||j,u=[],g=Math.max(4,t),d=Math.max(2,g-2),m=Math.max(1,d-i*2),b=f.hex(s)(l.topLeft||l.roundTopLeft);if(r){let M=f.hex(s).bold(` ${r} `),E=O(M).length;b+=f.hex(s)(l.horizontal),b+=M,b+=f.hex(s)(l.horizontal.repeat(Math.max(0,d-E-1)));}else b+=f.hex(s)(l.horizontal.repeat(d));b+=f.hex(s)(l.topRight||l.roundTopRight),u.push(b);for(let M=0;M<i;M++)u.push(f.hex(s)(l.vertical)+" ".repeat(d)+f.hex(s)(l.vertical));for(let M of e){let E=O(M),x=M;E.length>m&&(x=A(M,m));let G=m-O(x).length,q=" ".repeat(i)+x+" ".repeat(G)+" ".repeat(i);u.push(f.hex(s)(l.vertical)+q+f.hex(s)(l.vertical));}for(let M=0;M<i;M++)u.push(f.hex(s)(l.vertical)+" ".repeat(d)+f.hex(s)(l.vertical));return u.push(f.hex(s)(l.bottomLeft||l.roundBottomLeft)+f.hex(s)(l.horizontal.repeat(d))+f.hex(s)(l.bottomRight||l.roundBottomRight)),u}function eo(e,t="light",o=p.textMuted){let n=j.horizontal;return t==="heavy"&&(n=qo.heavy.horizontal),t==="double"&&(n=qo.double.horizontal),f.hex(o)(n.repeat(Math.max(0,e)))}function Ps(e,t,o){let n=Math.min(1,Math.max(0,e/t)),r=Math.round(n*o),s=o-r;return f.hex(p.success)(Go.filled.repeat(r))+f.hex(p.textDim)(Go.empty.repeat(s))}function je(e,t,o="#000000"){return f.bgHex(t).hex(o).bold(` ${e} `)}function Os(e){switch(e.toLowerCase()){case "easy":return je("Easy",p.success);case "medium":return je("Medium",p.warning);case "hard":return je("Hard",p.error);default:return je(e,p.textMuted)}}function $s(e){switch(e){case "ac":return f.hex(p.success)(Y.check);case "notac":return f.hex(p.warning)("\u25CB");default:return f.hex(p.textDim)(" ")}}function C(e,t){return f.hex(p.textMuted)("[")+f.hex(p.primary)(e)+f.hex(p.textMuted)("] ")+f.hex(p.text)(t)}function Vo(e){return e.map(t=>C(t.key,t.label)).join(" ")}function ot(e,t,o){let n=Math.max(20,o),r=f.hex(p.primary).bold(` ${e} `),s=f.hex(p.textMuted)(A(t,Math.max(8,n-2)));return [$(r,n),$(s,n)]}function we(e,t){let o=Math.max(10,t),n=f.hex(p.primary).bold(` ${e} `),r=Math.max(0,o-Et(n));return n+f.hex(p.textMuted)(j.horizontal.repeat(r))}function nt(e,t,o="normal"){let n=Math.max(20,t),r=o==="compact"?e.slice(0,3):e,s=Vo(r);return H([s],n).map(a=>$(a,n))}function rt(e,t,o,n,r=.5){let s=Math.max(20,o),i=Math.max(1,n),a=Math.max(8,Math.floor(s*r)),l=Math.max(8,s-a-1),u=[...e],g=[...t],d=[];for(;u.length<i;)u.push("");for(;g.length<i;)g.push("");for(let m=0;m<i;m++){let b=ue(A(u[m]??"",a),a),M=ue(A(g[m]??"",l),l);d.push(b+f.hex(p.border)(j.vertical)+M);}return d}var sc=["\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 ","\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D ","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],ic=["\u2566 \u2554\u2550\u2557\u2554\u2550\u2557\u2554\u2566\u2557\u2554\u2550\u2557\u2554\u2550\u2557\u2554\u2566\u2557\u2554\u2550\u2557","\u2551 \u2551\u2563 \u2551\u2563 \u2551 \u2551 \u2551 \u2551 \u2551\u2551\u2551\u2563 ","\u2569\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u2569 \u255A\u2550\u255D\u255A\u2550\u255D\u2550\u2569\u255D\u255A\u2550\u255D"];function st(e){return (e>=80?sc:ic).map(o=>$(f.hex(p.primary)(o),e))}function H(e,t){let o=Math.max(1,t),n=[];for(let r of e){if(O(r).length<=o){n.push(r);continue}let i=r.split(" "),a="",l=0;for(let u of i){let g=O(u).length;if(g>o){l>0&&(n.push(a),a="",l=0);let m=u;for(;O(m).length>0;){let b=m.slice(0,o);n.push(b),m=m.slice(o);}continue}let d=a?1:0;l+g+d<=o?(a+=(a?" ":"")+u,l+=g+d):(n.push(a),a=u,l=g);}a&&n.push(a);}return n}function ac(e){switch(e){case "status":case "testResult":case "submitResult":return 6;case "hint":case "submissions":case "snapshots":return 10;case "note":case "diff":return 12;default:return 0}}function wt(e,t){let o=Math.max(10,e),s=Math.max(4,o-3-2);if(t==="none")return {bodyHeight:s,drawerHeight:0};let i=1,a=s>=14?8:5,l=Math.max(3,s-a-i),u=Math.max(3,Math.min(ac(t),l));return {bodyHeight:Math.max(3,s-i-u),drawerHeight:u}}function no(e){return [{problem:null,slug:e,detail:null,loading:true,error:null,scrollOffset:0,contentLines:[],testResult:null,submissionResult:null,isRunning:false,successMessage:null,activeHintIndex:null,isBookmarked:false,drawerMode:"none",focusRegion:"body",drawerScrollOffset:0,drawerData:{statusMessage:null},submissionsHistory:null,submissionsLoading:false,snapshotsList:null,snapshotCursor:0,noteContent:null,diffContent:null},c.fetchProblemDetail(e)]}function Re(e){return {...e,drawerMode:"none",focusRegion:"body",drawerScrollOffset:0,drawerData:{statusMessage:null}}}function ne(e,t,o=null){return t==="none"?Re(e):{...e,drawerMode:t,focusRegion:"drawer",drawerScrollOffset:0,drawerData:{statusMessage:o}}}function ro(e,t,o,n){let r=cc(t,o,n);switch(e.type){case "PROBLEM_FOCUS_TOGGLE":return t.drawerMode==="none"?[t,c.none()]:[{...t,focusRegion:t.focusRegion==="body"?"drawer":"body"},c.none()];case "PROBLEM_SCROLL_UP":return [{...t,scrollOffset:Math.max(0,t.scrollOffset-1)},c.none()];case "PROBLEM_SCROLL_DOWN":return [{...t,scrollOffset:Math.min(r,t.scrollOffset+1)},c.none()];case "PROBLEM_PAGE_UP":{let s=Math.max(3,Math.floor(zo(o,t.drawerMode)*.8));return [{...t,scrollOffset:Math.max(0,t.scrollOffset-s)},c.none()]}case "PROBLEM_PAGE_DOWN":{let s=Math.max(3,Math.floor(zo(o,t.drawerMode)*.8));return [{...t,scrollOffset:Math.min(r,t.scrollOffset+s)},c.none()]}case "PROBLEM_TOP":return [{...t,scrollOffset:0},c.none()];case "PROBLEM_BOTTOM":return [{...t,scrollOffset:r},c.none()];case "PROBLEM_DETAIL_LOADED":{let s=lc(e.detail),i=de.has(e.detail.questionFrontendId);return [{...t,loading:false,detail:e.detail,contentLines:s,scrollOffset:0,isBookmarked:i,error:null,successMessage:null,drawerMode:"none",focusRegion:"body",drawerScrollOffset:0,drawerData:{statusMessage:null}},c.none()]}case "PROBLEM_DETAIL_ERROR":return [{...ne({...t,loading:false,error:e.error},"status",e.error)},c.none()];case "PROBLEM_PICK":return [t,c.pickProblem(t.slug)];case "PROBLEM_TEST":return [{...ne(t,"status","Running tests..."),isRunning:true,testResult:null,submissionResult:null,successMessage:null,error:null},c.testSolution(t.slug)];case "PROBLEM_SUBMIT":return [{...ne(t,"status","Submitting solution..."),isRunning:true,testResult:null,submissionResult:null,successMessage:null,error:null},c.submitSolution(t.slug)];case "PROBLEM_TEST_RESULT":return [{...ne(t,"testResult"),isRunning:false,testResult:e.result,submissionResult:null},c.none()];case "PROBLEM_SUBMIT_RESULT":return [{...ne(t,"submitResult"),isRunning:false,submissionResult:e.result,testResult:null},c.none()];case "PROBLEM_BOOKMARK":{if(!t.detail)return [t,c.none()];let s=t.detail.questionFrontendId;if(de.has(s)){de.remove(s);let a="Problem unbookmarked";return [{...ne(t,"status",a),isBookmarked:false,successMessage:a,error:null},c.none()]}de.add(s);let i="Problem bookmarked";return [{...ne(t,"status",i),isBookmarked:true,successMessage:i,error:null},c.none()]}case "PROBLEM_TOGGLE_HINT":return (t.detail?.hints||[]).length===0?[{...ne(t,"status","No hints available for this problem"),error:null,successMessage:null},c.none()]:t.drawerMode==="hint"?[Re(t),c.none()]:[{...ne(t,"hint"),activeHintIndex:t.activeHintIndex??0},c.none()];case "PROBLEM_NEXT_HINT":{let s=t.detail?.hints||[];if(s.length===0)return [t,c.none()];let i=t.activeHintIndex??0;return [{...t,activeHintIndex:Math.min(s.length-1,i+1),drawerScrollOffset:0},c.none()]}case "PROBLEM_PREV_HINT":{let s=t.activeHintIndex??0;return [{...t,activeHintIndex:Math.max(0,s-1),drawerScrollOffset:0},c.none()]}case "PROBLEM_HINT_SCROLL_UP":return [{...t,drawerScrollOffset:Math.max(0,t.drawerScrollOffset-1)},c.none()];case "PROBLEM_HINT_SCROLL_DOWN":return [{...t,drawerScrollOffset:Math.min(to(t,o,n),t.drawerScrollOffset+1)},c.none()];case "PROBLEM_NOTES":return t.detail?[t,c.openEditor(t.detail.questionFrontendId)]:[t,c.none()];case "PROBLEM_ACTION_ERROR":return [{...ne(t,"status",e.error),isRunning:false,error:e.error},c.none()];case "PROBLEM_ACTION_SUCCESS":return [{...ne(t,"status",e.message),isRunning:false,successMessage:e.message,error:null},c.none()];case "PROBLEM_CLOSE_RESULT":return [Re(t),c.none()];case "PROBLEM_SHOW_SUBMISSIONS":return t.drawerMode==="submissions"?[Re(t),c.none()]:[{...ne(t,"submissions"),submissionsLoading:true,submissionsHistory:null},c.fetchSubmissions(t.slug)];case "PROBLEM_SUBMISSIONS_LOADED":return [{...ne(t,"submissions"),submissionsLoading:false,submissionsHistory:e.submissions,error:null},c.none()];case "PROBLEM_SUBMISSIONS_ERROR":return [{...ne(t,"status",e.error),submissionsLoading:false,error:e.error},c.none()];case "PROBLEM_CLOSE_SUBMISSIONS":return [Re(t),c.none()];case "PROBLEM_SUBMISSIONS_SCROLL_UP":return [{...t,drawerScrollOffset:Math.max(0,t.drawerScrollOffset-1)},c.none()];case "PROBLEM_SUBMISSIONS_SCROLL_DOWN":return [{...t,drawerScrollOffset:Math.min(to(t,o,n),t.drawerScrollOffset+1)},c.none()];case "PROBLEM_SHOW_SNAPSHOTS":{if(t.drawerMode==="snapshots")return [Re(t),c.none()];let s=t.detail?.questionFrontendId||t.slug;return [{...ne(t,"snapshots"),snapshotsList:J.list(s),snapshotCursor:0},c.none()]}case "PROBLEM_CLOSE_SNAPSHOTS":return [Re(t),c.none()];case "PROBLEM_SNAPSHOT_UP":return !t.snapshotsList||t.snapshotsList.length===0?[t,c.none()]:[{...t,snapshotCursor:Math.max(0,t.snapshotCursor-1)},c.none()];case "PROBLEM_SNAPSHOT_DOWN":return !t.snapshotsList||t.snapshotsList.length===0?[t,c.none()]:[{...t,snapshotCursor:Math.min(t.snapshotsList.length-1,t.snapshotCursor+1)},c.none()];case "PROBLEM_VIEW_NOTE":return t.detail?[{...ne(t,"status","Loading note...")},c.loadNote(t.detail.questionFrontendId)]:[t,c.none()];case "PROBLEM_NOTE_LOADED":return [{...ne(t,"note"),noteContent:e.content,error:null},c.none()];case "PROBLEM_CLOSE_NOTE":return [Re(t),c.none()];case "PROBLEM_NOTE_SCROLL_UP":return [{...t,drawerScrollOffset:Math.max(0,t.drawerScrollOffset-1)},c.none()];case "PROBLEM_NOTE_SCROLL_DOWN":return [{...t,drawerScrollOffset:Math.min(to(t,o,n),t.drawerScrollOffset+1)},c.none()];case "PROBLEM_DIFF_SNAPSHOT":{if(!t.snapshotsList||t.snapshotsList.length===0)return [t,c.none()];let s=t.snapshotsList[t.snapshotCursor];return s?[t,c.diffSnapshot(t.slug,s.id.toString())]:[t,c.none()]}case "PROBLEM_DIFF_LOADED":return [{...ne(t,"diff"),diffContent:e.content,error:null},c.none()];case "PROBLEM_CLOSE_DIFF":return [Re(t),c.none()];case "PROBLEM_DIFF_SCROLL_UP":return [{...t,drawerScrollOffset:Math.max(0,t.drawerScrollOffset-1)},c.none()];case "PROBLEM_DIFF_SCROLL_DOWN":return [{...t,drawerScrollOffset:Math.min(to(t,o,n),t.drawerScrollOffset+1)},c.none()];case "PROBLEM_RESTORE_SNAPSHOT":{if(!t.snapshotsList||t.snapshotsList.length===0)return [t,c.none()];let s=t.snapshotsList[t.snapshotCursor];return s?[t,c.restoreSnapshot(t.slug,s.id.toString())]:[t,c.none()]}default:return [t,c.none()]}}function lc(e){return yo(e.content||"").split(`
|
|
245
|
-
`)}function zo(e,t){let o=Math.max(6,e-4);return wt(o,t).bodyHeight}function cc(e,t,o){let n=zo(t,e.drawerMode),r=Math.max(20,o-4),s=H(e.contentLines,r);return Math.max(0,s.length-n)}function to(e,t,o){if(e.drawerMode==="none"||e.drawerMode==="snapshots")return 0;let n=Math.max(6,t-4),r=wt(n,e.drawerMode),s=Math.max(1,r.drawerHeight-2),i=Math.max(20,o-2),a=uc(e,i);return Math.max(0,a.length-s)}function uc(e,t){let o=Math.max(10,t-2);switch(e.drawerMode){case "hint":{let n=e.detail?.hints||[],r=e.activeHintIndex??0,s=n[r]??"",i=vs(s);return H([i||"No hint content"],o)}case "submissions":return e.submissionsLoading?["Loading submissions..."]:!e.submissionsHistory||e.submissionsHistory.length===0?["No submissions found for this problem.","Use [s] Submit after picking a solution."]:e.submissionsHistory.map(n=>{let r=oo(n.statusDisplay||"-",10).padEnd(10),s=oo(n.runtime||"-",8).padEnd(8),i=oo(n.memory||"-",8).padEnd(8),a=oo(n.lang||"-",8).padEnd(8);return `${r} ${s} ${i} ${a}`});case "note":return H(pc(e.noteContent||"No notes found. Press e to edit."),o);case "diff":return (e.diffContent||"No diff available.").split(`
|
|
246
|
-
`)
|
|
247
|
-
`)
|
|
248
|
-
`)
|
|
249
|
-
`)}function
|
|
250
|
-
`)
|
|
251
|
-
`)
|
|
252
|
-
`)}function
|
|
253
|
-
`);if(e.
|
|
254
|
-
`);if(e.problems.length===0)return
|
|
255
|
-
`);
|
|
256
|
-
`)
|
|
257
|
-
`)}function
|
|
258
|
-
`)}function
|
|
259
|
-
`)}function
|
|
260
|
-
`)}
|
|
261
|
-
`)}
|
|
262
|
-
`)}function
|
|
263
|
-
`).
|
|
264
|
-
`)
|
|
265
|
-
`)
|
|
266
|
-
`)
|
|
267
|
-
`)}function
|
|
268
|
-
`)}function
|
|
269
|
-
`),
|
|
270
|
-
`)}function ui(e,t){switch(e.type){case "INIT":return [{...t,needsRender:true},c.checkAuth()];case "KEY_PRESS":{let{key:o}=e;if(o.ctrl&&o.name==="c")return [t,c.exit()];if(o.name==="q"&&t.screenState.screen==="home")return [t,c.exit()];if(o.name==="?")return t.screenState.screen==="help"?[{...t,...sn(t),needsRender:true},c.none()]:[{...t,...fe(t,{screen:"help",model:{scrollOffset:0}}),needsRender:true},c.none()];if(o.name==="escape"&&t.screenState.screen!=="home"){if(t.screenState.screen==="config"&&t.screenState.model.isEditing)return io(t,e);if(t.screenState.screen==="problem"){let n=t.screenState.model;if(n.drawerMode!=="none"){let[r,s]=ro({type:"PROBLEM_CLOSE_RESULT"},n,t.terminalHeight,t.terminalWidth);return [{...t,screenState:{screen:"problem",model:r},needsRender:true},s]}}if(t.screenState.screen==="workspace"){let n=t.screenState.model;if(n.showCreateInput||n.showDeleteConfirm||n.isEditing)return io(t,e)}return t.screenState.screen==="login"?io(t,e):[{...t,...sn(t),needsRender:true},c.none()]}return io(t,e)}case "RESIZE":return [{...t,terminalWidth:e.width,terminalHeight:e.height,needsRender:true},c.none()];case "NAVIGATE":return [{...t,...fe(t,e.to),needsRender:true},c.none()];case "GO_BACK":return [{...t,...sn(t),needsRender:true},c.none()];case "AUTH_CHECK_COMPLETE":return e.user?[{...t,isCheckingAuth:false,user:{username:e.user.username,isLoggedIn:true},needsRender:true},c.none()]:[{...t,isCheckingAuth:false,user:null,screenState:{screen:"login",model:{step:"instructions",sessionToken:"",csrfToken:"",focusedField:"session",error:null}},needsRender:true},c.none()];case "GLOBAL_ERROR":return [{...t,globalError:e.error,needsRender:true},c.none()];case "CLEAR_ERROR":return [{...t,globalError:null,needsRender:true},c.none()];case "FETCH_DAILY_SUCCESS":{let[o,n]=no(e.slug);return [{...t,...fe(t,{screen:"problem",model:o}),needsRender:true},n]}case "FETCH_RANDOM_SUCCESS":{let[o,n]=no(e.slug);return [{...t,...fe(t,{screen:"problem",model:o}),needsRender:true},n]}case "QUIT":return [t,c.exit()];case "LOGIN_SUCCESS":return [{...t,user:{username:e.username,isLoggedIn:true},screenState:{screen:"home",model:{menuIndex:0}},needsRender:true},c.none()];default:return gi(e,t)}}function fe(e,t){return {screenState:t,history:[...e.history,e.screenState],globalError:null}}function sn(e){if(e.history.length===0)return {screenState:{screen:"home",model:{menuIndex:0}},globalError:null};let t=[...e.history];return {screenState:t.pop(),history:t,globalError:null}}function io(e,t){let{screenState:o}=e;switch(o.screen){case "home":return pi(e,t);case "list":return Qc(e,t);case "problem":return Jc(e,t);case "timer":case "stats":case "config":return Zc(e,t);case "help":return eu(e,t);case "workspace":return pu(e,t);case "changelog":return gu(e,t);case "login":return du(e,t);default:return [e,c.none()]}}function pi(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,n=e.screenState.model;if(o.name==="l"){let[r,s]=Ho();return [{...e,...fe(e,{screen:"list",model:r}),needsRender:true},s]}if(o.name==="d")return [e,c.fetchDaily()];if(o.name==="r")return [e,c.fetchRandom()];if(o.name==="b"){let[r,s]=Ho();return [{...e,...fe(e,{screen:"list",model:{...r,bookmarkFilter:true}}),needsRender:true},s]}if(o.name==="t")return [{...e,...fe(e,{screen:"timer",model:{problemId:null,problemTitle:"Practice",difficulty:"Medium",remainingSeconds:2400,totalSeconds:2400,status:"idle",viewMode:"timer"}}),needsRender:true},c.none()];if(o.name==="s"){let[r,s]=Ls();return [{...e,...fe(e,{screen:"stats",model:r}),needsRender:true},s]}if(o.name==="y")return [{...e,globalError:"Use CLI command: leet sync (requires terminal interaction)",needsRender:true},c.none()];if(o.name==="w"){let[r,s]=Fs();return [{...e,...fe(e,{screen:"workspace",model:r}),needsRender:true},s]}if(o.name==="c"){let[r,s]=Rs();return [{...e,...fe(e,{screen:"config",model:r}),needsRender:true},s]}if(o.name==="?")return [{...e,...fe(e,{screen:"help",model:{scrollOffset:0}}),needsRender:true},c.none()];if(o.name==="v"){let[r,s]=Gs();return [{...e,...fe(e,{screen:"changelog",model:r}),needsRender:true},s]}if(o.name==="L")return [e,c.logout()];if(o.name==="j"||o.name==="down"){let[r,s]=Jt({type:"HOME_MENU_DOWN"},n);return [{...e,screenState:{screen:"home",model:r},needsRender:true},s]}if(o.name==="k"||o.name==="up"){let[r,s]=Jt({type:"HOME_MENU_UP"},n);return [{...e,screenState:{screen:"home",model:r},needsRender:true},s]}if(o.name==="return"){let s=["l","d","r","b","t","s","y","w","c","v","L","?"][n.menuIndex];if(s)return pi(e,{type:"KEY_PRESS",key:{name:s,sequence:s,ctrl:false,meta:false,shift:false}})}return [e,c.none()]}function Qc(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,n=e.screenState.model,r=null;if(n.searchMode)o.name==="escape"?r={type:"LIST_SEARCH_CANCEL"}:o.name==="return"?r={type:"LIST_SEARCH_SUBMIT"}:o.name==="backspace"?r={type:"LIST_SEARCH_BACKSPACE"}:o.sequence.length===1&&!o.ctrl&&!o.meta&&(r={type:"LIST_SEARCH_INPUT",char:o.sequence});else if(o.name==="j"||o.name==="down")r={type:"LIST_CURSOR_DOWN"};else if(o.name==="k"||o.name==="up")r={type:"LIST_CURSOR_UP"};else if(o.name==="g")r={type:"LIST_GO_TOP"};else if(o.name==="G")r={type:"LIST_GO_BOTTOM"};else if(o.name==="/")r={type:"LIST_SEARCH_START"};else if(o.name==="return"){let s=n.problems[n.cursor];if(s){let[i,a]=no(s.titleSlug);return [{...e,...fe(e,{screen:"problem",model:i}),needsRender:true},a]}r={type:"LIST_SELECT"};}else o.name==="1"?r={type:"LIST_FILTER_DIFFICULTY",difficulty:n.difficultyFilter==="Easy"?null:"Easy"}:o.name==="2"?r={type:"LIST_FILTER_DIFFICULTY",difficulty:n.difficultyFilter==="Medium"?null:"Medium"}:o.name==="3"?r={type:"LIST_FILTER_DIFFICULTY",difficulty:n.difficultyFilter==="Hard"?null:"Hard"}:o.name==="s"?r={type:"LIST_FILTER_STATUS",status:n.statusFilter==="solved"?null:"solved"}:o.name==="a"?r={type:"LIST_FILTER_STATUS",status:n.statusFilter==="attempted"?null:"attempted"}:o.name==="b"?r={type:"LIST_FILTER_BOOKMARKS"}:o.name==="c"?r={type:"LIST_CLEAR_FILTERS"}:o.name==="R"&&(r={type:"LIST_REFRESH"});if(r){let[s,i]=Uo(r,n,e.terminalHeight);return [{...e,screenState:{screen:"list",model:s},needsRender:true},i]}return [e,c.none()]}function gi(e,t){let{screenState:o}=t,n=t.terminalHeight;switch(o.screen){case "list":{if(!tu(e))return [t,c.none()];let[r,s]=Uo(e,o.model,n);return [{...t,screenState:{screen:"list",model:r},needsRender:true},s]}case "home":{if(!ou(e))return [t,c.none()];let[r,s]=Jt(e,o.model);return [{...t,screenState:{screen:"home",model:r},needsRender:true},s]}case "timer":{if(!nu(e))return [t,c.none()];let[r,s]=Xt(e,o.model);return [{...t,screenState:{screen:"timer",model:r},needsRender:true},s]}case "stats":{if(!ru(e))return [t,c.none()];let[r,s]=Bo(e,o.model);return [{...t,screenState:{screen:"stats",model:r},needsRender:true},s]}case "config":{if(!su(e))return [t,c.none()];let[r,s]=jo(e,o.model);return [{...t,screenState:{screen:"config",model:r},needsRender:true},s]}case "help":{if(!iu(e))return [t,c.none()];let r=o.model,s=ci(t.terminalWidth,t.terminalHeight-4),i=Math.max(3,Math.floor((t.terminalHeight-4)/2)),a=r.scrollOffset;switch(e.type){case "HELP_SCROLL_UP":a=Math.max(0,r.scrollOffset-1);break;case "HELP_SCROLL_DOWN":a=Math.min(s,r.scrollOffset+1);break;case "HELP_PAGE_UP":a=Math.max(0,r.scrollOffset-i);break;case "HELP_PAGE_DOWN":a=Math.min(s,r.scrollOffset+i);break;case "HELP_TOP":a=0;break;case "HELP_BOTTOM":a=s;break}return [{...t,screenState:{screen:"help",model:{scrollOffset:a}},needsRender:true},c.none()]}case "workspace":{if(!lu(e))return [t,c.none()];let[r,s]=Qo(e,o.model);return [{...t,screenState:{screen:"workspace",model:r},needsRender:true},s]}case "problem":{if(!au(e))return [t,c.none()];let[r,s]=ro(e,o.model,n,t.terminalWidth);return [{...t,screenState:{...o,model:r},needsRender:true},s]}case "changelog":{if(!cu(e))return [t,c.none()];let[r,s]=Xo(e,o.model,n,t.terminalWidth);return [{...t,screenState:{screen:"changelog",model:r},needsRender:true},s]}case "login":{if(!uu(e))return [t,c.none()];let[r,s]=en(e,o.model);return [{...t,screenState:{screen:"login",model:r},needsRender:true},s]}default:return [t,c.none()]}}function Jc(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,n=e.screenState.model,r=null;if(!r&&n.drawerMode==="note"&&(o.name==="n"||o.name==="escape")&&(r={type:"PROBLEM_CLOSE_NOTE"}),!r&&n.drawerMode==="diff"&&(o.name==="d"||o.name==="escape")&&(r={type:"PROBLEM_CLOSE_DIFF"}),!r){let i=Xc(o.name);i&&(r=i);}!r&&o.name==="tab"&&n.drawerMode!=="none"&&(r={type:"PROBLEM_FOCUS_TOGGLE"}),!r&&n.drawerMode!=="none"&&o.name==="escape"&&(r={type:"PROBLEM_CLOSE_RESULT"}),!r&&n.drawerMode==="hint"&&(o.name==="left"?r={type:"PROBLEM_PREV_HINT"}:o.name==="right"&&(r={type:"PROBLEM_NEXT_HINT"})),!r&&n.drawerMode!=="none"&&n.focusRegion==="drawer"&&(n.drawerMode==="snapshots"?o.name==="j"||o.name==="down"?r={type:"PROBLEM_SNAPSHOT_DOWN"}:o.name==="k"||o.name==="up"?r={type:"PROBLEM_SNAPSHOT_UP"}:o.name==="d"?r={type:"PROBLEM_DIFF_SNAPSHOT"}:o.name==="r"&&(r={type:"PROBLEM_RESTORE_SNAPSHOT"}):n.drawerMode==="hint"?o.name==="j"||o.name==="down"?r={type:"PROBLEM_HINT_SCROLL_DOWN"}:(o.name==="k"||o.name==="up")&&(r={type:"PROBLEM_HINT_SCROLL_UP"}):n.drawerMode==="submissions"?o.name==="j"||o.name==="down"?r={type:"PROBLEM_SUBMISSIONS_SCROLL_DOWN"}:(o.name==="k"||o.name==="up")&&(r={type:"PROBLEM_SUBMISSIONS_SCROLL_UP"}):n.drawerMode==="note"?o.name==="j"||o.name==="down"?r={type:"PROBLEM_NOTE_SCROLL_DOWN"}:(o.name==="k"||o.name==="up")&&(r={type:"PROBLEM_NOTE_SCROLL_UP"}):n.drawerMode==="diff"&&(o.name==="j"||o.name==="down"?r={type:"PROBLEM_DIFF_SCROLL_DOWN"}:(o.name==="k"||o.name==="up")&&(r={type:"PROBLEM_DIFF_SCROLL_UP"})));let s=n.drawerMode==="none"||n.focusRegion==="body";if(!r&&s&&(o.name==="j"||o.name==="down"?r={type:"PROBLEM_SCROLL_DOWN"}:o.name==="k"||o.name==="up"?r={type:"PROBLEM_SCROLL_UP"}:o.name==="pagedown"?r={type:"PROBLEM_PAGE_DOWN"}:o.name==="pageup"?r={type:"PROBLEM_PAGE_UP"}:o.name==="g"?r={type:"PROBLEM_TOP"}:o.name==="G"&&(r={type:"PROBLEM_BOTTOM"})),r){let[i,a]=ro(r,n,e.terminalHeight,e.terminalWidth);return [{...e,screenState:{screen:"problem",model:i},needsRender:true},a]}return [e,c.none()]}function Xc(e){return e==="p"?{type:"PROBLEM_PICK"}:e==="t"?{type:"PROBLEM_TEST"}:e==="s"?{type:"PROBLEM_SUBMIT"}:e==="b"?{type:"PROBLEM_BOOKMARK"}:e==="n"?{type:"PROBLEM_VIEW_NOTE"}:e==="e"?{type:"PROBLEM_NOTES"}:e==="h"?{type:"PROBLEM_TOGGLE_HINT"}:e==="H"||e==="S"?{type:"PROBLEM_SHOW_SUBMISSIONS"}:e==="v"||e==="V"||e==="w"?{type:"PROBLEM_SHOW_SNAPSHOTS"}:null}function Zc(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,{screenState:n}=e;if(n.screen==="timer"){let r=n.model;if(o.name==="space"){let[s,i]=Xt({type:r.status==="running"?"TIMER_PAUSE":"TIMER_START"},r);return [{...e,screenState:{...n,model:s},needsRender:true},i]}if(o.name==="r"){let[s,i]=Xt({type:"TIMER_RESET"},r);return [{...e,screenState:{...n,model:s},needsRender:true},i]}}if(n.screen==="config"){let r=n.model,s=null;if(r.isEditing?o.name==="escape"?s={type:"CONFIG_EDIT_CANCEL"}:o.name==="return"||o.name==="enter"?s={type:"CONFIG_EDIT_SAVE"}:o.name==="backspace"?s={type:"CONFIG_EDIT_BACKSPACE"}:o.sequence.length===1&&!o.ctrl&&!o.meta&&(s={type:"CONFIG_EDIT_INPUT",char:o.sequence}):o.name==="tab"||o.name==="h"||o.name==="l"?s={type:"CONFIG_TOGGLE_FOCUS"}:o.name==="left"?s={type:"CONFIG_FOCUS_LIST"}:o.name==="right"?s={type:"CONFIG_FOCUS_EDITOR"}:o.name==="j"||o.name==="down"?s={type:"CONFIG_OPTION_DOWN"}:o.name==="k"||o.name==="up"?s={type:"CONFIG_OPTION_UP"}:(o.name==="return"||o.name==="enter")&&(s={type:"CONFIG_EDIT_START"}),s){let[i,a]=jo(s,r);return [{...e,screenState:{...n,model:i},needsRender:true},a]}}if(n.screen==="stats"){let r=n.model;if(o.name==="r"||o.name==="R"){let[s,i]=Bo({type:"STATS_REFRESH"},r);return [{...e,screenState:{...n,model:s},needsRender:true},i]}}return [e,c.none()]}function eu(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,n=null;return o.name==="j"||o.name==="down"?n={type:"HELP_SCROLL_DOWN"}:o.name==="k"||o.name==="up"?n={type:"HELP_SCROLL_UP"}:o.name==="pagedown"?n={type:"HELP_PAGE_DOWN"}:o.name==="pageup"?n={type:"HELP_PAGE_UP"}:o.name==="g"?n={type:"HELP_TOP"}:o.name==="G"&&(n={type:"HELP_BOTTOM"}),n?gi(n,e):[e,c.none()]}function tu(e){return e.type.startsWith("LIST_")}function ou(e){return e.type.startsWith("HOME_")}function nu(e){return e.type.startsWith("TIMER_")}function ru(e){return e.type.startsWith("STATS_")}function su(e){return e.type.startsWith("CONFIG_")}function iu(e){return e.type.startsWith("HELP_")}function au(e){return e.type.startsWith("PROBLEM_")}function lu(e){return e.type.startsWith("WORKSPACE_")}function cu(e){return e.type.startsWith("CHANGELOG_")}function uu(e){return e.type.startsWith("LOGIN_")}function pu(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,n=e.screenState.model,r=null;if(n.showCreateInput?o.name==="escape"?r={type:"WORKSPACE_CREATE_CANCEL"}:o.name==="return"||o.name==="enter"?r={type:"WORKSPACE_CREATE_SUBMIT"}:o.name==="backspace"?r={type:"WORKSPACE_CREATE_BACKSPACE"}:o.sequence.length===1&&!o.ctrl&&!o.meta&&(r={type:"WORKSPACE_CREATE_INPUT",char:o.sequence}):n.showDeleteConfirm?o.name==="y"||o.name==="return"||o.name==="enter"?r={type:"WORKSPACE_DELETE_CONFIRM"}:(o.name==="n"||o.name==="escape")&&(r={type:"WORKSPACE_DELETE_CANCEL"}):n.isEditing?o.name==="escape"?r={type:"WORKSPACE_EDIT_CANCEL"}:o.name==="return"||o.name==="enter"?r={type:"WORKSPACE_EDIT_SAVE"}:o.name==="backspace"?r={type:"WORKSPACE_EDIT_BACKSPACE"}:o.sequence.length===1&&!o.ctrl&&!o.meta&&(r={type:"WORKSPACE_EDIT_INPUT",char:o.sequence}):o.name==="tab"||o.name==="h"||o.name==="l"?r={type:"WORKSPACE_TOGGLE_FOCUS"}:o.name==="left"?r={type:"WORKSPACE_FOCUS_LIST"}:o.name==="right"?r={type:"WORKSPACE_FOCUS_EDITOR"}:n.paneFocus==="list"?o.name==="j"||o.name==="down"?r={type:"WORKSPACE_DOWN"}:o.name==="k"||o.name==="up"?r={type:"WORKSPACE_UP"}:o.name==="return"||o.name==="enter"?r={type:"WORKSPACE_SELECT"}:o.name==="c"?r={type:"WORKSPACE_CREATE_START"}:o.name==="d"&&(r={type:"WORKSPACE_DELETE"}):o.name==="j"||o.name==="down"?r={type:"WORKSPACE_FIELD_DOWN"}:o.name==="k"||o.name==="up"?r={type:"WORKSPACE_FIELD_UP"}:(o.name==="return"||o.name==="enter")&&(r={type:"WORKSPACE_EDIT_START"}),r){let[s,i]=Qo(r,n);return [{...e,screenState:{screen:"workspace",model:s},needsRender:true},i]}return [e,c.none()]}function gu(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t;if(o.name==="k"||o.name==="up")return n(e,{type:"CHANGELOG_SCROLL_UP"});if(o.name==="j"||o.name==="down")return n(e,{type:"CHANGELOG_SCROLL_DOWN"});return [e,c.none()];function n(r,s){let i=r.screenState;if(i.screen!=="changelog")return [r,c.none()];let[a,l]=Xo(s,i.model,r.terminalHeight,r.terminalWidth);return [{...r,screenState:{screen:"changelog",model:a},needsRender:true},l]}}function du(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,n=e.screenState.model;if(o.ctrl&&o.name==="c")return [e,c.exit()];if(n.step==="instructions"){if(o.name==="return"||o.name==="enter")return r(e,{type:"LOGIN_SUBMIT"});if(o.name==="escape")return [e,c.exit()]}else if(n.step==="input"||n.step==="error"){if(o.name==="escape")return r(e,{type:"LOGIN_BACK"});if(o.name==="tab"||o.name==="down"||o.name==="up")return r(e,{type:"LOGIN_SWITCH_FOCUS"});if(o.name==="return"||o.name==="enter"){if(n.focusedField==="session"){if(n.sessionToken.length>0)return r(e,{type:"LOGIN_SET_FOCUS",field:"csrf"})}else if(n.csrfToken.length>0&&n.sessionToken.length>0)return r(e,{type:"LOGIN_SUBMIT"})}else if(o.name==="backspace"){if(n.focusedField==="session"){if(n.sessionToken.length>0)return r(e,{type:"LOGIN_SESSION_INPUT",value:n.sessionToken.slice(0,-1)})}else if(n.csrfToken.length>0)return r(e,{type:"LOGIN_CSRF_INPUT",value:n.csrfToken.slice(0,-1)})}else if(!o.ctrl&&!o.meta)return n.focusedField==="session"?r(e,{type:"LOGIN_SESSION_INPUT",value:n.sessionToken+o.sequence}):r(e,{type:"LOGIN_CSRF_INPUT",value:n.csrfToken+o.sequence})}return [e,c.none()];function r(s,i){let[a,l]=en(i,s.screenState.model);return [{...s,screenState:{screen:"login",model:a},needsRender:true},l]}}var yu="https://raw.githubusercontent.com/night-slayer18/leetcode-cli/main/docs/releases.md",Pe=null;function an(e,t){switch(e.type){case "CMD_NONE":return;case "CMD_BATCH":for(let o of e.commands)an(o,t);return;case "CMD_FETCH_STATS":Cu(t);return;case "CMD_CHECK_AUTH":hu(t);return;case "CMD_FETCH_PROBLEMS":Su(e.filters,e.append,t);return;case "CMD_FETCH_PROBLEM_DETAIL":bu(e.slug,t);return;case "CMD_START_TIMER_SUBSCRIPTION":Pe&&clearInterval(Pe),Pe=setInterval(()=>{t({type:"TIMER_TICK"});},e.intervalMs);return;case "CMD_STOP_TIMER_SUBSCRIPTION":Pe&&(clearInterval(Pe),Pe=null);return;case "CMD_PICK_PROBLEM":wu(e.slug,t);return;case "CMD_TEST_SOLUTION":Mu(e.slug,t);return;case "CMD_SUBMIT_SOLUTION":_u(e.slug,t);return;case "CMD_SAVE_CONFIG":Eu(e.key,e.value);return;case "CMD_EXIT":ao();return;case "CMD_FETCH_DAILY":ku(t);return;case "CMD_FETCH_RANDOM":Tu(t);return;case "CMD_FETCH_SUBMISSIONS":Pu(e.slug,t);return;case "CMD_LOAD_NOTE":Lu(e.problemId,t);return;case "CMD_DIFF_SNAPSHOT":xu(e.slug,e.snapshotId,t);return;case "CMD_RESTORE_SNAPSHOT":Ru(e.slug,e.snapshotId,t);return;case "CMD_FETCH_CHANGELOG":Ou(t);return;case "CMD_LOGOUT":$u(t);return;case "CMD_LOGIN":vu(e.session,e.csrf,t);return;default:return}}async function hu(e){let t=ae.get();if(!t){e({type:"AUTH_CHECK_COMPLETE",user:null});return}S.setCredentials(t);try{let o=await S.checkAuth();o.isSignedIn&&o.username?e({type:"AUTH_CHECK_COMPLETE",user:{username:o.username}}):e({type:"AUTH_CHECK_COMPLETE",user:null});}catch{e({type:"AUTH_CHECK_COMPLETE",user:null});}}async function Su(e,t,o){o({type:"LIST_FETCH_START"});try{let n=ae.get();n&&S.setCredentials(n);let r=await S.getProblems(e),s=r.problems.map(i=>({questionId:i.questionId,questionFrontendId:i.questionFrontendId,title:i.title,titleSlug:i.titleSlug,difficulty:i.difficulty,isPaidOnly:i.isPaidOnly,acRate:i.acRate,topicTags:i.topicTags,status:i.status}));o({type:"LIST_FETCH_SUCCESS",problems:s,total:r.total,append:t});}catch(n){o({type:"LIST_FETCH_ERROR",error:n instanceof Error?n.message:"Failed to fetch problems"});}}async function bu(e,t){try{let o=await S.getProblem(e);t({type:"PROBLEM_DETAIL_LOADED",detail:o});}catch(o){t({type:"PROBLEM_DETAIL_ERROR",error:o instanceof Error?o.message:"Failed to fetch problem"});}}async function Cu(e){e({type:"STATS_FETCH_START"});try{let t=ae.get();if(!t)throw new Error("You must be logged in to view stats");S.setCredentials(t);let o=await S.checkAuth();if(!o.isSignedIn||!o.username)throw new Error("Not logged in");let[n,r,s]=await Promise.all([S.getUserProfile(o.username),S.getSkillStats(o.username),S.getDailyChallenge()]);e({type:"STATS_FETCH_SUCCESS",stats:n,skills:r,daily:s});}catch(t){e({type:"STATS_FETCH_ERROR",error:t instanceof Error?t.message:"Failed to fetch statistics"});}}function Eu(e,t){switch(e){case "language":_.setLanguage(t);break;case "editor":_.setEditor(t);break;case "workdir":_.setWorkDir(t);break;case "repo":_.setRepo(t);break}}async function ln(e){let t=_.getLanguage(),o=await S.getProblem(e),n=Bt(t,o.codeSnippets),r=Ye(o.questionFrontendId,o.titleSlug,t),s=_.getWorkDir(),i=o.difficulty,a=o.topicTags.length>0?o.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",l=$e.join(s,i,a,r);try{return {code:await Oe.readFile(l,"utf-8"),lang:n,questionId:o.questionId}}catch{let g=$e.join(s,r);try{return {code:await Oe.readFile(g,"utf-8"),lang:n,questionId:o.questionId}}catch{throw new Error(`Could not read solution file at ${l}. Make sure you have picked the problem first.`)}}}async function wu(e,t){try{let o=await S.getProblem(e),n=_.getLanguage(),r=Be(n);if(!r)throw new Error(`Unsupported language: ${n}`);let s=o.codeSnippets??[],i=Wt(s,r);if(s.length>0&&!i)throw new Error(`No code template available for ${r}`);let a=i?i.code:jt(r,o.title),l=Gt(o.questionFrontendId,o.titleSlug,o.title,o.difficulty,a,r,o.content??void 0),u=_.getWorkDir(),g=o.difficulty,d=o.topicTags.length>0?o.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",m=$e.join(u,g,d);try{await Oe.mkdir(m,{recursive:!0});}catch{}let b=Ye(o.questionFrontendId,o.titleSlug,r),M=$e.join(m,b);existsSync(M)?t({type:"PROBLEM_ACTION_SUCCESS",message:`File ready: ${b}`}):(await Oe.writeFile(M,l,"utf-8"),t({type:"PROBLEM_ACTION_SUCCESS",message:`Created ${b}`}));}catch(o){t({type:"PROBLEM_ACTION_ERROR",error:o instanceof Error?o.message:"Failed to pick problem"});}}async function Mu(e,t){try{let{code:o,lang:n}=await ln(e),r=await S.getProblem(e),s=await S.testSolution(e,o,n,r.exampleTestcases,r.questionId);t({type:"PROBLEM_TEST_RESULT",result:s});}catch(o){t({type:"PROBLEM_ACTION_ERROR",error:o instanceof Error?o.message:"Test failed"});}}async function _u(e,t){try{let{code:o,lang:n}=await ln(e),r=await S.getProblem(e),s=await S.submitSolution(e,o,n,r.questionId);t({type:"PROBLEM_SUBMIT_RESULT",result:s});}catch(o){t({type:"PROBLEM_ACTION_ERROR",error:o instanceof Error?o.message:"Submit failed"});}}async function ku(e){try{let t=await S.getDailyChallenge();if(t&&t.question&&t.question.titleSlug)e({type:"FETCH_DAILY_SUCCESS",slug:t.question.titleSlug});else throw new Error("No daily challenge found")}catch(t){e({type:"GLOBAL_ERROR",error:t instanceof Error?t.message:"Failed to fetch daily challenge"});}}async function Tu(e){try{let t=await S.getRandomProblem();if(t)e({type:"FETCH_RANDOM_SUCCESS",slug:t});else throw new Error("No random problem found")}catch(t){e({type:"GLOBAL_ERROR",error:t instanceof Error?t.message:"Failed to fetch random problem"});}}async function Lu(e,t){try{let o=$e.join(_.getWorkDir(),".notes"),n=$e.join(o,`${e}.md`);if(existsSync(n)){let r=await Oe.readFile(n,"utf-8");t({type:"PROBLEM_NOTE_LOADED",content:r});}else t({type:"PROBLEM_NOTE_LOADED",content:'No notes found. Press "n" again to create/edit.'});}catch{t({type:"PROBLEM_ACTION_ERROR",error:"Failed to load note"});}}async function xu(e,t,o){try{let{code:n}=await ln(e),s=(await S.getProblem(e)).questionFrontendId,i=J.get(s,t);if(!i)throw new Error("Snapshot not found");let a=J.getCode(s,i),l=diffLines(n,a),u="";l.forEach(g=>{let d=g.added?"[green]":g.removed?"[red]":"[grey]",m=g.added?"+ ":g.removed?"- ":" ";g.value.split(`
|
|
271
|
-
`).forEach(b=>{b&&(u+=`${d}${m}${b}
|
|
272
|
-
`)
|
|
273
|
-
`);
|
|
248
|
+
`).length;console.log(),console.log(f.bold(`\u{1F4CA} Unified Diff: ${n} \u2192 ${o}`)),console.log(f.gray("\u2500".repeat(60))),console.log();let i=diffLines(e,t),a=0,l=0;for(let u of i){let p=u.value.split(`
|
|
249
|
+
`).filter(g=>g!=="");if(u.added){a+=p.length;for(let g of p)console.log(f.green("+ "+g));}else if(u.removed){l+=p.length;for(let g of p)console.log(f.red("- "+g));}else if(p.length<=6)for(let g of p)console.log(f.gray(" "+g));else console.log(f.gray(" "+p[0])),console.log(f.gray(" "+p[1])),console.log(f.dim(` ... (${p.length-4} unchanged lines)`)),console.log(f.gray(" "+p[p.length-2])),console.log(f.gray(" "+p[p.length-1]));}console.log(),console.log(f.gray("\u2500".repeat(60))),console.log(`${f.green("+"+a+" added")} ${f.gray("\xB7")} ${f.red("-"+l+" removed")} ${f.gray("\xB7")} ${f.gray(r+" \u2192 "+s+" lines")}`);}function to(e,t,n,o,r){if(r)ec(e,t,n,o);else {Os(e,n),Os(t,o);let s=diffLines(e,t),i=0,a=0;for(let l of s){let u=l.value.split(`
|
|
250
|
+
`).filter(p=>p!=="");l.added?i+=u.length:l.removed&&(a+=u.length);}console.log(),console.log(f.gray("\u2500".repeat(60))),console.log(`${f.bold("Summary:")} ${f.green("+"+i+" added")} ${f.gray("\xB7")} ${f.red("-"+a+" removed")}`),console.log(f.gray("Tip: Use --unified for line-by-line diff"));}}async function Ps(e,t){let{authorized:n}=await A();if(!n)return;let o=M.getWorkDir(),r=nn("Finding solution file...").start();try{let s=await de(o,e);if(!s){r.fail(`No solution file found for problem ${e}`),console.log(f.gray("Run `leetcode pick "+e+"` first to create a solution file."));return}let i=await readFile(s,"utf-8");if(r.text="Fetching comparison target...",t.file){if(r.stop(),!existsSync(t.file)){console.log(f.red(`File not found: ${t.file}`));return}if(!Xe(t.file,o)){console.log(f.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(f.gray(`File: ${t.file}`)),console.log(f.gray(`Workspace: ${o}`)),console.log(f.yellow(`
|
|
251
|
+
For security reasons, you can only diff files from within your workspace.`));return}let g=await readFile(t.file,"utf-8");to(i,g,"Your Solution",t.file,t.unified??!1);return}let a=await S.getProblemById(e);if(!a){r.fail(`Problem ${e} not found`);return}if(t.submission){let g=parseInt(t.submission,10),m=await S.getSubmissionDetails(g);r.stop(),to(i,m.code,"Your Solution",`Submission #${g}`,t.unified??!1);return}let u=(await S.getSubmissionList(a.titleSlug,50)).find(g=>g.statusDisplay==="Accepted");if(!u){r.fail("No accepted submissions found for this problem"),console.log(f.gray("Tip: Use --file to compare with a local file instead"));return}let p=await S.getSubmissionDetails(parseInt(u.id,10));r.stop(),to(i,p.code,"Your Solution","Last Accepted",t.unified??!1);}catch(s){r.fail("Failed to diff"),s instanceof Error&&console.log(f.red(s.message));}}async function vs(){let e=T.getActive(),t=T.getConfig(e);console.log(),console.log(f.bold.cyan(`\u{1F4C1} Active Workspace: ${e}`)),console.log(f.gray("\u2500".repeat(40))),console.log(` workDir: ${f.white(t.workDir)}`),console.log(` lang: ${f.white(t.lang)}`),t.editor&&console.log(` editor: ${f.white(t.editor)}`),t.syncRepo&&console.log(` syncRepo: ${f.white(t.syncRepo)}`),console.log();}async function As(){let e=T.list(),t=T.getActive();console.log(),console.log(f.bold("Workspaces:")),console.log();for(let n of e){let o=T.getConfig(n),r=n===t?f.green("\u25B8 "):" ",s=n===t?f.green.bold(n):n;console.log(`${r}${s}`),console.log(` ${f.gray(o.workDir)}`);}console.log();}async function $s(e,t){let n=e.trim();if(!Je(n)){console.log(f.red("Invalid workspace name.")),console.log(f.gray('Use 1-64 characters: letters, numbers, "-" or "_".'));return}if(T.exists(n)){console.log(f.red(`Workspace "${n}" already exists`));return}let o=t.workdir??join(homedir(),"leetcode",n),r={workDir:o,lang:"typescript"};T.create(n,r)?(console.log(f.green(`\u2713 Created workspace "${n}"`)),console.log(` workDir: ${f.gray(o)}`),console.log(),console.log(f.gray(`Switch to it: leetcode workspace use ${n}`))):console.log(f.red("Failed to create workspace"));}async function Ds(e){let t=e.trim();if(!Je(t)){console.log(f.red("Invalid workspace name."));return}if(!T.exists(t)){console.log(f.red(`Workspace "${t}" not found`)),console.log(f.gray("Use `leetcode workspace list` to see available workspaces"));return}if(T.setActive(t)){let o=T.getConfig(t);console.log(f.green(`\u2713 Switched to workspace "${t}"`)),console.log(` workDir: ${f.gray(o.workDir)}`);}else console.log(f.red("Failed to switch workspace"));}async function Is(e){let t=e.trim();if(!Je(t)){console.log(f.red("Invalid workspace name."));return}if(t==="default"){console.log(f.red("Cannot delete the default workspace"));return}if(!T.exists(t)){console.log(f.red(`Workspace "${t}" not found`));return}let{confirmed:n}=await Jn.prompt([{type:"confirm",name:"confirmed",message:`Delete workspace "${t}"? (files in workDir will NOT be deleted)`,default:false}]);if(!n){console.log(f.gray("Cancelled"));return}let o=T.delete(t);console.log(o?f.green(`\u2713 Deleted workspace "${t}"`):f.red("Failed to delete workspace"));}var no=join(homedir(),".leetcode"),kt=join(no,"version-cache.json"),cc=1440*60*1e3;function uc(){existsSync(no)||mkdirSync(no,{recursive:true});}function Ns(){if(existsSync(kt))try{return JSON.parse(readFileSync(kt,"utf-8"))}catch{return null}return null}function dc(e){uc(),writeFileSync(kt,JSON.stringify(e,null,2)+`
|
|
252
|
+
`);}var He={shouldCheck(){let e=Ns();return e?Date.now()-e.lastCheck>cc:true},getCached(){return Ns()},updateCache(e,t){dc({lastCheck:Date.now(),latestVersion:e,hasBreakingChanges:t});},clearCache(){if(existsSync(kt))try{unlinkSync(kt);}catch{}}};function rt(e,t){let n=e.replace("v","").split(".").map(Number),o=t.replace("v","").split(".").map(Number);for(let r=0;r<3;r++){let s=n[r]||0,i=o[r]||0;if(s>i)return true;if(s<i)return false}return false}function Hs(e,t){let n=parseInt(e.replace("v","").split(".")[0])||0;return (parseInt(t.replace("v","").split(".")[0])||0)>n}var hc=fileURLToPath(import.meta.url),Us=dirname(hc),Sc="https://registry.npmjs.org/@night-slayer18/leetcode-cli/latest",bc="@night-slayer18/leetcode-cli";function st(){let e=[join(Us,"../package.json"),join(Us,"../../package.json")];for(let t of e)try{let n=JSON.parse(readFileSync(t,"utf-8"));if(n.version)return n.version}catch{continue}throw new Error("Could not read package.json version. Ensure you are running from a valid installation.")}async function Gs(){let t=(await Zi(Sc,{timeout:{request:1e4},retry:{limit:2}}).json()).version,n=st(),o=Hs(n,t);return {version:t,hasBreakingChanges:o}}function Ec(e,t,n){console.log();let o=60,r="\u256D"+"\u2500".repeat(o-2)+"\u256E",s="\u2570"+"\u2500".repeat(o-2)+"\u256F";console.log(f.cyan(r));let i=` \u{1F680} Update available: ${f.gray(e)} \u2192 ${f.green(t)}`;if(console.log(f.cyan("\u2502")+i.padEnd(o+18)+f.cyan("\u2502")),n){console.log(f.cyan("\u2502")+"".padEnd(o-2)+f.cyan("\u2502"));let l=` ${f.yellow("\u26A0\uFE0F This update contains breaking changes!")}`;console.log(f.cyan("\u2502")+l.padEnd(o+20)+f.cyan("\u2502"));let u=` ${f.gray("Run:")} leetcode changelog ${f.gray("to review changes")}`;console.log(f.cyan("\u2502")+u.padEnd(o+16)+f.cyan("\u2502"));}console.log(f.cyan("\u2502")+"".padEnd(o-2)+f.cyan("\u2502"));let a=` ${f.gray("Run:")} npm update -g ${bc}`;console.log(f.cyan("\u2502")+a.padEnd(o+8)+f.cyan("\u2502")),console.log(f.cyan(s)),console.log();}async function js(e){let t=st();e.force&&He.clearCache();let n=He.getCached(),o,r;if(n&&!He.shouldCheck()&&!e.force)o=n.latestVersion,r=n.hasBreakingChanges;else {let s=nn("Checking for updates...").start();try{let i=await Gs();o=i.version,r=i.hasBreakingChanges,He.updateCache(o,r),s.stop();}catch(i){s.fail("Failed to check for updates"),process.env.DEBUG&&console.log(f.gray(` Debug: ${i instanceof Error?i.message:String(i)}`)),console.log(f.gray(" Could not reach npm registry. Check your internet connection."));return}}rt(o,t)?(Ec(t,o,r),e.checkOnly||r&&(console.log(f.yellow("\u{1F4A1} Tip: Review the changelog before updating to check for breaking changes.")),console.log(f.gray(` Run: leetcode changelog
|
|
253
|
+
`)))):(console.log(),console.log(f.green("\u2713")+` You're on the latest version (${f.cyan(t)})`),console.log());}async function qs(){if(!He.shouldCheck()){let e=He.getCached();e&&rt(e.latestVersion,st())&&Ws(st(),e.latestVersion,e.hasBreakingChanges);return}try{let e=await Gs();He.updateCache(e.version,e.hasBreakingChanges),rt(e.version,st())&&Ws(st(),e.version,e.hasBreakingChanges);}catch{}}function Ws(e,t,n){console.log(),n?(console.log(f.yellow(`\u26A0\uFE0F Update ${e} \u2192 ${t} available (breaking changes!)`)),console.log(f.gray(" Run: leetcode changelog && leetcode update"))):(console.log(f.cyan(`\u{1F680} Update available: ${e} \u2192 ${t}`)),console.log(f.gray(" Run: leetcode update"))),console.log();}var Tc=fileURLToPath(import.meta.url),Vs=dirname(Tc),Lc="https://raw.githubusercontent.com/night-slayer18/leetcode-cli/main/docs/releases.md";function Rc(){let e=[join(Vs,"../package.json"),join(Vs,"../../package.json")];for(let t of e)try{let n=JSON.parse(readFileSync(t,"utf-8"));if(n.version)return n.version}catch{continue}throw new Error("Could not read package.json version. Ensure you are running from a valid installation.")}async function Oc(){return await Zi(Lc,{timeout:{request:1e4},retry:{limit:2}}).text()}function xc(e){let t=[],n=/^## v?([\d.]+)/gm,o=[...e.matchAll(n)];for(let r=0;r<o.length;r++){let s=o[r],i=`v${s[1]}`,a=s.index+s[0].length,l=r+1<o.length?o[r+1].index:e.length,u=e.slice(a,l).trim(),p=u.includes("\u26A0\uFE0F Breaking Change");t.push({version:i,content:u,hasBreakingChanges:p});}return t}function Pc(e,t,n){let o=n?f.bgRed.white.bold(` ${e} `)+f.red(" \u26A0\uFE0F BREAKING CHANGES"):f.bgCyan.black.bold(` ${e} `);console.log(o),console.log();let r=t.split(`
|
|
254
|
+
`),s=false;for(let i of r)if(!(i.trim()===""&&!s)){if(i.startsWith("> **Release Date**")){let a=i.replace("> **Release Date**: ","").trim();console.log(f.gray(` \u{1F4C5} ${a}`));continue}if(i.startsWith("> **Focus**")){let a=i.replace("> **Focus**: ","").trim();console.log(f.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(f.bold.yellow(` ${a}`));else {let u="\u{1F4CC}";a.includes("Breaking")?u="\u26A0\uFE0F":a.includes("Feature")||a.includes("New")?u="\u{1F680}":a.includes("Fix")||a.includes("Bug")?u="\u{1F41B}":a.includes("Security")?u="\u{1F512}":a.includes("Improvement")?u="\u2728":a.includes("Architecture")?u="\u{1F3D7}\uFE0F":a.includes("Testing")?u="\u{1F9EA}":a.includes("Config")&&(u="\u2699\uFE0F"),console.log(f.bold.yellow(` ${u} ${a}`));}s=true;continue}if(i.startsWith("#### ")){let a=i.replace("#### ","").trim();console.log(f.bold.white(` ${a}`));continue}if(i.startsWith("- **")){let a=i.match(/^- \*\*(.+?)\*\*:?\s*(.*)/);console.log(a?f.cyan(` \u2022 ${f.bold(a[1])}`)+(a[2]?f.white(`: ${a[2]}`):""):f.cyan(` \u2022 ${i.replace("- ","")}`));continue}if(i.startsWith("- ")){let a=i.replace("- ","").trim();console.log(f.white(` \u2022 ${a}`));continue}i.startsWith("---")||i.trim()===">"||i.trim()&&console.log(f.gray(` ${i.trim()}`));}}async function zs(e,t={}){let n=nn("Fetching changelog...").start();try{let o=await Oc();n.stop();let r=xc(o);if(r.length===0){console.log(f.yellow("No release entries found."));return}let s=Rc(),i=r;if(e){let a=e.startsWith("v")?e:`v${e}`;if(i=r.filter(l=>l.version===a),i.length===0){console.log(f.red(`Version ${e} not found in changelog.`)),console.log(f.gray("Available versions: "+r.map(l=>l.version).join(", ")));return}}else if(t.latest)i=r.slice(0,1);else if(t.breaking){if(i=r.filter(a=>a.hasBreakingChanges),i.length===0){console.log(f.green("\u2713 No breaking changes in any release."));return}}else if(t.all)i=r;else {if(i=r.filter(a=>rt(a.version,s)),i.length===0){console.log(f.green(`\u2713 You're on the latest version (${s})`)),console.log(f.gray("Use --all to see the full changelog."));return}console.log(f.gray(`Showing changes since your version (${s})`)),console.log(f.gray("Use --all to see the full changelog."));}console.log(),console.log(f.bold.cyan("\u{1F4CB} LeetCode CLI Release Notes")),console.log(f.gray("\u2500".repeat(50))),console.log();for(let a of i)Pc(a.version,a.content,a.hasBreakingChanges),console.log(f.gray("\u2500".repeat(60))),console.log();if(!e&&!t.latest){let a=r.filter(l=>l.hasBreakingChanges).length;console.log(f.gray(`Showing ${i.length} of ${r.length} releases`)),a>0&&!t.breaking&&console.log(f.yellow(`${a} release(s) contain breaking changes. Use --breaking to filter.`));}}catch{n.fail("Failed to fetch changelog"),console.log(f.gray(" Could not fetch release notes from GitHub.")),console.log(f.gray(" Visit: https://github.com/night-slayer18/leetcode-cli/blob/main/docs/releases.md"));}}var c={none:()=>({type:"CMD_NONE"}),batch:(...e)=>({type:"CMD_BATCH",commands:e}),fetchProblems:(e,t=false)=>({type:"CMD_FETCH_PROBLEMS",filters:e,append:t}),fetchProblemDetail:e=>({type:"CMD_FETCH_PROBLEM_DETAIL",slug:e}),fetchStats:()=>({type:"CMD_FETCH_STATS"}),fetchDaily:()=>({type:"CMD_FETCH_DAILY"}),fetchRandom:()=>({type:"CMD_FETCH_RANDOM"}),checkAuth:()=>({type:"CMD_CHECK_AUTH"}),pickProblem:(e,t)=>({type:"CMD_PICK_PROBLEM",slug:e,lang:t}),testSolution:e=>({type:"CMD_TEST_SOLUTION",slug:e}),submitSolution:e=>({type:"CMD_SUBMIT_SOLUTION",slug:e}),startTimer:(e=1e3)=>({type:"CMD_START_TIMER_SUBSCRIPTION",intervalMs:e}),stopTimer:()=>({type:"CMD_STOP_TIMER_SUBSCRIPTION"}),saveConfig:(e,t)=>({type:"CMD_SAVE_CONFIG",key:e,value:t}),openEditor:e=>({type:"CMD_OPEN_EDITOR",id:e}),fetchSubmissions:e=>({type:"CMD_FETCH_SUBMISSIONS",slug:e}),exit:()=>({type:"CMD_EXIT"}),loadNote:e=>({type:"CMD_LOAD_NOTE",problemId:e}),diffSnapshot:(e,t)=>({type:"CMD_DIFF_SNAPSHOT",slug:e,snapshotId:t}),restoreSnapshot:(e,t)=>({type:"CMD_RESTORE_SNAPSHOT",slug:e,snapshotId:t}),loadWorkspaces:()=>({type:"CMD_LOAD_WORKSPACES"}),createWorkspace:e=>({type:"CMD_CREATE_WORKSPACE",name:e}),deleteWorkspace:e=>({type:"CMD_DELETE_WORKSPACE",name:e}),switchWorkspace:e=>({type:"CMD_SWITCH_WORKSPACE",name:e}),fetchChangelog:()=>({type:"CMD_FETCH_CHANGELOG"}),logout:()=>({type:"CMD_LOGOUT"}),login:(e,t)=>({type:"CMD_LOGIN",session:e,csrf:t})};function Ys(e){return {screenState:{screen:"home",model:{menuIndex:0}},history:[],user:e?{username:e,isLoggedIn:true}:null,isCheckingAuth:true,globalError:null,terminalWidth:process.stdout.columns||80,terminalHeight:process.stdout.rows||24,needsRender:true}}var sn=50;function vc(){return {problems:[],total:0,cursor:0,scrollOffset:0,page:0,loading:true,loadingMore:false,error:null,searchQuery:"",searchMode:false,searchBuffer:"",difficultyFilter:null,statusFilter:null,bookmarkFilter:false}}function ro(){let e=vc(),t={limit:sn,skip:0};return [e,c.fetchProblems(t,false)]}function so(e,t,n){let o=Math.max(3,n-13);switch(e.type){case "LIST_CURSOR_DOWN":{if(t.problems.length===0)return [t,c.none()];let r=Math.min(t.cursor+1,t.problems.length-1),s=t.scrollOffset;if(r>=t.scrollOffset+o&&(s=r-o+1),r>=t.problems.length-5&&t.problems.length<t.total&&!t.loadingMore&&!t.loading){let a=it(t,t.page+1);return [{...t,cursor:r,scrollOffset:s,loadingMore:true},c.fetchProblems(a,true)]}return [{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_CURSOR_UP":{if(t.problems.length===0)return [t,c.none()];let r=Math.max(t.cursor-1,0),s=t.scrollOffset;return r<t.scrollOffset&&(s=r),[{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_PAGE_DOWN":{let r=Math.min(t.cursor+o,t.problems.length-1),s=Math.min(t.scrollOffset+o,Math.max(0,t.problems.length-o));return [{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_PAGE_UP":{let r=Math.max(t.cursor-o,0),s=Math.max(t.scrollOffset-o,0);return [{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_GO_TOP":return [{...t,cursor:0,scrollOffset:0},c.none()];case "LIST_GO_BOTTOM":{let r=Math.max(0,t.problems.length-1),s=Math.max(0,t.problems.length-o);return [{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_SELECT":return [t,c.none()];case "LIST_SEARCH_START":return [{...t,searchMode:true,searchBuffer:t.searchQuery},c.none()];case "LIST_SEARCH_INPUT":return [{...t,searchBuffer:t.searchBuffer+e.char},c.none()];case "LIST_SEARCH_BACKSPACE":return [{...t,searchBuffer:t.searchBuffer.slice(0,-1)},c.none()];case "LIST_SEARCH_SUBMIT":{let r=it({...t,searchQuery:t.searchBuffer},0);return [{...t,searchMode:false,searchQuery:t.searchBuffer,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(r,false)]}case "LIST_SEARCH_CANCEL":return [{...t,searchMode:false,searchBuffer:""},c.none()];case "LIST_FILTER_DIFFICULTY":{let r=e.difficulty,s=it({...t,difficultyFilter:r},0);return [{...t,difficultyFilter:r,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(s,false)]}case "LIST_FILTER_STATUS":{let r=e.status,s=it({...t,statusFilter:r},0);return [{...t,statusFilter:r,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(s,false)]}case "LIST_FILTER_BOOKMARKS":{let r=!t.bookmarkFilter,s=it({...t},0);return [{...t,bookmarkFilter:r,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(s,false)]}case "LIST_CLEAR_FILTERS":{let r={limit:sn,skip:0};return [{...t,difficultyFilter:null,statusFilter:null,searchQuery:"",bookmarkFilter:false,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(r,false)]}case "LIST_REFRESH":{let r=it(t,0);return [{...t,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(r,false)]}case "LIST_FETCH_START":return [{...t,loading:true,error:null},c.none()];case "LIST_FETCH_SUCCESS":{let r=e.append?[...t.problems,...e.problems]:e.problems;return t.bookmarkFilter&&(r=r.filter(s=>pe.has(s.questionFrontendId))),[{...t,problems:r,total:t.bookmarkFilter?r.length:e.total,loading:false,loadingMore:false,page:e.append?t.page+1:0,error:null},c.none()]}case "LIST_FETCH_ERROR":return [{...t,loading:false,loadingMore:false,error:e.error},c.none()];default:return [t,c.none()]}}function it(e,t){let n={limit:sn,skip:t*sn};if(e.difficultyFilter&&(n.difficulty=e.difficultyFilter.toUpperCase()),e.statusFilter){let o={solved:"AC",attempted:"TRIED",todo:"NOT_STARTED"};n.status=o[e.statusFilter];}return e.searchQuery&&(n.searchKeywords=e.searchQuery),n}var Tt=[{key:"l",label:"Problem List",description:"Browse and search problems"},{key:"d",label:"Daily Challenge",description:"Today's daily problem"},{key:"r",label:"Random Problem",description:"Pick a random problem"},{key:"b",label:"Bookmarks",description:"View bookmarked problems"},{key:"t",label:"Timer",description:"Practice timer"},{key:"s",label:"Statistics",description:"View your progress"},{key:"y",label:"Sync",description:"Sync solutions to GitHub"},{key:"w",label:"Workspaces",description:"Manage workspaces"},{key:"c",label:"Config",description:"Settings and preferences"},{key:"v",label:"Changelog",description:"What's new in this version"},{key:"L",label:"Logout",description:"Sign out of LeetCode"},{key:"?",label:"Help",description:"Keyboard shortcuts and help"}];function an(e,t){switch(e.type){case "HOME_MENU_UP":{let n=Math.max(0,t.menuIndex-1);return [{...t,menuIndex:n},c.none()]}case "HOME_MENU_DOWN":{let n=Math.min(Tt.length-1,t.menuIndex+1);return [{...t,menuIndex:n},c.none()]}case "HOME_MENU_SELECT":return [t,c.none()];default:return [t,c.none()]}}function ln(e,t){switch(e.type){case "TIMER_START":return t.status==="running"?[t,c.none()]:[{...t,status:"running"},c.startTimer(1e3)];case "TIMER_PAUSE":return t.status!=="running"?[t,c.none()]:[{...t,status:"paused"},c.stopTimer()];case "TIMER_RESET":return [{...t,remainingSeconds:t.totalSeconds,status:"idle"},c.stopTimer()];case "TIMER_TICK":return t.status!=="running"?[t,c.none()]:t.remainingSeconds<=1?[{...t,remainingSeconds:0,status:"completed"},c.stopTimer()]:[{...t,remainingSeconds:t.remainingSeconds-1},c.none()];case "TIMER_COMPLETE":return [{...t,status:"completed"},c.stopTimer()];case "TIMER_SWITCH_VIEW":return [{...t,viewMode:e.view},c.none()];default:return [t,c.none()]}}function Ic(){return {loading:true,error:null,stats:null,dailyChallenge:null,skillStats:null}}function Qs(){return [Ic(),c.fetchStats()]}function io(e,t){switch(e.type){case "STATS_FETCH_START":return [{...t,loading:true,error:null},c.none()];case "STATS_FETCH_SUCCESS":return [{...t,loading:false,stats:e.stats,dailyChallenge:e.daily,skillStats:e.skills},c.none()];case "STATS_FETCH_ERROR":return [{...t,loading:false,error:e.error},c.none()];case "STATS_REFRESH":return [{...t,loading:true,error:null},c.fetchStats()];default:return [t,c.none()]}}function Fc(e){return [{id:"language",label:"Default Language",description:"Language for new solutions (example: typescript, python3, sql)",value:e.language},{id:"editor",label:"Editor Command",description:"Command used to open files (example: code, vim, nano)",value:e.editor||""},{id:"workdir",label:"Working Directory",description:"Directory where solution files are generated",value:e.workDir},{id:"repo",label:"Sync Repository",description:"Git repository URL used for sync operations",value:e.repo||""}]}function ao(e){return e.options[e.selectedOption]}function Hc(e,t){let n=t.trim();return e.id==="language"&&!n?"Language cannot be empty":e.id==="workdir"&&!n?"Working directory cannot be empty":null}function Bc(){let e=M.getConfig(),t=Fc(e);return {selectedOption:0,options:t,paneFocus:"list",isEditing:false,draftValue:t[0]?.value??"",validationError:null,isDirty:false,config:e}}function Xs(){return [Bc(),c.none()]}function Js(e,t){let n=(t+e.options.length)%e.options.length,o=e.options[n];return {...e,selectedOption:n,draftValue:o.value,isEditing:false,isDirty:false,validationError:null}}function lo(e,t){switch(e.type){case "CONFIG_OPTION_UP":return t.isEditing?[t,c.none()]:[Js(t,t.selectedOption-1),c.none()];case "CONFIG_OPTION_DOWN":return t.isEditing?[t,c.none()]:[Js(t,t.selectedOption+1),c.none()];case "CONFIG_FOCUS_LIST":return [{...t,paneFocus:"list",isEditing:false,isDirty:false},c.none()];case "CONFIG_FOCUS_EDITOR":return [{...t,paneFocus:"editor"},c.none()];case "CONFIG_TOGGLE_FOCUS":return [{...t,paneFocus:t.paneFocus==="list"?"editor":"list"},c.none()];case "CONFIG_EDIT_START":{let n=ao(t);return [{...t,paneFocus:"editor",isEditing:true,draftValue:n.value,validationError:null,isDirty:false},c.none()]}case "CONFIG_EDIT_INPUT":return t.isEditing?[{...t,draftValue:t.draftValue+e.char,validationError:null,isDirty:true},c.none()]:[t,c.none()];case "CONFIG_EDIT_BACKSPACE":return t.isEditing?[{...t,draftValue:t.draftValue.slice(0,-1),validationError:null,isDirty:true},c.none()]:[t,c.none()];case "CONFIG_EDIT_CANCEL":{let n=ao(t);return [{...t,isEditing:false,isDirty:false,draftValue:n.value,validationError:null},c.none()]}case "CONFIG_EDIT_SAVE":{if(!t.isEditing)return [t,c.none()];let n=ao(t),o=Hc(n,t.draftValue);if(o)return [{...t,validationError:o},c.none()];let r=[...t.options];return r[t.selectedOption]={...n,value:t.draftValue},[{...t,options:r,isEditing:false,isDirty:false,validationError:null},c.saveConfig(n.id,t.draftValue)]}default:return [t,c.none()]}}var d={primary:"#00B8D4",success:"#00E676",warning:"#FFEA00",error:"#FF1744",info:"#2979FF",text:"#FFFFFF",textMuted:"#90A4AE",textDim:"#546E7A",border:"#37474F",textBright:"#FFFFFF",bgHighlight:"#263238",cyan:"#00E5FF"},Q={check:"\u2714",cross:"\u2716",star:"\u2605",gear:"\u2699",folder:"\u{1F4C2}",target:"\u{1F3AF}",fire:"\u{1F525}",arrow:"\u2192",code:"\u{1F4DD}"},G={topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502",leftT:"\u251C",rightT:"\u2524",topT:"\u252C",bottomT:"\u2534",cross:"\u253C",roundTopLeft:"\u256D",roundTopRight:"\u256E",roundBottomLeft:"\u2570",roundBottomRight:"\u256F",heavyHorizontal:"\u2501",heavyVertical:"\u2503"},cn={tableColumns:{selector:2,status:3,id:6,difficulty:10,acceptance:8,premium:2}};var co={filled:"\u2588",empty:"\u2591"};var Wc=/\x1B\[[0-9;]*[a-zA-Z]/g;function P(e){return e.replace(Wc,"")}function Lt(e){return P(e).length}function $(e,t){if(t<=0)return "";if(t===1)return "\u2026";if(Lt(e)<=t)return e;let n=t-1,o="",r=0;for(let s=0;s<e.length&&r<n;){if(e[s]==="\x1B"){let i=e.slice(s).match(/^\x1B\[[0-9;]*[a-zA-Z]/);if(i){o+=i[0],s+=i[0].length;continue}}o+=e[s],s+=1,r+=1;}return e.includes("\x1B[")?`${o}\u2026\x1B[0m`:`${o}\u2026`}function ce(e,t){let n=P(e),o=t-n.length;return o>0?e+" ".repeat(o):e}function po(e,t){let n=P(e),o=t-n.length;return o>0?" ".repeat(o)+e:e}function v(e,t){if(t<=0)return "";let o=P(e).length;if(o>=t)return e;let r=Math.floor((t-o)/2),s=t-o-r;return " ".repeat(r)+e+" ".repeat(s)}var uo={light:G,round:G,heavy:{horizontal:"\u2501",vertical:"\u2503",topLeft:"\u250F",topRight:"\u2513",bottomLeft:"\u2517",bottomRight:"\u251B"},double:{horizontal:"\u2550",vertical:"\u2551",topLeft:"\u2554",topRight:"\u2557",bottomLeft:"\u255A",bottomRight:"\u255D"}};function he(e,t,n={}){let o=typeof n=="string"?{title:n}:n,{title:r,borderColor:s=d.textMuted,padding:i=0,borderStyle:a="round"}=o,l=uo[a]||G,u=[],p=Math.max(4,t),g=Math.max(2,p-2),m=Math.max(1,g-i*2),b=f.hex(s)(l.topLeft||l.roundTopLeft);if(r){let _=f.hex(s).bold(` ${r} `),C=P(_).length;b+=f.hex(s)(l.horizontal),b+=_,b+=f.hex(s)(l.horizontal.repeat(Math.max(0,g-C-1)));}else b+=f.hex(s)(l.horizontal.repeat(g));b+=f.hex(s)(l.topRight||l.roundTopRight),u.push(b);for(let _=0;_<i;_++)u.push(f.hex(s)(l.vertical)+" ".repeat(g)+f.hex(s)(l.vertical));for(let _ of e){let C=P(_),R=_;C.length>m&&(R=$(_,m));let q=m-P(R).length,K=" ".repeat(i)+R+" ".repeat(q)+" ".repeat(i);u.push(f.hex(s)(l.vertical)+K+f.hex(s)(l.vertical));}for(let _=0;_<i;_++)u.push(f.hex(s)(l.vertical)+" ".repeat(g)+f.hex(s)(l.vertical));return u.push(f.hex(s)(l.bottomLeft||l.roundBottomLeft)+f.hex(s)(l.horizontal.repeat(g))+f.hex(s)(l.bottomRight||l.roundBottomRight)),u}function un(e,t="light",n=d.textMuted){let o=G.horizontal;return t==="heavy"&&(o=uo.heavy.horizontal),t==="double"&&(o=uo.double.horizontal),f.hex(n)(o.repeat(Math.max(0,e)))}function Zs(e,t,n){let o=Math.min(1,Math.max(0,e/t)),r=Math.round(o*n),s=n-r;return f.hex(d.success)(co.filled.repeat(r))+f.hex(d.textDim)(co.empty.repeat(s))}function Ve(e,t,n="#000000"){return f.bgHex(t).hex(n).bold(` ${e} `)}function ei(e){switch(e.toLowerCase()){case "easy":return Ve("Easy",d.success);case "medium":return Ve("Medium",d.warning);case "hard":return Ve("Hard",d.error);default:return Ve(e,d.textMuted)}}function ti(e){switch(e){case "ac":return f.hex(d.success)(Q.check);case "notac":return f.hex(d.warning)("\u25CB");default:return f.hex(d.textDim)(" ")}}function E(e,t){return f.hex(d.textMuted)("[")+f.hex(d.primary)(e)+f.hex(d.textMuted)("] ")+f.hex(d.text)(t)}function go(e){return e.map(t=>E(t.key,t.label)).join(" ")}function at(e,t,n){let o=Math.max(20,n),r=f.hex(d.primary).bold(` ${e} `),s=f.hex(d.textMuted)($(t,Math.max(8,o-2)));return [v(r,o),v(s,o)]}function _e(e,t){let n=Math.max(10,t),o=f.hex(d.primary).bold(` ${e} `),r=Math.max(0,n-Lt(o));return o+f.hex(d.textMuted)(G.horizontal.repeat(r))}function lt(e,t,n="normal"){let o=Math.max(20,t),r=n==="compact"?e.slice(0,3):e,s=go(r);return H([s],o).map(a=>v(a,o))}function ct(e,t,n,o,r=.5){let s=Math.max(20,n),i=Math.max(1,o),a=Math.max(8,Math.floor(s*r)),l=Math.max(8,s-a-1),u=[...e],p=[...t],g=[];for(;u.length<i;)u.push("");for(;p.length<i;)p.push("");for(let m=0;m<i;m++){let b=ce($(u[m]??"",a),a),_=ce($(p[m]??"",l),l);g.push(b+f.hex(d.border)(G.vertical)+_);}return g}var Gc=["\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 ","\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D ","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],jc=["\u2566 \u2554\u2550\u2557\u2554\u2550\u2557\u2554\u2566\u2557\u2554\u2550\u2557\u2554\u2550\u2557\u2554\u2566\u2557\u2554\u2550\u2557","\u2551 \u2551\u2563 \u2551\u2563 \u2551 \u2551 \u2551 \u2551 \u2551\u2551\u2551\u2563 ","\u2569\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u2569 \u255A\u2550\u255D\u255A\u2550\u255D\u2550\u2569\u255D\u255A\u2550\u255D"];function ut(e){return (e>=80?Gc:jc).map(n=>v(f.hex(d.primary)(n),e))}function H(e,t){let n=Math.max(1,t),o=[];for(let r of e){if(P(r).length<=n){o.push(r);continue}let i=r.split(" "),a="",l=0;for(let u of i){let p=P(u).length;if(p>n){l>0&&(o.push(a),a="",l=0);let m=u;for(;P(m).length>0;){let b=m.slice(0,n);o.push(b),m=m.slice(n);}continue}let g=a?1:0;l+p+g<=n?(a+=(a?" ":"")+u,l+=p+g):(o.push(a),a=u,l=p);}a&&o.push(a);}return o}function qc(e){switch(e){case "status":case "testResult":case "submitResult":return 6;case "hint":case "submissions":case "snapshots":return 10;case "note":case "diff":return 12;default:return 0}}function Rt(e,t){let n=Math.max(10,e),s=Math.max(4,n-3-2);if(t==="none")return {bodyHeight:s,drawerHeight:0};let i=1,a=s>=14?8:5,l=Math.max(3,s-a-i),u=Math.max(3,Math.min(qc(t),l));return {bodyHeight:Math.max(3,s-i-u),drawerHeight:u}}function gn(e){return [{problem:null,slug:e,detail:null,loading:true,error:null,scrollOffset:0,contentLines:[],testResult:null,submissionResult:null,isRunning:false,successMessage:null,activeHintIndex:null,isBookmarked:false,drawerMode:"none",focusRegion:"body",drawerScrollOffset:0,drawerData:{statusMessage:null},submissionsHistory:null,submissionsLoading:false,snapshotsList:null,snapshotCursor:0,noteContent:null,diffContent:null},c.fetchProblemDetail(e)]}function xe(e){return {...e,drawerMode:"none",focusRegion:"body",drawerScrollOffset:0,drawerData:{statusMessage:null}}}function re(e,t,n=null){return t==="none"?xe(e):{...e,drawerMode:t,focusRegion:"drawer",drawerScrollOffset:0,drawerData:{statusMessage:n}}}function fn(e,t,n,o){let r=Vc(t,n,o);switch(e.type){case "PROBLEM_FOCUS_TOGGLE":return t.drawerMode==="none"?[t,c.none()]:[{...t,focusRegion:t.focusRegion==="body"?"drawer":"body"},c.none()];case "PROBLEM_SCROLL_UP":return [{...t,scrollOffset:Math.max(0,t.scrollOffset-1)},c.none()];case "PROBLEM_SCROLL_DOWN":return [{...t,scrollOffset:Math.min(r,t.scrollOffset+1)},c.none()];case "PROBLEM_PAGE_UP":{let s=Math.max(3,Math.floor(fo(n,t.drawerMode)*.8));return [{...t,scrollOffset:Math.max(0,t.scrollOffset-s)},c.none()]}case "PROBLEM_PAGE_DOWN":{let s=Math.max(3,Math.floor(fo(n,t.drawerMode)*.8));return [{...t,scrollOffset:Math.min(r,t.scrollOffset+s)},c.none()]}case "PROBLEM_TOP":return [{...t,scrollOffset:0},c.none()];case "PROBLEM_BOTTOM":return [{...t,scrollOffset:r},c.none()];case "PROBLEM_DETAIL_LOADED":{let s=Kc(e.detail),i=pe.has(e.detail.questionFrontendId);return [{...t,loading:false,detail:e.detail,contentLines:s,scrollOffset:0,isBookmarked:i,error:null,successMessage:null,drawerMode:"none",focusRegion:"body",drawerScrollOffset:0,drawerData:{statusMessage:null}},c.none()]}case "PROBLEM_DETAIL_ERROR":return [{...re({...t,loading:false,error:e.error},"status",e.error)},c.none()];case "PROBLEM_PICK":return [t,c.pickProblem(t.slug)];case "PROBLEM_TEST":return [{...re(t,"status","Running tests..."),isRunning:true,testResult:null,submissionResult:null,successMessage:null,error:null},c.testSolution(t.slug)];case "PROBLEM_SUBMIT":return [{...re(t,"status","Submitting solution..."),isRunning:true,testResult:null,submissionResult:null,successMessage:null,error:null},c.submitSolution(t.slug)];case "PROBLEM_TEST_RESULT":return [{...re(t,"testResult"),isRunning:false,testResult:e.result,submissionResult:null},c.none()];case "PROBLEM_SUBMIT_RESULT":return [{...re(t,"submitResult"),isRunning:false,submissionResult:e.result,testResult:null},c.none()];case "PROBLEM_BOOKMARK":{if(!t.detail)return [t,c.none()];let s=t.detail.questionFrontendId;if(pe.has(s)){pe.remove(s);let a="Problem unbookmarked";return [{...re(t,"status",a),isBookmarked:false,successMessage:a,error:null},c.none()]}pe.add(s);let i="Problem bookmarked";return [{...re(t,"status",i),isBookmarked:true,successMessage:i,error:null},c.none()]}case "PROBLEM_TOGGLE_HINT":return (t.detail?.hints||[]).length===0?[{...re(t,"status","No hints available for this problem"),error:null,successMessage:null},c.none()]:t.drawerMode==="hint"?[xe(t),c.none()]:[{...re(t,"hint"),activeHintIndex:t.activeHintIndex??0},c.none()];case "PROBLEM_NEXT_HINT":{let s=t.detail?.hints||[];if(s.length===0)return [t,c.none()];let i=t.activeHintIndex??0;return [{...t,activeHintIndex:Math.min(s.length-1,i+1),drawerScrollOffset:0},c.none()]}case "PROBLEM_PREV_HINT":{let s=t.activeHintIndex??0;return [{...t,activeHintIndex:Math.max(0,s-1),drawerScrollOffset:0},c.none()]}case "PROBLEM_HINT_SCROLL_UP":return [{...t,drawerScrollOffset:Math.max(0,t.drawerScrollOffset-1)},c.none()];case "PROBLEM_HINT_SCROLL_DOWN":return [{...t,drawerScrollOffset:Math.min(dn(t,n,o),t.drawerScrollOffset+1)},c.none()];case "PROBLEM_NOTES":return t.detail?[t,c.openEditor(t.detail.questionFrontendId)]:[t,c.none()];case "PROBLEM_ACTION_ERROR":return [{...re(t,"status",e.error),isRunning:false,error:e.error},c.none()];case "PROBLEM_ACTION_SUCCESS":return [{...re(t,"status",e.message),isRunning:false,successMessage:e.message,error:null},c.none()];case "PROBLEM_CLOSE_RESULT":return [xe(t),c.none()];case "PROBLEM_SHOW_SUBMISSIONS":return t.drawerMode==="submissions"?[xe(t),c.none()]:[{...re(t,"submissions"),submissionsLoading:true,submissionsHistory:null},c.fetchSubmissions(t.slug)];case "PROBLEM_SUBMISSIONS_LOADED":return [{...re(t,"submissions"),submissionsLoading:false,submissionsHistory:e.submissions,error:null},c.none()];case "PROBLEM_SUBMISSIONS_ERROR":return [{...re(t,"status",e.error),submissionsLoading:false,error:e.error},c.none()];case "PROBLEM_CLOSE_SUBMISSIONS":return [xe(t),c.none()];case "PROBLEM_SUBMISSIONS_SCROLL_UP":return [{...t,drawerScrollOffset:Math.max(0,t.drawerScrollOffset-1)},c.none()];case "PROBLEM_SUBMISSIONS_SCROLL_DOWN":return [{...t,drawerScrollOffset:Math.min(dn(t,n,o),t.drawerScrollOffset+1)},c.none()];case "PROBLEM_SHOW_SNAPSHOTS":{if(t.drawerMode==="snapshots")return [xe(t),c.none()];let s=t.detail?.questionFrontendId||t.slug;return [{...re(t,"snapshots"),snapshotsList:X.list(s),snapshotCursor:0},c.none()]}case "PROBLEM_CLOSE_SNAPSHOTS":return [xe(t),c.none()];case "PROBLEM_SNAPSHOT_UP":return !t.snapshotsList||t.snapshotsList.length===0?[t,c.none()]:[{...t,snapshotCursor:Math.max(0,t.snapshotCursor-1)},c.none()];case "PROBLEM_SNAPSHOT_DOWN":return !t.snapshotsList||t.snapshotsList.length===0?[t,c.none()]:[{...t,snapshotCursor:Math.min(t.snapshotsList.length-1,t.snapshotCursor+1)},c.none()];case "PROBLEM_VIEW_NOTE":return t.detail?[{...re(t,"status","Loading note...")},c.loadNote(t.detail.questionFrontendId)]:[t,c.none()];case "PROBLEM_NOTE_LOADED":return [{...re(t,"note"),noteContent:e.content,error:null},c.none()];case "PROBLEM_CLOSE_NOTE":return [xe(t),c.none()];case "PROBLEM_NOTE_SCROLL_UP":return [{...t,drawerScrollOffset:Math.max(0,t.drawerScrollOffset-1)},c.none()];case "PROBLEM_NOTE_SCROLL_DOWN":return [{...t,drawerScrollOffset:Math.min(dn(t,n,o),t.drawerScrollOffset+1)},c.none()];case "PROBLEM_DIFF_SNAPSHOT":{if(!t.snapshotsList||t.snapshotsList.length===0)return [t,c.none()];let s=t.snapshotsList[t.snapshotCursor];return s?[t,c.diffSnapshot(t.slug,s.id.toString())]:[t,c.none()]}case "PROBLEM_DIFF_LOADED":return [{...re(t,"diff"),diffContent:e.content,error:null},c.none()];case "PROBLEM_CLOSE_DIFF":return [xe(t),c.none()];case "PROBLEM_DIFF_SCROLL_UP":return [{...t,drawerScrollOffset:Math.max(0,t.drawerScrollOffset-1)},c.none()];case "PROBLEM_DIFF_SCROLL_DOWN":return [{...t,drawerScrollOffset:Math.min(dn(t,n,o),t.drawerScrollOffset+1)},c.none()];case "PROBLEM_RESTORE_SNAPSHOT":{if(!t.snapshotsList||t.snapshotsList.length===0)return [t,c.none()];let s=t.snapshotsList[t.snapshotCursor];return s?[t,c.restoreSnapshot(t.slug,s.id.toString())]:[t,c.none()]}default:return [t,c.none()]}}function Kc(e){return Dn(e.content||"").split(`
|
|
255
|
+
`)}function fo(e,t){let n=Math.max(6,e-4);return Rt(n,t).bodyHeight}function Vc(e,t,n){let o=fo(t,e.drawerMode),r=Math.max(20,n-4),s=H(e.contentLines,r);return Math.max(0,s.length-o)}function dn(e,t,n){if(e.drawerMode==="none"||e.drawerMode==="snapshots")return 0;let o=Math.max(6,t-4),r=Rt(o,e.drawerMode),s=Math.max(1,r.drawerHeight-2),i=Math.max(20,n-2),a=zc(e,i);return Math.max(0,a.length-s)}function zc(e,t){let n=Math.max(10,t-2);switch(e.drawerMode){case "hint":{let o=e.detail?.hints||[],r=e.activeHintIndex??0,s=o[r]??"",i=ni(s);return H([i||"No hint content"],n)}case "submissions":return e.submissionsLoading?["Loading submissions..."]:!e.submissionsHistory||e.submissionsHistory.length===0?["No submissions found for this problem.","Use [s] Submit after picking a solution."]:e.submissionsHistory.map(o=>{let r=pn(o.statusDisplay||"-",10).padEnd(10),s=pn(o.runtime||"-",8).padEnd(8),i=pn(o.memory||"-",8).padEnd(8),a=pn(o.lang||"-",8).padEnd(8);return `${r} ${s} ${i} ${a}`});case "note":return H(Yc(e.noteContent||"No notes found. Press e to edit."),n);case "diff":return (e.diffContent||"No diff available.").split(`
|
|
256
|
+
`).map(o=>ni(o));case "testResult":{let o=e.testResult;return o?o.compile_error?["Compile Error",...H([o.compile_error],n)]:o.runtime_error?["Runtime Error",...H([o.runtime_error],n)]:o.correct_answer?["All test cases passed"]:["Wrong answer"]:["No test result available."]}case "submitResult":{let o=e.submissionResult;if(!o)return ["No submission result available."];let r=[o.status_msg||"-",`Runtime: ${o.status_runtime||"-"}`,`Memory: ${o.status_memory||"-"}`];return o.runtime_error&&r.push(...H([o.runtime_error],n)),r}case "status":{let o=e.drawerData.statusMessage||e.successMessage||e.error||(e.isRunning?"Working...":"Ready");return H([o],n)}default:return []}}function ni(e){return P(e).replace(/\[green\]|\[red\]|\[grey\]/g,"").replace(/<\/?[^>]+(>|$)/g,"").replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/\s+/g," ").trim()}function pn(e,t){return e.length<=t?e:t<=1?"\u2026":`${e.slice(0,t-1)}\u2026`}function Yc(e){let t=e.split(`
|
|
257
|
+
`),n=[];for(let o of t){let r=o.trim();if(!r){n.length>0&&n[n.length-1]!==""&&n.push("");continue}if(r.startsWith("<!--")&&r.endsWith("-->"))continue;let s=o.replace(/\*\*(.*?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\[(.*?)\]\((.*?)\)/g,"$1 ($2)");s.startsWith("## ")?s=`\u2022 ${s.slice(3)}`:s.startsWith("# ")&&(s=s.slice(2)),n.push(s);}for(;n.length>0&&n[n.length-1]==="";)n.pop();return n.length>0?n:["No notes found. Press e to edit."]}var Jc=[{key:"lang",label:"Language"},{key:"workDir",label:"Work Dir"},{key:"editor",label:"Editor"},{key:"syncRepo",label:"Sync Repo"}];function mo(e,t,n){let o=[],r=Math.max(20,t),s=Math.max(8,n),i=e.selectedWorkspace?`Active: ${e.activeWorkspace} \u2022 Selected: ${e.selectedWorkspace}`:"Manage isolated problem-solving contexts";o.push(...at(`${Q.folder} Workspaces`,i,r)),o.push(f.hex(d.textMuted)(G.horizontal.repeat(r)));let a=Math.max(3,s-o.length-3);if(r>=90)o.push(...ct(oi(e,r),ri(e,r),r,a,.43));else {let l=Math.max(3,Math.floor(a*.45)),u=Math.max(3,a-l-1),p=oi(e,r).slice(0,l);for(;p.length<l;)p.push("");let g=ri(e,r).slice(0,u);for(;g.length<u;)g.push("");o.push(...p),o.push(f.hex(d.border)(G.horizontal.repeat(r))),o.push(...g);}for(;o.length<s-2;)o.push("");return o.push(f.hex(d.textMuted)(G.horizontal.repeat(r))),o.push(...Xc(e,r)),o.slice(0,s).join(`
|
|
258
|
+
`)}function oi(e,t){let n=t>=90?Math.max(20,Math.floor(t*.43)):t,o=[];if(o.push(_e("Workspace List",n)),o.push(""),e.workspaces.length===0)return o.push(f.hex(d.warning)("No workspaces found.")),o;for(let r=0;r<e.workspaces.length;r++){let s=e.workspaces[r],i=r===e.cursor,a=s===e.activeWorkspace,l=i?f.hex(d.primary).bold("\u25B6"):" ",u=a?f.hex(d.success)("\u25CF"):f.hex(d.textMuted)("\u25CB"),p=$(s,Math.max(6,n-8)),g=` ${l} ${u} ${p}`;i&&e.paneFocus==="list"?o.push(f.bgHex(d.bgHighlight)(g.padEnd(Math.max(0,n-1)))):o.push(g);}return o.push(""),o.push(f.hex(d.textMuted)(`Count: ${e.workspaces.length}`)),o}function ri(e,t){let n=t>=90?Math.max(20,t-Math.floor(t*.43)-1):t,o=[];if(o.push(_e("Properties",n)),o.push(""),!e.selectedWorkspace||!e.draftConfig)return o.push(f.hex(d.textMuted)("Select a workspace to view properties.")),o;o.push(f.hex(d.primary).bold($(e.selectedWorkspace,n-2))),o.push(e.selectedWorkspace===e.activeWorkspace?f.hex(d.success)("Currently active"):f.hex(d.textMuted)("Not active")),o.push("");for(let r of Jc){let s=e.selectedField===r.key,i=e.draftConfig[r.key]||"(empty)",a=$(i,Math.max(8,n-18)),l=s?f.hex(d.primary)("\u25B6"):" ",u=e.isDirty&&s?f.hex(d.warning)("*"):" ",p=`${l} ${r.label.padEnd(10)}: ${a} ${u}`;if(s&&e.paneFocus==="editor"){let g=e.isEditing?`${p}\u2588`:p;o.push(f.bgHex(d.bgHighlight)(g.padEnd(Math.max(0,n-1))));}else o.push(p);}return o.push(""),o.push(f.hex(d.textMuted)(e.isEditing?"Editing field: Enter=Save Esc=Cancel":"Press Enter to edit selected field")),o}function Xc(e,t){if(e.showCreateInput)return [`Create workspace: ${$(e.newWorkspaceName,Math.max(5,t-20))}\u2588`,`${E("Enter","Create")} ${E("Esc","Cancel")}`];if(e.showDeleteConfirm){let n=e.workspaces[e.cursor]||"";return [f.bgRed.white(` Delete "${n}"? `),`${E("Enter","Delete")} ${E("Esc","Cancel")}`]}if(e.error){let n=H([`Error: ${e.error}`],Math.max(20,t-2));return [f.hex(d.error)(n[0]??e.error)]}if(e.success){let n=H([e.success],Math.max(20,t-2));return [f.hex(d.success)(n[0]??e.success)]}return lt([{key:"\u2191/\u2193",label:e.paneFocus==="list"?"Select workspace":"Select field"},{key:"Tab/h/l",label:"Switch pane"},{key:"Enter",label:e.paneFocus==="list"?"Switch/Edit":e.isEditing?"Save":"Edit"},{key:"c",label:"Create"},{key:"d",label:"Delete"},{key:"Esc",label:"Back/Cancel"}],t,t<90?"compact":"normal")}var Ot=["lang","workDir","editor","syncRepo"];function Zc(e){return {lang:e.lang??"",workDir:e.workDir??"",editor:e.editor??"",syncRepo:e.syncRepo??""}}function ii(e){return e?Zc(T.getConfig(e)):null}function mn(e,t,n){let o=Math.max(0,Math.min(n,Math.max(0,t.length-1))),r=t[o]??null,s=ii(r);return {...e,workspaces:t,cursor:o,selectedWorkspace:r,selectedConfig:s,draftConfig:s?{...s}:null,isDirty:false,isEditing:false}}function ai(){let e=T.list(),t=T.getActive(),n=Math.max(0,e.indexOf(t)),o=e[n]??null,r=ii(o);return [{workspaces:e,activeWorkspace:t,cursor:n,paneFocus:"list",selectedField:"lang",selectedWorkspace:o,selectedConfig:r,draftConfig:r?{...r}:null,isEditing:false,isDirty:false,showCreateInput:false,newWorkspaceName:"",showDeleteConfirm:false,error:null,success:null},c.none()]}function si(e,t){if(!e.draftConfig)return e;let n=e.selectedField,o={...e.draftConfig,[n]:t(e.draftConfig[n])};return {...e,draftConfig:o,isDirty:true,error:null,success:null}}function yo(e,t){switch(e.type){case "WORKSPACE_UP":return t.isEditing?[t,c.none()]:[mn(t,t.workspaces,t.cursor-1),c.none()];case "WORKSPACE_DOWN":return t.isEditing?[t,c.none()]:[mn(t,t.workspaces,t.cursor+1),c.none()];case "WORKSPACE_SELECT":{if(t.isEditing||t.showCreateInput||t.showDeleteConfirm)return [t,c.none()];let n=t.workspaces[t.cursor];return n?n===t.activeWorkspace?[{...t,success:`Already on "${n}"`,error:null},c.none()]:T.setActive(n)?[{...t,activeWorkspace:n,success:`Switched to "${n}"`,error:null},c.switchWorkspace(n)]:[{...t,error:`Failed to switch to "${n}"`,success:null},c.none()]:[t,c.none()]}case "WORKSPACE_FOCUS_LIST":return [{...t,paneFocus:"list",isEditing:false,isDirty:false,error:null},c.none()];case "WORKSPACE_FOCUS_EDITOR":return [{...t,paneFocus:"editor",error:null},c.none()];case "WORKSPACE_TOGGLE_FOCUS":return [{...t,paneFocus:t.paneFocus==="list"?"editor":"list",isEditing:false,isDirty:false,error:null},c.none()];case "WORKSPACE_FIELD_UP":{if(t.paneFocus!=="editor"||t.isEditing)return [t,c.none()];let n=Math.max(0,Ot.indexOf(t.selectedField)-1);return [{...t,selectedField:Ot[n]},c.none()]}case "WORKSPACE_FIELD_DOWN":{if(t.paneFocus!=="editor"||t.isEditing)return [t,c.none()];let n=Math.min(Ot.length-1,Ot.indexOf(t.selectedField)+1);return [{...t,selectedField:Ot[n]},c.none()]}case "WORKSPACE_EDIT_START":return t.paneFocus!=="editor"||!t.draftConfig?[t,c.none()]:[{...t,isEditing:true,error:null,success:null},c.none()];case "WORKSPACE_EDIT_INPUT":return t.isEditing?[si(t,n=>n+e.char),c.none()]:[t,c.none()];case "WORKSPACE_EDIT_BACKSPACE":return t.isEditing?[si(t,n=>n.slice(0,-1)),c.none()]:[t,c.none()];case "WORKSPACE_EDIT_CANCEL":return [{...t,draftConfig:t.selectedConfig?{...t.selectedConfig}:null,isEditing:false,isDirty:false,error:null},c.none()];case "WORKSPACE_EDIT_SAVE":{if(!t.isEditing||!t.selectedWorkspace||!t.draftConfig)return [t,c.none()];let n={lang:t.draftConfig.lang.trim(),workDir:t.draftConfig.workDir.trim(),editor:t.draftConfig.editor.trim(),syncRepo:t.draftConfig.syncRepo.trim()};return n.lang?n.workDir?(T.setConfig({lang:n.lang,workDir:n.workDir,editor:n.editor||void 0,syncRepo:n.syncRepo||void 0},t.selectedWorkspace),[{...t,selectedConfig:n,draftConfig:{...n},isEditing:false,isDirty:false,error:null,success:`Saved "${t.selectedWorkspace}" properties`},c.none()]):[{...t,error:"Working directory is required"},c.none()]:[{...t,error:"Language is required"},c.none()]}case "WORKSPACE_CREATE_START":return [{...t,showCreateInput:true,newWorkspaceName:"",error:null,success:null,paneFocus:"list"},c.none()];case "WORKSPACE_CREATE_INPUT":return t.showCreateInput?[{...t,newWorkspaceName:t.newWorkspaceName+e.char,error:null},c.none()]:[t,c.none()];case "WORKSPACE_CREATE_BACKSPACE":return t.showCreateInput?[{...t,newWorkspaceName:t.newWorkspaceName.slice(0,-1),error:null},c.none()]:[t,c.none()];case "WORKSPACE_CREATE_CANCEL":return [{...t,showCreateInput:false,newWorkspaceName:"",error:null},c.none()];case "WORKSPACE_CREATE_SUBMIT":{if(!t.showCreateInput)return [t,c.none()];let n=t.newWorkspaceName.trim();if(!n)return [{...t,error:"Name cannot be empty"},c.none()];if(T.exists(n))return [{...t,error:"Workspace already exists"},c.none()];if(!T.create(n,{workDir:"",lang:"typescript"}))return [{...t,error:"Failed to create workspace"},c.none()];let r=T.list();return [{...mn({...t,showCreateInput:false,newWorkspaceName:""},r,r.indexOf(n)),success:`Created workspace "${n}"`,paneFocus:"list"},c.createWorkspace(n)]}case "WORKSPACE_DELETE":{let n=t.workspaces[t.cursor];return n?n==="default"?[{...t,error:"Cannot delete default workspace"},c.none()]:[{...t,showDeleteConfirm:true,error:null,success:null},c.none()]:[t,c.none()]}case "WORKSPACE_DELETE_CANCEL":return [{...t,showDeleteConfirm:false,error:null},c.none()];case "WORKSPACE_DELETE_CONFIRM":{let n=t.workspaces[t.cursor];if(!n)return [t,c.none()];if(n==="default")return [{...t,error:"Cannot delete default workspace"},c.none()];if(!T.delete(n))return [{...t,error:`Failed to delete "${n}"`},c.none()];let r=T.list(),s=T.getActive();return [{...mn({...t,showDeleteConfirm:false,activeWorkspace:s},r,Math.min(t.cursor,Math.max(0,r.length-1))),success:`Deleted workspace "${n}"`},c.deleteWorkspace(n)]}default:return [t,c.none()]}}function li(e){let t=[],n=/^## v?([\d.]+)/gm,o=[...e.matchAll(n)];for(let r=0;r<o.length;r++){let s=o[r],i=`v${s[1]}`,a=s.index+s[0].length,l=r+1<o.length?o[r+1].index:e.length,u=e.slice(a,l).trim(),p=u.includes("\u26A0\uFE0F Breaking Change"),g=u.match(/> \*\*Release Date\*\*: (.*)/),m=g?g[1].trim():void 0;t.push({version:i,content:u,hasBreakingChanges:p,date:m});}return t}function di(e,t){return e.loading||e.error?3:pi(e.entries,t).length}function ho(e,t,n){let o=[],s=f.hex(d.primary).bold(Q.code+" Changelog ")+f.hex(d.textMuted)("Latest updates and improvements");o.push(s),o.push(f.hex(d.textMuted)(G.horizontal.repeat(t))),o.push("");let i=Math.max(3,n-5);if(e.loading)o.push(""),o.push(" "+f.hex(d.primary)("\u22EF Loading release notes..."));else if(e.error)o.push(""),o.push(" "+f.red(Q.cross+" Error loading changelog:")),o.push(" "+f.red(e.error));else {let l=pi(e.entries,t),u=Math.max(0,l.length-i),p=Math.min(e.scrollOffset,u);if(l.slice(p,p+i).forEach(m=>{o.push(" "+m);}),u>0&&o.length<n-2){let m=`${p+1}-${Math.min(p+i,l.length)} of ${l.length}`;o.push(" "+f.hex(d.textMuted)(m));}}for(;o.length<n-2;)o.push("");o.push(f.hex(d.textMuted)(G.horizontal.repeat(t)));let a=[E("j/k","Scroll"),E("Esc","Back")];return o.push(a.join(" ")),o.slice(0,n).join(`
|
|
259
|
+
`)}function tu(e,t){let n=[],o=` ${e.version} `,r=e.hasBreakingChanges?f.bgRed.white.bold(o)+f.red(" \u26A0\uFE0F BREAKING CHANGES"):f.bgHex(d.primary).black.bold(o);n.push(r),e.date&&n.push(f.gray(` \u{1F4C5} ${e.date}`)),n.push("");let s=e.content.split(`
|
|
260
|
+
`),i=false;for(let a of s)if(!(a.trim()===""&&!i)&&!(a.startsWith("> **Release Date**")||a.startsWith("> **Focus**"))){if(a.startsWith("### ")){let l=a.replace("### ","").trim();n.push("");let u="\u{1F4CC}";l.includes("Breaking")?u="\u26A0\uFE0F":l.includes("Feature")||l.includes("New")?u="\u{1F680}":(l.includes("Fix")||l.includes("Bug"))&&(u="\u{1F41B}"),n.push(f.bold.yellow(`${u} ${l}`)),i=true;continue}if(a.startsWith("#### ")){n.push(f.bold.white(" "+a.replace("#### ","").trim()));continue}if(a.startsWith("- ")){let l=a.replace("- ","").trim(),u=l.match(/^\*\*(.+?)\*\*:?\s*(.*)/),p="";u?p=f.cyan(`\u2022 ${f.bold(u[1])}`)+(u[2]?f.white(`: ${u[2]}`):""):p=f.white(`\u2022 ${l}`),n.push(...ci(" "+p,t-3,5));continue}a.startsWith("---")||a.trim().length>0&&n.push(...ci(" "+f.gray(a.trim()),t-3,3));}return n}function ci(e,t,n){let o=Math.max(1,t);if(ui(e).length<=o)return [e];let r=e.split(" "),s=[],i="",a=" ".repeat(n);return r.forEach(l=>{ui(i+l).length+1>o?(s.push(i),i=a+l+" "):i+=l+" ";}),i&&s.push(i),s}function ui(e){return e.replace(/\x1B\[\d+m/g,"")}function pi(e,t){let n=[],o=Math.max(20,t-4);return e.forEach(r=>{n.push(...tu(r,o)),n.push(""),n.push(f.hex(d.border)(G.horizontal.repeat(o))),n.push("");}),n}function gi(e){return [{entries:[],scrollOffset:0,loading:true,error:null},c.fetchChangelog()]}function So(e,t,n,o){let r=Math.max(3,n-5),s=Math.max(0,di(t,o)-r);switch(e.type){case "CHANGELOG_SCROLL_UP":return [{...t,scrollOffset:Math.max(0,t.scrollOffset-1)},c.none()];case "CHANGELOG_SCROLL_DOWN":return [{...t,scrollOffset:Math.min(s,t.scrollOffset+1)},c.none()];case "CHANGELOG_FETCH_START":return [{...t,loading:true,error:null},c.none()];case "CHANGELOG_FETCH_SUCCESS":let i=li(e.content);return [{...t,loading:false,entries:i,error:null,scrollOffset:0},c.none()];case "CHANGELOG_FETCH_ERROR":return [{...t,loading:false,error:e.error},c.none()];default:return [t,c.none()]}}function bo(e,t,n){let o=[],r=[],s=ut(t);if(r.push(...s),r.push(""),r.push(v(f.hex(d.textMuted)("Please authenticate to access LeetCode features"),t)),r.push(""),r.push(""),e.step==="instructions"){let l=Math.max(28,Math.min(100,t-4)),u=[f.hex(d.warning).bold("How to Login:"),"","1. Open https://leetcode.com in your browser","2. Login to your account","3. Open DevTools (F12) \u2192 Application \u2192 Cookies \u2192 leetcode.com","4. Copy the values of "+f.bold.cyan("LEETCODE_SESSION")+" and "+f.bold.cyan("csrftoken"),"","Default storage: system keychain.","Use LEETCODECLI_CREDENTIAL_BACKEND=file + LEETCODECLI_MASTER_KEY for encrypted file mode.","If LEETCODE_SESSION and LEETCODE_CSRF_TOKEN are set, login runs in read-only env mode."];he(u,l,{title:"Authentication Instructions",borderColor:d.primary,padding:1,borderStyle:"round"}).forEach(g=>r.push(v(g,t))),r.push(""),r.push(v(E("Enter","Continue to Login"),t));}else if(e.step==="input"||e.step==="verifying"||e.step==="error"){let l=Math.max(28,Math.min(100,t-4)),u=[],p=e.focusedField==="session",g=e.focusedField==="csrf",m=Math.max(12,l-20),b=Y=>Y.length>m?"..."+Y.slice(-(m-3)):Y,_=e.sessionToken?b(e.sessionToken):f.gray("Paste here..."),C=e.csrfToken?b(e.csrfToken):e.sessionToken?f.gray("Paste here..."):f.gray("Waiting..."),R=e.sessionToken?b(e.sessionToken):f.gray("(empty)"),q=e.csrfToken?b(e.csrfToken):f.gray("(empty)");u.push(f.bold("LEETCODE_SESSION:")),u.push(p?f.hex(d.primary)("> ")+_:" "+R+(e.sessionToken?f.green(" \u2714"):"")),u.push(""),u.push(f.bold("csrftoken:")),u.push(g?f.hex(d.primary)("> ")+C:" "+q+(e.csrfToken?f.green(" \u2714"):"")),u.push(""),e.error?u.push(v(f.red(e.error),l-4)):e.step==="verifying"?u.push(v(f.yellow("Verifying credentials..."),l-4)):u.push(v(f.gray("Use Command+V to paste"),l-4)),he(u,l,{title:"Enter Credentials",borderColor:e.error?d.error:d.primary,padding:1}).forEach(Y=>r.push(v(Y,t))),r.push(""),e.step==="input"&&r.push(v(E("Enter",e.focusedField==="session"?"Next":"Login")+" "+E("Esc","Cancel"),t));}else e.step==="success"&&(r.push(""),r.push(v(f.green.bold("\u2714 Login Successful!"),t)),r.push(v("Redirecting...",t)));let i=r.length,a=Math.max(0,Math.floor((n-i)/2));for(let l=0;l<a;l++)o.push("");for(o.push(...r);o.length<n;)o.push("");return o.slice(0,n).join(`
|
|
261
|
+
`)}function Eo(e,t){switch(e.type){case "LOGIN_SESSION_INPUT":return [{...t,sessionToken:e.value},c.none()];case "LOGIN_CSRF_INPUT":return [{...t,csrfToken:e.value},c.none()];case "LOGIN_SWITCH_FOCUS":return [{...t,focusedField:t.focusedField==="session"?"csrf":"session"},c.none()];case "LOGIN_SET_FOCUS":return [{...t,focusedField:e.field},c.none()];case "LOGIN_BACK":return [{...t,step:"instructions",focusedField:"session",error:null},c.none()];case "LOGIN_SUBMIT":return t.step==="instructions"?[{...t,step:"input",focusedField:"session"},c.none()]:!t.sessionToken||!t.csrfToken?[{...t,error:"Both fields are required"},c.none()]:[{...t,step:"verifying",error:null},c.login(t.sessionToken,t.csrfToken)];case "LOGIN_SUCCESS":return [{...t,step:"success"},c.none()];case "LOGIN_ERROR":return [{...t,step:"input",error:e.error},c.none()]}return [t,c.none()]}function fi(e){let{username:t,isConnected:n,width:o}=e,r=[],s=f.hex(d.primary).bold(`${Q.fire} LeetCode CLI`),i=n?f.hex(d.success)("\u25CF Connected"):f.hex(d.error)("\u25CB Offline"),a=t?f.hex(d.text)(`${Q.code} ${t}`):f.hex(d.textMuted)("Not logged in"),l=s,u=`${i} ${a}`,p=P(u).length,g=Math.max(1,o-p-1),m=H([l],g)[0]??l,b=P(m).length,_=o-b-p,C=_>0?" ".repeat(_):" ";return r.push(m+C+u),r.push(f.hex(d.textMuted)(G.horizontal.repeat(o))),r}function mi(e){let{screen:t,hints:n,message:o,width:r}=e,s=[];s.push(f.hex(d.textMuted)(G.horizontal.repeat(r)));let i=go(n),a=f.bgHex(d.bgHighlight).hex(d.primary)(` ${t.toUpperCase()} `),l;if(o){let _=f.hex(d.warning)(o);l=i+" "+_;}else l=i;let u=P(a).length,p=Math.max(1,r-u-1);l=H([l],p)[0]??"";let g=P(l).length,m=r-g-u,b=m>0?" ".repeat(m):" ";return s.push(l+b+a),s}function yi(e){switch(e){case "home":return [{key:"j/k",label:"Navigate"},{key:"\u21B5",label:"Select"},{key:"q",label:"Quit"},{key:"?",label:"Help"}];case "list":return [{key:"j/k",label:"Move"},{key:"/",label:"Search"},{key:"1-3",label:"Filter"},{key:"\u21B5",label:"Open"},{key:"Esc",label:"Back"}];case "problem":return [{key:"j/k",label:"Scroll"},{key:"p",label:"Pick"},{key:"t",label:"Test"},{key:"s",label:"Submit"},{key:"Esc",label:"Back"}];case "timer":return [{key:"Space",label:"Start/Pause"},{key:"r",label:"Reset"},{key:"Esc",label:"Back"}];case "help":return [{key:"j/k",label:"Scroll"},{key:"PgUp/PgDn",label:"Page"},{key:"?/Esc",label:"Close"}];case "workspace":return [{key:"Tab",label:"Switch Pane"},{key:"Enter",label:"Switch/Edit"},{key:"c/d",label:"Create/Delete"},{key:"Esc",label:"Back"}];case "config":return [{key:"Tab",label:"Switch Pane"},{key:"Enter",label:"Edit/Save"},{key:"Esc",label:"Back"}];default:return [{key:"Esc",label:"Back"},{key:"?",label:"Help"}]}}function hi(e,t,n){let o=[],r=Math.max(1,n),s=t>=80?6:3,i=Tt.length+4,a=s+2+i+4,l=Math.max(0,Math.floor((r-a)/2));for(let C=0;C<l;C++)o.push("");let u=ut(t);o.push(...u),o.push("");let p=f.hex(d.textMuted)("A modern command-line interface for LeetCode");o.push(v(p,t)),o.push("");let g=Math.max(4,Math.min(100,t-2)),m=[];for(let C=0;C<Tt.length;C++){let R=Tt[C],q=C===e.menuIndex,K=q?f.hex(d.primary)(" \u25B6 "):" ",Y=f.hex(d.primary)(`[${R.key}]`),It=q?f.hex(d.textBright).bold(R.label):f.hex(d.text)(R.label),Nt=f.hex(d.textMuted)(` - ${R.description}`),Ue=`${K}${Y} ${It}`,qi=P(Ue).length,Ki=P(Nt).length;qi+Ki<g-6&&(Ue+=Nt);let Vi=P(Ue),$o=Math.max(0,g-4-Vi.length);Ue=Ue+($o>0?" ".repeat($o):""),q?m.push(f.bgHex(d.bgHighlight)(Ue)):m.push(Ue);}let b=he(m,g,"Menu");for(let C of b)o.push(v(C,t));o.push("");let _=[f.hex(d.textMuted)(`${Q.arrow} Press `)+f.hex(d.primary)("j/k")+f.hex(d.textMuted)(" or ")+f.hex(d.primary)("\u2191/\u2193")+f.hex(d.textMuted)(" to navigate"),f.hex(d.textMuted)(`${Q.arrow} Press `)+f.hex(d.primary)("Enter")+f.hex(d.textMuted)(" or the highlighted key to select")];for(let C of _)o.push(v(C,t));for(;o.length<r;)o.push("");return o.slice(0,r).join(`
|
|
262
|
+
`)}function Si(e,t,n){let o=[],r=n;if(o.push(ru(e,t)),o.push(""),o.push(su(e,t)),o.push(iu(e,t)),o.push(""),e.loading&&e.problems.length===0)return o.push(...uu(t,r-6)),o.join(`
|
|
263
|
+
`);if(e.error&&e.problems.length===0)return o.push(...du(e.error,t,r-6)),o.join(`
|
|
264
|
+
`);if(e.problems.length===0)return o.push(...pu(t,r-6)),o.join(`
|
|
265
|
+
`);o.push(au(t)),o.push(f.hex(d.textMuted)(G.horizontal.repeat(t)));let s=Math.max(3,r-9),i=e.problems.slice(e.scrollOffset,e.scrollOffset+s);for(let a=0;a<i.length;a++){let l=i[a],u=e.scrollOffset+a===e.cursor;o.push(lu(l,u,t));}for(let a=i.length;a<s;a++)o.push("");return o.push(f.hex(d.textMuted)(G.horizontal.repeat(t))),o.push(cu(e,t)),o.join(`
|
|
266
|
+
`)}function ru(e,t){let n=e.bookmarkFilter?"\u2605 Bookmarks":`${Q.folder} Problems`,o=f.hex(d.primary).bold(n),r=f.hex(d.textMuted)(`(${e.problems.length}${e.bookmarkFilter?" bookmarked":` of ${e.total}`})`),s=e.loadingMore?f.hex(d.primary)(" \u22EF Loading more..."):"",i=`${o} ${r}${s}`;if(t<60)return i;if(e.total>0){let a=e.problems.filter(b=>b.status==="ac").length,u=Zs(a,e.problems.length,20),p=f.hex(d.textMuted)(` ${a} solved`),g=u+p,m=t-P(i).length-P(g).length;return i+(m>0?" ".repeat(m):" ")+g}return i}function su(e,t){let n=f.hex(d.textMuted)(`${Q.target} Search: `);if(e.searchMode){let o=e.searchBuffer||"",r=f.hex(d.primary)("\u258C"),s=Math.max(10,Math.min(30,t-P(n).length-4)),i=f.bgHex(d.bgHighlight).hex(d.textBright)(` ${o}${r} `.padEnd(s)),a=t>60?f.hex(d.textMuted)(" (Enter to search, Esc to cancel)"):"";return n+i+a}if(e.searchQuery){let o=f.hex(d.primary).underline(e.searchQuery),r=f.hex(d.textMuted)(" [c] to clear");return n+o+r}return n+f.hex(d.textDim)("Press / to search...")}function iu(e,t){let n=[];n.push(f.hex(d.textMuted)(`${Q.gear} Filters: `));let o=[{key:"1",value:"Easy",color:d.success},{key:"2",value:"Medium",color:d.warning},{key:"3",value:"Hard",color:d.error}];for(let i of o)e.difficultyFilter===i.value?n.push(Ve(i.value,i.color)):n.push(f.hex(d.textMuted)("[")+f.hex(d.textDim)(i.key)+f.hex(d.textMuted)("] ")+f.hex(d.textDim)(i.value)),n.push(" ");n.push(f.hex(d.textMuted)(" \u2502 "));let r=[{key:"s",value:"solved",label:"Solved",color:d.success},{key:"a",value:"attempted",label:"Tried",color:d.warning}];for(let i of r)e.statusFilter===i.value?n.push(Ve(i.label,i.color)):n.push(f.hex(d.textMuted)("[")+f.hex(d.textDim)(i.key)+f.hex(d.textMuted)("] ")+f.hex(d.textDim)(i.label)),n.push(" ");return (e.difficultyFilter||e.statusFilter||e.searchQuery||e.bookmarkFilter)&&(n.push(f.hex(d.textMuted)(" \u2502 ")),n.push(E("c","Clear All"))),H([n.join("")],Math.max(10,t-1))[0]??""}function au(e){let t=bi(e),n=Math.max(8,e-t.selector-t.status-t.id-t.difficulty-t.acceptance-t.premium-6),o=[" "+ce("",t.selector)+ce("",t.status)+ce("ID",t.id),ce("Title",n)];return t.difficulty>0&&o.push(ce("Diff",t.difficulty)),t.acceptance>0&&o.push(po("Acc %",t.acceptance)),t.premium>0&&o.push(" "+ce("",t.premium)),f.hex(d.textMuted)(o.join(""))}function lu(e,t,n){let o=bi(n),r=Math.max(8,n-o.selector-o.status-o.id-o.difficulty-o.acceptance-o.premium-6),s=t?f.hex(d.primary).bold("\u25B6 "):" ",i=ti(e.status),a=Lt(i)<o.status?i+" ".repeat(o.status-Lt(i)):i,l=f.hex(d.textMuted)(ce(e.questionFrontendId,o.id)),u=t?f.hex(d.textBright).bold($(e.title,r)):f.hex(d.text)($(e.title,r)),p=ce(u,r),g=e.difficulty==="Easy"?d.success:e.difficulty==="Medium"?d.warning:d.error,m=o.difficulty>0?f.hex(g)(ce(e.difficulty,o.difficulty)):"",b=o.acceptance>0?f.hex(d.textMuted)(po(`${Math.round(e.acRate)}%`,o.acceptance)):"",_=o.premium>0?e.isPaidOnly?f.hex(d.warning)("\u{1F48E}"):" ":"",C=" "+s+a+l+p+m+(o.acceptance>0?b:"")+(o.premium>0?" "+_:"");if(t){let R=P(C),q=n-R.length;return f.bgHex(d.bgHighlight)(C+(q>0?" ".repeat(q):""))}return C}function cu(e,t){let n=e.problems.length>0?`${e.cursor+1} of ${e.problems.length}`:"0 of 0",o=f.hex(d.textMuted)(`Position: ${n}`),r=e.problems.length<e.total?f.hex(d.textMuted)(` (${e.total-e.problems.length} more available)`):"",s=[E("j/k","Move"),E("g/G","Top/Bottom"),E("b","Bookmarks"),E("\u21B5","Open")],i=t<70?`${E("j/k","Move")} ${E("\u21B5","Open")}`:s.join(" "),a=t-P(o+r).length-P(i).length;return o+r+(a>0?" ".repeat(a):" ")+i}function bi(e){return e>=78?cn.tableColumns:e>=62?{...cn.tableColumns,id:5,difficulty:8,acceptance:0,premium:0}:{...cn.tableColumns,status:2,id:4,difficulty:0,acceptance:0,premium:0}}function uu(e,t){let n=[],o=Math.floor(t/2);for(let i=0;i<o-1;i++)n.push("");let r=f.hex(d.primary)("\u22EF"),s=f.hex(d.textMuted)(" Loading problems...");for(n.push(" "+r+s);n.length<t;)n.push("");return n}function du(e,t,n){let o=[],r=Math.floor(n/2);for(let s=0;s<r-2;s++)o.push("");for(o.push(" "+f.hex(d.error)(`${Q.cross} Error: ${e}`)),o.push(""),o.push(" "+f.hex(d.textMuted)("Press R to retry"));o.length<n;)o.push("");return o}function pu(e,t){let n=[],o=Math.floor(t/2);for(let r=0;r<o-2;r++)n.push("");for(n.push(" "+f.hex(d.textMuted)("No problems found.")),n.push(""),n.push(" "+f.hex(d.textMuted)("Try adjusting your filters or search query."));n.length<t;)n.push("");return n}function Ei(e,t,n){let o=[],r=n,s=[v(`Solving: ${e.problemTitle}`,t-4),v(`Difficulty: ${e.difficulty}`,t-4)];o.push(...he(s,t,"Timer")),o.push("");let i=Math.floor(e.remainingSeconds/60),a=e.remainingSeconds%60,l=`${i.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`,u=gu(l,e.status),p=Math.max(...u.map(K=>P(K).length),0),g=Math.floor((t-p)/2),m=u.map(K=>" ".repeat(Math.max(0,g))+K),b=r-o.length-8,_=Math.max(0,Math.floor(b/2)-3);for(let K=0;K<_;K++)o.push("");o.push(...m);for(let K=0;K<_;K++)o.push("");let C="",R=d.textMuted;switch(e.status){case "running":C=" RUNNING ",R=d.success;break;case "paused":C=" PAUSED ",R=d.warning;break;case "idle":C=" READY ",R=d.primary;break;case "completed":C=" TIME UP! ",R=d.error;break}for(o.push(""),o.push(v(f.bgHex(R).black.bold(C),t)),o.push("");o.length<r-3;)o.push("");let q="";return e.status==="running"?q=E("Space","Pause")+" "+E("R","Reset"):q=E("Space","Start")+" "+E("R","Reset"),q+=" "+E("Esc","Back"),o.push(v(q,t)),o.join(`
|
|
267
|
+
`)}function gu(e,t){let n={0:["\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"],1:[" \u2588\u2588 "," \u2588\u2588 "," \u2588\u2588 "," \u2588\u2588 "," \u2588\u2588 "],2:["\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 ","\u2588\u2588\u2588\u2588\u2588\u2588"],3:["\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"],4:["\u2588\u2588 \u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588"," \u2588\u2588"],5:["\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 ","\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"],6:["\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 ","\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"],7:["\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588"," \u2588\u2588"," \u2588\u2588"," \u2588\u2588"],8:["\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"],9:["\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"],":":[" "," \u2588\u2588 "," "," \u2588\u2588 "," "]},o=["","","","",""],r=t==="running"?f.hex(d.success):t==="paused"?f.hex(d.warning):t==="completed"?f.hex(d.error):f.hex(d.primary);for(let s of e){let i=n[s]||n[0];for(let a=0;a<5;a++)o[a]+=r(i[a])+" ";}return o}var Ci=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function wi(e,t){try{let n=JSON.parse(e),o=new Date,r=Math.min(52,Math.floor((t-10)/3)),s=[];for(let p=r-1;p>=0;p--){let g=new Date(o);g.setDate(g.getDate()-p*7-g.getDay());let m=0,b=0;for(let C=0;C<7;C++){let R=new Date(g);if(R.setDate(R.getDate()+C),R>o)break;let q=new Date(Date.UTC(R.getFullYear(),R.getMonth(),R.getDate())),K=Math.floor(q.getTime()/1e3).toString(),Y=n[K]||0;m+=Y,Y>0&&b++;}let _=new Date(g);_.setDate(_.getDate()+6),s.push({start:`${Ci[g.getMonth()]} ${g.getDate()}`,end:`${Ci[_.getMonth()]} ${_.getDate()}`,count:m,days:b});}let i=[],a=s.reduce((p,g)=>p+g.count,0),l=s.reduce((p,g)=>p+g.days,0);i.push(f.bold(`\u{1F4C5} Activity (Last ${r} Weeks)`)),i.push(f.gray("\u2500".repeat(t)));let u=s.slice(-8);for(let p of u){let g=`${p.start} - ${p.end}`.padEnd(18),b=p.count>0?f.green("\u2588".repeat(Math.min(p.count,10))).padEnd(10):f.gray("\xB7").padEnd(10),_=p.count>0?`${p.count} subs`.padEnd(10):"".padEnd(10),C=p.days>0?`${p.days}d active`:"";i.push(` ${f.white(g)} ${b} ${f.cyan(_)} ${f.yellow(C)}`);}return i.push(f.gray(`Total: ${a} subs, ${l} days`)),i}catch{return [f.red("Error parsing calendar data")]}}function _i(e,t){try{let n=JSON.parse(e),o=new Date,r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=[];for(let u=6;u>=0;u--){let p=new Date(o);p.setDate(p.getDate()-u);let g=new Date(Date.UTC(p.getFullYear(),p.getMonth(),p.getDate())),m=Math.floor(g.getTime()/1e3).toString();s.push({label:r[p.getDay()],count:n[m]||0});}let i=Math.max(...s.map(u=>u.count),1),a=5,l=[];l.push(f.bold("\u{1F4C8} Trend (Last 7 Days)"));for(let u=a;u>=1;u--){let p=` ${u===a?i.toString().padStart(2):" "} \u2502`;for(let g of s)Math.round(g.count/i*a)>=u?p+=f.green(" \u2588\u2588 "):p+=" ";l.push(p);}return l.push(` 0 \u2514${"\u2500\u2500\u2500\u2500".repeat(7)}`),l.push(` ${s.map(u=>u.label.padEnd(4)).join("")}`),l}catch{return [f.red("Error generating trend")]}}function ki(e,t,n){let o=[],r=n;if(e.loading)return mu(t,r);if(e.error)return Mi(e.error,t,r);if(!e.stats||!e.skillStats)return Mi("No data available",t,r);o.push("");let s=[`User: ${f.bold(e.stats.username)} Rank: #${e.stats.ranking} Streak: ${e.stats.streak} \u{1F525}`];o.push(...he(s,t,"Profile")),o.push("");let i=r-7;if(i>8&&e.stats.submissionCalendar){let a=_i(e.stats.submissionCalendar);o.push(...he(a,t,"Trend")),o.push(""),i-=a.length+2;}if(i>8&&e.stats.submissionCalendar){let a=wi(e.stats.submissionCalendar,t-4);o.push(...he(a,t,"Activity")),o.push(""),i-=a.length+2;}if(i>5&&e.skillStats){let a=fu(e,t-4);o.push(...he(a,t,"Top Skills"));}for(;o.length<r-1;)o.push("");return o.push(v(E("Esc","Back")+" "+E("R","Refresh"),t)),o.join(`
|
|
268
|
+
`)}function fu(e,t){let n=e.skillStats,r=[...n.advanced,...n.intermediate,...n.fundamental].sort((s,i)=>i.problemsSolved-s.problemsSolved).slice(0,10).map(s=>`${s.tagName} (${s.problemsSolved})`).join(" \u2022 ");return [$(r,t-4)]}function mu(e,t){let n=[],o=Math.floor(t/2);for(let r=0;r<o;r++)n.push("");for(n.push(v(f.hex(d.primary)("Loading stats..."),e));n.length<t;)n.push("");return n.join(`
|
|
269
|
+
`)}function Mi(e,t,n){let o=[],r=Math.floor(n/2);for(let s=0;s<r;s++)o.push("");for(o.push(v(f.hex(d.error)(`Error: ${e}`),t));o.length<n;)o.push("");return o.join(`
|
|
270
|
+
`)}var yu={language:"Example: typescript, python3, cpp, sql",editor:"Example: code, vim, nvim",workdir:"Example: /Users/name/leetcode",repo:"Example: https://github.com/user/leetcode.git"};function Ri(e,t,n){let o=Math.max(20,t),r=Math.max(8,n),s=[];s.push(...at(`${Q.gear} Configuration`,"Workspace-local CLI settings",o)),s.push(f.hex(d.textMuted)(G.horizontal.repeat(o)));let i=Math.max(3,r-s.length-3);if(o>=90)s.push(...ct(Ti(e,o),Li(e,o),o,i,.4));else {let a=Math.max(3,Math.floor(i*.4)),l=Math.max(3,i-a-1),u=Ti(e,o).slice(0,a);for(;u.length<a;)u.push("");let p=Li(e,o).slice(0,l);for(;p.length<l;)p.push("");s.push(...u),s.push(f.hex(d.border)(G.horizontal.repeat(o))),s.push(...p);}for(;s.length<r-2;)s.push("");return s.push(f.hex(d.textMuted)(G.horizontal.repeat(o))),s.push(...hu(e,o)),s.slice(0,r).join(`
|
|
271
|
+
`)}function Ti(e,t){let n=t>=90?Math.max(20,Math.floor(t*.4)):t,o=[];o.push(_e("Options",n)),o.push("");for(let r=0;r<e.options.length;r++){let s=e.options[r],i=r===e.selectedOption,l=`${i?f.hex(d.primary)("\u25B6"):" "} ${$(s.label,Math.max(8,n-4))}`;i&&e.paneFocus==="list"?o.push(f.bgHex(d.bgHighlight)(l.padEnd(Math.max(0,n-1)))):o.push(l);}return o}function Li(e,t){let n=t>=90?Math.max(20,t-Math.floor(t*.4)-1):t,o=e.options[e.selectedOption],r=[];r.push(_e("Editor",n)),r.push(""),r.push(f.hex(d.primary).bold(o.label)),r.push(...H([f.hex(d.textMuted)(o.description)],Math.max(12,n-2))),r.push("");let i=`Value: ${(e.isEditing?`${e.draftValue}\u2588`:e.draftValue)||"(empty)"}`,a=$(i,Math.max(8,n-2));return e.paneFocus==="editor"?r.push(f.bgHex(d.bgHighlight)(a.padEnd(Math.max(0,n-1)))):r.push(a),r.push(f.hex(d.textMuted)($(yu[o.id]||"",n-2))),r.push(""),o.id==="language"||o.id==="workdir"?r.push(f.hex(d.textMuted)("Validation: required")):r.push(f.hex(d.textMuted)("Validation: optional")),e.validationError?r.push(f.hex(d.error)($(e.validationError,n-2))):e.isDirty?r.push(f.hex(d.warning)("Unsaved changes")):r.push(f.hex(d.success)("No pending changes")),r}function hu(e,t){return lt([{key:"\u2191/\u2193",label:(e.paneFocus==="list","Move option")},{key:"Tab/h/l",label:"Switch pane"},{key:"Enter",label:e.isEditing?"Save":"Edit"},{key:"Esc",label:e.isEditing?"Cancel edit":"Back"}],t,t<90?"compact":"normal")}function Oi(e,t,n){let o=[],r=Math.max(30,t),s=Math.max(10,n);if(e.loading)return _o("Loading problem details...",r,s,d.primary);if(e.error&&!e.detail)return _o(`Error: ${e.error}`,r,s,d.error);if(!e.detail)return _o("Problem detail not found",r,s,d.error);let i=f.bgHex(d.bgHighlight).hex(d.textMuted)(` ${e.detail.questionFrontendId} `),a=f.hex(d.textBright).bold(` ${e.detail.title} `),l=ei(e.detail.difficulty),u=e.isBookmarked?f.hex(d.warning)(" \u2605"):"",p=(e.detail.topicTags||[]).map(m=>f.hex(d.info)(`#${m.name}`)).join(" ");o.push(v(`${i}${a}${l}${u}`,r)),o.push(v($(p,r),r)),o.push(f.hex(d.textMuted)(un(r)));let g=Rt(s,e.drawerMode);for(o.push(...Su(e,r,g.bodyHeight)),e.drawerMode!=="none"&&g.drawerHeight>0&&(o.push(f.hex(d.border)(un(r))),o.push(...Eu(e,r,g.drawerHeight)));o.length<s-2;)o.push("");return o.push(f.hex(d.textMuted)(un(r))),o.push(...bu(e,r)),o.slice(0,s).join(`
|
|
272
|
+
`)}function Su(e,t,n){let o=[],r=Math.max(12,t-4),s=H(e.contentLines,r),i=Math.max(0,s.length-n),a=Math.min(e.scrollOffset,i),l=s.slice(a,a+n);for(let u of l)o.push(` ${f.hex(d.text)(u)}`);for(;o.length<n;)o.push("");return o}function bu(e,t){let n=t>=130?[E("p","Pick"),E("t","Test"),E("s","Submit"),E("h","Hint"),E("H","Subs"),E("V","Snaps"),E("b",e.isBookmarked?"Unbookmark":"Bookmark"),E("n","Note"),E("e","Edit")]:[E("p","Pick"),E("t","Test"),E("s","Submit"),E("h","Hint"),E("H","Subs"),E("V","Snaps"),E("n","Note")],o=e.drawerMode==="none"?[E("Esc","Back")]:[E("Tab",`Focus ${e.focusRegion==="body"?"Drawer":"Body"}`),E("Esc","Close Drawer")],r=[...n,...o].join(" ");return [v($(r,Math.max(20,t-2)),t)]}function Eu(e,t,n){let o=e.drawerMode;if(o==="snapshots")return Cu(e,t,n);let r=_u(e),s=Mu(o),i=wu(e,o,t),a=Math.max(1,n-2),l=Math.max(0,i.length-a),u=Math.min(e.drawerScrollOffset,l),p=i.slice(u,u+a),g=[_e(e.focusRegion==="drawer"?`${r} \u2022 Focused`:r,t)];for(g.push(...p.map(m=>$(m,t)));g.length<n-1;)g.push("");return g.push(f.hex(d.textMuted)($(s,t))),g.slice(0,n)}function Cu(e,t,n){let o=e.focusRegion==="drawer"?"Snapshots \u2022 Focused":"Snapshots",r=[_e(o,t)];if(!e.snapshotsList||e.snapshotsList.length===0)r.push(f.hex(d.warning)("No snapshots saved.")),r.push(f.hex(d.textMuted)("Create snapshots from your solution workflow."));else {let s=Math.max(1,n-2),i=Math.floor(e.snapshotCursor/s)*s,a=e.snapshotsList.slice(i,i+s);for(let l=0;l<a.length;l++){let u=a[l],g=i+l===e.snapshotCursor,m=g?f.hex(d.primary)("\u25B6"):" ",b=$(u.name,20).padEnd(20),_=$(u.language,10).padEnd(10),C=`${m} ${String(u.id).padStart(3)} ${b} ${_} ${String(u.lines).padStart(4)}L`;r.push(g?f.bgHex(d.bgHighlight)($(C,t).padEnd(Math.max(0,t-1))):C);}}for(;r.length<n-1;)r.push("");return r.push(f.hex(d.textMuted)($(`${E("j/k","Move")} ${E("d/r","Diff/Restore")} ${E("V/Esc","Close")}`,t))),r.slice(0,n)}function wu(e,t,n){let o=Math.max(10,n-2);switch(t){case "hint":{let r=e.detail?.hints||[],s=e.activeHintIndex??0,i=r[s]??"No hints available",a=Lu(i);return [f.hex(d.primary).bold(`Hint ${s+1}/${Math.max(1,r.length)}`),...H([a||"No hint content"],o)]}case "submissions":return e.submissionsLoading?[f.hex(d.primary)("Loading submissions...")]:!e.submissionsHistory||e.submissionsHistory.length===0?[f.hex(d.warning)("No submissions found for this problem."),f.hex(d.textMuted)("Use [s] Submit after picking a solution.")]:e.submissionsHistory.map(r=>{let s=r.statusDisplay==="Accepted"?d.success:d.error,i=f.hex(s)($(r.statusDisplay,12).padEnd(12)),a=f.hex(d.cyan)($(r.runtime||"-",8).padEnd(8)),l=f.hex(d.textMuted)($(r.memory||"-",8).padEnd(8)),u=f.hex(d.info)($(r.lang||"-",8).padEnd(8));return `${i} ${a} ${l} ${u}`});case "note":return H(Ru(e.noteContent||"No notes found. Press e to edit."),o);case "diff":return (e.diffContent||"No diff available.").split(`
|
|
273
|
+
`).map(s=>Tu(s));case "testResult":{let r=e.testResult;return r?r.compile_error?[f.hex(d.error).bold("Compile Error"),...H([r.compile_error],o)]:r.runtime_error?[f.hex(d.error).bold("Runtime Error"),...H([r.runtime_error],o)]:r.correct_answer?[f.hex(d.success).bold("All test cases passed")]:[f.hex(d.warning).bold("Wrong answer")]:["No test result available."]}case "submitResult":{let r=e.submissionResult;if(!r)return ["No submission result available."];let i=[r.status_msg==="Accepted"?f.hex(d.success).bold(r.status_msg):f.hex(d.error).bold(r.status_msg),f.hex(d.cyan)(`Runtime: ${r.status_runtime||"-"}`),f.hex(d.textMuted)(`Memory: ${r.status_memory||"-"}`)];return r.runtime_error&&i.push(...H([r.runtime_error],o)),i}case "status":{let r=e.drawerData.statusMessage||e.successMessage||e.error||(e.isRunning?"Working...":"Ready"),s=e.error?d.error:e.successMessage?d.success:e.isRunning?d.primary:d.textMuted;return H([r],o).map(i=>f.hex(s)(i))}default:return []}}function _u(e){switch(e.drawerMode){case "hint":return "Hints";case "submissions":return "Submissions";case "snapshots":return "Snapshots";case "note":return "Notes";case "diff":return "Diff";case "testResult":return "Test Result";case "submitResult":return "Submission Result";case "status":return ku(e);default:return "Drawer"}}function Mu(e){switch(e){case "hint":return `${E("\u2190/\u2192","Prev/Next")} ${E("j/k","Scroll")} ${E("h/Esc","Close")}`;case "submissions":return `${E("j/k","Scroll")} ${E("H/Esc","Close")}`;case "snapshots":return `${E("j/k","Move")} ${E("d/r","Diff/Restore")} ${E("V/Esc","Close")}`;case "note":return `${E("j/k","Scroll")} ${E("e","Edit")} ${E("n/Esc","Close")}`;case "diff":return `${E("j/k","Scroll")} ${E("d/Esc","Close")}`;default:return `${E("Esc","Close")}`}}function ku(e){let n=(e.drawerData.statusMessage||e.successMessage||e.error||(e.isRunning?"Working...":"Ready")).toLowerCase();return n.includes("running tests")?"Testing":n.includes("submitting")?"Submitting":n.includes("bookmark")?"Bookmark":n.includes("error")?"Error":"Status"}function Tu(e){return e.startsWith("[green]")?f.green(e.slice(7)):e.startsWith("[red]")?f.red(e.slice(5)):e.startsWith("[grey]")?f.gray(e.slice(6)):e.startsWith("+")?f.green(e):e.startsWith("-")?f.red(e):e}function Lu(e){return P(e).replace(/<\/?[^>]+(>|$)/g,"").replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/\s+/g," ").trim()}function Ru(e){let t=e.split(`
|
|
274
|
+
`),n=[];for(let o of t){let r=o.trim();if(!r){n.length>0&&n[n.length-1]!==""&&n.push("");continue}if(r.startsWith("<!--")&&r.endsWith("-->"))continue;let s=o.replace(/\*\*(.*?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\[(.*?)\]\((.*?)\)/g,"$1 ($2)");s.startsWith("## ")?s=`${f.hex(d.primary).bold("\u2022")} ${s.slice(3)}`:s.startsWith("# ")&&(s=f.hex(d.primary).bold(s.slice(2))),n.push(s);}for(;n.length>0&&n[n.length-1]==="";)n.pop();return n.length>0?n:["No notes found. Press e to edit."]}function _o(e,t,n,o){let r=[],s=Math.max(0,Math.floor(n/2)-1);for(let i=0;i<s;i++)r.push("");for(r.push(v(f.hex(o)(e),t));r.length<n;)r.push("");return r.join(`
|
|
275
|
+
`)}function xi(e){let t=[],{terminalWidth:n,terminalHeight:o}=e;if(e.isCheckingAuth)return xu(n,o);let r=fi({username:e.user?.username??"Guest",isConnected:e.user?.isLoggedIn??false,width:n});t.push(...r);let s=Math.max(1,o-4),i=Ou(e,n,s);t.push(i);let a=e.screenState.screen==="problem"||e.screenState.screen==="help"?[]:yi(e.screenState.screen),l=mi({screen:e.screenState.screen,hints:a,message:e.globalError??void 0,width:n});return t.push(...l),Au(t.join(`
|
|
276
|
+
`),n,o)}function Ou(e,t,n){let{screenState:o}=e;switch(o.screen){case "home":return hi(o.model,t,n);case "list":return Si(o.model,t,n);case "help":return Pu(o.model,t,n);case "login":return bo(o.model,t,n);case "workspace":return mo(o.model,t,n);case "timer":return Ei(o.model,t,n);case "stats":return ki(o.model,t,n);case "config":return Ri(o.model,t,n);case "problem":return Oi(o.model,t,n);case "changelog":return ho(o.model,t,n)}}function xu(e,t){let n=[],o=Math.floor(t/2);for(let i=0;i<o-5;i++)n.push("");let r=ut(e);n.push(...r),n.push("");let s=f.hex(d.primary)("\u22EF Checking authentication...");for(n.push(v(s,e));n.length<t;)n.push("");return n.join(`
|
|
277
|
+
`)}function Pu(e,t,n){let o=[],r=Math.max(20,t),s=Math.max(8,n);o.push(...at(`${Q.star} Keyboard Cheat Sheet`,"All shortcuts in one place",r)),o.push(f.hex(d.textMuted)(G.horizontal.repeat(r)));let i=r<90?"compact":"normal",a=lt([{key:"j/k",label:"Scroll"},{key:"PgUp/PgDn",label:"Page"},{key:"g/G",label:"Top/Bottom"},{key:"?/Esc",label:"Close"}],r,i).slice(0,1),l=1+a.length,u=Math.max(3,s-o.length-l),p=Pi(r),g=Math.max(0,p.length-u),m=Math.min(e.scrollOffset,g),b=p.slice(m,m+u);for(o.push(...b);o.length<s-l;)o.push("");return o.push(f.hex(d.textMuted)(G.horizontal.repeat(r))),o.push(...a),o.slice(0,s).join(`
|
|
278
|
+
`)}function vu(){return [{section:"Global",items:[["?","Toggle help"],["Ctrl+C","Quit app"],["Esc","Back / close panel"]]},{section:"Navigation",items:[["j / \u2193","Move down"],["k / \u2191","Move up"],["g / G","Top / Bottom"],["PgUp/PgDn","Page jump"]]},{section:"Home",items:[["l","Problem list"],["d / r","Daily / Random"],["w / c","Workspace / Config"],["q","Quit"]]},{section:"List",items:[["/","Search"],["1/2/3","Difficulty filters"],["s / a / b","Status / Attempted / Bookmarks"],["Enter","Open problem"]]},{section:"Problem",items:[["p / t / s","Pick / Test / Submit"],["h / H / V","Hint / Subs / Snapshots"],["b / n / e","Bookmark / Note / Edit note"],["j / k","Scroll content/panel"]]},{section:"Workspace/Config",items:[["Tab / h / l","Switch pane"],["Enter","Switch or edit/save"],["c / d","Create / Delete workspace"],["Esc","Cancel edit or go back"]]}]}function Mo(e,t){let n=[],o=Math.max(20,t),r=Math.max(8,Math.min(14,Math.floor(o*.26))),s=Math.max(8,o-r-3);n.push(_e(e.section,t));for(let[i,a]of e.items){let l=H([a],s),u=f.hex(d.cyan)(ce(i,r));n.push(` ${u} ${f.hex(d.text)(l[0]??"")}`);for(let p=1;p<l.length;p++)n.push(` ${" ".repeat(r)} ${f.hex(d.textMuted)(l[p])}`);}return n}function Pi(e){let t=vu();if(e<90){let i=[];for(let a of t)i.push(...Mo(a,e)),i.push("");return i}let n=[],o=.49,r=Math.max(8,Math.floor(e*o)),s=Math.max(8,e-r-1);for(let i=0;i<t.length;i+=2){let a=Mo(t[i],r),l=t[i+1]?Mo(t[i+1],s):[],u=Math.max(a.length,l.length);n.push(...ct(a,l,e,u,o)),n.push("");}return n}function vi(e,t){let n=Math.max(20,e),o=Math.max(8,t),r=Math.max(3,o-5);return Math.max(0,Pi(n).length-r)}function Au(e,t,n){let o=Math.max(1,t),r=Math.max(1,n),s=e.split(`
|
|
279
|
+
`),i=[];for(let a=0;a<s.length;a++){let l=s[a]??"";P(l).length>o?i.push($(l,o)):i.push(l);}for(;i.length<r;)i.push("");return i.slice(0,r).join(`
|
|
280
|
+
`)}function Ai(e,t){switch(e.type){case "INIT":return [{...t,needsRender:true},c.checkAuth()];case "KEY_PRESS":{let{key:n}=e;if(n.ctrl&&n.name==="c")return [t,c.exit()];if(n.name==="q"&&t.screenState.screen==="home")return [t,c.exit()];if(n.name==="?")return t.screenState.screen==="help"?[{...t,...ko(t),needsRender:true},c.none()]:[{...t,...ge(t,{screen:"help",model:{scrollOffset:0}}),needsRender:true},c.none()];if(n.name==="escape"&&t.screenState.screen!=="home"){if(t.screenState.screen==="config"&&t.screenState.model.isEditing)return yn(t,e);if(t.screenState.screen==="problem"){let o=t.screenState.model;if(o.drawerMode!=="none"){let[r,s]=fn({type:"PROBLEM_CLOSE_RESULT"},o,t.terminalHeight,t.terminalWidth);return [{...t,screenState:{screen:"problem",model:r},needsRender:true},s]}}if(t.screenState.screen==="workspace"){let o=t.screenState.model;if(o.showCreateInput||o.showDeleteConfirm||o.isEditing)return yn(t,e)}return t.screenState.screen==="login"?yn(t,e):[{...t,...ko(t),needsRender:true},c.none()]}return yn(t,e)}case "RESIZE":return [{...t,terminalWidth:e.width,terminalHeight:e.height,needsRender:true},c.none()];case "NAVIGATE":return [{...t,...ge(t,e.to),needsRender:true},c.none()];case "GO_BACK":return [{...t,...ko(t),needsRender:true},c.none()];case "AUTH_CHECK_COMPLETE":return e.user?[{...t,isCheckingAuth:false,user:{username:e.user.username,isLoggedIn:true},needsRender:true},c.none()]:[{...t,isCheckingAuth:false,user:null,screenState:{screen:"login",model:{step:"instructions",sessionToken:"",csrfToken:"",focusedField:"session",error:null}},needsRender:true},c.none()];case "GLOBAL_ERROR":return [{...t,globalError:e.error,needsRender:true},c.none()];case "CLEAR_ERROR":return [{...t,globalError:null,needsRender:true},c.none()];case "FETCH_DAILY_SUCCESS":{let[n,o]=gn(e.slug);return [{...t,...ge(t,{screen:"problem",model:n}),needsRender:true},o]}case "FETCH_RANDOM_SUCCESS":{let[n,o]=gn(e.slug);return [{...t,...ge(t,{screen:"problem",model:n}),needsRender:true},o]}case "QUIT":return [t,c.exit()];case "LOGIN_SUCCESS":return [{...t,user:{username:e.username,isLoggedIn:true},screenState:{screen:"home",model:{menuIndex:0}},needsRender:true},c.none()];default:return Di(e,t)}}function ge(e,t){return {screenState:t,history:[...e.history,e.screenState],globalError:null}}function ko(e){if(e.history.length===0)return {screenState:{screen:"home",model:{menuIndex:0}},globalError:null};let t=[...e.history];return {screenState:t.pop(),history:t,globalError:null}}function yn(e,t){let{screenState:n}=e;switch(n.screen){case "home":return $i(e,t);case "list":return $u(e,t);case "problem":return Du(e,t);case "timer":case "stats":case "config":return Nu(e,t);case "help":return Fu(e,t);case "workspace":return Yu(e,t);case "changelog":return Qu(e,t);case "login":return Ju(e,t);default:return [e,c.none()]}}function $i(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:n}=t,o=e.screenState.model;if(n.name==="l"){let[r,s]=ro();return [{...e,...ge(e,{screen:"list",model:r}),needsRender:true},s]}if(n.name==="d")return [e,c.fetchDaily()];if(n.name==="r")return [e,c.fetchRandom()];if(n.name==="b"){let[r,s]=ro();return [{...e,...ge(e,{screen:"list",model:{...r,bookmarkFilter:true}}),needsRender:true},s]}if(n.name==="t")return [{...e,...ge(e,{screen:"timer",model:{problemId:null,problemTitle:"Practice",difficulty:"Medium",remainingSeconds:2400,totalSeconds:2400,status:"idle",viewMode:"timer"}}),needsRender:true},c.none()];if(n.name==="s"){let[r,s]=Qs();return [{...e,...ge(e,{screen:"stats",model:r}),needsRender:true},s]}if(n.name==="y")return [{...e,globalError:"Use CLI command: leet sync (requires terminal interaction)",needsRender:true},c.none()];if(n.name==="w"){let[r,s]=ai();return [{...e,...ge(e,{screen:"workspace",model:r}),needsRender:true},s]}if(n.name==="c"){let[r,s]=Xs();return [{...e,...ge(e,{screen:"config",model:r}),needsRender:true},s]}if(n.name==="?")return [{...e,...ge(e,{screen:"help",model:{scrollOffset:0}}),needsRender:true},c.none()];if(n.name==="v"){let[r,s]=gi();return [{...e,...ge(e,{screen:"changelog",model:r}),needsRender:true},s]}if(n.name==="L")return [e,c.logout()];if(n.name==="j"||n.name==="down"){let[r,s]=an({type:"HOME_MENU_DOWN"},o);return [{...e,screenState:{screen:"home",model:r},needsRender:true},s]}if(n.name==="k"||n.name==="up"){let[r,s]=an({type:"HOME_MENU_UP"},o);return [{...e,screenState:{screen:"home",model:r},needsRender:true},s]}if(n.name==="return"){let s=["l","d","r","b","t","s","y","w","c","v","L","?"][o.menuIndex];if(s)return $i(e,{type:"KEY_PRESS",key:{name:s,sequence:s,ctrl:false,meta:false,shift:false}})}return [e,c.none()]}function $u(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:n}=t,o=e.screenState.model,r=null;if(o.searchMode)n.name==="escape"?r={type:"LIST_SEARCH_CANCEL"}:n.name==="return"?r={type:"LIST_SEARCH_SUBMIT"}:n.name==="backspace"?r={type:"LIST_SEARCH_BACKSPACE"}:n.sequence.length===1&&!n.ctrl&&!n.meta&&(r={type:"LIST_SEARCH_INPUT",char:n.sequence});else if(n.name==="j"||n.name==="down")r={type:"LIST_CURSOR_DOWN"};else if(n.name==="k"||n.name==="up")r={type:"LIST_CURSOR_UP"};else if(n.name==="g")r={type:"LIST_GO_TOP"};else if(n.name==="G")r={type:"LIST_GO_BOTTOM"};else if(n.name==="/")r={type:"LIST_SEARCH_START"};else if(n.name==="return"){let s=o.problems[o.cursor];if(s){let[i,a]=gn(s.titleSlug);return [{...e,...ge(e,{screen:"problem",model:i}),needsRender:true},a]}r={type:"LIST_SELECT"};}else n.name==="1"?r={type:"LIST_FILTER_DIFFICULTY",difficulty:o.difficultyFilter==="Easy"?null:"Easy"}:n.name==="2"?r={type:"LIST_FILTER_DIFFICULTY",difficulty:o.difficultyFilter==="Medium"?null:"Medium"}:n.name==="3"?r={type:"LIST_FILTER_DIFFICULTY",difficulty:o.difficultyFilter==="Hard"?null:"Hard"}:n.name==="s"?r={type:"LIST_FILTER_STATUS",status:o.statusFilter==="solved"?null:"solved"}:n.name==="a"?r={type:"LIST_FILTER_STATUS",status:o.statusFilter==="attempted"?null:"attempted"}:n.name==="b"?r={type:"LIST_FILTER_BOOKMARKS"}:n.name==="c"?r={type:"LIST_CLEAR_FILTERS"}:n.name==="R"&&(r={type:"LIST_REFRESH"});if(r){let[s,i]=so(r,o,e.terminalHeight);return [{...e,screenState:{screen:"list",model:s},needsRender:true},i]}return [e,c.none()]}function Di(e,t){let{screenState:n}=t,o=t.terminalHeight;switch(n.screen){case "list":{if(!Hu(e))return [t,c.none()];let[r,s]=so(e,n.model,o);return [{...t,screenState:{screen:"list",model:r},needsRender:true},s]}case "home":{if(!Bu(e))return [t,c.none()];let[r,s]=an(e,n.model);return [{...t,screenState:{screen:"home",model:r},needsRender:true},s]}case "timer":{if(!Uu(e))return [t,c.none()];let[r,s]=ln(e,n.model);return [{...t,screenState:{screen:"timer",model:r},needsRender:true},s]}case "stats":{if(!Wu(e))return [t,c.none()];let[r,s]=io(e,n.model);return [{...t,screenState:{screen:"stats",model:r},needsRender:true},s]}case "config":{if(!Gu(e))return [t,c.none()];let[r,s]=lo(e,n.model);return [{...t,screenState:{screen:"config",model:r},needsRender:true},s]}case "help":{if(!ju(e))return [t,c.none()];let r=n.model,s=vi(t.terminalWidth,t.terminalHeight-4),i=Math.max(3,Math.floor((t.terminalHeight-4)/2)),a=r.scrollOffset;switch(e.type){case "HELP_SCROLL_UP":a=Math.max(0,r.scrollOffset-1);break;case "HELP_SCROLL_DOWN":a=Math.min(s,r.scrollOffset+1);break;case "HELP_PAGE_UP":a=Math.max(0,r.scrollOffset-i);break;case "HELP_PAGE_DOWN":a=Math.min(s,r.scrollOffset+i);break;case "HELP_TOP":a=0;break;case "HELP_BOTTOM":a=s;break}return [{...t,screenState:{screen:"help",model:{scrollOffset:a}},needsRender:true},c.none()]}case "workspace":{if(!Ku(e))return [t,c.none()];let[r,s]=yo(e,n.model);return [{...t,screenState:{screen:"workspace",model:r},needsRender:true},s]}case "problem":{if(!qu(e))return [t,c.none()];let[r,s]=fn(e,n.model,o,t.terminalWidth);return [{...t,screenState:{...n,model:r},needsRender:true},s]}case "changelog":{if(!Vu(e))return [t,c.none()];let[r,s]=So(e,n.model,o,t.terminalWidth);return [{...t,screenState:{screen:"changelog",model:r},needsRender:true},s]}case "login":{if(!zu(e))return [t,c.none()];let[r,s]=Eo(e,n.model);return [{...t,screenState:{screen:"login",model:r},needsRender:true},s]}default:return [t,c.none()]}}function Du(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:n}=t,o=e.screenState.model,r=null;if(!r&&o.drawerMode==="note"&&(n.name==="n"||n.name==="escape")&&(r={type:"PROBLEM_CLOSE_NOTE"}),!r&&o.drawerMode==="diff"&&(n.name==="d"||n.name==="escape")&&(r={type:"PROBLEM_CLOSE_DIFF"}),!r){let i=Iu(n.name);i&&(r=i);}!r&&n.name==="tab"&&o.drawerMode!=="none"&&(r={type:"PROBLEM_FOCUS_TOGGLE"}),!r&&o.drawerMode!=="none"&&n.name==="escape"&&(r={type:"PROBLEM_CLOSE_RESULT"}),!r&&o.drawerMode==="hint"&&(n.name==="left"?r={type:"PROBLEM_PREV_HINT"}:n.name==="right"&&(r={type:"PROBLEM_NEXT_HINT"})),!r&&o.drawerMode!=="none"&&o.focusRegion==="drawer"&&(o.drawerMode==="snapshots"?n.name==="j"||n.name==="down"?r={type:"PROBLEM_SNAPSHOT_DOWN"}:n.name==="k"||n.name==="up"?r={type:"PROBLEM_SNAPSHOT_UP"}:n.name==="d"?r={type:"PROBLEM_DIFF_SNAPSHOT"}:n.name==="r"&&(r={type:"PROBLEM_RESTORE_SNAPSHOT"}):o.drawerMode==="hint"?n.name==="j"||n.name==="down"?r={type:"PROBLEM_HINT_SCROLL_DOWN"}:(n.name==="k"||n.name==="up")&&(r={type:"PROBLEM_HINT_SCROLL_UP"}):o.drawerMode==="submissions"?n.name==="j"||n.name==="down"?r={type:"PROBLEM_SUBMISSIONS_SCROLL_DOWN"}:(n.name==="k"||n.name==="up")&&(r={type:"PROBLEM_SUBMISSIONS_SCROLL_UP"}):o.drawerMode==="note"?n.name==="j"||n.name==="down"?r={type:"PROBLEM_NOTE_SCROLL_DOWN"}:(n.name==="k"||n.name==="up")&&(r={type:"PROBLEM_NOTE_SCROLL_UP"}):o.drawerMode==="diff"&&(n.name==="j"||n.name==="down"?r={type:"PROBLEM_DIFF_SCROLL_DOWN"}:(n.name==="k"||n.name==="up")&&(r={type:"PROBLEM_DIFF_SCROLL_UP"})));let s=o.drawerMode==="none"||o.focusRegion==="body";if(!r&&s&&(n.name==="j"||n.name==="down"?r={type:"PROBLEM_SCROLL_DOWN"}:n.name==="k"||n.name==="up"?r={type:"PROBLEM_SCROLL_UP"}:n.name==="pagedown"?r={type:"PROBLEM_PAGE_DOWN"}:n.name==="pageup"?r={type:"PROBLEM_PAGE_UP"}:n.name==="g"?r={type:"PROBLEM_TOP"}:n.name==="G"&&(r={type:"PROBLEM_BOTTOM"})),r){let[i,a]=fn(r,o,e.terminalHeight,e.terminalWidth);return [{...e,screenState:{screen:"problem",model:i},needsRender:true},a]}return [e,c.none()]}function Iu(e){return e==="p"?{type:"PROBLEM_PICK"}:e==="t"?{type:"PROBLEM_TEST"}:e==="s"?{type:"PROBLEM_SUBMIT"}:e==="b"?{type:"PROBLEM_BOOKMARK"}:e==="n"?{type:"PROBLEM_VIEW_NOTE"}:e==="e"?{type:"PROBLEM_NOTES"}:e==="h"?{type:"PROBLEM_TOGGLE_HINT"}:e==="H"||e==="S"?{type:"PROBLEM_SHOW_SUBMISSIONS"}:e==="v"||e==="V"||e==="w"?{type:"PROBLEM_SHOW_SNAPSHOTS"}:null}function Nu(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:n}=t,{screenState:o}=e;if(o.screen==="timer"){let r=o.model;if(n.name==="space"){let[s,i]=ln({type:r.status==="running"?"TIMER_PAUSE":"TIMER_START"},r);return [{...e,screenState:{...o,model:s},needsRender:true},i]}if(n.name==="r"){let[s,i]=ln({type:"TIMER_RESET"},r);return [{...e,screenState:{...o,model:s},needsRender:true},i]}}if(o.screen==="config"){let r=o.model,s=null;if(r.isEditing?n.name==="escape"?s={type:"CONFIG_EDIT_CANCEL"}:n.name==="return"||n.name==="enter"?s={type:"CONFIG_EDIT_SAVE"}:n.name==="backspace"?s={type:"CONFIG_EDIT_BACKSPACE"}:n.sequence.length===1&&!n.ctrl&&!n.meta&&(s={type:"CONFIG_EDIT_INPUT",char:n.sequence}):n.name==="tab"||n.name==="h"||n.name==="l"?s={type:"CONFIG_TOGGLE_FOCUS"}:n.name==="left"?s={type:"CONFIG_FOCUS_LIST"}:n.name==="right"?s={type:"CONFIG_FOCUS_EDITOR"}:n.name==="j"||n.name==="down"?s={type:"CONFIG_OPTION_DOWN"}:n.name==="k"||n.name==="up"?s={type:"CONFIG_OPTION_UP"}:(n.name==="return"||n.name==="enter")&&(s={type:"CONFIG_EDIT_START"}),s){let[i,a]=lo(s,r);return [{...e,screenState:{...o,model:i},needsRender:true},a]}}if(o.screen==="stats"){let r=o.model;if(n.name==="r"||n.name==="R"){let[s,i]=io({type:"STATS_REFRESH"},r);return [{...e,screenState:{...o,model:s},needsRender:true},i]}}return [e,c.none()]}function Fu(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:n}=t,o=null;return n.name==="j"||n.name==="down"?o={type:"HELP_SCROLL_DOWN"}:n.name==="k"||n.name==="up"?o={type:"HELP_SCROLL_UP"}:n.name==="pagedown"?o={type:"HELP_PAGE_DOWN"}:n.name==="pageup"?o={type:"HELP_PAGE_UP"}:n.name==="g"?o={type:"HELP_TOP"}:n.name==="G"&&(o={type:"HELP_BOTTOM"}),o?Di(o,e):[e,c.none()]}function Hu(e){return e.type.startsWith("LIST_")}function Bu(e){return e.type.startsWith("HOME_")}function Uu(e){return e.type.startsWith("TIMER_")}function Wu(e){return e.type.startsWith("STATS_")}function Gu(e){return e.type.startsWith("CONFIG_")}function ju(e){return e.type.startsWith("HELP_")}function qu(e){return e.type.startsWith("PROBLEM_")}function Ku(e){return e.type.startsWith("WORKSPACE_")}function Vu(e){return e.type.startsWith("CHANGELOG_")}function zu(e){return e.type.startsWith("LOGIN_")}function Yu(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:n}=t,o=e.screenState.model,r=null;if(o.showCreateInput?n.name==="escape"?r={type:"WORKSPACE_CREATE_CANCEL"}:n.name==="return"||n.name==="enter"?r={type:"WORKSPACE_CREATE_SUBMIT"}:n.name==="backspace"?r={type:"WORKSPACE_CREATE_BACKSPACE"}:n.sequence.length===1&&!n.ctrl&&!n.meta&&(r={type:"WORKSPACE_CREATE_INPUT",char:n.sequence}):o.showDeleteConfirm?n.name==="y"||n.name==="return"||n.name==="enter"?r={type:"WORKSPACE_DELETE_CONFIRM"}:(n.name==="n"||n.name==="escape")&&(r={type:"WORKSPACE_DELETE_CANCEL"}):o.isEditing?n.name==="escape"?r={type:"WORKSPACE_EDIT_CANCEL"}:n.name==="return"||n.name==="enter"?r={type:"WORKSPACE_EDIT_SAVE"}:n.name==="backspace"?r={type:"WORKSPACE_EDIT_BACKSPACE"}:n.sequence.length===1&&!n.ctrl&&!n.meta&&(r={type:"WORKSPACE_EDIT_INPUT",char:n.sequence}):n.name==="tab"||n.name==="h"||n.name==="l"?r={type:"WORKSPACE_TOGGLE_FOCUS"}:n.name==="left"?r={type:"WORKSPACE_FOCUS_LIST"}:n.name==="right"?r={type:"WORKSPACE_FOCUS_EDITOR"}:o.paneFocus==="list"?n.name==="j"||n.name==="down"?r={type:"WORKSPACE_DOWN"}:n.name==="k"||n.name==="up"?r={type:"WORKSPACE_UP"}:n.name==="return"||n.name==="enter"?r={type:"WORKSPACE_SELECT"}:n.name==="c"?r={type:"WORKSPACE_CREATE_START"}:n.name==="d"&&(r={type:"WORKSPACE_DELETE"}):n.name==="j"||n.name==="down"?r={type:"WORKSPACE_FIELD_DOWN"}:n.name==="k"||n.name==="up"?r={type:"WORKSPACE_FIELD_UP"}:(n.name==="return"||n.name==="enter")&&(r={type:"WORKSPACE_EDIT_START"}),r){let[s,i]=yo(r,o);return [{...e,screenState:{screen:"workspace",model:s},needsRender:true},i]}return [e,c.none()]}function Qu(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:n}=t;if(n.name==="k"||n.name==="up")return o(e,{type:"CHANGELOG_SCROLL_UP"});if(n.name==="j"||n.name==="down")return o(e,{type:"CHANGELOG_SCROLL_DOWN"});return [e,c.none()];function o(r,s){let i=r.screenState;if(i.screen!=="changelog")return [r,c.none()];let[a,l]=So(s,i.model,r.terminalHeight,r.terminalWidth);return [{...r,screenState:{screen:"changelog",model:a},needsRender:true},l]}}function Ju(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:n}=t,o=e.screenState.model;if(n.ctrl&&n.name==="c")return [e,c.exit()];if(o.step==="instructions"){if(n.name==="return"||n.name==="enter")return r(e,{type:"LOGIN_SUBMIT"});if(n.name==="escape")return [e,c.exit()]}else if(o.step==="input"||o.step==="error"){if(n.name==="escape")return r(e,{type:"LOGIN_BACK"});if(n.name==="tab"||n.name==="down"||n.name==="up")return r(e,{type:"LOGIN_SWITCH_FOCUS"});if(n.name==="return"||n.name==="enter"){if(o.focusedField==="session"){if(o.sessionToken.length>0)return r(e,{type:"LOGIN_SET_FOCUS",field:"csrf"})}else if(o.csrfToken.length>0&&o.sessionToken.length>0)return r(e,{type:"LOGIN_SUBMIT"})}else if(n.name==="backspace"){if(o.focusedField==="session"){if(o.sessionToken.length>0)return r(e,{type:"LOGIN_SESSION_INPUT",value:o.sessionToken.slice(0,-1)})}else if(o.csrfToken.length>0)return r(e,{type:"LOGIN_CSRF_INPUT",value:o.csrfToken.slice(0,-1)})}else if(!n.ctrl&&!n.meta)return o.focusedField==="session"?r(e,{type:"LOGIN_SESSION_INPUT",value:o.sessionToken+n.sequence}):r(e,{type:"LOGIN_CSRF_INPUT",value:o.csrfToken+n.sequence})}return [e,c.none()];function r(s,i){let[a,l]=Eo(i,s.screenState.model);return [{...s,screenState:{screen:"login",model:a},needsRender:true},l]}}var ed="https://raw.githubusercontent.com/night-slayer18/leetcode-cli/main/docs/releases.md",{credentials:ze}=Ge,Pe=null;function To(e,t){switch(e.type){case "CMD_NONE":return;case "CMD_BATCH":for(let n of e.commands)To(n,t);return;case "CMD_FETCH_STATS":rd(t);return;case "CMD_CHECK_AUTH":td(t);return;case "CMD_FETCH_PROBLEMS":nd(e.filters,e.append,t);return;case "CMD_FETCH_PROBLEM_DETAIL":od(e.slug,t);return;case "CMD_START_TIMER_SUBSCRIPTION":Pe&&clearInterval(Pe),Pe=setInterval(()=>{t({type:"TIMER_TICK"});},e.intervalMs);return;case "CMD_STOP_TIMER_SUBSCRIPTION":Pe&&(clearInterval(Pe),Pe=null);return;case "CMD_PICK_PROBLEM":id(e.slug,t);return;case "CMD_TEST_SOLUTION":ad(e.slug,t);return;case "CMD_SUBMIT_SOLUTION":ld(e.slug,t);return;case "CMD_SAVE_CONFIG":sd(e.key,e.value);return;case "CMD_EXIT":hn();return;case "CMD_FETCH_DAILY":cd(t);return;case "CMD_FETCH_RANDOM":ud(t);return;case "CMD_FETCH_SUBMISSIONS":fd(e.slug,t);return;case "CMD_LOAD_NOTE":dd(e.problemId,t);return;case "CMD_DIFF_SNAPSHOT":pd(e.slug,e.snapshotId,t);return;case "CMD_RESTORE_SNAPSHOT":gd(e.slug,e.snapshotId,t);return;case "CMD_FETCH_CHANGELOG":md(t);return;case "CMD_LOGOUT":yd(t);return;case "CMD_LOGIN":hd(e.session,e.csrf,t);return;default:return}}async function td(e){let t=await ze.get();if(!t){let n=await ze.status();if(n.reason){let o=typeof ye=="function"?ye(n):"Authentication is not configured.";e({type:"GLOBAL_ERROR",error:o});}e({type:"AUTH_CHECK_COMPLETE",user:null});return}S.setCredentials(t);try{let n=await S.checkAuth();n.isSignedIn&&n.username?e({type:"AUTH_CHECK_COMPLETE",user:{username:n.username}}):e({type:"AUTH_CHECK_COMPLETE",user:null});}catch{e({type:"AUTH_CHECK_COMPLETE",user:null});}}async function nd(e,t,n){n({type:"LIST_FETCH_START"});try{let o=await ze.get();o&&S.setCredentials(o);let r=await S.getProblems(e),s=r.problems.map(i=>({questionId:i.questionId,questionFrontendId:i.questionFrontendId,title:i.title,titleSlug:i.titleSlug,difficulty:i.difficulty,isPaidOnly:i.isPaidOnly,acRate:i.acRate,topicTags:i.topicTags,status:i.status}));n({type:"LIST_FETCH_SUCCESS",problems:s,total:r.total,append:t});}catch(o){n({type:"LIST_FETCH_ERROR",error:o instanceof Error?o.message:"Failed to fetch problems"});}}async function od(e,t){try{let n=await S.getProblem(e);t({type:"PROBLEM_DETAIL_LOADED",detail:n});}catch(n){t({type:"PROBLEM_DETAIL_ERROR",error:n instanceof Error?n.message:"Failed to fetch problem"});}}async function rd(e){e({type:"STATS_FETCH_START"});try{let t=await ze.get();if(!t)throw new Error("You must be logged in to view stats");S.setCredentials(t);let n=await S.checkAuth();if(!n.isSignedIn||!n.username)throw new Error("Not logged in");let[o,r,s]=await Promise.all([S.getUserProfile(n.username),S.getSkillStats(n.username),S.getDailyChallenge()]);e({type:"STATS_FETCH_SUCCESS",stats:o,skills:r,daily:s});}catch(t){e({type:"STATS_FETCH_ERROR",error:t instanceof Error?t.message:"Failed to fetch statistics"});}}function sd(e,t){switch(e){case "language":M.setLanguage(t);break;case "editor":M.setEditor(t);break;case "workdir":M.setWorkDir(t);break;case "repo":M.setRepo(t);break}}async function Lo(e){let t=M.getLanguage(),n=await S.getProblem(e),o=Qt(t,n.codeSnippets),r=et(n.questionFrontendId,n.titleSlug,t),s=M.getWorkDir(),i=n.difficulty,a=n.topicTags.length>0?n.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",l=Ae.join(s,i,a,r);try{return {code:await ve.readFile(l,"utf-8"),lang:o,questionId:n.questionId}}catch{let p=Ae.join(s,r);try{return {code:await ve.readFile(p,"utf-8"),lang:o,questionId:n.questionId}}catch{throw new Error(`Could not read solution file at ${l}. Make sure you have picked the problem first.`)}}}async function id(e,t){try{let n=await S.getProblem(e),o=M.getLanguage(),r=qe(o);if(!r)throw new Error(`Unsupported language: ${o}`);let s=n.codeSnippets??[],i=Jt(s,r);if(s.length>0&&!i)throw new Error(`No code template available for ${r}`);let a=i?i.code:Xt(r,n.title),l=Zt(n.questionFrontendId,n.titleSlug,n.title,n.difficulty,a,r,n.content??void 0),u=M.getWorkDir(),p=n.difficulty,g=n.topicTags.length>0?n.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",m=Ae.join(u,p,g);try{await ve.mkdir(m,{recursive:!0});}catch{}let b=et(n.questionFrontendId,n.titleSlug,r),_=Ae.join(m,b);existsSync(_)?t({type:"PROBLEM_ACTION_SUCCESS",message:`File ready: ${b}`}):(await ve.writeFile(_,l,"utf-8"),t({type:"PROBLEM_ACTION_SUCCESS",message:`Created ${b}`}));}catch(n){t({type:"PROBLEM_ACTION_ERROR",error:n instanceof Error?n.message:"Failed to pick problem"});}}async function ad(e,t){try{let{code:n,lang:o}=await Lo(e),r=await S.getProblem(e),s=await S.testSolution(e,n,o,r.exampleTestcases,r.questionId);t({type:"PROBLEM_TEST_RESULT",result:s});}catch(n){t({type:"PROBLEM_ACTION_ERROR",error:n instanceof Error?n.message:"Test failed"});}}async function ld(e,t){try{let{code:n,lang:o}=await Lo(e),r=await S.getProblem(e),s=await S.submitSolution(e,n,o,r.questionId);t({type:"PROBLEM_SUBMIT_RESULT",result:s});}catch(n){t({type:"PROBLEM_ACTION_ERROR",error:n instanceof Error?n.message:"Submit failed"});}}async function cd(e){try{let t=await S.getDailyChallenge();if(t&&t.question&&t.question.titleSlug)e({type:"FETCH_DAILY_SUCCESS",slug:t.question.titleSlug});else throw new Error("No daily challenge found")}catch(t){e({type:"GLOBAL_ERROR",error:t instanceof Error?t.message:"Failed to fetch daily challenge"});}}async function ud(e){try{let t=await S.getRandomProblem();if(t)e({type:"FETCH_RANDOM_SUCCESS",slug:t});else throw new Error("No random problem found")}catch(t){e({type:"GLOBAL_ERROR",error:t instanceof Error?t.message:"Failed to fetch random problem"});}}async function dd(e,t){try{let n=Ae.join(M.getWorkDir(),".notes"),o=Ae.join(n,`${e}.md`);if(existsSync(o)){let r=await ve.readFile(o,"utf-8");t({type:"PROBLEM_NOTE_LOADED",content:r});}else t({type:"PROBLEM_NOTE_LOADED",content:'No notes found. Press "n" again to create/edit.'});}catch{t({type:"PROBLEM_ACTION_ERROR",error:"Failed to load note"});}}async function pd(e,t,n){try{let{code:o}=await Lo(e),s=(await S.getProblem(e)).questionFrontendId,i=X.get(s,t);if(!i)throw new Error("Snapshot not found");let a=X.getCode(s,i),l=diffLines(o,a),u="";l.forEach(p=>{let g=p.added?"[green]":p.removed?"[red]":"[grey]",m=p.added?"+ ":p.removed?"- ":" ";p.value.split(`
|
|
281
|
+
`).forEach(b=>{b&&(u+=`${g}${m}${b}
|
|
282
|
+
`);});}),n({type:"PROBLEM_DIFF_LOADED",content:u});}catch(o){n({type:"PROBLEM_ACTION_ERROR",error:o instanceof Error?o.message:"Diff failed"});}}async function gd(e,t,n){try{let o=await S.getProblem(e),r=o.questionFrontendId,s=X.get(r,t);if(!s)throw new Error("Snapshot not found");let i=X.getCode(r,s),a=M.getLanguage(),l=et(o.questionFrontendId,o.titleSlug,s.language||a),u=M.getWorkDir(),p=o.difficulty,g=o.topicTags.length>0?o.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",m=Ae.join(u,p,g),b=Ae.join(m,l);await ve.writeFile(b,i,"utf-8"),n({type:"PROBLEM_ACTION_SUCCESS",message:`Restored snapshot '${s.name}'`});}catch{n({type:"PROBLEM_ACTION_ERROR",error:"Restore failed"});}}async function fd(e,t){try{let n=await S.getSubmissionList(e,20);t({type:"PROBLEM_SUBMISSIONS_LOADED",submissions:n});}catch(n){t({type:"PROBLEM_SUBMISSIONS_ERROR",error:n instanceof Error?n.message:"Failed to fetch submissions"});}}async function md(e){e({type:"CHANGELOG_FETCH_START"});try{let t=await Zi(ed).text();e({type:"CHANGELOG_FETCH_SUCCESS",content:t});}catch(t){e({type:"CHANGELOG_FETCH_ERROR",error:t.message||"Failed to fetch changelog"});}}function Ni(){Pe&&(clearInterval(Pe),Pe=null);}async function yd(e){let t=await ze.clear();if(!t.ok){e({type:"GLOBAL_ERROR",error:t.message});return}e({type:"AUTH_CHECK_COMPLETE",user:null});}async function hd(e,t,n){let o=await ze.status();if(o.mode==="env-readonly"){n({type:"LOGIN_ERROR",error:"Environment credential mode is read-only. Unset LEETCODE_SESSION and LEETCODE_CSRF_TOKEN to use interactive login."});return}if(o.mode==="keychain"&&o.reason==="KEYCHAIN_UNAVAILABLE"){n({type:"LOGIN_ERROR",error:"System keychain is unavailable. Use LEETCODE_SESSION and LEETCODE_CSRF_TOKEN in headless environments."});return}let r={session:e,csrfToken:t};S.setCredentials(r);try{let s=await S.checkAuth();if(s.isSignedIn&&s.username){let i=await ze.set(r);if(!i.ok){n({type:"LOGIN_ERROR",error:i.message});return}n({type:"LOGIN_SUCCESS",username:s.username}),setTimeout(()=>{n({type:"AUTH_CHECK_COMPLETE",user:{username:s.username}});},1e3);}else n({type:"LOGIN_ERROR",error:"Invalid credentials. Please check your session cookies."});}catch(s){n({type:"LOGIN_ERROR",error:s instanceof Error?s.message:"Login failed"});}}var Fi={"\x1B[A":"up","\x1B[B":"down","\x1B[C":"right","\x1B[D":"left","\x1B[5~":"pageup","\x1B[6~":"pagedown","\x1B[H":"home","\x1B[F":"end","\x1B[2~":"insert","\x1B[3~":"delete","\x1B":"escape","\r":"return","\n":"return","\x7F":"backspace","\b":"backspace"," ":"space"," ":"tab"};function Hi(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e),n=t.toString(),o=t.length===1&&t[0]<27,r=t.length===2&&t[0]===27,s;Fi[n]?s=Fi[n]:o&&t.length===1?s=String.fromCharCode(t[0]+96):r&&t.length===2?s=String.fromCharCode(t[1]):s=n;let i=/^[A-Z]$/.test(s);return {name:s,sequence:n,ctrl:o,meta:r,shift:i}}var Sd="\x1B[?1049h",bd="\x1B[?1049l",Ed="\x1B[?25l",Cd="\x1B[?25h";function Ro(){process.stdout.write(Sd),process.stdout.write(Ed);}function Oo(){process.stdout.write(Cd),process.stdout.write(bd),process.stdout.write("\x1B[0m");}function xo(){process.stdin.isTTY&&process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8");}function Po(){process.stdin.isTTY&&process.stdin.setRawMode(false);}var Te,ht=false,Ye=true,vo=null,yt=false,Pt=null,vt=null,At=null;function ft(e){if(!ht)return;let t=Te.screenState.screen,[n,o]=Ai(e,Te);Te=n,t!==n.screenState.screen&&(Ye=true,bn="",Be=[]),o.type!=="CMD_NONE"&&(o.type==="CMD_OPEN_EDITOR"?(_d(),tn(o.id,"edit",{silent:true}).catch(r=>{ft({type:"GLOBAL_ERROR",error:r instanceof Error?r.message:"Failed to open editor"});}).finally(()=>{Md(),Ye=true,Be=[],Te={...Te,needsRender:true},ft({type:"PROBLEM_VIEW_NOTE"}),Bi();})):To(o,ft)),Te.needsRender&&(Bi(),Te={...Te,needsRender:false});}var bn="",Be=[],gt="\x1B[0m";function Bi(){if(!ht)return;let e=xi(Te);if(e===bn)return;bn=e;let t=e.split(`
|
|
283
|
+
`);if(Ye||Be.length===0){stdout.write(gt),stdout.write(Sn.cursorTo(0,0)),stdout.write(Sn.eraseScreen),stdout.write(e),stdout.write(gt),Ye=false,Be=t;return}let n=Math.max(Be.length,t.length),o=[];for(let r=0;r<n;r++){let s=Be[r]??"",i=t[r]??"";s!==i&&(o.push(gt),o.push(Sn.cursorTo(0,r)),o.push(Sn.eraseLine),i.length>0&&o.push(i),o.push(gt));}o.length>0&&stdout.write(o.join("")),Be=t;}function Ui(e){if(yt||!ht)return;let t=Hi(e);ft({type:"KEY_PRESS",key:t});}var Ao=false;function wd(){Ao||(Ao=true,ht=false,yt=false,stdin.off("data",Ui),Pt&&(stdout.off("resize",Pt),Pt=null),vt&&(process.off("SIGINT",vt),vt=null),At&&(process.off("SIGTERM",At),At=null),Ni(),stdout.write(gt),Oo(),En.show(),Po(),stdin.pause(),vo?.(),vo=null);}function _d(){yt||(yt=true,stdout.write(gt),Oo(),En.show(),Po(),stdin.pause());}function Md(){!ht||!yt||(yt=false,Ro(),En.hide(),xo(),stdin.resume(),Ye=true);}async function Wi(e){if(!stdin.isTTY||!stdout.isTTY)throw new Error("TUI requires an interactive terminal");let t=new Promise(n=>{vo=n;});return Te=e,ht=true,Ao=false,Ye=true,bn="",Be=[],Ro(),En.hide(),xo(),stdin.on("data",Ui),Pt=()=>{ft({type:"RESIZE",width:stdout.columns||80,height:stdout.rows||24}),Ye=true;},stdout.on("resize",Pt),ft({type:"INIT"}),vt=()=>{hn();},At=()=>{hn();},process.on("SIGINT",vt),process.on("SIGTERM",At),await t}function hn(){wd();}async function Gi(e={}){let{username:t}=e,n=Ys(t);await Wi(n);}var N=new Command;N.configureHelp({sortSubcommands:true,subcommandTerm:e=>{let t=e.name(),n=e.alias(),o=n?`${t}|${n}`:t;return f.cyan(o.padEnd(16))},subcommandDescription:e=>f.white(e.description()),optionTerm:e=>f.yellow(e.flags),optionDescription:e=>f.white(e.description)});N.name("leetcode").usage("[command] [options]").description(f.bold.cyan("\u{1F525} A modern LeetCode CLI built with TypeScript")).version("3.0.0","-v, --version","Output the version number").helpOption("-h, --help","Display help for command").addHelpText("after",`
|
|
274
284
|
${f.yellow("Examples:")}
|
|
275
285
|
${f.cyan("$ leetcode login")} Login to LeetCode
|
|
276
286
|
${f.cyan("$ leetcode list -d easy")} List easy problems
|
|
@@ -285,7 +295,7 @@ ${f.yellow("How to login:")}
|
|
|
285
295
|
3. Open Developer Tools (F12) \u2192 Application \u2192 Cookies
|
|
286
296
|
4. Copy values of ${f.green("LEETCODE_SESSION")} and ${f.green("csrftoken")}
|
|
287
297
|
5. Paste when prompted by this command
|
|
288
|
-
`).action(
|
|
298
|
+
`).action(nr);N.command("logout").description("Clear stored credentials").action(or);N.command("whoami").description("Check current login status").action(rr);N.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",`
|
|
289
299
|
${f.yellow("Examples:")}
|
|
290
300
|
${f.cyan("$ leetcode list")} List first 20 problems
|
|
291
301
|
${f.cyan("$ leetcode list -d easy")} List easy problems only
|
|
@@ -293,12 +303,12 @@ ${f.yellow("Examples:")}
|
|
|
293
303
|
${f.cyan("$ leetcode list -t array -t string")} Filter by multiple tags
|
|
294
304
|
${f.cyan('$ leetcode list -q "two sum"')} Search by keywords
|
|
295
305
|
${f.cyan("$ leetcode list -n 50 -p 2")} Show 50 problems, page 2
|
|
296
|
-
`).action(
|
|
306
|
+
`).action(Sr);N.command("show <id>").alias("s").description("Show problem description").addHelpText("after",`
|
|
297
307
|
${f.yellow("Examples:")}
|
|
298
308
|
${f.cyan("$ leetcode show 1")} Show by problem ID
|
|
299
309
|
${f.cyan("$ leetcode show two-sum")} Show by problem slug
|
|
300
310
|
${f.cyan("$ leetcode s 412")} Short alias
|
|
301
|
-
`).action(
|
|
311
|
+
`).action(qt);N.command("hint <id>").alias("h").description("Show hints for a problem").option("-a, --all","Show all hints at once").addHelpText("after",`
|
|
302
312
|
${f.yellow("Examples:")}
|
|
303
313
|
${f.cyan("$ leetcode hint 1")} Show hints for problem 1
|
|
304
314
|
${f.cyan("$ leetcode hint two-sum")} Show hints by slug
|
|
@@ -306,18 +316,18 @@ ${f.yellow("Examples:")}
|
|
|
306
316
|
${f.cyan("$ leetcode h 412")} Short alias
|
|
307
317
|
|
|
308
318
|
${f.gray("Hints are revealed one at a time. Press Enter to see more.")}
|
|
309
|
-
`).action(
|
|
319
|
+
`).action(br);N.command("daily").alias("d").description("Show today's daily challenge").addHelpText("after",`
|
|
310
320
|
${f.yellow("Examples:")}
|
|
311
321
|
${f.cyan("$ leetcode daily")} Show today's challenge
|
|
312
322
|
${f.cyan("$ leetcode d")} Short alias
|
|
313
|
-
`).action(
|
|
323
|
+
`).action(zr);N.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",`
|
|
314
324
|
${f.yellow("Examples:")}
|
|
315
325
|
${f.cyan("$ leetcode random")} Get any random problem
|
|
316
326
|
${f.cyan("$ leetcode random -d medium")} Random medium problem
|
|
317
327
|
${f.cyan("$ leetcode random -t array")} Random array problem
|
|
318
328
|
${f.cyan("$ leetcode random --pick")} Random + create file
|
|
319
329
|
${f.cyan("$ leetcode r -d easy --pick")} Random easy + file
|
|
320
|
-
`).action(
|
|
330
|
+
`).action(Yr);N.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",`
|
|
321
331
|
${f.yellow("Examples:")}
|
|
322
332
|
${f.cyan("$ leetcode pick 1")} Pick by problem ID
|
|
323
333
|
${f.cyan("$ leetcode pick two-sum")} Pick by problem slug
|
|
@@ -330,7 +340,7 @@ ${f.gray("Files are organized by: workDir/Difficulty/Category/")}
|
|
|
330
340
|
${f.yellow("Examples:")}
|
|
331
341
|
${f.cyan("$ leetcode pick-batch 1 2 3")} Pick problems 1, 2, and 3
|
|
332
342
|
${f.cyan("$ leetcode pick-batch 1 2 3 -l py")} Pick with Python
|
|
333
|
-
`).action(
|
|
343
|
+
`).action($r);N.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",`
|
|
334
344
|
${f.yellow("Examples:")}
|
|
335
345
|
${f.cyan("$ leetcode test 1")} Test by problem ID
|
|
336
346
|
${f.cyan("$ leetcode test two-sum")} Test by problem slug
|
|
@@ -340,25 +350,25 @@ ${f.yellow("Examples:")}
|
|
|
340
350
|
${f.cyan("$ leetcode t 412")} Short alias
|
|
341
351
|
|
|
342
352
|
${f.gray("Testcases use \\n to separate multiple inputs.")}
|
|
343
|
-
`).action(
|
|
353
|
+
`).action(Hr);N.command("submit <file>").alias("x").description("Submit solution to LeetCode").addHelpText("after",`
|
|
344
354
|
${f.yellow("Examples:")}
|
|
345
355
|
${f.cyan("$ leetcode submit 1")} Submit by problem ID
|
|
346
356
|
${f.cyan("$ leetcode submit two-sum")} Submit by problem slug
|
|
347
357
|
${f.cyan("$ leetcode submit ./path/to/file.py")} Submit by file path
|
|
348
358
|
${f.cyan("$ leetcode x 412")} Short alias
|
|
349
|
-
`).action(
|
|
359
|
+
`).action(Wr);N.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",`
|
|
350
360
|
${f.yellow("Examples:")}
|
|
351
361
|
${f.cyan("$ leetcode diff 1")} Compare with last accepted
|
|
352
362
|
${f.cyan("$ leetcode diff 1 -u")} Show unified diff
|
|
353
363
|
${f.cyan("$ leetcode diff 1 -s 12345")} Compare with specific submission
|
|
354
364
|
${f.cyan("$ leetcode diff 1 -f other.py")} Compare with local file
|
|
355
|
-
`).action(
|
|
365
|
+
`).action(Ps);N.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",`
|
|
356
366
|
${f.yellow("Examples:")}
|
|
357
367
|
${f.cyan("$ leetcode submissions 1")} View submissions for problem
|
|
358
368
|
${f.cyan("$ leetcode submissions 1 -n 5")} Show last 5 submissions
|
|
359
369
|
${f.cyan("$ leetcode submissions 1 --last")} Show last accepted submission
|
|
360
370
|
${f.cyan("$ leetcode submissions 1 --download")} Download last accepted code
|
|
361
|
-
`).action(
|
|
371
|
+
`).action(Xr);N.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",`
|
|
362
372
|
${f.yellow("Options Explained:")}
|
|
363
373
|
${f.cyan("-c, --calendar")} Shows a table of your weekly submissions and active days
|
|
364
374
|
for the past 12 weeks. Useful for tracking consistency.
|
|
@@ -376,10 +386,10 @@ ${f.yellow("Examples:")}
|
|
|
376
386
|
${f.cyan("$ leetcode stat -c")} Weekly activity table
|
|
377
387
|
${f.cyan("$ leetcode stat -s")} Topic-wise breakdown
|
|
378
388
|
${f.cyan("$ leetcode stat -t")} 7-day trend chart
|
|
379
|
-
`).action((e,t)=>
|
|
389
|
+
`).action((e,t)=>Vr(e,t));N.command("today").description("Show today's progress summary").addHelpText("after",`
|
|
380
390
|
${f.yellow("Examples:")}
|
|
381
391
|
${f.cyan("$ leetcode today")} Show streak, solved, and daily challenge
|
|
382
|
-
`).action(
|
|
392
|
+
`).action(rs);N.command("bookmark <action> [id]").description("Manage problem bookmarks").addHelpText("after",`
|
|
383
393
|
${f.yellow("Actions:")}
|
|
384
394
|
${f.cyan("add <id>")} Bookmark a problem
|
|
385
395
|
${f.cyan("remove <id>")} Remove a bookmark
|
|
@@ -390,7 +400,7 @@ ${f.yellow("Examples:")}
|
|
|
390
400
|
${f.cyan("$ leetcode bookmark add 1")} Bookmark problem 1
|
|
391
401
|
${f.cyan("$ leetcode bookmark remove 1")} Remove bookmark
|
|
392
402
|
${f.cyan("$ leetcode bookmark list")} List all bookmarks
|
|
393
|
-
`).action(
|
|
403
|
+
`).action(ns);N.command("note <id> [action]").description("View or edit notes for a problem").addHelpText("after",`
|
|
394
404
|
${f.yellow("Actions:")}
|
|
395
405
|
${f.cyan("edit")} Open notes in editor (default)
|
|
396
406
|
${f.cyan("view")} Display notes in terminal
|
|
@@ -399,10 +409,10 @@ ${f.yellow("Examples:")}
|
|
|
399
409
|
${f.cyan("$ leetcode note 1")} Edit notes for problem 1
|
|
400
410
|
${f.cyan("$ leetcode note 1 edit")} Edit notes (explicit)
|
|
401
411
|
${f.cyan("$ leetcode note 1 view")} View notes in terminal
|
|
402
|
-
`).action(
|
|
412
|
+
`).action(tn);N.command("sync").description("Sync solutions to Git repository").addHelpText("after",`
|
|
403
413
|
${f.yellow("Examples:")}
|
|
404
414
|
${f.cyan("$ leetcode sync")} Sync all solutions to remote
|
|
405
|
-
`).action(
|
|
415
|
+
`).action(ss);N.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 (omit value to clear)").option("-i, --interactive","Interactive configuration").addHelpText("after",`
|
|
406
416
|
${f.yellow("Examples:")}
|
|
407
417
|
${f.cyan("$ leetcode config")} View current config
|
|
408
418
|
${f.cyan("$ leetcode config -l python3")} Set language to Python
|
|
@@ -412,8 +422,8 @@ ${f.yellow("Examples:")}
|
|
|
412
422
|
${f.cyan("$ leetcode config --repo")} Clear git repository
|
|
413
423
|
${f.cyan("$ leetcode config -i")} Interactive setup
|
|
414
424
|
|
|
415
|
-
${f.gray(`Supported languages: ${
|
|
416
|
-
`).action(async e=>{e.interactive?await
|
|
425
|
+
${f.gray(`Supported languages: ${Rr()}`)}
|
|
426
|
+
`).action(async e=>{e.interactive?await es():await Zr(e);});N.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",`
|
|
417
427
|
${f.yellow("How it works:")}
|
|
418
428
|
Start a problem with a countdown timer to simulate interview conditions.
|
|
419
429
|
Default time limits: Easy (20 min), Medium (40 min), Hard (60 min).
|
|
@@ -424,7 +434,7 @@ ${f.yellow("Examples:")}
|
|
|
424
434
|
${f.cyan("$ leetcode timer 1 -m 30")} Start with 30 minute limit
|
|
425
435
|
${f.cyan("$ leetcode timer --stats")} Show your solve time statistics
|
|
426
436
|
${f.cyan("$ leetcode timer --stop")} Stop active timer
|
|
427
|
-
`).action((e,t)=>
|
|
437
|
+
`).action((e,t)=>is(e,t));var $t=N.command("workspace").description("Manage workspaces for different contexts");$t.command("current").description("Show current workspace").action(vs);$t.command("list").description("List all workspaces").action(As);$t.command("create <name>").description("Create a new workspace").option("-w, --workdir <path>","Set working directory for this workspace").action($s);$t.command("use <name>").description("Switch to a workspace").action(Ds);$t.command("delete <name>").description("Delete a workspace").action(Is);var St=N.command("collab").description("Collaborative coding with a partner").addHelpText("after",`
|
|
428
438
|
${f.yellow("Subcommands:")}
|
|
429
439
|
${f.cyan("host <id>")} Create a room and get a code to share
|
|
430
440
|
${f.cyan("join <code>")} Join a room with the shared code
|
|
@@ -438,7 +448,7 @@ ${f.yellow("Examples:")}
|
|
|
438
448
|
${f.gray("$ leetcode collab join ABC123")} Join your partner's session
|
|
439
449
|
${f.gray("$ leetcode collab sync")} Upload your code after solving
|
|
440
450
|
${f.gray("$ leetcode collab compare")} Compare solutions
|
|
441
|
-
`);
|
|
451
|
+
`);St.command("host <problemId>").description("Host a collaboration session").action(cs);St.command("join <roomCode>").description("Join a collaboration session").action(us);St.command("sync").description("Sync your code with partner").action(ds);St.command("compare").description("Compare your solution with partner").action(ps);St.command("leave").description("Leave the collaboration session").action(gs);St.command("status").description("Show collaboration status").action(fs);var Dt=N.command("snapshot").description("Save and restore solution versions").addHelpText("after",`
|
|
442
452
|
${f.yellow("Subcommands:")}
|
|
443
453
|
${f.cyan("save <id> [name]")} Save current solution as a snapshot
|
|
444
454
|
${f.cyan("list <id>")} List all snapshots for a problem
|
|
@@ -451,16 +461,16 @@ ${f.yellow("Examples:")}
|
|
|
451
461
|
${f.gray("$ leetcode snapshot list 1")} List snapshots
|
|
452
462
|
${f.gray("$ leetcode snapshot restore 1 2")} Restore snapshot #2
|
|
453
463
|
${f.gray("$ leetcode snapshot diff 1 1 2")} Compare snapshots
|
|
454
|
-
`);
|
|
464
|
+
`);Dt.command("save <id> [name]").description("Save current solution as a snapshot").action(_s);Dt.command("list <id>").description("List all snapshots for a problem").action(Ms);Dt.command("restore <id> <snapshot>").description("Restore a snapshot").action(ks);Dt.command("diff <id> <snap1> <snap2>").description("Compare two snapshots").action(Ts);Dt.command("delete <id> <snapshot>").description("Delete a snapshot").action(Ls);N.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",`
|
|
455
465
|
${f.yellow("Examples:")}
|
|
456
466
|
${f.cyan("$ leetcode update")} Check for updates
|
|
457
467
|
${f.cyan("$ leetcode update --force")} Force re-check npm registry
|
|
458
468
|
${f.cyan("$ leetcode update --check-only")} Just check, minimal output
|
|
459
|
-
`).action(
|
|
469
|
+
`).action(js);N.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",`
|
|
460
470
|
${f.yellow("Examples:")}
|
|
461
471
|
${f.cyan("$ leetcode changelog")} Show what's new since your version
|
|
462
472
|
${f.cyan("$ leetcode changelog --all")} View full changelog
|
|
463
473
|
${f.cyan("$ leetcode changelog 2.0.0")} Show specific version
|
|
464
474
|
${f.cyan("$ leetcode changelog --latest")} Show latest version only
|
|
465
475
|
${f.cyan("$ leetcode changelog --breaking")} Filter to breaking changes
|
|
466
|
-
`).action((e,t)=>
|
|
476
|
+
`).action((e,t)=>zs(e,t));N.showHelpAfterError("(add --help for additional information)");var Td=process.argv.length>2&&!["update","changelog","--version","-v","--help","-h"].includes(process.argv[2]);Td&&qs().catch(()=>{});var ji=process.argv.slice(2);ji.length===0&&process.stdout.isTTY?Gi({username:""}).catch(e=>{console.error("Failed to launch TUI:",e.message),process.exit(1);}):ji.length===0?(console.log(),console.log(f.bold.cyan(" \u{1F525} LeetCode CLI")),console.log(f.gray(" A modern command-line interface for LeetCode")),console.log(),N.outputHelp()):N.parse();
|