import { html } from "https://esm.town/v/postpostscript/html";
import { getValEndpointFromUrl, getValNameFromUrl } from "https://esm.town/v/postpostscript/meta";
import { blob } from "https://esm.town/v/std/blob";
export const URL = getValEndpointFromUrl(import.meta.url);
export const DEFAULT_PREFIX = `${getValNameFromUrl(import.meta.url)}:`;
export async function poll(url = URL, { initialDelay = 1000, tries = 10, retryMs = 1000, log = true }) {
for (let i = 0; i < tries; i++) {
try {
log && console.log("provideBlob.poll attempt", url);
const res = await fetch(url, {
headers: {
"Content-Type": "application/octet-stream",
},
});
if (res.status !== 200) {
throw new Error(await res.text());
}
log && console.log("provideBlob.poll attempt succeeded", url);
return res.blob();
} catch (e) {
log && console.log("provideBlob.poll attempt failed:", e.message, url);
}
await new Promise((resolve) => setTimeout(resolve, retryMs));
}
}
export function provideBlob(getValue: (() => Promise<any> | any) | Promise<any>, prefix = DEFAULT_PREFIX) {
const id = crypto.randomUUID();
const result = (async () => {
let value;
try {
value = await (getValue instanceof Promise
? getValue
: getValue());
} catch (e) {
value = {
"error": e.message,
};
}
blob.set(`${prefix}${id}`, value);
return value;
})();
const url = `${URL}/${id}`;
return {
url,
result,
jsPromise({ initialDelay = 1000, tries = 10, retryMs = 1000, log = true } = {}) {
return html`(async () => {
// https://stackoverflow.com/a/9899701
// licence: CC BY-SA 4.0
function docReady(fn) {
if (document.readyState === "complete" || document.readyState === "interactive") {
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
const url = ${JSON.stringify(url)};
window.provideBlobCache ??= {}
const result = new Promise((resolve, reject) => {
window.provideBlobCache[url] = {
resolve,
reject,
}
})
docReady(() => {
const $script = document.createElement("script")
$script.type = "module"
$script.innerHTML = \`
import { poll } from "${import.meta.url}"
const url = ${JSON.stringify(url)}
const {
resolve,
reject,
} = window.provideBlobCache[url]
poll(url, {
initialDelay: ${initialDelay},
tries: ${tries},
retryMs: ${retryMs},
log: ${log},
})
.then(resolve)
.catch(reject)
\`
document.body.appendChild($script)
})
return result
})()`;