// ==UserScript==
// @name Observable API Cache-First (200 only)
// @namespace tlarkworthy.cache.observable
// @version 0.2
// @description Cache-first for https://api.observablehq.com/* (only cache HTTP 200 responses)
// @match *://*/*
// @grant none
// @run-at document-start
// ==/UserScript==
(() => {
const CACHE_NAME = 'observable-api-cache-v1';
const isTarget = (url) => {
try {
const u = new URL(url, location.href);
return u.origin === 'https://api.observablehq.com';
} catch {
return false;
}
};
const toCacheKeyRequest = (input, init) => {
if (typeof input === 'string') return new Request(new URL(input, location.href).href);
if (input instanceof Request) return new Request(input.url);
return new Request(String(input));
};
const origFetch = window.fetch.bind(window);
window.fetch = async function patchedFetch(input, init) {
const method = (init && init.method)
? String(init.method).toUpperCase()
: (input instanceof Request)
? String(input.method || 'GET').toUpperCase()
: 'GET';
const urlStr = (typeof input === 'string')
? input
: (input instanceof Request)
? input.url
: String(input);
if (method !== 'GET' || !isTarget(urlStr)) {
return origFetch(input, init);
}
try {
const cache = await caches.open(CACHE_NAME);
const cacheKeyReq = toCacheKeyRequest(input, init);
const cached = await cache.match(cacheKeyReq);
if (cached) return cached.clone();
const netResp = await origFetch(input, init);
if (netResp.status === 200) {
try { await cache.put(cacheKeyReq, netResp.clone()); } catch (_) {}
}
return netResp;
} catch {
return origFetch(input, init);
}
};
})();
I got annoyed by the AWS degraded service that caused many dependancies to 522 so I asked chatGPT to cache them via a Tampermonkey script.