Fix fetch monkey patch

Wait for `global_context` to exist. Fix bug with b64 encoding. Respect
mime type.
This commit is contained in:
Adrian Vollmer 2024-04-08 18:54:49 +02:00
parent d0a6ba478e
commit b37d287cc6
4 changed files with 53 additions and 10 deletions

View File

@ -64,7 +64,7 @@ var retrieve_file = function(path) {
console.warn("File not found: " + path);
return "";
} else {
return file.data;
return file;
}
};

View File

@ -49,14 +49,55 @@ window.history.replaceState = myReplaceState;
const { fetch: originalFetch } = window;
async function waitFor(predicate, timeout) {
return new Promise((resolve, reject) => {
const check = () => {
console.log('checking', predicate());
if (!predicate()) return;
clearInterval(interval);
resolve();
};
const interval = setInterval(check, 100);
check();
if (!timeout) return;
setTimeout(() => {
clearInterval(interval);
reject();
}, timeout);
});
}
var _base64ToArrayBuffer = function (base64) {
if (!base64) { return []}
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
};
window.fetch = async (...args) => {
// wait until global_context is ready
try {
await waitFor(() => window.hasOwnProperty("global_context"), 10000);
} catch (err) {
throw err;
}
let [resource, config ] = args;
var path = normalize_path(resource);
var response;
if (is_virtual(path)) {
var data = retrieve_file(path);
var file = retrieve_file(path);
var data = file.data;
if (file.base64encoded) {
data = _base64ToArrayBuffer(data);
}
response = new Response(data);
response.headers.set("content-type", file.mime_type);
} else {
response = await originalFetch(resource, config);
}

View File

@ -39,7 +39,7 @@ var retrieve_file = function(path) {
console.warn("File not found: " + path);
return "";
} else {
return file.data;
return file;
}
};
@ -91,7 +91,7 @@ var embed_js = function(doc) {
let [path, get_parameters, anchor] = split_url(src);
path = normalize_path(path);
console.debug("Embed script: " + path);
var src = retrieve_file(path) + ' \n//# sourceURL=' + path;
var src = retrieve_file(path).data + ' \n//# sourceURL=' + path;
newScript.appendChild(doc.createTextNode(src));
newScript.removeAttribute('src');
oldScript.parentNode.replaceChild(newScript, oldScript);
@ -111,7 +111,7 @@ var embed_css = function(doc) {
var href = link.getAttribute('href');
let [path, get_parameters, anchor] = split_url(href);
path = normalize_path(path);
style.textContent = retrieve_file(path);
style.textContent = retrieve_file(path).data;
link.replaceWith(style);
};
});
@ -161,11 +161,11 @@ var embed_img = function(img) {
if (is_virtual(src)) {
var path = normalize_path(src);
const file = retrieve_file(path);
const mime_type = window.global_context.file_tree[path].mime_type;
const mime_type = file.mime_type;
if (mime_type == 'image/svg+xml') {
img.setAttribute('src', "data:image/svg+xml;charset=utf-8;base64, " + btoa(file));
img.setAttribute('src', "data:image/svg+xml;charset=utf-8;base64, " + btoa(file.data));
} else {
img.setAttribute('src', `data:${mime_type};base64, ${file}`);
img.setAttribute('src', `data:${mime_type};base64, ${file.data}`);
}
};
};

View File

@ -145,9 +145,10 @@ def prepare_file(filename, before, after):
"ttf",
"gif",
"ico",
"wasm",
]:
# JSON doesn't allow binary data
data = base64.b64encode(data)
data = base64.b64encode(data).decode()
base64encoded = True
elif ext in ["html", "htm"]:
@ -163,6 +164,7 @@ def prepare_file(filename, before, after):
data = data.decode()
except UnicodeError:
data = base64.b64encode(data).decode()
base64encoded = True
logger.debug("loaded file: %s [%s, %d bytes]" % (filename, mime_type, len(data)))