2025-02-06 09:42:59 +01:00
|
|
|
function registerWasmHTTPListener(wasm, { base, cacheName, passthrough, args = [] } = {}) {
|
2021-01-21 23:07:42 +01:00
|
|
|
let path = new URL(registration.scope).pathname
|
|
|
|
if (base && base !== '') path = `${trimEnd(path, '/')}/${trimStart(base, '/')}`
|
|
|
|
|
2021-01-22 00:58:30 +01:00
|
|
|
const handlerPromise = new Promise(setHandler => {
|
|
|
|
self.wasmhttp = {
|
|
|
|
path,
|
|
|
|
setHandler,
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
const go = new Go()
|
|
|
|
go.argv = [wasm, ...args]
|
2024-10-16 13:20:29 +02:00
|
|
|
const source = cacheName
|
|
|
|
? caches.open(cacheName).then((cache) => cache.match(wasm)).then((response) => response ?? fetch(wasm))
|
|
|
|
: caches.match(wasm).then(response => (response) ?? fetch(wasm))
|
|
|
|
WebAssembly.instantiateStreaming(source, go.importObject).then(({ instance }) => go.run(instance))
|
2021-01-21 23:59:35 +01:00
|
|
|
|
2021-01-21 23:28:52 +01:00
|
|
|
addEventListener('fetch', e => {
|
2025-02-06 09:42:59 +01:00
|
|
|
if (passthrough?.(e.request)) {
|
2025-02-05 17:48:27 -08:00
|
|
|
e.respondWith(fetch(e.request))
|
|
|
|
return;
|
|
|
|
}
|
2025-02-06 09:42:59 +01:00
|
|
|
|
2021-01-21 23:07:42 +01:00
|
|
|
const { pathname } = new URL(e.request.url)
|
|
|
|
if (!pathname.startsWith(path)) return
|
|
|
|
|
2021-01-21 23:28:52 +01:00
|
|
|
e.respondWith(handlerPromise.then(handler => handler(e.request)))
|
2021-01-21 23:07:42 +01:00
|
|
|
})
|
2021-01-21 23:23:27 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
function trimStart(s, c) {
|
|
|
|
let r = s
|
|
|
|
while (r.startsWith(c)) r = r.slice(c.length)
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
|
|
|
function trimEnd(s, c) {
|
|
|
|
let r = s
|
|
|
|
while (r.endsWith(c)) r = r.slice(0, -c.length)
|
|
|
|
return r
|
|
|
|
}
|