worker.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. importScripts(
  2. // Batched optimization
  3. "./lightning-fs.min.js?v=0.0.2.3",
  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. // try {
  27. // // First assume path is itself a file
  28. // await pfs.unlink(path)
  29. // // if that worked we're done
  30. // return
  31. // } catch (err) {
  32. // // Otherwise, path must be a directory
  33. // if (err.code !== 'EISDIR') throw err
  34. // }
  35. // Knowing path is a directory,
  36. // first, assume everything inside path is a file.
  37. let files = await pfs.readdir(path);
  38. for (let file of files) {
  39. let child = path + '/' + file
  40. try {
  41. await pfs.unlink(child)
  42. } catch (err) {
  43. if (err.code !== 'EISDIR') throw err
  44. }
  45. }
  46. // Assume what's left are directories and recurse.
  47. let dirs = await pfs.readdir(path)
  48. for (let dir of dirs) {
  49. let child = path + '/' + dir
  50. await rimraf(child, pfs)
  51. }
  52. // Finally, delete the empty directory
  53. await pfs.rmdir(path)
  54. }
  55. });
  56. }