// @bun
import{Jb as H,Kb as K,Lb as X}from"./chunk-mttbh4fd.js";import{Sb as U,Tb as ee}from"./chunk-zt8mhebs.js";import{Zb as O}from"./chunk-bqh4yh6g.js";import y from"fs";import j from"path";import I from"process";var W=[{domain:"php.net",aliases:["php"]},{domain:"ruby-lang.org",aliases:["ruby"]},{domain:"go.dev",aliases:["go"]},{domain:"nodejs.org",aliases:["node"]},{domain:"python.org",aliases:["python","py"]},{domain:"curl.se",aliases:["curl"]},{domain:"git-scm.com",aliases:["git"]},{domain:"vim.org",aliases:["vim","vi"]},{domain:"npmjs.com",aliases:["npm"]},{domain:"classic.yarnpkg.com",aliases:["yarn"]},{domain:"bun.sh",aliases:["bun","bun.com"]},{domain:"s3tools.org",aliases:["s3cmd"]},{domain:"aws.amazon.com/cdk",aliases:["cdk","aws/cdk"]},{domain:"info-zip.org/zip",aliases:["zip"]},{domain:"info-zip.org/unzip",aliases:["unzip"]}];function oe(e){let t=W.find((o)=>o.domain===e);return t?t.aliases:[]}function ae(e){return W.find((t)=>t.domain===e)?.replace===!0}function Ie(){let e={};for(let t of W)for(let o of t.aliases)e[o]=t.domain;return e}ee();async function ne(e,t={}){let{timeout:o=30000}=t,n=await re(e,o),i=await le(e,o),s=await ce(e,o);return ue(n,i,s,e)}async function re(e,t){let o=`https://pkgx.dev/pkgs/${e}.json`;try{let n=await fetch(o,{headers:{Accept:"application/json","User-Agent":"ts-pkgx"},signal:AbortSignal.timeout(t)});if(!n.ok)return null;return await n.json()}catch{return null}}async function ce(e,t){let o=["darwin/aarch64","linux/x86-64","linux/aarch64"];for(let n of o)try{let i=`https://dist.pkgx.dev/${e}/${n}/versions.txt`,s=await fetch(i,{headers:{Accept:"text/plain","User-Agent":"ts-pkgx"},signal:AbortSignal.timeout(t)});if(s.ok){let r=(await s.text()).split(`
`).map((c)=>c.trim()).filter((c)=>c.length>0);if(r.length>0)return r.reverse()}}catch{continue}return console.warn(`No versions found for ${e}`),[]}async function le(e,t){try{let n=await import("fs"),i=await import("path"),s=await import("process"),r=i.join(s.cwd(),"src/pantry",e,"package.yml");if(n.existsSync(r)){let c=n.readFileSync(r,"utf-8");return q(c)}}catch{}let o=`https://raw.githubusercontent.com/pkgxdev/pantry/main/projects/${e}/package.yml`;try{let n=await fetch(o,{headers:{Accept:"text/plain","User-Agent":"ts-pkgx"},signal:AbortSignal.timeout(t)});if(!n.ok)return console.warn(`Pantry data not found for ${e}`),null;let i=await n.text();return q(i)}catch(n){return console.warn(`Failed to fetch pantry data for ${e}:`,n instanceof Error?n.message:String(n)),null}}function q(e){let t={},o=e.split(`
`),n=!1;for(let a=0;a<o.length;a++){let d=o[a];if(d.match(/^versions:\s*$/)){n=!0;continue}if(n){let x=d.match(/^\s+github:\s+([^\s#]+)/);if(x){t.versions={github:x[1].trim()};break}if(d.match(/^[a-z]/))n=!1}}let i=!1,s={};for(let a=0;a<o.length;a++){let d=o[a];if(d.match(/^dependencies:\s*$/)){i=!0;continue}if(i){let x=d.match(/^\s{2}([a-z0-9./]+):\s*['"]?([^'"#\n]+)['"]?/);if(x){let S=x[1].trim(),h=x[2].trim();s[S]=h}if(d.match(/^[a-z]/)&&!d.match(/^\s/))break}}if(Object.keys(s).length>0)t.dependencies=s;let r=!1,c=!1,l={};for(let a=0;a<o.length;a++){let d=o[a];if(d.match(/^build:\s*$/)){r=!0;continue}if(r&&d.match(/^\s{2}dependencies:\s*$/)){c=!0;continue}if(c){let x=d.match(/^\s{4}(darwin|linux):\s*$/);if(x){let h=x[1];a++;while(a<o.length){let b=o[a],u=b.match(/^\s{6,}([a-z0-9./]+):\s*['"]?([^'"#\n]+)['"]?/);if(u){let g=u[1].trim(),m=u[2].trim();l[`${h}:${g}`]=m,a++}else if(b.match(/^\s{0,5}\S/)){a--;break}else a++}continue}let S=d.match(/^ {4}([a-z0-9./]+):\s*['"]?([^'"#\n]+)['"]?/);if(S&&!d.match(/^ {5}/)){let h=S[1].trim(),b=S[2].trim();if(!["if","run","working-directory","env","script"].includes(h))l[h]=b}if(d.match(/^\s{2}(script|env|working-directory):\s*$/)||d.match(/^[a-z]/))break}}if(Object.keys(l).length>0)t.build={dependencies:l};return t}function ue(e,t,o,n){let i=[],s=[];if(t?.dependencies)for(let[l,a]of Object.entries(t.dependencies)){let d=a.toString().trim();i.push(d==="*"?l:`${l}@${d}`)}if(t?.build?.dependencies)for(let[l,a]of Object.entries(t.build.dependencies)){let d=a.toString().trim();s.push(d==="*"?l:`${l}@${d}`)}let r=[...i,...s],c=n.split("/").pop()?.replace(/\.(org|com|io|net|dev)$/,"")||n;return{name:e?.displayName||e?.name||c,domain:e?.project||n,brief:e?.brief||e?.description||"",description:e?.description||e?.brief||"",displayName:e?.displayName,homepage:e?.homepage,github:e?.github,brew_url:e?.brew_url,license:e?.license,provides:e?.provides||[],companions:t?.companions||[],dependencies:i,buildDependencies:s,allDependencies:r,versions:o,build:t?.build,interprets:e?.interprets}}async function Ue(e,t={}){let o=new Map,n=e.map(async(i)=>{try{let s=await ne(i,t);o.set(i,s)}catch(s){console.error(`Failed to scrape ${i}:`,s)}});return await Promise.all(n),o}async function Fe(e={}){try{let t=await fetch("https://pkgx.dev/pkgs/index.json",{headers:{Accept:"application/json"}});if(t.ok)return(await t.json()).map((o)=>o.project)}catch{}throw Error("Failed to fetch package index from pkgx.dev/pkgs/index.json")}function Q(e){if(e.includes("/")){let[t,...o]=e.split("/"),n=o.join("/"),i=t.replace(/\./g,"");if(t.includes("github.com")){let r=n.split("/");return r[r.length-1].replace(/[.-]/g,"").toLowerCase()}let s=n.replace(/[/.-]/g,"");return`${i}${s}`.toLowerCase()}return e.replace(/\./g,"").toLowerCase()}function pe(e,t){switch(e){case"versions":if(Array.isArray(t)&&t.length>0)return`  /**
   * Available versions from newest to oldest.
   * @see https://ts-pkgx.netlify.app/usage for installation instructions
   */`;break;case"programs":if(Array.isArray(t)&&t.length>0)return`  /**
   * Executable programs provided by this package.
   * These can be run after installation.
   */`;break;case"dependencies":if(Array.isArray(t)&&t.length>0)return`  /**
   * Runtime dependencies for this package.
   * These are required when running the package.${t.some((o)=>typeof o==="string"&&o.includes(":"))?"\n   * OS-specific dependencies are prefixed with `os:` (e.g., `linux:freetype.org`).":""}
   */`;break;case"buildDependencies":if(Array.isArray(t)&&t.length>0)return`  /**
   * Build dependencies for this package.
   * These are only required when building the package from source.${t.some((o)=>typeof o==="string"&&o.includes(":"))?"\n   * OS-specific dependencies are prefixed with `os:` (e.g., `linux:gnu.org/gcc`).":""}
   */`;break;case"companions":if(Array.isArray(t)&&t.length>0)return`  /**
   * Related packages that work well with this package.
   * Consider installing these for enhanced functionality.
   */`;break;case"aliases":if(Array.isArray(t)&&t.length>0)return`  /**
   * Alternative names for this package.
   * You can use any of these names to access the package.
   */`;break;case"installCommand":return`  /**
   * Command to install this package using launchpad.
   * @example launchpad install package-name
   */`;case"description":return`  /**
   * Brief description of what this package does.
   */`;case"domain":return`  /**
   * The canonical domain name for this package.
   */`;case"name":return`  /**
   * The display name of this package.
   */`;default:return null}return null}function te(e){let t=[];t.push("{");for(let[o,n]of Object.entries(e)){if(o==="fetchedAt")continue;let i=pe(o,n);if(i)t.push(i);if(n===void 0){t.push(`  ${o}: undefined,`);continue}if(Array.isArray(n))if(n.length===0)t.push(`  ${o}: [] as const,`);else if(typeof n[0]==="string"){let s=n;if(o==="aliases"){let r=e.name;s=n.filter((c)=>{if(c.includes("--")||c.includes("$SHELL")||c.includes("+")||c.includes("(")||c.includes(")"))return!1;if(c===r)return!1;return!0})}if(s.length===0)t.push(`  ${o}: [] as const,`);else{t.push(`  ${o}: [`);for(let r of s)t.push(`    '${String(r).replace(/'/g,"\\'")}',`);t.push("  ] as const,")}}else{let s=JSON.stringify(n).replace(/"/g,"'");t.push(`  ${o}: ${s} as const,`)}else if(typeof n==="string")t.push(`  ${o}: '${String(n).replace(/'/g,"\\'")}' as const,`);else if(typeof n==="number"||typeof n==="boolean")t.push(`  ${o}: ${n} as const,`);else if(n===null)t.push(`  ${o}: null,`);else if(typeof n==="object")t.push(`  ${o}: ${te(n)},`);else{let s=JSON.stringify(n).replace(/"/g,"'");t.push(`  ${o}: ${s},`)}}return t.push("}"),t.join(`
`)}function de(e,t,o){let n=[];if(n.push("/**"),e.description)n.push(` * **${o}** - ${e.description.trim()}`);else n.push(` * **${o}** - pkgx package`);if(n.push(" *"),n.push(` * @domain \`${e.domain||t}\``),e.programs&&e.programs.length>0){let i=e.programs.slice(0,5).join("`, `"),s=e.programs.length>5?`, ... (+${e.programs.length-5} more)`:"";n.push(` * @programs \`${i}\`${s}`)}if(e.versions&&e.versions.length>0)n.push(` * @version \`${e.versions[0]}\` (${e.versions.length} versions available)`),n.push(" * @versions From newest version to oldest.");if(e.installCommand)n.push(" *"),n.push(` * @install \`${e.installCommand}\``);if(e.aliases&&e.aliases.length>0){let i=e.aliases.filter((s)=>{return!s.includes("--")&&!s.includes("$SHELL")&&!s.includes("+")&&!s.includes("(")&&!s.includes(")")});if(i.length>0){let s=e.name,r=i.filter((l)=>l!==s),c=i.find((l)=>l===s);if(c)n.push(` * @name \`${c}\``);if(r.length>0)n.push(` * @aliases ${r.map((l)=>`\`${l}\``).join(", ")}`)}}if(e.homepageUrl)n.push(` * @homepage ${e.homepageUrl}`);if(e.dependencies&&e.dependencies.length>0){let i=e.dependencies.slice(0,3).join("`, `"),s=e.dependencies.length>3?`, ... (+${e.dependencies.length-3} more)`:"",r=e.dependencies.some((c)=>c.includes(":"))?" (includes OS-specific dependencies with `os:package` format)":"";n.push(` * @dependencies \`${i}\`${s}${r}`)}if(e.buildDependencies&&e.buildDependencies.length>0){let i=e.buildDependencies.slice(0,3).join("`, `"),s=e.buildDependencies.length>3?`, ... (+${e.buildDependencies.length-3} more)`:"",r=e.buildDependencies.some((c)=>c.includes(":"))?" (includes OS-specific dependencies with `os:package` format)":"";n.push(` * @buildDependencies \`${i}\`${s}${r} - required only when building from source`)}if(e.companions&&e.companions.length>0){let i=e.companions.slice(0,3).join("`, `"),s=e.companions.length>3?`, ... (+${e.companions.length-3} more)`:"";n.push(` * @companions \`${i}\`${s}`)}if(n.push(" *"),n.push(" * @example"),n.push(" * ```typescript"),n.push(" * import { pantry } from 'ts-pkgx'"),n.push(" *"),e.aliases&&e.aliases.length>0){let i=e.aliases.find((s)=>{return!s.includes("--")&&!s.includes("$SHELL")&&!s.includes("+")&&!s.includes("(")&&!s.includes(")")});if(i){let s=i.replace(/[^a-z0-9]/gi,""),r=t.replace(/[.-]/g,"").replace(/\//g,"").toLowerCase();if(i===e.name)n.push(" * // Access the package"),n.push(` * const pkg = pantry.${s}`),n.push(" * // Or access via domain"),n.push(` * const samePkg = pantry.${r}`),n.push(" * console.log(pkg === samePkg) // true");else n.push(" * // Access via alias (recommended)"),n.push(` * const pkg = pantry.${s}`),n.push(" * // Or access via domain"),n.push(` * const samePkg = pantry.${r}`),n.push(" * console.log(pkg === samePkg) // true")}else{let s=t.replace(/[.-]/g,"").replace(/\//g,"").toLowerCase();n.push(` * const pkg = pantry.${s}`)}}else{let i=t.replace(/[.-]/g,"").replace(/\//g,"").toLowerCase();n.push(` * const pkg = pantry.${i}`)}if(n.push(` * console.log(pkg.name)        // "${e.name||o}"`),e.description){let i=e.description.length>50?`${e.description.substring(0,47)}...`:e.description;n.push(` * console.log(pkg.description) // "${i}"`)}if(e.programs&&e.programs.length>0)n.push(` * console.log(pkg.programs)    // [${e.programs.slice(0,2).map((i)=>`"${i}"`).join(", ")}${e.programs.length>2?", ...":""}]`);if(e.versions&&e.versions.length>0)n.push(` * console.log(pkg.versions[0]) // "${e.versions[0]}" (latest)`);return n.push(" * ```"),n.push(" *"),n.push(` * @see https://ts-pkgx.netlify.app/packages/${t.replace(/\./g,"-")}.md`),n.push(" * @see https://ts-pkgx.netlify.app/usage"),n.push(" */"),n.join(`
`)}function ge(e,t){function o(l){if(!l||l.length<2)return!1;if(l.includes("--")||l.includes("$SHELL")||l.includes("+")||l.includes("(")||l.includes(")"))return!1;if(["cli","app","tool","server","client","api","lib","core"].includes(l.toLowerCase()))return!1;if(/^\d+(?:\.\d+)*/.test(l))return!1;return!0}let n,i;if(t==="classic.yarnpkg.com")n="classicYarnPackage",i="yarn";else if(t==="yarnpkg.com")n="yarnPackage",i="yarn";else if(e.aliases&&e.aliases.length>0){let l=e.aliases.find((a)=>o(a));if(l){let a=l.replace(/[^a-z0-9]/gi,"");n=`${a.charAt(0).toLowerCase()}${a.slice(1)}Package`,i=l}else n=`${Q(t)}Package`,i=e.name||t}else n=`${Q(t)}Package`,i=e.name||t;let s=n.replace(/[^\w$]/g,""),r=de(e,t,i),c=te(e);return`${r}
export const ${s} = ${c}

export type ${s.charAt(0).toUpperCase()+s.slice(1)} = typeof ${s}
`}function ie(e){let t=e.replace(/\{\{[^}]*\}\}/g,"").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");if(!t||t.length===0)return"package";let o=t.replace(/[^\w.-]/g,"-");if(o.length>200)o=`${o.substring(0,150)}...${o.substring(o.length-45)}`;return o}function T(e,t,o){if(!y.existsSync(e))y.mkdirSync(e,{recursive:!0});let n;if(t.includes("/")){let r=t.split("/"),c=r[0],l=r.slice(1),a=j.join(e,c,...l.slice(0,-1));if(!y.existsSync(a))y.mkdirSync(a,{recursive:!0});let d=ie(l[l.length-1]);n=j.join(a,`${d}.ts`)}else{let r=t.replace(/\./g,"");n=j.join(e,`${r}.ts`)}let i={...o};delete i.fetchedAt;let s=ge(i,t);return y.writeFileSync(n,s),n}function he(e,t={}){try{let o=t.cacheDir||H;if(t.cache===!1)return console.log(`Cache disabled for ${e}, skipping cache check`),null;let n=(U[e]||e).replace(/\//g,"-"),i=j.join(o,`${n}.json`);if(console.log(`Checking for cache file: ${i}`),!y.existsSync(i))return null;let s=JSON.parse(y.readFileSync(i,"utf-8"));if(!s.fetchedAt)return console.log(`Cache for ${e} missing fetchedAt timestamp, invalidating`),null;if(["Crafters of fine Open Source products","Go home.","Package information for","pkgx package","Loading...","Please wait..."].some((l)=>s.description&&s.description.includes(l)))return console.log(`Cache for ${e} has generic description "${s.description}", invalidating`),null;if(!s.versions||s.versions.length===0)return console.log(`Cache for ${e} has no versions, invalidating`),null;let r=(t.cacheExpirationMinutes||K)*60*1000,c=Date.now();if(c-s.fetchedAt>r)return console.log(`Cache for ${e} has expired (age: ${Math.round((c-s.fetchedAt)/60000)} minutes)`),null;return console.log(`Using cached data for ${e} (age: ${Math.round((c-s.fetchedAt)/60000)} minutes)`),{packageInfo:s,filePath:i}}catch(o){return console.error(`Error reading cache for ${e}:`,o),null}}function fe(e,t,o={}){let n={...t,fetchedAt:Date.now()},i=o.cacheDir||H;if(!y.existsSync(i))y.mkdirSync(i,{recursive:!0});let s=e.replace(/\//g,"-"),r=j.join(i,`${s}.json`);y.writeFileSync(r,JSON.stringify(n,null,2));let c=o.outputDir||"packages";if(!y.existsSync(c))y.mkdirSync(c,{recursive:!0});let l=T(c,e,t);return{cachePath:r,outputPath:l}}function se(){return Promise.resolve()}async function Je(e={}){let t=e.apiUrl||"https://api.github.com/repos/pkgxdev/pantry/contents/projects";try{console.log(`Fetching projects from GitHub API: ${t}`);let o=await fetch(t,{headers:{Accept:"application/vnd.github.v3+json"}});if(!o.ok)throw Error(`Failed to fetch from GitHub API: ${o.statusText}`);let n=(await o.json()).filter((i)=>i.type==="dir").map((i)=>({name:i.name,url:i.html_url}));return console.log(`Retrieved ${n.length} projects from GitHub API`),n.sort((i,s)=>i.name.localeCompare(s.name)),n}catch(o){throw console.error("Error fetching projects from GitHub API:",o),o}}async function B(e,t={}){let o=e,n=e;if(e.includes("/")){let[i,s]=e.split("/");console.log(`Identified nested package: domain=${i}, name=${s}`)}if(U[e])console.log(`'${e}' is an alias for '${U[e]}', redirecting...`),n=U[e],e=U[e];try{let i=t.timeout||X,s=await ne(e,{timeout:i,useClientSideScraper:!0}),r={name:s.displayName||s.name||e.split("/").pop()||e,domain:s.domain||e,description:s.description||s.brief||"",packageYmlUrl:`https://github.com/pkgxdev/pantry/tree/main/projects/${e}/package.yml`,homepageUrl:s.homepage||"",githubUrl:s.github||"",installCommand:`launchpad install ${e}`,pkgxInstallCommand:`sh <(curl https://pkgx.sh) +${e} -- $SHELL -i`,launchpadInstallCommand:`launchpad install ${e}`,programs:s.provides||[],companions:Array.isArray(s.companions)?s.companions:[],dependencies:Array.isArray(s.dependencies)?s.dependencies:[],buildDependencies:s.buildDependencies||[],versions:s.versions||[],aliases:[]};if(!r.versions||r.versions.length===0){let c=r.domain||e;if(!["apache.org","breakfastquay.com","catb.org","bloomreach.com","cairographics.org","certifi.io","charm.sh","aws.amazon.com","google.com","microsoft.com","mozilla.org","freedesktop.org","gnome.org","kde.org","sourceforge.net","sf.net"].some((l)=>c.startsWith(l)))try{let l=r.domain||e,a=await me(l);r.versions=a}catch(l){console.warn(`Failed to fetch versions for ${e} from GitHub API:`,l),r.versions=[]}}if(r.versions&&r.versions.length>0)try{r.versions.sort((c,l)=>{try{return-1*Bun.semver.order(c,l)}catch{return l.localeCompare(c)}})}catch(c){console.warn(`Warning: Failed to sort versions for ${e} using semver:`,c)}return r.name=r.name||o,r.domain=r.domain||n,r.programs=r.programs||[],r.companions=r.companions||[],r.dependencies=r.dependencies||[],r.versions=r.versions||[],{packageInfo:r,originalName:o,fullDomainName:n}}catch(i){return console.error(`Error in fetchPantryPackage for ${e}:`,i),ye(e,o,n)}}async function me(e){try{let{shouldProceedWithGitHubRequest:t,saveRateLimitInfo:o}=await import("./chunk-dzbc6g1z.js");if(!t())return console.warn("Skipping GitHub API request for versions due to rate limiting"),[];let n=await fetch(`https://api.github.com/repos/pkgxdev/pantry/contents/projects/${e}`,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"ts-pkgx"},signal:AbortSignal.timeout(15000)});if(o(n.headers),n.status===403){let i=n.headers.get("X-RateLimit-Remaining"),s=n.headers.get("X-RateLimit-Reset"),r=s?new Date(Number(s)*1000).toLocaleString():"unknown";return console.warn(`GitHub API rate limit exceeded. Remaining: ${i||0}, Reset: ${r}`),[]}if(!n.ok)throw Error(`GitHub API responded with ${n.status}: ${n.statusText}`);return(await n.json()).filter((i)=>i.name.match(/^v\d+/)).map((i)=>i.name)}catch(t){return console.error("Error fetching versions from GitHub:",t),[]}}var $e=300000,R=null;function ke(){let e=async(t)=>{if(console.log(`
Received ${t} signal. Cleaning up resources...`),R)clearInterval(R);await se(),console.log("Resources cleaned up. Exiting."),setTimeout(()=>{console.log("Forcing process exit..."),I.exit(0)},5000)};I.on("SIGINT",()=>e("SIGINT")),I.on("SIGTERM",()=>e("SIGTERM")),I.on("uncaughtException",(t)=>{console.error("Uncaught exception:",t),e("uncaughtException")})}ke();I.on("uncaughtException",(e)=>{let t=String(e);if(console.error("Uncaught exception caught:",e.message),e.message.includes("No target found for targetId")||e.message.includes("Assertion error")||e.message.includes("Target page, context or browser has been closed")||e.message.includes("Failed to connect")||e.message.includes("Connection closed")||e.message.includes("Protocol error")||t.includes("WebSocket connection closed")||e.message.includes("Browser has been closed")){console.error("Browser/network connection error detected, continuing execution...");return}console.error("Non-browser error, exiting..."),I.exit(1)});I.on("unhandledRejection",(e,t)=>{let o=String(e);if(console.error("Unhandled rejection caught:",o),o.includes("No target found for targetId")||o.includes("Assertion error")||o.includes("Target page, context or browser has been closed")||o.includes("Failed to connect")||o.includes("Connection closed")||o.includes("Protocol error")||o.includes("WebSocket connection closed")||o.includes("Browser has been closed")){console.error("Browser/network connection error in promise, continuing execution...");return}console.error("Non-browser promise rejection, exiting..."),I.exit(1)});function Le(){if(R)clearInterval(R);R=setInterval(()=>{console.log("Running periodic browser resource cleanup..."),se().then(()=>console.log("Periodic cleanup completed")).catch((e)=>console.error("Error during periodic cleanup:",e))},$e)}async function Ge(e={}){let t=e.timeout||X,o=e.outputDir||"packages",n=e.cacheDir||H,i=e.cache!==!1,s=e.cacheExpirationMinutes||K,r=Math.min(e.concurrency||6,8),c=e.pantryDir||"src/pantry";if(!e.outputJson)console.log(`Starting bulk fetch with concurrency: ${r}, timeout: ${t}ms`);let l=Date.now(),a=[];try{if(!e.outputJson)console.log("Scanning local pantry for packages...");try{if(a=await be(c),!e.outputJson)console.log(`Found ${a.length} packages in local pantry`)}catch(p){if(!e.outputJson)console.warn("Failed to scan local pantry, falling back to consts:",p);try{let{ALL_KNOWN_PACKAGES:$}=await import("./chunk-z0wja48y.js");if(a=[...$].filter((w)=>w&&w!=="undefined"&&w!=="aliases"&&w!=="index"),!e.outputJson)console.log(`Using comprehensive package list: ${a.length} packages`)}catch($){if(!e.outputJson)console.warn("Failed to load consts, falling back to GitHub API:",$);try{let w=await fetch("https://api.github.com/repos/pkgxdev/pantry/contents/projects",{headers:{"User-Agent":"ts-pkgx-fetcher",Accept:"application/vnd.github.v3+json"}});if(w.ok){let k=(await w.json()).filter((P)=>P.type==="dir").map((P)=>P.name).sort();if(!e.outputJson)console.log(`Retrieved ${k.length} projects from GitHub API`);a=k}else throw Error(`GitHub API returned ${w.status}`)}catch(w){if(!e.outputJson)console.warn("Failed to fetch from GitHub API, falling back to local discovery:",w);if(y.existsSync(o))a=y.readdirSync(o).filter((k)=>k.endsWith(".ts")).map((k)=>j.basename(k,".ts")),console.log(`Found ${a.length} existing packages`)}}}if(a.length===0)return console.error("No packages found to process"),[];let d=["android.com","apache.org","akuity.io","alsa-project.org","anchore.com","aomedia.googlesource.com","apollographql.com","facebook.com","google.com","microsoft.com","mozilla.org","sourceforge.net","x.org","xiph.org","yui.github.io","crates.io","gitlab.com","github.com"],x=new Set,S=a.filter((p)=>p.startsWith("github.com/"));for(let p of S){let $=p.split("/");if($.length>2){let w=$.slice(0,2).join("/");x.add(w)}}if(a=a.filter((p)=>{if(p.endsWith("/.pkgroot"))return console.log(`Filtering out .pkgroot marker: ${p}`),!1;if(p.endsWith("/README.rst"))return console.log(`Filtering out README.rst documentation: ${p}`),!1;if(p==="agwa.name")return console.log("Filtering out standalone agwa.name - only agwa.name/git-crypt is valid"),!1;if(d.includes(p))return console.log(`Filtering out parent domain ${p} - only has nested packages`),!1;if(x.has(p))return console.log(`Filtering out GitHub parent path ${p} - only has nested packages`),!1;if(p==="undefined"||p==="aliases"||p==="index")return!1;return!0}),console.log(`Found ${a.length} packages to process`),e.limit&&e.limit>0)a=a.slice(0,e.limit),console.log(`Limited to ${a.length} packages`);let h=[],b=[],u=0,g=Math.min(r,6),m=[];for(let p=0;p<a.length;p+=g)m.push(a.slice(p,p+g));if(!e.outputJson)console.log(`Processing ${a.length} packages in ${m.length} batches...`);for(let p=0;p<m.length;p++){let $=m[p];if(!e.outputJson)console.log(`Processing batch ${p+1}/${m.length} (${$.length} packages)`);let w=$.map(async(f)=>{try{let C=j.join(n,`${f.replace(/\//g,"-")}.json`);if(i&&y.existsSync(C)){let G=y.statSync(C),J=(Date.now()-G.mtime.getTime())/60000;if(J<s){if(!e.outputJson)console.log(`Using cached data for ${f} (age: ${Math.round(J)} minutes)`);try{let M=JSON.parse(y.readFileSync(C,"utf-8"));delete M.fetchedAt;let N=T(o,f,M);if(!e.outputJson)console.log(`Using cached data for ${f} (saved to ${N})`);return{success:!0,packageName:f}}catch{console.warn(`Cache file corrupted for ${f}, will refetch`)}}}let L=await xe(f,{...e,pantryDir:c,timeout:t,cache:i,cacheDir:n,cacheExpirationMinutes:s});if(L){let{outputPath:G}=fe(f,L.packageInfo,{cacheDir:n,outputDir:o,cache:i});if(!e.outputJson)console.log(`Successfully processed ${f} (saved to ${G})`);return{success:!0,packageName:f}}else return console.warn(`Failed to fetch ${f}`),{success:!1,packageName:f}}catch(C){return console.error(`Error processing ${f}:`,C),{success:!1,packageName:f}}}),k=await Promise.allSettled(w);for(let f of k)if(u++,f.status==="fulfilled")if(f.value.success)h.push(f.value.packageName);else b.push(f.value.packageName);else console.error("Batch promise rejected:",f.reason),b.push("unknown");let P=Math.round((Date.now()-l)/1000),D=Math.round(u/P*10)/10,F=Math.round((a.length-u)/D);if(!e.outputJson)console.log(`Batch ${p+1}/${m.length} complete. Progress: ${u}/${a.length} (${Math.round(u/a.length*100)}%) | Success: ${h.length} | Failed: ${b.length} | Rate: ${D}/s | ETA: ${F}s`);if(p<m.length-1)await new Promise((f)=>setTimeout(f,1000))}let v=Math.round((Date.now()-l)/1000);if(!e.outputJson){if(console.log(`
Completed in ${v}s. Successfully processed: ${h.length}, Failed: ${b.length}`),b.length>0)console.log(`Failed packages: ${b.slice(0,10).join(", ")}${b.length>10?` ... and ${b.length-10} more`:""}`)}return h}catch(d){return console.error("Error in fetchAndSaveAllPackages:",d),[]}}function ye(e,t,o){let n=e.split("/"),i=n[0];return{packageInfo:{name:(n.length>1?n.slice(1).join("/"):null)||e,domain:i,description:`Package information for ${e}`,packageYmlUrl:"",homepageUrl:"",githubUrl:"",installCommand:`launchpad install ${e}`,pkgxInstallCommand:`sh <(curl https://pkgx.sh) +${e} -- $SHELL -i`,launchpadInstallCommand:`launchpad install ${e}`,programs:[],companions:[],dependencies:[],versions:[]},originalName:t,fullDomainName:o}}async function we(e,t,o,n=!1,i=1,s=3,r=!1,c={}){try{let l=c.cache!==!1,a=c.cacheDir||H;if(!l)console.log(`Cache disabled for ${e}, will fetch directly`);else{let h=he(e,{cacheDir:a,cacheExpirationMinutes:c.cacheExpirationMinutes,cache:c.cache});if(h){let{packageInfo:b}=h,u=b.domain||e,g=b.aliases||[],m=T(t,e,b);return console.log(`Using cached data for ${e} (saved to ${m})`),{success:!0,fullDomainName:u,aliases:g,filePath:m}}}let d=o+(i-1)*1e4;console.log(`Using timeout for ${e} (attempt ${i}): ${d}ms`);let x=d,S=new Promise((h,b)=>{setTimeout(()=>{console.error(`Operation timeout for ${e} after ${x}ms`),b(Error(`Operation timeout after ${x}ms`))},x)});if(e.includes("/")){let h=e.split("/"),b=h[0],u=h.slice(1).join("/");console.log(`Processing nested package: domain=${b}, subPath=${u}`);try{let g=B(`${b}/${u}`,{timeout:d,browser:c.browser}),m=await Promise.race([g,S]),{packageInfo:v,originalName:p,fullDomainName:$}=m;if(v.versions&&v.versions.length>0)try{v.versions.sort((f,C)=>{try{return-1*Bun.semver.order(f,C)}catch{return C.localeCompare(f)}})}catch(f){console.warn(`Warning: Failed to sort versions for ${e} using semver:`,f)}let w=$.replace(/\//g,"-"),k=[];if(v.aliases&&v.aliases.length>0)k.push(...v.aliases);for(let[f,C]of Object.entries(U))if(C===$&&!k.includes(f))k.push(f);if(p!==$&&!k.includes(p))k.push(p);let P=["cli","app","tool","server","client","api","lib","core"];if(!k.includes(u)&&!P.includes(u.toLowerCase()))k.push(u);let D={...v,fullPath:e,aliases:k.length>0?k:[]};if(l){let f=j.join(a,`${w}.json`),C={...D,fetchedAt:Date.now()};if(!y.existsSync(a))y.mkdirSync(a,{recursive:!0});y.writeFileSync(f,JSON.stringify(C,null,2)),console.log(`Saved package data to cache: ${f}`)}let F=T(t,$,D);return console.log(`Successfully saved nested package ${e} to ${F} with aliases: ${k.join(", ")||"none"}`),{success:!0,fullDomainName:$,aliases:k,filePath:F}}catch(g){if(g.toString().includes("404")||g.toString().includes("Not Found"))return console.error(`Package ${e} returned 404 Not Found.`),console.error(`Skipping ${e} to avoid overwriting existing files.`),{success:!1,fullDomainName:e};throw g}}else try{let h=B(e,{timeout:d,browser:c.browser}),b=await Promise.race([h,S]),{packageInfo:u,originalName:g,fullDomainName:m}=b,v=u.description&&u.description.trim()!=="",p=u.versions&&u.versions.length>0,$=u.programs&&u.programs.length>0,w=u.packageYmlUrl&&u.packageYmlUrl.length>0,k=u.dependencies&&u.dependencies.length>0,P=u.companions&&u.companions.length>0,D=v&&(u.description.toLowerCase().trim()==="go home."||u.description.toLowerCase().trim()==="page not found"||u.description.toLowerCase().trim()==="not found"||u.description.toLowerCase().trim()==="404"||u.description.toLowerCase().trim()==="error"),F=v&&!D,f=p||$||w||k||P,C=u.domain&&u.domain.includes(".");if(!(F||f||C))return console.error(`Package ${e} appears to have no meaningful data. Skipping to avoid creating empty files.`),{success:!1,fullDomainName:e};let L=u.name&&u.name!==m&&u.name!==m.split("/")[0]&&u.name.length>1&&!u.name.includes("/")?ie(u.name):null,G=m.replace(/\//g,"-"),J=L?j.join(t,`${L}.ts`):j.join(t,`${G}.ts`);if(y.existsSync(J)){let A=y.readFileSync(J,"utf-8"),E=A.includes("dependencies: [")&&!A.includes("dependencies: [] as const"),Z=u.dependencies.length===0,Y=!A.includes("description: 'Package information for")&&!A.includes("description: '' as const"),V=u.description.includes("Package information for")||u.description.trim()==="";if(E&&Z||Y&&V)return console.warn(`\u26A0\uFE0F  Existing file ${J} has better data than new fetch. Skipping to prevent data loss.`),console.warn(`   Existing deps: ${E}, New deps: ${!Z}`),console.warn(`   Existing desc: ${Y}, New desc: ${!V}`),{success:!1,fullDomainName:e}}if(u.versions&&u.versions.length>0)try{u.versions.sort((A,E)=>{try{return-1*Bun.semver.order(A,E)}catch{return E.localeCompare(A)}})}catch(A){console.warn(`Warning: Failed to sort versions for ${e} using semver:`,A)}let M=m.replace(/\//g,"-"),N=[];if(u.aliases&&u.aliases.length>0)N.push(...u.aliases);for(let[A,E]of Object.entries(U))if(E===m&&!N.includes(A))N.push(A);if(g!==m&&!N.includes(g))N.push(g);let _={...u,fullPath:e,aliases:N.length>0?N:[]};if(l){let A=j.join(a,`${M}.json`),E={..._,fetchedAt:Date.now()};if(!y.existsSync(a))y.mkdirSync(a,{recursive:!0});y.writeFileSync(A,JSON.stringify(E,null,2)),console.log(`Saved package data to cache: ${A}`)}let z=T(t,m,_);return console.log(`Successfully saved ${e} to ${z} with aliases: ${N.join(", ")||"none"}`),{success:!0,fullDomainName:m,aliases:N,filePath:z}}catch(h){if(h.toString().includes("404")||h.toString().includes("Not Found"))return console.error(`Package ${e} returned 404 Not Found. Skipping to avoid overwriting existing files.`),{success:!1,fullDomainName:e};throw h}}catch(l){let a=String(l),d=a.includes("Operation timed out after")||a.includes("Operation timeout after")||a.includes("timeout")||a.includes("Timeout")||a.includes("Navigation timeout"),x=a.includes("No target found")||a.includes("targetId")||a.includes("Target page, context or browser has been closed")||a.includes("Protocol error")||a.includes("Connection closed")||a.includes("Assertion error")||a.includes("Browser has been closed")||a.includes("Target closed")||a.includes("Session closed")||a.includes("WebSocket connection closed");if(d)console.error(`Timeout error for ${e}:`,a.substring(0,200)),await new Promise((h)=>setTimeout(h,1000*i));else if(x){if(console.error(`Browser connection error for ${e}:`,a.substring(0,200)),c.browser)try{await c.browser.close().catch(()=>{})}catch{}await new Promise((h)=>setTimeout(h,3000*i))}if(i>=s){if(console.error(`Failed to fetch package ${e} after ${i} attempts:`,l),r){let h=j.join(I.cwd(),`${e.replace(/\//g,"-")}-error.txt`);y.writeFileSync(h,`Error fetching ${e}:
${l.toString()}

Stack:
${l.stack||"No stack trace available"}`),console.error(`Saved error details to ${h}`)}return console.error(`Skipping ${e} after ${i} failed attempts to avoid overwriting existing files.`),{success:!1,fullDomainName:e}}console.error(`Attempt ${i} failed for ${e}, retrying...`,l);let S=500*i;if(x)S=2000*i;else if(d)S=1000*i;return await new Promise((h)=>setTimeout(h,S)),we(e,t,o,n,i+1,s,r,c)}}async function be(e="src/pantry"){if(!y.existsSync(e))throw Error(`Pantry directory not found: ${e}. Please run 'bun ./bin/cli.ts update-pantry' first.`);let t=[];function o(n,i=""){let s=y.readdirSync(n,{withFileTypes:!0}),r=j.join(n,"package.yml");if(i&&y.existsSync(r))t.push(i);for(let c of s)if(c.isDirectory()&&!c.name.startsWith(".")){let l=i?`${i}/${c.name}`:c.name,a=j.join(n,c.name);o(a,l)}}return o(e),console.log(`Found ${t.length} packages in pantry`),t.sort()}async function ve(e,t="src/pantry"){let o=j.join(t,e,"package.yml");if(!y.existsSync(o))return console.warn(`Package.yml not found for ${e}`),null;try{let n=y.readFileSync(o,"utf-8"),i=[],s=[],r=n.split(`
`),c=!1,l=!1,a=!1,d="";for(let g of r){if(g.match(/^dependencies:\s*$/)){c=!0,l=!1,a=!1;continue}if(g.match(/^\s{2}dependencies:\s*$/)){l=!0,c=!1,a=!1;continue}if(c||l){if(g.match(/^\s*$/)||c&&g.match(/^\S/)||l&&!g.match(/^\s{4,}/)){c=!1,l=!1,a=!1;continue}let m=g.match(/^\s{2}(linux|darwin|windows):\s*$/);if(m){a=!0,d=m[1];continue}if(a){let v=g.match(/^\s{4,}([^\s:]+):\s*['"]?([^'"]+)['"]?/);if(v){let p=v[1],$=v[2].trim(),w=`${d}:`;if($&&$!=="*"){let k=/^[~^>=<@]/.test($),P=/^\d+(?:\.\d+)*$/.test($),D=`${w}${p}${k?"":P?"@":"^"}${$}`;if(l)s.push(D);else i.push(D)}else{let k=`${w}${p}`;if(l)s.push(k);else i.push(k)}}else if(!g.match(/^\s{4,}/)&&!g.match(/^\s*$/))a=!1,d=""}else{let v=g.match(/^\s{2,3}([^\s:]+):\s*['"]?([^'"]+)['"]?/);if(v){let p=v[1],$=v[2].trim();if(["linux","darwin","windows"].includes(p))continue;if($&&$!=="*"){let w=/^[~^>=<@]/.test($),k=/^\d+(?:\.\d+)*$/.test($),P=`${p}${w?"":k?"@":"^"}${$}`;if(l)s.push(P);else i.push(P)}else{let w=p;if(l)s.push(w);else i.push(w)}}}}}let x=[],S=!1;for(let g of r){if(g.match(/^runtime:\s*$/)){S=!0;continue}if(S){if(g.match(/^\s*$/)||g.match(/^\S/)){S=!1;continue}if(g.match(/^\s+env:\s*$/))continue;if(g.match(/^\s+[A-Z_]+:\s*\$\{\{/))continue;let m=g.match(/^\s+([^\s:]+):\s*['"]?([^'"]+)['"]?/);if(m){let v=m[1],p=m[2].trim();if(/^[A-Z_]+$/.test(v))continue;if(p&&p!=="*"){let $=/^[~^>=<@]/.test(p),w=/^\d+(?:\.\d+)*$/.test(p),k=$?"":w?"@":"^";x.push(`${v}${k}${p}`)}else x.push(v)}}}let h="",b="",u=n.match(/distributable:[\t\v\f\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*\n\s*url:\s*(.+)/);if(u){let g=u[1].trim();if(g.includes("github.com")){let m=g.match(/git\+https:\/\/github\.com\/([^/]+\/[^.]+)/);if(m){if(b=`https://github.com/${m[1]}`,m[1]==="python-attrs/attrs")h="https://www.attrs.org/"}}}return{name:e.split("/").pop()||e,domain:e,dependencies:i,buildDependencies:s,companions:x,homepageUrl:h,githubUrl:b}}catch(n){return console.warn(`Error reading package.yml for ${e}:`,n),null}}async function xe(e,t={}){let o=t.pantryDir||"src/pantry";try{let n=await ve(e,o);if(!n)return console.warn(`No pantry information found for ${e}`),null;try{let i=await B(e,t),s=n.domain||i.packageInfo.domain,r=oe(s),c=i.packageInfo.aliases||[];if(r.length>0)if(ae(s))c=r;else c=[...new Set([...c,...r])];return{packageInfo:{...i.packageInfo,dependencies:n.dependencies&&n.dependencies.length>0?n.dependencies:i.packageInfo.dependencies,buildDependencies:n.buildDependencies&&n.buildDependencies.length>0?n.buildDependencies:i.packageInfo.buildDependencies,companions:n.companions&&n.companions.length>0?n.companions:i.packageInfo.companions,domain:n.domain||i.packageInfo.domain,name:i.packageInfo.name||n.name||e.split("/").pop()||e,homepageUrl:n.homepageUrl||i.packageInfo.homepageUrl,githubUrl:n.githubUrl||i.packageInfo.githubUrl,aliases:c},originalName:i.originalName,fullDomainName:i.fullDomainName}}catch(i){return console.warn(`Failed to fetch web metadata for ${e}, using pantry data only:`,i),{packageInfo:{name:n.name||e.split("/").pop()||e,domain:n.domain||e,description:`Package from pantry: ${e}`,installCommand:`launchpad install ${e}`,pkgxInstallCommand:`sh <(curl https://pkgx.sh) +${e} -- $SHELL -i`,launchpadInstallCommand:`launchpad install ${e}`,programs:[],companions:n.companions||[],dependencies:n.dependencies||[],versions:[],packageYmlUrl:`https://github.com/pkgxdev/pantry/tree/main/projects/${e}/package.yml`,homepageUrl:"",githubUrl:""},originalName:e,fullDomainName:e}}}catch(n){return console.error(`Error processing pantry package ${e}:`,n),null}}export{Ie as eb,ne as fb,Ue as gb,Fe as hb,T as ib,he as jb,fe as kb,se as lb,Je as mb,B as nb,ke as ob,Le as pb,Ge as qb,we as rb,be as sb,ve as tb,xe as ub};

//# debugId=DAA631EBEC5E50C564756E2164756E21
