import{yb as R,zb as T}from"./chunk-jkfbbcs7.js";import{oc as V}from"./chunk-ghzc37v7.js";import O from"node:fs";import _ from"node:path";function N(j,q){let J=R(j);if(J.length===0)return q;if(T(j))return J;return[...new Set([...q,...J])]}function C(j){let q=[],J=O.readdirSync(j,{withFileTypes:!0});for(let w of J){let E=_.join(j,w.name);if(w.isDirectory())q.push(...C(E));else if(w.isFile()&&w.name.endsWith(".ts")&&w.name!=="index.ts"&&w.name!=="aliases.ts")q.push(E)}return q}function M(j,q){let J=j.split("."),w=q.split("."),E=Math.max(J.length,w.length);for(let Q=0;Q<E;Q++){let H=J[Q],U=w[Q];if(H===void 0)return-1;if(U===void 0)return 1;let X=/^\d+$/.test(H),Y=/^\d+$/.test(U);if(X&&Y){let I=Number.parseInt(H,10)-Number.parseInt(U,10);if(I!==0)return I}else if(X!==Y)return X?-1:1;else if(H!==U)return H<U?-1:1}return 0}function y(j,q){let J=(j.startsWith("v")?j.slice(1):j).split("+")[0],w=(q.startsWith("v")?q.slice(1):q).split("+")[0],E=J.indexOf("-"),Q=E===-1?J:J.slice(0,E),H=E===-1?null:J.slice(E+1),U=w.indexOf("-"),X=U===-1?w:w.slice(0,U),Y=U===-1?null:w.slice(U+1),I=Q.split("."),W=X.split(".");for(let $=0;$<Math.max(I.length,W.length);$++){let L=Number.parseInt(I[$]||"0",10),z=Number.parseInt(W[$]||"0",10);if(L>z)return-1;if(L<z)return 1}if(H===null&&Y!==null)return-1;if(H!==null&&Y===null)return 1;if(H!==null&&Y!==null){let $=M(H,Y);return $===0?0:-$}return 0}function G(j){return j.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function b(j){let q=j.programs.map((H)=>`"${G(H)}"`).join(", "),J=j.dependencies.map((H)=>`"${G(H)}"`).join(", "),w=j.buildDependencies.map((H)=>`"${G(H)}"`).join(", "),E=j.aliases.map((H)=>`"${G(H)}"`).join(", "),Q=j.versions.map((H)=>`"${G(H)}"`).join(", ");return`    .{
        .name = "${G(j.name)}",
        .domain = "${G(j.domain)}",
        .description = "${G(j.description)}",
        .homepage_url = ${j.homepageUrl?`"${G(j.homepageUrl)}"`:"null"},
        .programs = &[_][]const u8{ ${q} },
        .dependencies = &[_][]const u8{ ${J} },
        .build_dependencies = &[_][]const u8{ ${w} },
        .aliases = &[_][]const u8{ ${E} },
        .versions = &[_][]const u8{ ${Q} },
    }`}function K(j){let q=j,J=q.indexOf("#");if(J>=0)q=q.slice(0,J);q=q.trim();let w="",E=q.indexOf(":");if(E>=0&&["linux","darwin","windows"].includes(q.slice(0,E)))w=`${q.slice(0,E)}:`,q=q.slice(E+1);let Q=q.search(/[\^~><=@]/),H=(Q>=0?q.slice(0,Q):q).trim();return w+H}function v(j){if(!j||typeof j!=="object")return[];let q=(w)=>{let E=(w||"").trim();if(E===""||E==="*")return"";return/^[\^~><=@]/.test(E)?E:`@${E}`},J=[];for(let[w,E]of Object.entries(j))if((w==="linux"||w==="darwin"||w==="windows")&&E&&typeof E==="object")for(let[Q,H]of Object.entries(E))J.push(`${w}:${Q}${q(H)}`);else if(typeof E==="string")J.push(`${w}${q(E)}`);return J}async function P(j,q){let J=_.join(j,`${q}.ts`);if(!O.existsSync(J))return[];try{let w=await import(`file://${_.resolve(J)}`);return v(w.recipe?.dependencies)}catch{return[]}}function S(j,q){let J=new Set(j.map(K)),w=[...j];for(let E of q){let Q=K(E);if(!J.has(Q))J.add(Q),w.push(E)}return w}async function h(j,q){console.log(`\uD83D\uDD0D Scanning packages directory: ${j}`);let J=_.resolve(j,"..","recipes"),w=C(j);console.log(`\uD83D\uDCE6 Found ${w.length} package files`);let E=[],Q=0,H=0;for(let X of w)try{let I=O.readFileSync(X,"utf-8").match(/export const (\w+) = \{/);if(!I){console.warn(`⚠️  Could not find export const in ${X}`),H++;continue}let L=(await import(`file://${_.resolve(X)}`))[I[1]];if(!L||!L.domain){console.warn(`⚠️  Invalid package data in ${X}`),H++;continue}let z=Array.isArray(L.versions)?[...L.versions].sort(y):[];if(E.push({name:L.name||L.domain,domain:L.domain,description:L.description||"",homepageUrl:L.homepageUrl,programs:Array.isArray(L.programs)?L.programs:[],dependencies:S(Array.isArray(L.dependencies)?L.dependencies:[],await P(J,L.domain)),buildDependencies:Array.isArray(L.buildDependencies)?L.buildDependencies:[],aliases:N(L.domain,Array.isArray(L.aliases)?L.aliases:[]),versions:z}),Q++,Q%100===0)console.log(`  Processed ${Q}/${w.length} packages...`)}catch(Y){console.error(`❌ Error processing ${X}:`,Y),H++}console.log(`✅ Processed ${Q} packages (${H} errors)`),E.sort((X,Y)=>X.domain.localeCompare(Y.domain));let U=F(E);O.writeFileSync(q,U,"utf-8"),console.log(`✅ Generated Zig definitions: ${q}`),console.log(`\uD83D\uDCCA Total packages: ${E.length}`),Z(q)}function Z(j){try{let{execFileSync:q}=V("node:child_process");q("zig",["fmt",j],{stdio:"ignore"}),console.log(`✨ Formatted with zig fmt: ${j}`)}catch{}}function F(j){let q=j.map((J)=>b(J)).join(`,
`);return`//! Package definitions generated from ts-pantry
//! DO NOT EDIT MANUALLY - This file is auto-generated
//! Total packages: ${j.length}

const std = @import("std");

/// Package information
pub const PackageInfo = struct {
    name: []const u8,
    domain: []const u8,
    description: []const u8,
    homepage_url: ?[]const u8,
    programs: []const []const u8,
    dependencies: []const []const u8,
    build_dependencies: []const []const u8,
    aliases: []const []const u8,
    versions: []const []const u8,
};

/// All known packages (${j.length} total)
pub const packages = [_]PackageInfo{
${q}
};

/// Get package by domain name
pub fn getPackageByDomain(domain: []const u8) ?*const PackageInfo {
    for (&packages) |*pkg| {
        if (std.mem.eql(u8, pkg.domain, domain)) {
            return pkg;
        }
    }
    return null;
}

/// Get package by name (checks domain and aliases)
pub fn getPackageByName(name: []const u8) ?*const PackageInfo {
    for (&packages) |*pkg| {
        // Check domain
        if (std.mem.eql(u8, pkg.domain, name)) {
            return pkg;
        }

        // Check full name
        if (std.mem.eql(u8, pkg.name, name)) {
            return pkg;
        }

        // Check aliases
        for (pkg.aliases) |alias| {
            if (std.mem.eql(u8, alias, name)) {
                return pkg;
            }
        }
    }
    return null;
}

/// Get all package domains
pub fn getAllDomains(allocator: std.mem.Allocator) ![][]const u8 {
    // eslint-disable-next-line prefer-const
    var domains = try allocator.alloc([]const u8, packages.len);
    for (packages, 0..) |pkg, i| {
        domains[i] = pkg.domain;
    }
    return domains;
}

/// Get total package count
pub fn getPackageCount() usize {
    return packages.len;
}

test "Package registry has entries" {
    try std.testing.expect(packages.len > 0);
}

test "Can find node package" {
    const node = getPackageByName("node");
    if (node) |pkg| {
        try std.testing.expectEqualStrings("nodejs.org", pkg.domain);
    }
}

test "Can find package by domain" {
    const node = getPackageByDomain("nodejs.org");
    try std.testing.expect(node != null);
}

test "Can find package by alias" {
    const bun = getPackageByName("bun");
    if (bun) |pkg| {
        try std.testing.expect(
            std.mem.eql(u8, pkg.domain, "bun.sh") or
            std.mem.eql(u8, pkg.domain, "bun.com")
        );
    }
}
`}async function f(j,q){console.log(`\uD83D\uDD0D Generating Zig aliases from: ${j}`);let J=C(j),w={};for(let H of J)try{let X=O.readFileSync(H,"utf-8").match(/export const (\w+) = \{/);if(!X)continue;let W=(await import(`file://${_.resolve(H)}`))[X[1]];if(!W||!W.domain)continue;if(W.aliases&&Array.isArray(W.aliases))for(let L of W.aliases)w[L]=W.domain;if(W.name&&W.name!==W.domain)w[W.name]=W.domain;let $=W.domain.split(".")[0];if($&&!w[$])w[$]=W.domain}catch(U){console.error(`Error processing ${H}:`,U)}let Q=`//! Package aliases generated from ts-pantry
//! DO NOT EDIT MANUALLY - This file is auto-generated

const std = @import("std");

pub const Alias = struct {
    alias: []const u8,
    domain: []const u8,
};

pub const aliases = [_]Alias{
${Object.entries(w).sort(([H],[U])=>H.localeCompare(U)).map(([H,U])=>`    .{ .alias = "${G(H)}", .domain = "${G(U)}" }`).join(`,
`)}
};

/// Resolve an alias to a domain name
pub fn resolve_alias(alias: []const u8) ?[]const u8 {
    for (aliases) |entry| {
        if (std.mem.eql(u8, entry.alias, alias)) {
            return entry.domain;
        }
    }
    return null;
}

test "Alias resolution works" {
    const resolved = resolve_alias("node");
    if (resolved) |domain| {
        try std.testing.expectEqualStrings("nodejs.org", domain);
    }
}
`;O.writeFileSync(q,Q,"utf-8"),console.log(`✅ Generated Zig aliases: ${q}`),console.log(`\uD83D\uDCCA Total aliases: ${Object.keys(w).length}`)}export{h as generateZigDefinitions,f as generateZigAliases,y as compareVersions};
