Skip to content

Commit

Permalink
API: distinguish between npm 404s and other thrown errors
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewbranch committed Mar 8, 2024
1 parent 320cc1f commit d93848f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 14 deletions.
5 changes: 5 additions & 0 deletions .changeset/fresh-queens-clean.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@arethetypeswrong/core": patch
---

API: distinguish between npm 404s and other thrown errors
37 changes: 23 additions & 14 deletions packages/core/src/createPackage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,20 +227,22 @@ async function getNpmTarballUrl(
for (const packageSpec of packageSpecs) {
const manifestUrl = `https://registry.npmjs.org/${packageSpec.name}/${packageSpec.version || "latest"}`;
const doc = packument || (await fetch(manifestUrl).then((r) => r.json()));
if (typeof doc !== "object") {
continue;
if (typeof doc !== "object" || (doc.error && doc.error !== "Not found")) {
throw new Error(`Unexpected response from ${manifestUrl}: ${JSON.stringify(doc)}`);
}
const isManifest = !!doc.version;
let tarballUrl, packageVersion;
if (packageSpec.versionKind === "range") {
packageVersion = maxSatisfying(
Object.keys(doc.versions).filter(
(v) =>
(allowDeprecated || !doc.versions[v].deprecated) &&
(!before || !doc.time || new Date(doc.time[v]) <= before),
),
packageSpec.version,
);
packageVersion =
doc.versions &&
maxSatisfying(
Object.keys(doc.versions).filter(
(v) =>
(allowDeprecated || !doc.versions[v].deprecated) &&
(!before || !doc.time || new Date(doc.time[v]) <= before),
),
packageSpec.version,
);
if (!packageVersion) {
continue;
}
Expand All @@ -256,17 +258,24 @@ async function getNpmTarballUrl(
tarballUrl = doc.versions[packageVersion].dist.tarball;
} else if (isManifest) {
packageVersion = doc.version;
tarballUrl = doc.dist.tarball;
tarballUrl = doc.dist?.tarball;
} else {
packageVersion = doc["dist-tags"].latest;
tarballUrl = doc.versions[packageVersion].dist.tarball;
packageVersion = doc["dist-tags"]?.latest;
tarballUrl = doc.versions?.[packageVersion].dist.tarball;
}

if (packageVersion && tarballUrl) {
return { packageName: packageSpec.name, packageVersion, tarballUrl };
}
}
throw new Error(`Failed to find a matching version for ${packageSpecs[0].name}`);
throw new Npm404Error(packageSpecs);
}

export class Npm404Error extends Error {
kind = "Npm404Error";
constructor(public packageSpecs: readonly ParsedPackageSpec[]) {
super(`Failed to find a matching version for ${packageSpecs[0].name}`);
}
}

export async function createPackageFromTarballUrl(tarballUrl: string): Promise<Package> {
Expand Down

0 comments on commit d93848f

Please sign in to comment.