summaryrefslogtreecommitdiff
path: root/data/extensions/jsr@javascriptrestrictor/nscl/common/CachedStorage.js
blob: 6b1a7272b43dbcef587994c9b46be1d937d92088 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/*
 * NoScript Commons Library
 * Reusable building blocks for cross-browser security/privacy WebExtensions.
 * Copyright (C) 2020-2024 Giorgio Maone <https://maone.net>
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

var CachedStorage = (() => {
  const scopes = new WeakMap();

  const DEFER_DELAY = 1000;
  let deferredTasks = null;
  const performTasks = async () => {
    for (let t of deferredTasks) t();
    deferredTasks = null;
  };
  const deferTasks = (...tasks) => {
    if (!deferredTasks) {
      deferredTasks = tasks;
      setTimeout(performTasks, DEFER_DELAY);
    } else {
      deferredTasks.push(...tasks);
    }
  };

  const addNameSpace = (nameSpace, properties, keys) => {
    const prefix = nameSpace ? `${nameSpace}.` : "";
    const nameSpacedProps = {};
    for (const key of keys) {
      nameSpacedProps[`${prefix}${key}`] = properties[key];
    }
    return nameSpacedProps;
  };
  const removeNameSpace = (nameSpace, properties) => {
    if (!nameSpace) return properties;
    const len = nameSpace.length + 1;
    const props = {};
    for (const [key, val] of Object.entries(properties)) {
      props[key.substring(len)] = val;
    }
    return props;
  };

  return {
    async init(
      properties = null,
      nameSpace = "",
      scope = null,
      storageType = "session"
    ) {
      if (!properties) {
        console.warn("CachedStorage.init(): no properties!");
        return null;
      }

      scope ??= (nameSpace && globalThis[nameSpace]) || globalThis;

      for (let p in properties) {
        if (p in scope) {
          // already initialized
          return scope;
        }
        break;
      }

      if (!(storageType in browser.storage)) {
        console.warn(
          `CachedStorage.init(): no browser.storage.${storageType}, falling back to vanilla properties`
        );
        return Object.assign(scope, properties);
      }

      const keys = Object.keys(properties);
      if (nameSpace) {
        properties = addNameSpace(nameSpace, properties, keys);
      } else {
        nameSpace = "";
      }

      let metadata = scopes.get(scope);
      if (!metadata) {
        scopes.set(scope, (metadata = { storage: {} }));
      }

      const ns = (metadata.storage[storageType] ??= new Map()).get(nameSpace);
      if (ns) {
        for (const key of keys) ns.add(key);
      } else {
        metadata.storage[storageType].set(nameSpace, new Set(keys));
      }
      return Object.assign(
        scope,
        removeNameSpace(
          nameSpace,
          await browser.storage[storageType].get(properties)
        )
      );
    },
    async save(scope = globalThis, defer = false) {
      const metadata = scopes.get(scope);
      if (!metadata) {
        console.warn(
          `CacheStorage.save(): metadata not found for scope ${scope}!`
        );
        return false;
      }

      if (metadata.deferredSave) return;
      if ((defer ||= Date.now() - metadata.lastSaved < 20)) {
        metadata.deferredSave = true;
        return Promise.resolve(
          deferTasks(() => {
            metadata.deferredSave = false;
            this.save(scope);
          })
        );
      }

      const savingTasks = [];
      for (const [storageType, ns] of Object.entries(metadata.storage)) {
        for (const [nameSpace, keys] of ns.entries()) {
          const properties = addNameSpace(nameSpace, scope, keys);
          savingTasks.push(browser.storage[storageType].set(properties));
        }
      }
      metadata.lastSaved = Date.now();
      return await Promise.allSettled(savingTasks);
    },
  };
})();