"use strict";exports.id=1318,exports.ids=[1318],exports.modules={61318:(e,t,r)=>{r.d(t,{v:()=>_});var o=r(61282),s=r(92048),a=r(55315),i=r.n(a);class n{constructor(){}static getInstance(){return n.instance||(n.instance=new n),n.instance}normalize(e){let t=e.match(/^ssh:\/\/git@([^:\/]+)(:\d+)?\/(.+?)(\.git)?$/);if(t)return`https://${t[1]}/${t[3]}`.toLowerCase().replace(/\/$/,"");let r=e.match(/^git@([^:]+):(.+?)(\.git)?$/);return r?`https://${r[1]}/${r[2]}`.toLowerCase().replace(/\/$/,""):e.replace(/\.git\/?$/,"").replace(/\/$/,"").toLowerCase()}isSameRepository(e,t){return this.normalize(e)===this.normalize(t)}extractRepoName(e){let t=e.match(/^ssh:\/\/git@[^\/]+\/(.+?)(\.git)?$/);if(t){let e=t[1].split("/");return e[e.length-1]}let r=e.match(/:(.+?)(\.git)?$/);if(r&&e.startsWith("git@")){let e=r[1].split("/");return e[e.length-1]}let o=e.match(/\/([^\/]+?)(\.git)?$/);return o?o[1]:""}getUrlType(e){return e.startsWith("https://")?"https":e.startsWith("git@")||e.startsWith("ssh://")?"ssh":null}validate(e){if(!e||"string"!=typeof e||""===e.trim())return{valid:!1,error:"EMPTY_URL"};let t=e.trim();return t.startsWith("https://")?/^https:\/\/[^\/]+\/[^\/]+\/[^\/]+(\.git)?$/.test(t)?{valid:!0}:{valid:!1,error:"INVALID_URL_FORMAT"}:t.startsWith("git@")?/^git@[^:]+:.+\/.+(\.git)?$/.test(t)?{valid:!0}:{valid:!1,error:"INVALID_URL_FORMAT"}:t.startsWith("ssh://")&&/^ssh:\/\/git@[^\/]+(:\d+)?\/[^\/]+\/.+(\.git)?$/.test(t)?{valid:!0}:{valid:!1,error:"INVALID_URL_FORMAT"}}}var l=r(57440),c=r(84770);function d(e){return{id:e.id,cloneUrl:e.clone_url,normalizedCloneUrl:e.normalized_clone_url,targetPath:e.target_path,repositoryId:e.repository_id||void 0,status:e.status,pid:e.pid||void 0,progress:e.progress,errorCategory:e.error_category||void 0,errorCode:e.error_code||void 0,errorMessage:e.error_message||void 0,startedAt:e.started_at?new Date(e.started_at):void 0,completedAt:e.completed_at?new Date(e.completed_at):void 0,createdAt:new Date(e.created_at)}}function u(e,t){let r=e.prepare(`
    SELECT * FROM clone_jobs
    WHERE id = ?
  `).get(t);return r?d(r):null}function g(e,t,r){let o=[],s=[];void 0!==r.status&&(o.push("status = ?"),s.push(r.status)),void 0!==r.pid&&(o.push("pid = ?"),s.push(r.pid)),void 0!==r.progress&&(o.push("progress = ?"),s.push(r.progress)),void 0!==r.repositoryId&&(o.push("repository_id = ?"),s.push(r.repositoryId)),void 0!==r.errorCategory&&(o.push("error_category = ?"),s.push(r.errorCategory)),void 0!==r.errorCode&&(o.push("error_code = ?"),s.push(r.errorCode)),void 0!==r.errorMessage&&(o.push("error_message = ?"),s.push(r.errorMessage)),void 0!==r.startedAt&&(o.push("started_at = ?"),s.push(r.startedAt.getTime())),void 0!==r.completedAt&&(o.push("completed_at = ?"),s.push(r.completedAt.getTime())),0!==o.length&&(s.push(t),e.prepare(`
    UPDATE clone_jobs
    SET ${o.join(", ")}
    WHERE id = ?
  `).run(...s))}var h=r(67722);class p extends Error{constructor(e){super(e.message),this.name="CloneManagerError",this.category=e.category,this.code=e.code,this.recoverable=e.recoverable,this.suggestedAction=e.suggestedAction}}let m={EMPTY_URL:{category:"validation",code:"EMPTY_URL",message:"Clone URL is required",recoverable:!0,suggestedAction:"Please enter a valid git clone URL"},INVALID_URL_FORMAT:{category:"validation",code:"INVALID_URL_FORMAT",message:"Invalid URL format. Please use HTTPS or SSH URL.",recoverable:!0,suggestedAction:"Enter a valid URL like https://github.com/owner/repo or git@github.com:owner/repo"},DUPLICATE_CLONE_URL:{category:"validation",code:"DUPLICATE_CLONE_URL",message:"This repository is already registered",recoverable:!1,suggestedAction:"Use the existing repository instead"},CLONE_IN_PROGRESS:{category:"validation",code:"CLONE_IN_PROGRESS",message:"A clone operation is already in progress for this URL",recoverable:!1,suggestedAction:"Wait for the current clone to complete"},DIRECTORY_EXISTS:{category:"filesystem",code:"DIRECTORY_EXISTS",message:"Target directory already exists",recoverable:!0,suggestedAction:"Choose a different directory or remove the existing one"},INVALID_TARGET_PATH:{category:"validation",code:"INVALID_TARGET_PATH",message:"Target path is invalid or outside allowed directory",recoverable:!0,suggestedAction:"Use a path within the configured base directory"},AUTH_FAILED:{category:"auth",code:"AUTH_FAILED",message:"Authentication failed",recoverable:!0,suggestedAction:"Check your credentials or SSH keys"},NETWORK_ERROR:{category:"network",code:"NETWORK_ERROR",message:"Network error occurred",recoverable:!0,suggestedAction:"Check your internet connection and try again"},GIT_ERROR:{category:"git",code:"GIT_ERROR",message:"Git command failed",recoverable:!1,suggestedAction:"Check the error message for details"},CLONE_TIMEOUT:{category:"network",code:"CLONE_TIMEOUT",message:"Clone operation timed out",recoverable:!0,suggestedAction:"Try again or clone a smaller repository"}};class _{constructor(e,t={}){this.db=e,this.urlNormalizer=n.getInstance(),this.config={basePath:t.basePath||process.env.WORKTREE_BASE_PATH||"/tmp/repos",timeout:t.timeout||6e5},this.activeProcesses=new Map}validateCloneRequest(e){let t=this.urlNormalizer.validate(e);return t.valid?{valid:!0,normalizedUrl:this.urlNormalizer.normalize(e),repoName:this.urlNormalizer.extractRepoName(e)}:{valid:!1,error:m[t.error||"INVALID_URL_FORMAT"]}}checkDuplicateRepository(e){return function(e,t){let r=e.prepare(`
    SELECT * FROM repositories
    WHERE normalized_clone_url = ?
  `).get(t);return r?{id:r.id,name:r.name,path:r.path,enabled:1===r.enabled,cloneUrl:r.clone_url||void 0,normalizedCloneUrl:r.normalized_clone_url||void 0,cloneSource:r.clone_source,isEnvManaged:1===r.is_env_managed,createdAt:new Date(r.created_at),updatedAt:new Date(r.updated_at)}:null}(this.db,e)}checkActiveCloneJob(e){return function(e,t){let r=e.prepare(`
    SELECT * FROM clone_jobs
    WHERE normalized_clone_url = ?
      AND status IN ('pending', 'running')
    ORDER BY created_at DESC
    LIMIT 1
  `).get(t);return r?d(r):null}(this.db,e)}createCloneJob(e){return function(e,t){let r=(0,c.randomUUID)(),o=Date.now();return e.prepare(`
    INSERT INTO clone_jobs (
      id, clone_url, normalized_clone_url, target_path,
      status, progress, created_at
    )
    VALUES (?, ?, ?, ?, 'pending', 0, ?)
  `).run(r,t.cloneUrl,t.normalizedCloneUrl,t.targetPath,o),{id:r,cloneUrl:t.cloneUrl,normalizedCloneUrl:t.normalizedCloneUrl,targetPath:t.targetPath,status:"pending",progress:0,createdAt:new Date(o)}}(this.db,e)}getTargetPath(e){return i().join(this.config.basePath,e)}async startCloneJob(e,t){let r=this.validateCloneRequest(e);if(!r.valid)return{success:!1,error:r.error};let o=r.normalizedUrl,a=r.repoName,i=this.checkDuplicateRepository(o);if(i)return{success:!1,error:{...m.DUPLICATE_CLONE_URL,message:`This repository is already registered as "${i.name}"`}};let n=this.checkActiveCloneJob(o);if(n)return{success:!1,jobId:n.id,error:m.CLONE_IN_PROGRESS};let c=t||this.getTargetPath(a);if(t&&!(0,l.j)(t,this.config.basePath))return{success:!1,error:{...m.INVALID_TARGET_PATH,message:`Target path must be within ${this.config.basePath}`}};if((0,s.existsSync)(c))return{success:!1,error:{...m.DIRECTORY_EXISTS,message:`Target directory already exists: ${c}`}};let d=this.createCloneJob({cloneUrl:e,normalizedCloneUrl:o,targetPath:c});return this.executeClone(d.id,e,c).catch(e=>{console.error(`[CloneManager] Clone failed for job ${d.id}:`,e)}),{success:!0,jobId:d.id}}async executeClone(e,t,r){g(this.db,e,{status:"running",startedAt:new Date});let a=i().dirname(r);return(0,s.existsSync)(a)||(0,s.mkdirSync)(a,{recursive:!0}),new Promise((s,a)=>{let i=(0,o.spawn)("git",["clone","--progress",t,r],{stdio:["ignore","pipe","pipe"]});this.activeProcesses.set(e,i),i.pid&&g(this.db,e,{pid:i.pid});let n="";i.stderr?.on("data",t=>{n+=t.toString();let r=this.parseGitProgress(t.toString());null!==r&&g(this.db,e,{progress:r})});let l=setTimeout(()=>{i.kill("SIGTERM"),g(this.db,e,{status:"failed",errorCategory:"network",errorCode:"CLONE_TIMEOUT",errorMessage:"Clone operation timed out",completedAt:new Date}),this.activeProcesses.delete(e),a(new p(m.CLONE_TIMEOUT))},this.config.timeout);i.on("close",async o=>{if(clearTimeout(l),this.activeProcesses.delete(e),0===o)await this.onCloneSuccess(e,t,r),s();else{let t=this.parseGitError(n,o);g(this.db,e,{status:"failed",errorCategory:t.category,errorCode:t.code,errorMessage:t.message,completedAt:new Date}),a(new p(t))}}),i.on("error",t=>{clearTimeout(l),this.activeProcesses.delete(e);let r={category:"system",code:"SPAWN_ERROR",message:`Failed to spawn git process: ${t.message}`,recoverable:!1,suggestedAction:"Ensure git is installed and available in PATH"};g(this.db,e,{status:"failed",errorCategory:r.category,errorCode:r.code,errorMessage:r.message,completedAt:new Date}),a(new p(r))})})}async onCloneSuccess(e,t,r){let o=u(this.db,e);if(!o)return;let s=this.urlNormalizer.getUrlType(t),a=function(e,t){let r=(0,c.randomUUID)(),o=Date.now();return e.prepare(`
    INSERT INTO repositories (
      id, name, path, enabled, clone_url, normalized_clone_url,
      clone_source, is_env_managed, created_at, updated_at
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(r,t.name,t.path,!1!==t.enabled?1:0,t.cloneUrl||null,t.normalizedCloneUrl||null,t.cloneSource,t.isEnvManaged?1:0,o,o),{id:r,name:t.name,path:t.path,enabled:!1!==t.enabled,cloneUrl:t.cloneUrl,normalizedCloneUrl:t.normalizedCloneUrl,cloneSource:t.cloneSource,isEnvManaged:t.isEnvManaged||!1,createdAt:new Date(o),updatedAt:new Date(o)}}(this.db,{name:i().basename(r),path:r,cloneUrl:t,normalizedCloneUrl:o.normalizedCloneUrl,cloneSource:s||"https"});try{let e=await (0,h.e9)(r);e.length>0&&((0,h.h2)(this.db,e),console.log(`[CloneManager] Registered ${e.length} worktree(s) for ${r}`))}catch(e){console.error(`[CloneManager] Failed to scan worktrees for ${r}:`,e)}g(this.db,e,{status:"completed",progress:100,repositoryId:a.id,completedAt:new Date})}parseGitProgress(e){let t=e.match(/(?:Receiving objects|Resolving deltas|Cloning into[^:]*?):\s*(\d+)%/);if(t){let e=parseInt(t[1],10);return isNaN(e)?null:e}return null}parseGitError(e,t){let r=e.toLowerCase(),o=e.substring(0,200);return["authentication failed","permission denied","could not read from remote repository"].some(e=>r.includes(e))?{...m.AUTH_FAILED,message:`Authentication failed: ${o}`}:["could not resolve host","connection refused","network is unreachable"].some(e=>r.includes(e))?{...m.NETWORK_ERROR,message:`Network error: ${o}`}:{...m.GIT_ERROR,message:`Git clone failed (exit code ${t}): ${o}`}}getCloneJobStatus(e){let t=u(this.db,e);if(!t)return null;let r={jobId:t.id,status:t.status,progress:t.progress,repositoryId:t.repositoryId};return"failed"===t.status&&t.errorCode&&(r.error={category:t.errorCategory||"system",code:t.errorCode,message:t.errorMessage||"Unknown error"}),r}cancelCloneJob(e){let t=this.activeProcesses.get(e);if(t)return t.kill("SIGTERM"),this.activeProcesses.delete(e),g(this.db,e,{status:"cancelled",completedAt:new Date}),!0;let r=u(this.db,e);return!!r&&"pending"===r.status&&(g(this.db,e,{status:"cancelled",completedAt:new Date}),!0)}}},57440:(e,t,r)=>{r.d(t,{j:()=>a});var o=r(55315),s=r.n(o);function a(e,t){if(!e||""===e.trim()||e.includes("\0"))return!1;let r=e;try{r=decodeURIComponent(e)}catch{r=e}if(r.includes("\0"))return!1;let o=s().resolve(t),a=s().resolve(t,r),i=s().relative(o,a);return!(i.startsWith("..")||s().isAbsolute(i))}},67722:(e,t,r)=>{r.d(t,{Lj:()=>u,a$:()=>c,e9:()=>d,h2:()=>g});var o=r(61282),s=r(21764),a=r(55315),i=r.n(a),n=r(75748),l=r(93346);function c(){let e=process.env.WORKTREE_REPOS;if(e&&e.trim())return e.split(",").map(e=>e.trim()).filter(e=>e.length>0);let t=(0,l.Hb)("CM_ROOT_DIR");return t&&t.trim()?[t.trim()]:[]}async function d(e){let t=(0,s.promisify)(o.exec);try{let{stdout:r}=await t("git worktree list",{cwd:e}),o=function(e){if(!e||""===e.trim())return[];let t=e.trim().split("\n"),r=[];for(let e of t){let t=e.trim();if(!t)continue;let o=t.match(/^(.+?)\s+([a-z0-9]+)\s+(?:\[(.+?)\]|\(detached HEAD\))/);if(o){let[,e,t,s]=o;r.push({path:e.trim(),branch:s||`detached-${t}`,commit:t})}}return r}(r),s=i().resolve(e),a=i().basename(s);return o.map(e=>({id:function(e,t){if(!e)return"";let r=e=>e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),o=r(e);if(t){let e=r(t);return`${e}-${o}`}return o}(e.branch,a),name:e.branch,path:i().resolve(e.path),repositoryPath:s,repositoryName:a})).filter(e=>["/etc","/root","/sys","/proc","/dev","/boot","/bin","/sbin","/usr/bin","/usr/sbin"].some(t=>e.path.startsWith(t))?(console.warn(`Skipping potentially unsafe worktree path: ${e.path}`),!1):!(e.path.includes("\0")||e.path.includes(".."))||(console.warn(`Skipping path with potentially malicious characters: ${e.path}`),!1))}catch(r){let e=r instanceof Error?r.message:String(r),t=r.code;if(e?.includes("not a git repository")||128===t)return[];throw r}}async function u(e){let t=[];for(let r of e)try{console.log(`Scanning repository: ${r}`);let e=await d(r);t.push(...e),console.log(`  Found ${e.length} worktree(s)`)}catch(e){console.error(`Error scanning repository ${r}:`,e)}return t}function g(e,t){if(0===t.length)return;let r=new Map;for(let e of t){let t=e.repositoryPath||"";r.has(t)||r.set(t,[]),r.get(t).push(e)}for(let[t,o]of r){if(!t)continue;let r=(0,n.Pv)(e,t),s=new Set(o.map(e=>e.id)),a=r.filter(e=>!s.has(e));if(a.length>0){let r=(0,n.pM)(e,a);console.log(`Removed ${r.deletedCount} deleted worktree(s) from ${t}`)}for(let t of o)(0,n.ly)(e,t)}}}};