Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/bundlejs-api.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378/** * Enhanced npm package name parser. * * Parses package specifiers in various formats: * - Simple: react, lodash * - Versioned: react@18.2.0, lodash@^4.17.0 * - Scoped: @types/node, @tanstack/react-query@5.0.0 * - With subpath: lodash/get, @emotion/react@11/jsx-runtime * * Enhancements over basic parser: * - Integrates package name validation * - Provides URL-escaped name for registry calls * - Extracts scope separately * - Includes structured validation result * * @module * * @example Basic usage * ```ts * import { parsePackageName, parsePackageSpec } from "./parse-package-name.ts"; * * const result = parsePackageName("@tanstack/react-query@5.0.0/build"); * // { * // name: "@tanstack/react-query", * // version: "5.0.0", * // path: "/build", * // scope: "@tanstack", * // escapedName: "@tanstack%2freact-query", * // isScoped: true * // } * ``` */
import { validatePackageName, type ValidateResult } from "./validate-package-name.ts";
// =============================================================================// Types// =============================================================================
/** * Options for parsing package names. */export interface ParsePackageOptions { /** * If true, return partial result instead of throwing on parse errors. * @default false */ ignoreError?: boolean;
/** * Default version when none is specified. * Set to null to indicate no version. * @default "latest" */ defaultVersion?: string | null;
/** * Whether to validate the package name. * @default false */ validate?: boolean;}
/** * Result of parsing a package specifier. */export interface ParsedPackage { /** Full package name (e.g., "@types/node") */ name: string; /** Version or version range (e.g., "^18.0.0") */ version: string | null; /** Subpath within package (e.g., "/get") */ path: string; /** Package scope if scoped (e.g., "@types") */ scope: string | null; /** URL-escaped name for registry API calls */ escapedName: string; /** Whether this is a scoped package */ isScoped: boolean; /** Validation result if validate=true was passed */ validation?: ValidateResult;}
/** * Extended result including the original input. */export interface ParsedPackageSpec extends ParsedPackage { /** Original input string */ raw: string; /** Whether the input contained an explicit version */ hasExplicitVersion: boolean;}
// =============================================================================// Regex Patterns// =============================================================================
/** * Pattern for scoped packages: @scope/name@version/path * * Groups: * 1. Full scoped name (@scope/name) * 2. Version (optional) * 3. Path (optional) */export const RE_SCOPED = /^(@[^/]+\/[^@/]+)(?:@([^/]+))?(\/.*)?$/;
/** * Pattern for non-scoped packages: name@version/path * * Groups: * 1. Package name * 2. Version (optional) * 3. Path (optional) */export const RE_NON_SCOPED = /^([^@/]+)(?:@([^/]+))?(\/.*)?$/;
// =============================================================================// Core Parsing// =============================================================================
/** * Parse a package name string into components. * * @param input Package specifier string * @param options Parsing options * @returns Parsed components * @throws Error if parse fails and ignoreError is false * * @example Scoped package * ```ts * parsePackageName("@tanstack/react-query@5.0.0/build") * // { * // name: "@tanstack/react-query", * // version: "5.0.0", * // path: "/build", * // scope: "@tanstack", * // escapedName: "@tanstack%2freact-query", * // isScoped: true * // } * ``` * * @example Non-scoped package * ```ts * parsePackageName("lodash@^4.17.0/get") * // { * // name: "lodash", * // version: "^4.17.0", * // path: "/get", * // scope: null, * // escapedName: "lodash", * // isScoped: false * // } * ``` */export function parsePackageName( input: string, options: ParsePackageOptions = {}): ParsedPackage { const { ignoreError = false, defaultVersion = "latest", validate = false, } = options;
// Try scoped pattern first, then non-scoped const match = RE_SCOPED.exec(input) || RE_NON_SCOPED.exec(input);
if (!match) { if (!ignoreError) { throw new Error(`[parse-package-name] invalid package name: ${input}`); } return { name: "", version: defaultVersion, path: "", scope: null, escapedName: "", isScoped: false, ...(validate ? { validation: { valid: false, errors: ["Invalid format"], warnings: [] } } : {}), }; }
const name = match[1] || ""; const version = match[2] ?? defaultVersion; const path = match[3] || "";
// Extract scope from scoped packages const isScoped = name.startsWith("@"); const scope = isScoped ? name.slice(0, name.indexOf("/")) : null;
// Escape name for registry URLs (/ -> %2f) const escapedName = name.replace("/", "%2f");
// Optionally validate const validation = validate ? validatePackageName(name) : undefined;
return { name, version, path, scope, escapedName, isScoped, ...(validation ? { validation } : {}), };}
/** * Parse a package specifier with additional metadata. * * @param input Package specifier string * @param options Parsing options * @returns Extended parsed result */export function parsePackageSpec( input: string, options: ParsePackageOptions = {}): ParsedPackageSpec { const parsed = parsePackageName(input, options);
return { ...parsed, raw: input, hasExplicitVersion: Boolean( RE_SCOPED.exec(input)?.[2] || RE_NON_SCOPED.exec(input)?.[2] ), };}
// =============================================================================// Utility Functions// =============================================================================
/** * Check if a string looks like a package name (not a path, URL, etc). * * @param input String to check * @returns True if it looks like a package name * * @example * ```ts * isPackageName("react") // true * isPackageName("@types/node") // true * isPackageName("./local") // false * isPackageName("https://...") // false * ``` */export function isPackageName(input: string): boolean { if (!input || typeof input !== "string") return false;
// Not a path if (input.startsWith(".") || input.startsWith("/") || input.startsWith("~")) { return false; }
// Not a URL if (/^[a-z][a-z0-9+.-]*:/i.test(input)) { return false; }
// Try to parse const match = RE_SCOPED.exec(input) || RE_NON_SCOPED.exec(input); return match !== null;}
/** * Build a package specifier string from components. * * @param name Package name * @param version Optional version * @param path Optional subpath * @returns Package specifier string * * @example * ```ts * buildPackageSpec("react", "18.2.0") * // "react@18.2.0" * * buildPackageSpec("@types/node", "^20", "/fs") * // "@types/node@^20/fs" * ``` */export function buildPackageSpec( name: string, version?: string | null, path?: string): string { let result = name;
if (version) { result += `@${version}`; }
if (path) { // Ensure path starts with / result += path.startsWith("/") ? path : `/${path}`; }
return result;}
/** * Normalize a subpath (ensure leading slash, remove trailing slash). * * @param path Subpath to normalize * @returns Normalized path */export function normalizeSubpath(path: string): string { if (!path) return "";
let normalized = path;
// Ensure leading slash if (!normalized.startsWith("/")) { normalized = "/" + normalized; }
// Remove trailing slash (unless it's just "/") if (normalized.length > 1 && normalized.endsWith("/")) { normalized = normalized.slice(0, -1); }
return normalized;}
/** * Join multiple subpaths. * * @param paths Paths to join * @returns Joined path */export function joinSubpaths(...paths: (string | undefined | null)[]): string { const parts = paths .filter((p): p is string => Boolean(p)) .flatMap((p) => p.split("/").filter(Boolean));
if (parts.length === 0) return ""; return "/" + parts.join("/");}
// =============================================================================// Scope Utilities// =============================================================================
/** * Extract scope from a package name. * * @param name Package name * @returns Scope with @ prefix, or null */export function getScope(name: string): string | null { if (!name.startsWith("@")) return null; const slashIdx = name.indexOf("/"); return slashIdx > 0 ? name.slice(0, slashIdx) : null;}
/** * Get the unscoped name from a package name. * * @param name Package name * @returns Name without scope * * @example * getUnscopedName("@types/node") // "node" * getUnscopedName("react") // "react" */export function getUnscopedName(name: string): string { if (!name.startsWith("@")) return name; const slashIdx = name.indexOf("/"); return slashIdx > 0 ? name.slice(slashIdx + 1) : name;}
// =============================================================================// Default Export (for backwards compatibility)// =============================================================================
export default parsePackageName;