Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions src/core/purl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import type { Client } from "./client.ts";
import { create, type Registry } from "./registry.ts";
import { InvalidPURLError } from "./errors.ts";

const QUALIFIER_KEY_PATTERN = /^[a-z][a-z0-9._-]*$/;

/** Decode a percent-encoded PURL component, throwing InvalidPURLError on malformed sequences. */
function decodePURLComponent(purlStr: string, value: string): string {
try {
Expand Down Expand Up @@ -147,8 +149,20 @@ export function buildPURL(parts: {
purl += `@${encodeURIComponent(parts.version)}`;
}
if (parts.qualifiers && Object.keys(parts.qualifiers).length > 0) {
const qs = Object.entries(parts.qualifiers)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
const qualifiers = new Map<string, string>();
for (const [key, value] of Object.entries(parts.qualifiers)) {
const canonicalKey = key.toLowerCase();
if (!QUALIFIER_KEY_PATTERN.test(canonicalKey)) {
throw new InvalidPURLError(purl, `invalid qualifier key "${key}"`);
}
if (qualifiers.has(canonicalKey)) {
throw new InvalidPURLError(purl, `duplicate qualifier key "${canonicalKey}"`);
}
qualifiers.set(canonicalKey, value);
}
const qs = [...qualifiers]
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
.join("&");
purl += `?${qs}`;
}
Expand Down
19 changes: 19 additions & 0 deletions test/unit/purl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,25 @@ describe("purl", () => {
).toBe("pkg:npm/lodash?arch=x86_64&os=linux");
});

it("canonicalizes qualifier keys and ordering", () => {
expect(
buildPURL({
type: "npm",
name: "lodash",
qualifiers: { Zeta: "1", arch: "x86_64", Distro: "debian" },
}),
).toBe("pkg:npm/lodash?arch=x86_64&distro=debian&zeta=1");
});

it("rejects invalid or colliding qualifier keys", () => {
expect(() =>
buildPURL({ type: "npm", name: "lodash", qualifiers: { "bad key": "value" } }),
).toThrow('invalid qualifier key "bad key"');
expect(() =>
buildPURL({ type: "npm", name: "lodash", qualifiers: { Arch: "arm64", arch: "x86_64" } }),
).toThrow('duplicate qualifier key "arch"');
});

it("builds PURL with subpath", () => {
expect(buildPURL({ type: "npm", name: "lodash", subpath: "lib/index.js" })).toBe(
"pkg:npm/lodash#lib/index.js",
Expand Down
Loading