Web Workers

Table of Contents

References

Support

js
return `Worker supported: ${!!window.Worker}`
txtUpdated 60.8w ago
Worker supported: true

Implementation

jsworker.jsimplementation
// gross hack around one of @codemirror/view bugs
let document = { documentElement: { style: {} } };

postMessage("Version: 0.0.6");
postMessage("Location: " + typeof location + JSON.stringify(location));
importScripts("../web.bundle.js");
postMessage("dotlit: " + typeof dotlit);
postMessage("lit" + JSON.stringify(dotlit.lit.location));

const getFsTest = async (filepath) => {
  postMessage(`Getting ${filepath} from local fs.`);
  try {
    const path = dotlit.lit.utils.path;
    const all = [];
    const visit = async (root) => {
      let p;
      try {
        const list = await dotlit.lit.fs.readdir(root);
        p = Promise.all(
          list.map(async (key) => {
            const pathname = path.join(root, key);
            const stat = await dotlit.lit.fs.stat(pathname);
            let contents;
            if (key === ".git" || !key) {
              return { pathname, type: stat.type };
            } else if (stat.type === "dir") contents = await visit(pathname);
            else
              contents = await dotlit.lit.fs.readFile(pathname, {
                encoding: "utf8",
                localOnly: true,
              });
            postMessage("file: " + pathname);
            const item = { pathname, type: stat.type, contents };
            all.push(item);
            return item;
          })
        );
      } catch (err) {
        postMessage("err: " + err.message);
      }
      return p;
    };

    await visit(filepath);
    postMessage("done");
  } catch (err) {
    postMessage("error:" + err.toString());
    postMessage("done");
  }
};

getFsTest("/");

jsworker2.jsimplementation
postMessage("hi")
console.log("anyone here?")

Check if web server has up to date content yet? This delay is really why we need a service worker in the first place.

js> text !collapse
return (async fn => {
  const resp = await fetch('./worker.js')
  return resp.status + "\n" + (await resp.text())
})()

Testing

Current REPL results in script execution from cross-origin? Due to data:uri was resolving the raw event from postMessage not ev.data which is necessary.

js
return new Promise((resolve,reject) => {
  let myWorker;
  try {
    myWorker = new Worker('worker.js')
    myWorker.onmessage = (ev) => {
      if (ev.data === 'done') resolve(ev.data)
      else console.log(ev.data)
    }
    myWorker.onerror = (err) => {
      resolve({msg: "worker.onerror: " + err.message + " (" + err.filename + ":" + err.lineno + ")", err, err},)
    }
  } catch(err) {
    resolve({msg: "Caught err", err})
  }
  
})
txtUpdated 57.3w ago
Version: 2
Location: object{}
dotlit: object
lit{"src":"","root":"/","base":"https://dotlit.org/","query":{}}
Getting /index.lit from local fs.
length+3551
done
js
return new Promise((resolve,reject) => {
  let myWorker;
  try {
    myWorker = new Worker('/web.bundle.js')
    myWorker.onmessage = (ev) => {
      if (ev.data === 'done') resolve(ev.data)
      else console.log(ev.data)
    }
    myWorker.onerror = (err) => {
      resolve({msg: "worker.onerror: " + err.message + " (" + err.filename + ":" + err.lineno + ")", err})
    }
  } catch(err) {
    resolve({msg: "Caught err", err})
  }
  
})
txtUpdated 57.3w ago
{ msg: 'worker.onerror: ReferenceError: Can\'t find variable: document (https://dotlit.org/web.bundle.js:112608)',
  err: { isTrusted: [Getter] } }