2021-01-21 22:06:22 +01:00
|
|
|
importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.15.7/misc/wasm/wasm_exec.js')
|
2019-11-27 08:53:34 +01:00
|
|
|
|
2021-01-21 23:17:39 +01:00
|
|
|
async function startWasm(wasm, { env, args = [] }) {
|
2019-11-27 08:53:34 +01:00
|
|
|
const go = new Go()
|
2021-01-21 22:14:51 +01:00
|
|
|
go.env = env
|
2020-06-14 15:34:58 +02:00
|
|
|
go.argv = [wasm, ...args]
|
2019-11-27 08:53:34 +01:00
|
|
|
const { instance } = await WebAssembly.instantiateStreaming(fetch(wasm), go.importObject)
|
|
|
|
return go.run(instance)
|
|
|
|
}
|
|
|
|
|
2021-01-21 23:13:57 +01:00
|
|
|
function trimStart(s, c) {
|
2019-11-27 11:20:52 +01:00
|
|
|
let r = s
|
|
|
|
while (r.startsWith(c)) r = r.slice(c.length)
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
2021-01-21 23:13:57 +01:00
|
|
|
function trimEnd(s, c) {
|
2019-11-27 11:20:52 +01:00
|
|
|
let r = s
|
|
|
|
while (r.endsWith(c)) r = r.slice(0, -c.length)
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
2019-12-02 16:52:40 +01:00
|
|
|
// addEventListener('install', (event) => {
|
|
|
|
// event.waitUntil(skipWaiting())
|
|
|
|
// })
|
2019-11-27 11:20:52 +01:00
|
|
|
|
2019-12-02 16:52:40 +01:00
|
|
|
let nextHandlerId = 1
|
|
|
|
const handlerResolvers = {}
|
|
|
|
const handlers = []
|
2019-11-27 01:12:09 +01:00
|
|
|
|
2019-12-02 16:52:40 +01:00
|
|
|
self.wasmhttp = {
|
2019-11-27 08:53:34 +01:00
|
|
|
registerHandler: (handlerId, handler) => {
|
|
|
|
handlerResolvers[handlerId](handler)
|
|
|
|
delete handlerResolvers[handlerId]
|
|
|
|
},
|
2019-11-27 01:12:09 +01:00
|
|
|
}
|
2019-12-02 16:52:40 +01:00
|
|
|
|
2019-12-02 17:09:32 +01:00
|
|
|
addEventListener('activate', event => {
|
|
|
|
event.waitUntil(clients.claim())
|
|
|
|
})
|
2019-12-02 16:52:40 +01:00
|
|
|
|
2021-01-21 23:07:42 +01:00
|
|
|
function registerWasmHTTPListener(wasm, base, args) {
|
|
|
|
let path = new URL(registration.scope).pathname
|
|
|
|
if (base && base !== '') path = `${trimEnd(path, '/')}/${trimStart(base, '/')}`
|
|
|
|
|
|
|
|
addEventListener('fetch', async e => {
|
2021-01-21 23:13:57 +01:00
|
|
|
console.log("new fetch !")
|
|
|
|
|
2021-01-21 23:07:42 +01:00
|
|
|
const { pathname } = new URL(e.request.url)
|
|
|
|
if (!pathname.startsWith(path)) return
|
|
|
|
|
2021-01-21 23:13:57 +01:00
|
|
|
console.log("path OK!")
|
|
|
|
|
2021-01-21 23:07:42 +01:00
|
|
|
const handlerId = `${nextHandlerId++}`
|
|
|
|
const handlerPromise = new Promise(resolve => handlerResolvers[handlerId] = resolve)
|
|
|
|
|
|
|
|
// FIXME await ? catch ?
|
|
|
|
startWasm(wasm, { env: { WASMHTTP_HANDLER_ID: handlerId, WASMHTTP_PATH: path }, args })
|
|
|
|
|
|
|
|
const handler = await handlerPromise
|
2021-01-21 23:13:57 +01:00
|
|
|
|
2021-01-21 23:07:42 +01:00
|
|
|
e.respondWith(handler(e.request))
|
|
|
|
})
|
|
|
|
}
|