// Where a runtime plugin is installed from, as a user types it: `[@]`, // `github:/[#]`, or `file:.tgz`. Parsing only — nothing here reaches // the network or the disk. import path from "node:path"; import { NPM_BUILTIN_MODULE_NAMES } from "./npmBuiltinNames.js"; export type InstallSource = { kind: "npm"; name: string; spec: string | null } | { kind: "github"; owner: string; repo: string; tag: string | null } | { kind: "file"; path: string }; export type ParsedInstallSource = { ok: true; source: InstallSource } | { ok: false; error: string }; const MAX_NPM_NAME_LENGTH = 214; const MAX_TAG_LENGTH = 255; // npm's rule for a NEW package name (validate-npm-package-name 7.0.1), one segment at a time: lower // case, URL-safe, no `~'!()*`. Its leading `.`, `-` and `_` checks apply to the WHOLE name, so inside // a scoped name a segment may start with `-` or `_` (`@_scope/-pkg`). A leading `.` is refused in every // segment here: it is what would let one read as `.` or `..` in a path. Split rather than one pattern, // so no quantifier nests. const NPM_UNSCOPED_NAME = /^[a-z0-9][a-z0-9\-._]*$/; const NPM_SCOPED_SEGMENT = /^[a-z0-9\-_][a-z0-9\-._]*$/; // semver 2.0.0: a numeric identifier has no leading zero; an identifier is never empty. const NUMERIC_IDENTIFIER = /^(?:0|[1-9]\d*)$/; const ALPHANUMERIC_IDENTIFIER = /^[0-9A-Za-z-]+$/; const ALL_DIGITS = /^\d+$/; // A dist-tag cannot parse as a version or a range, so one that starts with a letter is unambiguous. const DIST_TAG = /^[A-Za-z][A-Za-z0-9._-]*$/; const GITHUB_OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/; const GITHUB_REPO = /^[A-Za-z0-9._-]{1,100}$/; const GITHUB_TAG = /^[A-Za-z0-9._+/-]+$/; const GITHUB_PREFIX = "github:"; const FILE_PREFIX = "file:"; const PACKAGE_FILE_SUFFIX = ".tgz"; const refuse = (error: string): ParsedInstallSource => ({ ok: false, error }); function isNpmNameShape(name: string): boolean { if (!name.startsWith("@")) return NPM_UNSCOPED_NAME.test(name); const slash = name.indexOf("/"); return slash > 1 && NPM_SCOPED_SEGMENT.test(name.slice(1, slash)) && NPM_SCOPED_SEGMENT.test(name.slice(slash + 1)); } // npm refuses these whole names for a new package. npm compares them lower-cased; a name reaching here // is already lower case, so an exact match is the same test. const NPM_EXCLUDED_NAMES: ReadonlySet = new Set(["node_modules", "favicon.ico"]); const isNpmReservedName = (name: string): boolean => NPM_EXCLUDED_NAMES.has(name) || NPM_BUILTIN_MODULE_NAMES.has(name); export const isNpmPackageName = (name: string): boolean => name.length <= MAX_NPM_NAME_LENGTH && isNpmNameShape(name) && !isNpmReservedName(name); const isVersionCore = (core: string): boolean => { const parts = core.split("."); return parts.length === 3 && parts.every((part) => NUMERIC_IDENTIFIER.test(part)); }; // A prerelease identifier that is all digits is numeric, so no leading zero; a build identifier may have one. const isLabel = (label: string, prerelease: boolean): boolean => label.split(".").every((part) => ALPHANUMERIC_IDENTIFIER.test(part) && (!prerelease || !ALL_DIGITS.test(part) || NUMERIC_IDENTIFIER.test(part))); /** `major.minor.patch`, then an optional `-prerelease` and an optional `+build`, as semver 2.0.0 defines them. */ function isSemverShape(version: string): boolean { const plus = version.indexOf("+"); const build = plus === -1 ? null : version.slice(plus + 1); const withoutBuild = plus === -1 ? version : version.slice(0, plus); const dash = withoutBuild.indexOf("-"); const core = dash === -1 ? withoutBuild : withoutBuild.slice(0, dash); const prerelease = dash === -1 ? null : withoutBuild.slice(dash + 1); return isVersionCore(core) && (prerelease === null || isLabel(prerelease, true)) && (build === null || isLabel(build, false)); } /** A version npm can install as asked: an exact version or a dist-tag. A range is refused, because * what it resolves to would change between the confirmation and the next install. */ export const isNpmVersionSpec = (spec: string): boolean => isSemverShape(spec) || DIST_TAG.test(spec); /** An exact version — what a package's own `version` must be, since it becomes part of a file name * and a cache folder. */ export const isExactVersion = (version: string): boolean => isSemverShape(version); function parseNpm(input: string): ParsedInstallSource { const specAt = input.lastIndexOf("@"); const hasSpec = specAt > 0; const name = hasSpec ? input.slice(0, specAt) : input; const spec = hasSpec ? input.slice(specAt + 1) : null; if (!isNpmPackageName(name)) return refuse(`not an npm package name: ${JSON.stringify(name)}`); if (spec !== null && !isNpmVersionSpec(spec)) return refuse(`not an exact version or a dist-tag: ${JSON.stringify(spec)} (a range is not accepted)`); return { ok: true, source: { kind: "npm", name, spec } }; } const isGithubTag = (tag: string): boolean => tag.length <= MAX_TAG_LENGTH && GITHUB_TAG.test(tag) && !tag.split("/").some((part) => part === "" || part === "." || part === ".."); function parseGithub(rest: string): ParsedInstallSource { const hash = rest.indexOf("#"); const ownerRepo = hash === -1 ? rest : rest.slice(0, hash); const tag = hash === -1 ? null : rest.slice(hash + 1); const [owner = "", repo = "", ...extra] = ownerRepo.split("/"); if (extra.length > 0 || !GITHUB_OWNER.test(owner)) return refuse(`not a GitHub owner/repo: ${JSON.stringify(ownerRepo)}`); if (!GITHUB_REPO.test(repo) || repo === "." || repo === "..") return refuse(`not a GitHub owner/repo: ${JSON.stringify(ownerRepo)}`); if (tag !== null && !isGithubTag(tag)) return refuse(`not a release tag: ${JSON.stringify(tag)}`); return { ok: true, source: { kind: "github", owner, repo, tag } }; } // A package file already on disk. Absolute only: core has no working directory of its own, so the host // resolves a relative path against its own before calling. A folder is not a source — packing one // runs its lifecycle scripts, and installing never runs plugin code. function parseFile(rest: string): ParsedInstallSource { if (rest === "") return refuse("a file: source names no file"); if (rest.includes("\0")) return refuse("a file: source contains a NUL byte"); if (!path.isAbsolute(rest)) return refuse(`a file: source must be an absolute path: ${JSON.stringify(rest)}`); if (!rest.endsWith(PACKAGE_FILE_SUFFIX)) return refuse(`a file: source must name a ${PACKAGE_FILE_SUFFIX} package file: ${JSON.stringify(rest)}`); return { ok: true, source: { kind: "file", path: path.normalize(rest) } }; } export function parseInstallSource(input: unknown): ParsedInstallSource { if (typeof input !== "string") return refuse("an install source is a string"); const trimmed = input.trim(); if (trimmed === "") return refuse("an install source is empty"); if (trimmed.startsWith(GITHUB_PREFIX)) return parseGithub(trimmed.slice(GITHUB_PREFIX.length)); if (trimmed.startsWith(FILE_PREFIX)) return parseFile(trimmed.slice(FILE_PREFIX.length)); return parseNpm(trimmed); } /** The ledger's `source` field for what was actually installed: the resolved version or tag. */ export function sourceLabel(source: InstallSource, resolved: string): string { if (source.kind === "npm") return `npm:${source.name}@${resolved}`; if (source.kind === "github") return `github:${source.owner}/${source.repo}#${resolved}`; return `${FILE_PREFIX}${source.path}`; } /** The file name `npm pack` gives the package — `@scope/name` 1.2.3 → `scope-name-1.2.3.tgz`. */ export const packageFileName = (name: string, version: string): string => `${name.replace(/^@/, "").replaceAll("/", "-")}-${version}.tgz`; const CONTENT_ID_LENGTH = 12; /** `npm pack`'s name with a short hash of the bytes before `.tgz` — `scope-name-1.2.3-0123456789ab.tgz`. * Two different packages with one name and version (a GitHub tag published again) then get different * files. The hash is short, so the install also refuses to write over an existing file whose bytes * differ: that is what keeps a file an entry points at from changing. */ export const installedFileName = (name: string, version: string, sha256Hex: string): string => packageFileName(name, version).replace(/\.tgz$/, `-${sha256Hex.slice(0, CONTENT_ID_LENGTH)}.tgz`);