worker.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. importScripts(
  2. // Batched optimization
  3. "./lightning-fs.min.js",
  4. // Fixed a bug
  5. "./magic_portal.js"
  6. );
  7. const detect = () => {
  8. if (typeof window !== 'undefined' && !self.skipWaiting) {
  9. return 'window'
  10. } else if (typeof self !== 'undefined' && !self.skipWaiting) {
  11. return 'Worker'
  12. } else if (typeof self !== 'undefined' && self.skipWaiting) {
  13. return 'ServiceWorker'
  14. }
  15. };
  16. const fsName = 'logseq';
  17. const createFS = () => new LightningFS(fsName);
  18. let fs = createFS();
  19. let pfs = fs.promises;
  20. if (detect() === 'Worker') {
  21. const portal = new MagicPortal(self);
  22. portal.set('fs', fs);
  23. portal.set('pfs', pfs);
  24. portal.set('workerThread', {
  25. rimraf: async function (path) {
  26. // Knowing path is a directory,
  27. // first, assume everything inside path is a file.
  28. let files = await pfs.readdir(path);
  29. for (let file of files) {
  30. let child = path + '/' + file
  31. try {
  32. await pfs.unlink(child)
  33. } catch (err) {
  34. if (err.code !== 'EISDIR') throw err
  35. }
  36. }
  37. // Assume what's left are directories and recurse.
  38. let dirs = await pfs.readdir(path)
  39. for (let dir of dirs) {
  40. let child = path + '/' + dir
  41. await rimraf(child, pfs)
  42. }
  43. // Finally, delete the empty directory
  44. await pfs.rmdir(path)
  45. }
  46. });
  47. }