Skip to content

Commit

Permalink
Fix handling of permanent redirect detection
Browse files Browse the repository at this point in the history
For some reason, the code assumed that the fetch API would not follow permanent
redirects.

The fetch API follows redirects by default and that's a good thing as requests
on the `/specifications/[shortname]/versions/latest` API endpoint typically
return a 302 to the actual version that is the current latest version.

This update rather relies on the `redirected` flag to detect redirects and
checks the final URL to see whether the W3C API knows the spec under a
different shortname.
  • Loading branch information
tidoust committed Nov 13, 2024
1 parent e079b80 commit 79588ff
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
19 changes: 11 additions & 8 deletions src/fetch-info.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,17 +99,20 @@ async function fetchInfoFromW3CApi(specs, options) {
if (res.status === 404) {
return;
}
if (res.status === 301) {
const rawLocation = res.headers.get('location');
const location = rawLocation.startsWith('/specifications/') ?
rawLocation.substring('/specifications/'.length) :
rawLocation.location;
throw new Error(`W3C API redirected to "${location}" ` +
`for "${spec.shortname}" (${spec.url}), update the shortname!`);
}
if (res.status !== 200) {
throw new Error(`W3C API returned an error, status code is ${res.status}, url was ${url}`);
}

// Has the shortname changed from a W3C perspective?
if (res.redirected) {
const match = res.url.match(/\/specifications\/([^\/]+)\//);
const w3cShortname = match ? match[1] : '';
if (w3cShortname !== spec.shortname) {
throw new Error(`W3C API redirects "${spec.shortname}" to ` +
`"${w3cShortname}", update the shortname!`);
}
}

try {
const body = await res.json();
return body;
Expand Down
12 changes: 11 additions & 1 deletion test/fetch-info.js
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ describe("fetch-info module", function () {
});
});

describe("fetch from W3C API", () => {
describe("fetch from W3C API", () => {
it("works on a TR spec", async () => {
const spec = getW3CSpec("hr-time-2", "hr-time");
const info = await fetchInfo([spec]);
Expand Down Expand Up @@ -313,6 +313,16 @@ describe("fetch-info module", function () {
assert.equal(info.__series["CSS"].title, "Cascading Style Sheets");
assert.equal(info.__series["css"].title, "CSS Snapshot");
});

it("detects redirects", async () => {
const spec = {
url: "https://www.w3.org/TR/webaudio/",
shortname: "webaudio"
};
await assert.rejects(
fetchInfo([spec]),
/^Error: W3C API redirects "webaudio" to "webaudio-.*"/);
});
});

describe("fetch from Specref", () => {
Expand Down

0 comments on commit 79588ff

Please sign in to comment.