@warp-drive-mirror/experiments 0.2.7-beta.0 → 0.2.7-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +70 -0
- package/README.md +2 -1
- package/declarations/data-worker.d.ts +35 -2
- package/declarations/data-worker.d.ts.map +1 -0
- package/declarations/document-storage-CwwTQ49-.d.ts +91 -0
- package/declarations/document-storage-CwwTQ49-.d.ts.map +1 -0
- package/declarations/document-storage.d.ts +2 -1
- package/declarations/image-fetch.d.ts +60 -1
- package/declarations/image-fetch.d.ts.map +1 -0
- package/declarations/image-worker.d.ts +40 -1
- package/declarations/image-worker.d.ts.map +1 -0
- package/declarations/storage.d.ts +359 -0
- package/declarations/storage.d.ts.map +1 -0
- package/declarations/types-CRs-Qww6.d.ts +17 -0
- package/declarations/types-CRs-Qww6.d.ts.map +1 -0
- package/declarations/worker-fetch.d.ts +23 -1
- package/declarations/worker-fetch.d.ts.map +1 -0
- package/dist/data-worker.js +235 -339
- package/dist/data-worker.js.map +1 -0
- package/dist/document-storage-LM925Stz.js +270 -0
- package/dist/document-storage-LM925Stz.js.map +1 -0
- package/dist/document-storage.js +3 -1
- package/dist/image-fetch.js +108 -79
- package/dist/image-fetch.js.map +1 -0
- package/dist/image-worker.js +95 -95
- package/dist/image-worker.js.map +1 -0
- package/dist/storage.js +914 -0
- package/dist/storage.js.map +1 -0
- package/dist/unpkg/dev/data-worker.js +231 -338
- package/dist/unpkg/dev/data-worker.js.map +1 -0
- package/dist/unpkg/dev/document-storage-DkiEg9rY.js +268 -0
- package/dist/unpkg/dev/document-storage-DkiEg9rY.js.map +1 -0
- package/dist/unpkg/dev/document-storage.js +2 -348
- package/dist/unpkg/dev/image-fetch.js +104 -71
- package/dist/unpkg/dev/image-fetch.js.map +1 -0
- package/dist/unpkg/dev/image-worker.js +93 -94
- package/dist/unpkg/dev/image-worker.js.map +1 -0
- package/dist/unpkg/dev/storage.js +913 -0
- package/dist/unpkg/dev/storage.js.map +1 -0
- package/dist/unpkg/dev/worker-fetch.js +112 -145
- package/dist/unpkg/dev/worker-fetch.js.map +1 -0
- package/dist/unpkg/dev-deprecated/data-worker.js +231 -338
- package/dist/unpkg/dev-deprecated/data-worker.js.map +1 -0
- package/dist/unpkg/dev-deprecated/document-storage-DkiEg9rY.js +268 -0
- package/dist/unpkg/dev-deprecated/document-storage-DkiEg9rY.js.map +1 -0
- package/dist/unpkg/dev-deprecated/document-storage.js +2 -348
- package/dist/unpkg/dev-deprecated/image-fetch.js +104 -71
- package/dist/unpkg/dev-deprecated/image-fetch.js.map +1 -0
- package/dist/unpkg/dev-deprecated/image-worker.js +93 -94
- package/dist/unpkg/dev-deprecated/image-worker.js.map +1 -0
- package/dist/unpkg/dev-deprecated/storage.js +913 -0
- package/dist/unpkg/dev-deprecated/storage.js.map +1 -0
- package/dist/unpkg/dev-deprecated/worker-fetch.js +112 -145
- package/dist/unpkg/dev-deprecated/worker-fetch.js.map +1 -0
- package/dist/unpkg/prod/data-worker.js +224 -324
- package/dist/unpkg/prod/data-worker.js.map +1 -0
- package/dist/unpkg/prod/document-storage-D0k_6GM9.js +262 -0
- package/dist/unpkg/prod/document-storage-D0k_6GM9.js.map +1 -0
- package/dist/unpkg/prod/document-storage.js +2 -338
- package/dist/unpkg/prod/image-fetch.js +101 -71
- package/dist/unpkg/prod/image-fetch.js.map +1 -0
- package/dist/unpkg/prod/image-worker.js +93 -94
- package/dist/unpkg/prod/image-worker.js.map +1 -0
- package/dist/unpkg/prod/storage.js +844 -0
- package/dist/unpkg/prod/storage.js.map +1 -0
- package/dist/unpkg/prod/worker-fetch.js +109 -145
- package/dist/unpkg/prod/worker-fetch.js.map +1 -0
- package/dist/unpkg/prod-deprecated/data-worker.js +224 -324
- package/dist/unpkg/prod-deprecated/data-worker.js.map +1 -0
- package/dist/unpkg/prod-deprecated/document-storage-D0k_6GM9.js +262 -0
- package/dist/unpkg/prod-deprecated/document-storage-D0k_6GM9.js.map +1 -0
- package/dist/unpkg/prod-deprecated/document-storage.js +2 -338
- package/dist/unpkg/prod-deprecated/image-fetch.js +101 -71
- package/dist/unpkg/prod-deprecated/image-fetch.js.map +1 -0
- package/dist/unpkg/prod-deprecated/image-worker.js +93 -94
- package/dist/unpkg/prod-deprecated/image-worker.js.map +1 -0
- package/dist/unpkg/prod-deprecated/storage.js +844 -0
- package/dist/unpkg/prod-deprecated/storage.js.map +1 -0
- package/dist/unpkg/prod-deprecated/worker-fetch.js +109 -145
- package/dist/unpkg/prod-deprecated/worker-fetch.js.map +1 -0
- package/dist/worker-fetch.js +116 -153
- package/dist/worker-fetch.js.map +1 -0
- package/package.json +9 -9
- package/declarations/data-worker/cache-handler.d.ts +0 -7
- package/declarations/data-worker/fetch.d.ts +0 -21
- package/declarations/data-worker/types.d.ts +0 -31
- package/declarations/data-worker/utils.d.ts +0 -12
- package/declarations/data-worker/worker.d.ts +0 -23
- package/declarations/document-storage/index.d.ts +0 -90
- package/declarations/image-worker/fetch.d.ts +0 -18
- package/declarations/image-worker/types.d.ts +0 -21
- package/declarations/image-worker/worker.d.ts +0 -14
- package/dist/index-CGCX7hY2.js +0 -349
package/dist/storage.js
ADDED
|
@@ -0,0 +1,914 @@
|
|
|
1
|
+
import { getGlobalConfig, macroCondition } from "@embroider/macros";
|
|
2
|
+
import { defineSignal, entangleSignal, getOrCreateInternalSignal, makeInitializer, memoized, notifyInternalSignal, withSignalStore } from "@warp-drive-mirror/core/signals/-leaked";
|
|
3
|
+
|
|
4
|
+
//#region src/storage/-private/reactive-map.ts
|
|
5
|
+
/**
|
|
6
|
+
* A reactive wrapper around the browser's Map API that provides
|
|
7
|
+
* granular per-key reactivity via WarpDrive's signal system.
|
|
8
|
+
*/
|
|
9
|
+
var SignalMap = class {
|
|
10
|
+
_map = {};
|
|
11
|
+
_signals = withSignalStore(this._map);
|
|
12
|
+
subscribe(key) {
|
|
13
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
14
|
+
if (!test) throw new Error(`ReactiveMap keys must be strings, got ${typeof key}`);
|
|
15
|
+
})(typeof key === "string");
|
|
16
|
+
const existing = this._signals.has(key);
|
|
17
|
+
entangleSignal(this._signals, this._map, key, void 0);
|
|
18
|
+
const size = this._size;
|
|
19
|
+
this._size = existing ? size : size + 1;
|
|
20
|
+
return existing;
|
|
21
|
+
}
|
|
22
|
+
notify(key) {
|
|
23
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
24
|
+
if (!test) throw new Error(`ReactiveMap keys must be strings, got ${typeof key}`);
|
|
25
|
+
})(typeof key === "string");
|
|
26
|
+
const signal = getOrCreateInternalSignal(this._signals, this._map, key, 0);
|
|
27
|
+
notifyInternalSignal(signal);
|
|
28
|
+
}
|
|
29
|
+
clear() {
|
|
30
|
+
for (const value of this._signals.values()) notifyInternalSignal(value);
|
|
31
|
+
this._size = 0;
|
|
32
|
+
}
|
|
33
|
+
get size() {
|
|
34
|
+
return this._size;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
defineSignal(SignalMap.prototype, "_size", 0);
|
|
38
|
+
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/storage/cache.ts
|
|
41
|
+
const DEFAULT_CACHE_ID = "reactive-cache";
|
|
42
|
+
const CACHES = /* @__PURE__ */ new Map();
|
|
43
|
+
const StorageEvents = new BroadcastChannel("reactive-cache-events");
|
|
44
|
+
const CACHE_URL = `${location.origin}/api/reactive-cache.json`;
|
|
45
|
+
/**
|
|
46
|
+
* Emits a {@link StorageEvent} on the local context to
|
|
47
|
+
* match the broadcast event.
|
|
48
|
+
*/
|
|
49
|
+
function emitStorageEvent(event) {
|
|
50
|
+
window.dispatchEvent(new CustomEvent("storage", { detail: event }));
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Updates the cache and re-emits the event on the local context as a StorageEvent
|
|
54
|
+
* This is necessary to trigger the reactive updates in the current tab.
|
|
55
|
+
*/
|
|
56
|
+
function handleCacheEvent(event) {
|
|
57
|
+
const { data } = event;
|
|
58
|
+
const cache = CACHES.get(data.storageArea);
|
|
59
|
+
if (!cache) return;
|
|
60
|
+
if (data.key === null) {
|
|
61
|
+
cache._data = /* @__PURE__ */ new Map();
|
|
62
|
+
emitStorageEvent({
|
|
63
|
+
storageArea: cache,
|
|
64
|
+
key: null,
|
|
65
|
+
oldValue: null,
|
|
66
|
+
newValue: null
|
|
67
|
+
});
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (data.newValue === null) cache._data.delete(data.key);
|
|
71
|
+
else cache._data.set(data.key, data.newValue);
|
|
72
|
+
emitStorageEvent({
|
|
73
|
+
storageArea: cache,
|
|
74
|
+
key: data.key,
|
|
75
|
+
oldValue: data.oldValue,
|
|
76
|
+
newValue: data.newValue
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
StorageEvents.addEventListener("message", handleCacheEvent);
|
|
80
|
+
/**
|
|
81
|
+
* A reactive interface for json stored in the browser [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) API.
|
|
82
|
+
*
|
|
83
|
+
* This is a good option for larger data sets than can be efficiently stored in localStorage
|
|
84
|
+
* but should not be used as a permanent DB or storage solution.
|
|
85
|
+
*/
|
|
86
|
+
var CacheStorage = class CacheStorage {
|
|
87
|
+
#cache;
|
|
88
|
+
#cacheId;
|
|
89
|
+
#inititalization;
|
|
90
|
+
_data = /* @__PURE__ */ new Map();
|
|
91
|
+
_nextUpdate = null;
|
|
92
|
+
_bufferedEvents = [];
|
|
93
|
+
async #initialize() {
|
|
94
|
+
const cache = await caches.open(this.#cacheId);
|
|
95
|
+
this.#cache = cache;
|
|
96
|
+
this._data = await deserializeFromCache(cache);
|
|
97
|
+
return this;
|
|
98
|
+
}
|
|
99
|
+
constructor(cacheId) {
|
|
100
|
+
this.#cacheId = cacheId;
|
|
101
|
+
this.#cache = null;
|
|
102
|
+
this.#inititalization = this.#initialize();
|
|
103
|
+
}
|
|
104
|
+
get length() {
|
|
105
|
+
return this._data.size;
|
|
106
|
+
}
|
|
107
|
+
#update(key, oldValue, newValue) {
|
|
108
|
+
const cache = this.#cache;
|
|
109
|
+
if (!cache) throw new Error("Cache not initialized");
|
|
110
|
+
this._bufferedEvents.push({
|
|
111
|
+
storageArea: this.#cacheId,
|
|
112
|
+
key,
|
|
113
|
+
oldValue,
|
|
114
|
+
newValue
|
|
115
|
+
});
|
|
116
|
+
if (!this._nextUpdate) this._nextUpdate = window.setTimeout(() => {
|
|
117
|
+
const events = this._bufferedEvents;
|
|
118
|
+
this._bufferedEvents = [];
|
|
119
|
+
this._nextUpdate = null;
|
|
120
|
+
serializeToCache(cache, this._data);
|
|
121
|
+
for (const event of events) StorageEvents.postMessage(event);
|
|
122
|
+
}, 0);
|
|
123
|
+
}
|
|
124
|
+
clear() {
|
|
125
|
+
this._data = /* @__PURE__ */ new Map();
|
|
126
|
+
this.#update(null, null, null);
|
|
127
|
+
}
|
|
128
|
+
getItem(key) {
|
|
129
|
+
return this._data.get(key) ?? null;
|
|
130
|
+
}
|
|
131
|
+
key(index) {
|
|
132
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
133
|
+
if (!test) throw new Error("ReactiveStorage.key: index must be a number");
|
|
134
|
+
})(typeof index === "number");
|
|
135
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
136
|
+
if (!test) throw new Error("ReactiveStorage.key: index must be a non-negative integer");
|
|
137
|
+
})(index >= 0 && Number.isInteger(index));
|
|
138
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
139
|
+
if (!test) throw new Error("ReactiveStorage.key: index must be less than the number of items in storage");
|
|
140
|
+
})(index < this.length);
|
|
141
|
+
let i = 0;
|
|
142
|
+
for (const value of this._data.keys()) {
|
|
143
|
+
if (i === index) return value;
|
|
144
|
+
i++;
|
|
145
|
+
}
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
removeItem(key) {
|
|
149
|
+
if (this._data.has(key)) {
|
|
150
|
+
const oldValue = this._data.get(key) ?? null;
|
|
151
|
+
this._data.delete(key);
|
|
152
|
+
this.#update(key, oldValue, null);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
setItem(key, value) {
|
|
156
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
157
|
+
if (!test) throw new Error("ReactiveStorage.setItem: key must be a string");
|
|
158
|
+
})(typeof key === "string");
|
|
159
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
160
|
+
if (!test) throw new Error("ReactiveStorage.setItem: value must be a string");
|
|
161
|
+
})(typeof value === "string");
|
|
162
|
+
const oldValue = this._data.get(key) ?? null;
|
|
163
|
+
if (oldValue === value) return;
|
|
164
|
+
this._data.set(key, value);
|
|
165
|
+
this.#update(key, oldValue, value);
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Get the singleton CacheStorage instance.
|
|
169
|
+
*
|
|
170
|
+
*/
|
|
171
|
+
static get(cacheId = DEFAULT_CACHE_ID) {
|
|
172
|
+
let cache = CACHES.get(cacheId);
|
|
173
|
+
if (!cache) {
|
|
174
|
+
cache = new CacheStorage(cacheId);
|
|
175
|
+
CACHES.set(cacheId, cache);
|
|
176
|
+
}
|
|
177
|
+
return cache.#inititalization;
|
|
178
|
+
}
|
|
179
|
+
static expectCache(cacheId = DEFAULT_CACHE_ID) {
|
|
180
|
+
const cache = CACHES.get(cacheId);
|
|
181
|
+
if (!cache) throw new Error(`Cache with id ${cacheId} not found. Make sure to call CacheStorage.get(${cacheId}) first.`);
|
|
182
|
+
return cache;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Returns the IDs of all {@link CacheStorage} instances that have been
|
|
186
|
+
* opened in this context via {@link CacheStorage.get}.
|
|
187
|
+
*/
|
|
188
|
+
static getAllCacheIds() {
|
|
189
|
+
return Array.from(CACHES.keys());
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
function serializeToCache(cache, data) {
|
|
193
|
+
const entries = Array.from(data.entries());
|
|
194
|
+
const blob = JSON.stringify({
|
|
195
|
+
version: 1,
|
|
196
|
+
data: entries
|
|
197
|
+
});
|
|
198
|
+
const response = new Response(blob);
|
|
199
|
+
return cache.put(CACHE_URL, response);
|
|
200
|
+
}
|
|
201
|
+
function deserializeFromCache(cache) {
|
|
202
|
+
return cache.match(CACHE_URL).then((response) => {
|
|
203
|
+
if (!response) return /* @__PURE__ */ new Map();
|
|
204
|
+
return response.json().then((json) => {
|
|
205
|
+
if (json.version !== 1) throw new Error(`Unsupported cache version: ${json.version}`);
|
|
206
|
+
return new Map(json.data);
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
//#endregion
|
|
212
|
+
//#region src/storage/storage.ts
|
|
213
|
+
let localStorageInstance = null;
|
|
214
|
+
let sessionStorageInstance = null;
|
|
215
|
+
let localStorageOptions = {};
|
|
216
|
+
let sessionStorageOptions = {};
|
|
217
|
+
/**
|
|
218
|
+
* Retrieves the singleton instance of the LocalStorage service.
|
|
219
|
+
*
|
|
220
|
+
* If the instance does not already exist, it is created.
|
|
221
|
+
*/
|
|
222
|
+
function getLocalStorage() {
|
|
223
|
+
if (!localStorageInstance) localStorageInstance = new ReactiveStorage(localStorage, localStorageOptions);
|
|
224
|
+
return localStorageInstance;
|
|
225
|
+
}
|
|
226
|
+
function getSessionStorage() {
|
|
227
|
+
if (!sessionStorageInstance) sessionStorageInstance = new ReactiveStorage(sessionStorage, sessionStorageOptions);
|
|
228
|
+
return sessionStorageInstance;
|
|
229
|
+
}
|
|
230
|
+
const CacheStorages = /* @__PURE__ */ new Map();
|
|
231
|
+
function getCacheStorage(namespace = null) {
|
|
232
|
+
const key = namespace ?? "reactive-cache";
|
|
233
|
+
let cache = CacheStorages.get(key);
|
|
234
|
+
if (!cache) {
|
|
235
|
+
const storage = CacheStorage.expectCache(key);
|
|
236
|
+
cache = new ReactiveStorage(storage);
|
|
237
|
+
CacheStorages.set(key, cache);
|
|
238
|
+
}
|
|
239
|
+
return cache;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Configure options for the localStorage singleton.
|
|
243
|
+
* Must be called before getLocalStorage() is first invoked.
|
|
244
|
+
*/
|
|
245
|
+
function configureLocalStorage(options) {
|
|
246
|
+
localStorageOptions = options;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Configure options for the sessionStorage singleton.
|
|
250
|
+
* Must be called before getSessionStorage() is first invoked.
|
|
251
|
+
*/
|
|
252
|
+
function configureSessionStorage(options) {
|
|
253
|
+
sessionStorageOptions = options;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Check if an error is a quota exceeded error
|
|
257
|
+
*/
|
|
258
|
+
function isQuotaExceededError(error) {
|
|
259
|
+
if (error instanceof DOMException) {
|
|
260
|
+
if (error.name === "QuotaExceededError") return true;
|
|
261
|
+
if (error.name === "NS_ERROR_DOM_QUOTA_REACHED") return true;
|
|
262
|
+
}
|
|
263
|
+
return false;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Check if an error indicates storage is unavailable (private browsing, etc.)
|
|
267
|
+
*/
|
|
268
|
+
function isStorageUnavailableError(error) {
|
|
269
|
+
if (error instanceof DOMException) {
|
|
270
|
+
if (error.name === "SecurityError") return true;
|
|
271
|
+
if (error.name === "InvalidStateError") return true;
|
|
272
|
+
}
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* A reactive wrapper around the Web Storage API (localStorage/sessionStorage)
|
|
277
|
+
* that provides signal-based access to storage items and length.
|
|
278
|
+
*
|
|
279
|
+
* Will automatically update when storage events occur in other tabs/windows.
|
|
280
|
+
*/
|
|
281
|
+
var ReactiveStorage = class {
|
|
282
|
+
_storage;
|
|
283
|
+
_options;
|
|
284
|
+
_memoryOnly = false;
|
|
285
|
+
_values = {};
|
|
286
|
+
_effects = /* @__PURE__ */ new Map();
|
|
287
|
+
setEffect(key, fn) {
|
|
288
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
289
|
+
if (!test) throw new Error(`Can only set effect once for key: ${key}`);
|
|
290
|
+
})(!this._effects.has(key));
|
|
291
|
+
this._effects.set(key, fn);
|
|
292
|
+
}
|
|
293
|
+
constructor(storage, options = {}) {
|
|
294
|
+
this._storage = storage;
|
|
295
|
+
this._options = options;
|
|
296
|
+
if (!(storage instanceof CacheStorage)) try {
|
|
297
|
+
const testKey = "__storage_test__";
|
|
298
|
+
storage.setItem(testKey, testKey);
|
|
299
|
+
storage.removeItem(testKey);
|
|
300
|
+
this._length = storage.length;
|
|
301
|
+
} catch (error) {
|
|
302
|
+
if (options.fallbackToMemory && isStorageUnavailableError(error)) {
|
|
303
|
+
this._memoryOnly = true;
|
|
304
|
+
this._length = 0;
|
|
305
|
+
} else throw error;
|
|
306
|
+
}
|
|
307
|
+
if (!this._memoryOnly) window.addEventListener("storage", (event) => {
|
|
308
|
+
const data = "detail" in event ? event.detail : event;
|
|
309
|
+
if (data.storageArea === storage) {
|
|
310
|
+
this._values[data.key] = data.newValue;
|
|
311
|
+
this._signals.notify(data.key);
|
|
312
|
+
this._length = this._storage.length;
|
|
313
|
+
const effect = this._effects.get(data.key);
|
|
314
|
+
if (effect) effect(data);
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Reactive access to the number of keys in Storage
|
|
320
|
+
*/
|
|
321
|
+
get length() {
|
|
322
|
+
return this._length;
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Non-reactive way to peek the current value of a key in Storage
|
|
326
|
+
*/
|
|
327
|
+
peekItem(key) {
|
|
328
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
329
|
+
if (!test) throw new Error("ReactiveStorage.peekItem: key must be a string");
|
|
330
|
+
})(typeof key === "string");
|
|
331
|
+
const keyStr = String(key);
|
|
332
|
+
if (this._memoryOnly) return this._values[keyStr] ?? null;
|
|
333
|
+
const value = this._values[keyStr];
|
|
334
|
+
if (value !== void 0) return value;
|
|
335
|
+
return this._storage.getItem(keyStr);
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Reactive access to Storage contents
|
|
339
|
+
*/
|
|
340
|
+
getItem(key) {
|
|
341
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
342
|
+
if (!test) throw new Error("ReactiveStorage.getItem: key must be a string");
|
|
343
|
+
})(typeof key === "string");
|
|
344
|
+
const keyStr = String(key);
|
|
345
|
+
if (this._memoryOnly) {
|
|
346
|
+
this._signals.subscribe(keyStr);
|
|
347
|
+
return this._values[keyStr] ?? null;
|
|
348
|
+
}
|
|
349
|
+
const value = this._values[keyStr];
|
|
350
|
+
if (value !== void 0) {
|
|
351
|
+
this._signals.subscribe(keyStr);
|
|
352
|
+
return value;
|
|
353
|
+
}
|
|
354
|
+
const item = this._storage.getItem(keyStr);
|
|
355
|
+
this._values[keyStr] = item;
|
|
356
|
+
this._signals.subscribe(keyStr);
|
|
357
|
+
return item;
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Set a value in Storage, triggering reactivity
|
|
361
|
+
*/
|
|
362
|
+
setItem(key, value) {
|
|
363
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
364
|
+
if (!test) throw new Error("ReactiveStorage.setItem: key must be a string");
|
|
365
|
+
})(typeof key === "string");
|
|
366
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
367
|
+
if (!test) throw new Error("ReactiveStorage.setItem: value must be a string");
|
|
368
|
+
})(typeof value === "string");
|
|
369
|
+
const keyStr = String(key);
|
|
370
|
+
const valueStr = String(value);
|
|
371
|
+
if (this._values[keyStr] === valueStr) return;
|
|
372
|
+
if (this._memoryOnly) {
|
|
373
|
+
const currentValue = this._values[keyStr];
|
|
374
|
+
if (currentValue === null || currentValue === void 0) this._length += 1;
|
|
375
|
+
this._values[keyStr] = valueStr;
|
|
376
|
+
this._signals.notify(keyStr);
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
try {
|
|
380
|
+
this._storage.setItem(keyStr, valueStr);
|
|
381
|
+
this._values[keyStr] = valueStr;
|
|
382
|
+
this._signals.notify(keyStr);
|
|
383
|
+
this._length = this._storage.length;
|
|
384
|
+
} catch (error) {
|
|
385
|
+
if (isQuotaExceededError(error)) {
|
|
386
|
+
if (this._options.updateOnQuotaExceeded) {
|
|
387
|
+
this._values[keyStr] = valueStr;
|
|
388
|
+
this._signals.notify(keyStr);
|
|
389
|
+
}
|
|
390
|
+
if (this._options.onQuotaExceeded) {
|
|
391
|
+
const result = this._options.onQuotaExceeded(keyStr, valueStr);
|
|
392
|
+
if (result instanceof Promise ? false : result) {
|
|
393
|
+
this._storage.setItem(keyStr, valueStr);
|
|
394
|
+
this._length = this._storage.length;
|
|
395
|
+
}
|
|
396
|
+
} else throw error;
|
|
397
|
+
} else throw error;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Remove a value from Storage, triggering reactivity
|
|
402
|
+
*/
|
|
403
|
+
removeItem(key) {
|
|
404
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
405
|
+
if (!test) throw new Error("ReactiveStorage.removeItem: key must be a string");
|
|
406
|
+
})(typeof key === "string");
|
|
407
|
+
const keyStr = String(key);
|
|
408
|
+
if (this._memoryOnly) {
|
|
409
|
+
const value = this._values[keyStr];
|
|
410
|
+
if (value !== null && value !== void 0) this._length -= 1;
|
|
411
|
+
this._values[keyStr] = null;
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
this._storage.removeItem(keyStr);
|
|
415
|
+
this._values[keyStr] = null;
|
|
416
|
+
this._signals.notify(keyStr);
|
|
417
|
+
this._length = this._storage.length;
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Clears all keys from Storage, triggering reactivity
|
|
421
|
+
*/
|
|
422
|
+
clear() {
|
|
423
|
+
this._values = {};
|
|
424
|
+
this._signals.clear();
|
|
425
|
+
this._length = 0;
|
|
426
|
+
if (this._memoryOnly) return;
|
|
427
|
+
this._storage.clear();
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Reactive access to the key at the given index
|
|
431
|
+
*/
|
|
432
|
+
key(index) {
|
|
433
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
434
|
+
if (!test) throw new Error("ReactiveStorage.key: index must be a number");
|
|
435
|
+
})(typeof index === "number");
|
|
436
|
+
this._length;
|
|
437
|
+
if (this._memoryOnly) return Object.keys(this._values).filter((k) => this._values[k] !== null)[index] ?? null;
|
|
438
|
+
return this._storage.key(index);
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
defineSignal(ReactiveStorage.prototype, "_length", 0);
|
|
442
|
+
defineSignal(ReactiveStorage.prototype, "_signals", makeInitializer(() => new SignalMap()));
|
|
443
|
+
|
|
444
|
+
//#endregion
|
|
445
|
+
//#region src/storage/-private/storage-infra.ts
|
|
446
|
+
/**
|
|
447
|
+
* Configuration options for fields that are also query parameters
|
|
448
|
+
*/
|
|
449
|
+
/**
|
|
450
|
+
* Metadata attached to persisted resource classes
|
|
451
|
+
*/
|
|
452
|
+
/**
|
|
453
|
+
* A function which generates a unique primary-key
|
|
454
|
+
* string for a given LocalResource or SessionResource
|
|
455
|
+
* instance.
|
|
456
|
+
*
|
|
457
|
+
* Use functions when you want to create more than
|
|
458
|
+
* one instance of a resource type, each with its own
|
|
459
|
+
* persisted data.
|
|
460
|
+
*/
|
|
461
|
+
/**
|
|
462
|
+
* Symbol used to store persistence metadata on classes
|
|
463
|
+
*/
|
|
464
|
+
const PERSISTED_RESOURCE_META = Symbol("StorageResourceMeta");
|
|
465
|
+
/**
|
|
466
|
+
* Setup persisted resource metadata on target
|
|
467
|
+
* if not already present
|
|
468
|
+
*
|
|
469
|
+
* @private
|
|
470
|
+
*/
|
|
471
|
+
function initMeta(target) {
|
|
472
|
+
let meta = target[PERSISTED_RESOURCE_META];
|
|
473
|
+
if (!meta) {
|
|
474
|
+
meta = {
|
|
475
|
+
id: "",
|
|
476
|
+
namespace: null,
|
|
477
|
+
pkFn: null,
|
|
478
|
+
type: "",
|
|
479
|
+
fields: /* @__PURE__ */ new Map(),
|
|
480
|
+
initializers: /* @__PURE__ */ new Map(),
|
|
481
|
+
paramConfigs: null,
|
|
482
|
+
paramCompanion: null,
|
|
483
|
+
instances: null,
|
|
484
|
+
typeOverrides: null
|
|
485
|
+
};
|
|
486
|
+
target[PERSISTED_RESOURCE_META] = meta;
|
|
487
|
+
}
|
|
488
|
+
return meta;
|
|
489
|
+
}
|
|
490
|
+
function useMeta(meta, instance) {
|
|
491
|
+
if (meta.id === "" && meta.pkFn) {
|
|
492
|
+
meta.instances = meta.instances ?? /* @__PURE__ */ new WeakMap();
|
|
493
|
+
let instanceMeta = meta.instances.get(instance);
|
|
494
|
+
if (!instanceMeta) {
|
|
495
|
+
instanceMeta = { ...meta };
|
|
496
|
+
const pk = meta.pkFn(instance);
|
|
497
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
498
|
+
if (!test) throw new Error("Primary key function must return a non-empty string.");
|
|
499
|
+
})(typeof pk === "string" && pk.length > 0);
|
|
500
|
+
instanceMeta.id = pk;
|
|
501
|
+
meta.instances.set(instance, instanceMeta);
|
|
502
|
+
}
|
|
503
|
+
return instanceMeta;
|
|
504
|
+
}
|
|
505
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
506
|
+
if (!test) throw new Error("StorageResourceMeta must have a valid id.");
|
|
507
|
+
})(typeof meta.id === "string" && meta.id.length > 0);
|
|
508
|
+
return meta;
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Load storage field
|
|
512
|
+
*/
|
|
513
|
+
function getField(instance, meta, key, overrideType) {
|
|
514
|
+
const stored = getStorage(overrideType || meta.type, meta.namespace).getItem(keyFor(meta, key));
|
|
515
|
+
if (stored) return JSON.parse(stored);
|
|
516
|
+
else {
|
|
517
|
+
const initializer = meta.initializers.get(key);
|
|
518
|
+
if (initializer) {
|
|
519
|
+
const value = initializer.call(instance);
|
|
520
|
+
if (value !== void 0) return value;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
return null;
|
|
524
|
+
}
|
|
525
|
+
function keyFor(meta, key) {
|
|
526
|
+
return `persisted:${meta.id}:${key}`;
|
|
527
|
+
}
|
|
528
|
+
function getStorage(type, namespace) {
|
|
529
|
+
if (type === "local-resource") return getLocalStorage();
|
|
530
|
+
else if (type === "session-resource") return getSessionStorage();
|
|
531
|
+
else return getCacheStorage(namespace);
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Update storage field
|
|
535
|
+
*/
|
|
536
|
+
function setField(meta, key, value, overrideType) {
|
|
537
|
+
getStorage(overrideType || meta.type, meta.namespace).setItem(keyFor(meta, key), JSON.stringify(value));
|
|
538
|
+
}
|
|
539
|
+
function getResourceMeta(target) {
|
|
540
|
+
const meta = target[PERSISTED_RESOURCE_META];
|
|
541
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
542
|
+
if (!test) throw new Error("StorageResourceMeta not found on target. Did you forget to use the @LocalResource() or @SessionResource() decorator?");
|
|
543
|
+
})(meta !== void 0);
|
|
544
|
+
return meta;
|
|
545
|
+
}
|
|
546
|
+
function _createStorageResource(id, type, namespace) {
|
|
547
|
+
return function(target) {
|
|
548
|
+
const meta = getResourceMeta(target.prototype);
|
|
549
|
+
meta.id = typeof id === "string" ? id : "";
|
|
550
|
+
meta.pkFn = typeof id === "function" ? id : null;
|
|
551
|
+
meta.type = type;
|
|
552
|
+
meta.namespace = namespace;
|
|
553
|
+
if (meta.pkFn !== null) {
|
|
554
|
+
const originalConstructor = target.prototype.constructor;
|
|
555
|
+
target.prototype.constructor = function DynamicStorageInitializer(...args) {
|
|
556
|
+
const instance = new originalConstructor(...args);
|
|
557
|
+
installEffectsForDynamicInstance(meta, instance);
|
|
558
|
+
return instance;
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
if (!("toJSON" in target.prototype)) target.prototype.toJSON = function() {
|
|
562
|
+
const instanceMeta = useMeta(meta, this);
|
|
563
|
+
const isLocalResource = meta.type === "local-resource" || meta.type === "cache-resource";
|
|
564
|
+
const fields = isLocalResource ? new Set(meta.fields.keys()) : /* @__PURE__ */ new Set();
|
|
565
|
+
for (const [key, overrideType] of meta.typeOverrides?.entries() ?? []) if (overrideType === "local-storage") fields.add(key);
|
|
566
|
+
else if (overrideType === "session-storage" && isLocalResource) fields.delete(key);
|
|
567
|
+
let idKey = "$key";
|
|
568
|
+
while (fields.has(idKey)) idKey = `_${idKey}`;
|
|
569
|
+
const data = { [idKey]: instanceMeta.id };
|
|
570
|
+
for (const key of fields) {
|
|
571
|
+
const value = getField(this, instanceMeta, key, meta.typeOverrides?.get(key) ?? null);
|
|
572
|
+
if (value !== null) data[key] = value;
|
|
573
|
+
}
|
|
574
|
+
return data;
|
|
575
|
+
};
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
async function installEffectsForDynamicInstance(meta, instance) {
|
|
579
|
+
await Promise.resolve();
|
|
580
|
+
for (const [key, value] of meta.fields.entries()) if (typeof value === "function") installEffect(useMeta(meta, instance), key);
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* Returns the descriptor but is cast
|
|
584
|
+
* to void to satisfy Typescript's incorrect
|
|
585
|
+
* typing for legacy decorators.
|
|
586
|
+
*/
|
|
587
|
+
function setupField(target, key, orgDesc, type) {
|
|
588
|
+
const meta = initMeta(target);
|
|
589
|
+
meta.fields.set(key, null);
|
|
590
|
+
const overrideType = type === "local" ? "local-storage" : type === "session" ? "session-storage" : type === "cache" ? "cache-storage" : null;
|
|
591
|
+
if (overrideType) {
|
|
592
|
+
meta.typeOverrides = meta.typeOverrides || /* @__PURE__ */ new Map();
|
|
593
|
+
meta.typeOverrides.set(key, overrideType);
|
|
594
|
+
}
|
|
595
|
+
const initializer = orgDesc?.initializer || null;
|
|
596
|
+
meta.initializers.set(key, initializer);
|
|
597
|
+
return memoized(target, key, {
|
|
598
|
+
configurable: true,
|
|
599
|
+
enumerable: true,
|
|
600
|
+
get() {
|
|
601
|
+
return getField(this, useMeta(meta, this), key, overrideType);
|
|
602
|
+
},
|
|
603
|
+
set(value) {
|
|
604
|
+
setField(useMeta(meta, this), key, value, overrideType);
|
|
605
|
+
}
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
async function installEffect(meta, key) {
|
|
609
|
+
await Promise.resolve();
|
|
610
|
+
const effect = meta.fields.get(key);
|
|
611
|
+
getStorage(meta.type, meta.namespace).setEffect(keyFor(meta, key), (event) => {
|
|
612
|
+
const oldValue = event.oldValue ? JSON.parse(event.oldValue) : null;
|
|
613
|
+
const newValue = event.newValue ? JSON.parse(event.newValue) : null;
|
|
614
|
+
effect({
|
|
615
|
+
key,
|
|
616
|
+
from: oldValue,
|
|
617
|
+
to: newValue
|
|
618
|
+
});
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Get or create the param companion object for a StorageResource instance.
|
|
623
|
+
*
|
|
624
|
+
* The companion object contains URL-serialized versions of all @param decorated fields.
|
|
625
|
+
* Each param field gets a corresponding property on the companion that:
|
|
626
|
+
* - Reads: Serializes the storage value to a URL string (returns null if not active)
|
|
627
|
+
* - Writes: Deserializes the URL string and updates the storage value
|
|
628
|
+
*
|
|
629
|
+
* The companion object is reactive using trackedObject, ensuring that changes
|
|
630
|
+
* to the underlying storage fields trigger updates in the query param system.
|
|
631
|
+
*
|
|
632
|
+
* This companion object is what QPRoute will bind to for URL query params.
|
|
633
|
+
*
|
|
634
|
+
* @private
|
|
635
|
+
* @param instance - The StorageResource instance
|
|
636
|
+
* @param groupControlMap - Optional map of fieldName -> controlFieldName for grouped params
|
|
637
|
+
* @returns The companion object with serialized param properties
|
|
638
|
+
*/
|
|
639
|
+
function getParamCompanion(instance, groupControlMap) {
|
|
640
|
+
const meta = getResourceMeta(instance);
|
|
641
|
+
const instanceMeta = useMeta(meta, instance);
|
|
642
|
+
if (instanceMeta.paramCompanion) return instanceMeta.paramCompanion;
|
|
643
|
+
const companion = {};
|
|
644
|
+
instanceMeta.paramCompanion = companion;
|
|
645
|
+
const paramConfigs = instanceMeta.paramConfigs;
|
|
646
|
+
if (!paramConfigs || paramConfigs.size === 0) return companion;
|
|
647
|
+
for (const [fieldName, config] of paramConfigs.entries()) {
|
|
648
|
+
const controlFieldName = groupControlMap?.[fieldName];
|
|
649
|
+
createParamField(companion, fieldName, config, controlFieldName, instance, meta);
|
|
650
|
+
}
|
|
651
|
+
return companion;
|
|
652
|
+
}
|
|
653
|
+
function isActiveGroupParam(companion, controlFieldName) {
|
|
654
|
+
return companion[controlFieldName] !== null;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* The default value of a param is determined by:
|
|
658
|
+
* - the getDefault() function if provided, and its return is not undefined
|
|
659
|
+
* - the initializer value provided to the field, if not undefined
|
|
660
|
+
* - null otherwise
|
|
661
|
+
*
|
|
662
|
+
* The value is the deserialized form (i.e., the local storage value type)
|
|
663
|
+
*/
|
|
664
|
+
function getParamFieldDefaultValue(meta, config, fieldName, instance) {
|
|
665
|
+
const defaultValue = config.getDefault?.(instance);
|
|
666
|
+
if (defaultValue !== void 0) return defaultValue;
|
|
667
|
+
const initializer = meta.initializers.get(fieldName);
|
|
668
|
+
if (initializer) {
|
|
669
|
+
const initValue = initializer.call(instance);
|
|
670
|
+
if (initValue !== void 0) return initValue;
|
|
671
|
+
}
|
|
672
|
+
return null;
|
|
673
|
+
}
|
|
674
|
+
function createParamField(companion, fieldName, config, controlFieldName, instance, meta) {
|
|
675
|
+
const desc = {
|
|
676
|
+
configurable: true,
|
|
677
|
+
enumerable: true,
|
|
678
|
+
get() {
|
|
679
|
+
if (!config.initialized) {
|
|
680
|
+
config.initialized = true;
|
|
681
|
+
return null;
|
|
682
|
+
}
|
|
683
|
+
if (controlFieldName && !isActiveGroupParam(companion, controlFieldName)) return null;
|
|
684
|
+
const defaultValue = getParamFieldDefaultValue(meta, config, fieldName, instance);
|
|
685
|
+
const rawValue = instance[fieldName];
|
|
686
|
+
if (rawValue === defaultValue) return null;
|
|
687
|
+
const serialized = config.serialize(rawValue, instance);
|
|
688
|
+
if (!serialized) return null;
|
|
689
|
+
return serialized;
|
|
690
|
+
},
|
|
691
|
+
set(urlValue) {
|
|
692
|
+
/**
|
|
693
|
+
* set will never come from anything except URL deserialization.
|
|
694
|
+
* which is managed by Ember.
|
|
695
|
+
*
|
|
696
|
+
* Our job is to not unnecessarily update the storage resource
|
|
697
|
+
* so we need to run the compare function to see if the
|
|
698
|
+
* incoming URL value is different from the existing local value.
|
|
699
|
+
*/
|
|
700
|
+
if (!urlValue) return;
|
|
701
|
+
const rawValue = instance[fieldName];
|
|
702
|
+
if (config.serialize(rawValue, instance) === urlValue) return;
|
|
703
|
+
instance[fieldName] = config.deserialize(urlValue, instance);
|
|
704
|
+
}
|
|
705
|
+
};
|
|
706
|
+
memoized(companion, fieldName, desc);
|
|
707
|
+
Object.defineProperty(companion, fieldName, desc);
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
//#endregion
|
|
711
|
+
//#region src/storage/storage-resource.ts
|
|
712
|
+
/**
|
|
713
|
+
* Decorator which transforms a class into a StorageResource
|
|
714
|
+
* persisted in localStorage.
|
|
715
|
+
*
|
|
716
|
+
* LocalResources must either be singletons or expect all instances
|
|
717
|
+
* to share state unless a primary key function is provided.
|
|
718
|
+
*
|
|
719
|
+
* When a primary key function is provided, each instance
|
|
720
|
+
* will have its own persisted data based on the key generated
|
|
721
|
+
* by the function.
|
|
722
|
+
*
|
|
723
|
+
* The function will be called once per instance during
|
|
724
|
+
* initialization to determine the unique ID for that instance.
|
|
725
|
+
*/
|
|
726
|
+
function LocalResource(id) {
|
|
727
|
+
return _createStorageResource(id, "local-resource", null);
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Decorator which transforms a class into a StorageResource
|
|
731
|
+
* persisted in sessionStorage.
|
|
732
|
+
*
|
|
733
|
+
* SessionResources must either be singletons or expect all instances
|
|
734
|
+
* to share state unless a primary key function is provided.
|
|
735
|
+
*
|
|
736
|
+
* When a primary key function is provided, each instance
|
|
737
|
+
* will have its own persisted data based on the key generated
|
|
738
|
+
* by the function.
|
|
739
|
+
*
|
|
740
|
+
* The function will be called once per instance during
|
|
741
|
+
* initialization to determine the unique ID for that instance.
|
|
742
|
+
*/
|
|
743
|
+
function SessionResource(id) {
|
|
744
|
+
return _createStorageResource(id, "session-resource", null);
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Decorator which transforms a class into a StorageResource
|
|
748
|
+
* persisted via the [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache).
|
|
749
|
+
* api and shared across all tabs/windows under the same origin.
|
|
750
|
+
*
|
|
751
|
+
* CacheResources must either be singletons or expect all instances
|
|
752
|
+
* to share state unless a primary key function is provided.
|
|
753
|
+
*
|
|
754
|
+
* When a primary key function is provided, each instance
|
|
755
|
+
* will have its own persisted data based on the key generated
|
|
756
|
+
* by the function.
|
|
757
|
+
*
|
|
758
|
+
* The function will be called once per instance during
|
|
759
|
+
* initialization to determine the unique ID for that instance.
|
|
760
|
+
*
|
|
761
|
+
* All object cached in the same `namespace` share the namespace's storage context,
|
|
762
|
+
* so partitioning can be achieved by using different namespaces for different groups
|
|
763
|
+
* of data.
|
|
764
|
+
*/
|
|
765
|
+
function CacheResource(id, namespace = null) {
|
|
766
|
+
return _createStorageResource(id, "cache-resource", namespace);
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Decorator which marks a property as a field on
|
|
770
|
+
* a LocalResource or SessionResource
|
|
771
|
+
*
|
|
772
|
+
* The field's value will be initialized from the persisted resource data
|
|
773
|
+
* if available, falling back to the property's default value otherwise.
|
|
774
|
+
*
|
|
775
|
+
* Fields can be of any type that is serializable to and restorable from JSON,
|
|
776
|
+
* but complex types (like objects or arrays) should be handled with care to avoid
|
|
777
|
+
* unintended mutations or reactivity issues.
|
|
778
|
+
*
|
|
779
|
+
* By default, fields are persisted in the storage type defined by the resource decorator
|
|
780
|
+
* (@LocalResource or @SessionResource). However, you can override this behavior
|
|
781
|
+
* by passing 'local' or 'session' as an argument to the decorator.
|
|
782
|
+
*
|
|
783
|
+
* ---
|
|
784
|
+
*
|
|
785
|
+
* **Example:**
|
|
786
|
+
*
|
|
787
|
+
* ```ts
|
|
788
|
+
* @LocalResource('user-settings')
|
|
789
|
+
* class UserSettings {
|
|
790
|
+
* @field
|
|
791
|
+
* theme: 'light' | 'dark' = 'light';
|
|
792
|
+
*
|
|
793
|
+
* @field('session')
|
|
794
|
+
* sessionToken: string | null = null;
|
|
795
|
+
* }
|
|
796
|
+
* ```
|
|
797
|
+
*
|
|
798
|
+
*/
|
|
799
|
+
function field(...args) {
|
|
800
|
+
if (args.length === 0) {
|
|
801
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
802
|
+
if (!test) throw new Error("field decorator requires at least 1 argument or should be used without parens");
|
|
803
|
+
})(true);
|
|
804
|
+
return setupField;
|
|
805
|
+
}
|
|
806
|
+
if (args.length === 1) {
|
|
807
|
+
const type = args[0];
|
|
808
|
+
return (target, key, desc) => setupField(target, key, desc, type);
|
|
809
|
+
}
|
|
810
|
+
if (args.length === 2 || args.length === 3) {
|
|
811
|
+
const [target, key, descriptor] = args;
|
|
812
|
+
return setupField(target, key, descriptor);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
function input(type) {
|
|
816
|
+
macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
817
|
+
if (!test) throw new Error("input decorator requires a valid type argument");
|
|
818
|
+
})([
|
|
819
|
+
"number",
|
|
820
|
+
"boolean",
|
|
821
|
+
"float"
|
|
822
|
+
].includes(type));
|
|
823
|
+
return function(target, key, desc) {
|
|
824
|
+
const originalSet = desc.set;
|
|
825
|
+
desc.set = function(value) {
|
|
826
|
+
switch (type) {
|
|
827
|
+
case "number":
|
|
828
|
+
value = Number(value);
|
|
829
|
+
break;
|
|
830
|
+
case "boolean":
|
|
831
|
+
value = value === "false" || value === "" || value === "0" || value === "undefined" || value === "null" || value === false || value === 0 || value === null || value === void 0 ? 0 : 1;
|
|
832
|
+
break;
|
|
833
|
+
default: macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) && ((test) => {
|
|
834
|
+
if (!test) throw new Error(`Unsupported input type: ${type}`);
|
|
835
|
+
})(false);
|
|
836
|
+
}
|
|
837
|
+
originalSet.call(this, value);
|
|
838
|
+
};
|
|
839
|
+
return desc;
|
|
840
|
+
};
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Effects are fields that run a side-effecting function.
|
|
844
|
+
*
|
|
845
|
+
* Effects are intended to enable synchronizing get states between
|
|
846
|
+
* tabs or windows that result in needing to synchronize other
|
|
847
|
+
* non-reactive state.
|
|
848
|
+
*
|
|
849
|
+
* For example, when a user selects a light/dark mode theme preference
|
|
850
|
+
* that differs from the system preference, effects can be used to trigger
|
|
851
|
+
* DOM updates on the documentElement necessary to ensure its state is
|
|
852
|
+
* consistent with the persisted resource state and reactive application state.
|
|
853
|
+
*
|
|
854
|
+
* To do this without an effect would require either setting up your own
|
|
855
|
+
* storage event listeners or consuming the reactive state of the property
|
|
856
|
+
* in another effect-like API such as an Ember modifier or React useEffect,
|
|
857
|
+
*
|
|
858
|
+
* Effects *only* run when the stored value changes due to storage events
|
|
859
|
+
* emitted from other tabs or windows. They do not run when the property
|
|
860
|
+
* is updated in the same context.
|
|
861
|
+
*
|
|
862
|
+
* ---
|
|
863
|
+
*
|
|
864
|
+
* **Example:**
|
|
865
|
+
*
|
|
866
|
+
* ```ts
|
|
867
|
+
* @LocalResource('user-preferences')
|
|
868
|
+
* class UserPreferences {
|
|
869
|
+
* @effect(syncThemeToDOM)
|
|
870
|
+
* explicitThemePreference: 'light' | 'dark' | null = null;
|
|
871
|
+
*
|
|
872
|
+
* @matchMedia('(prefers-color-scheme: dark)')
|
|
873
|
+
* systemPrefersDarkMode: boolean = false;
|
|
874
|
+
* }
|
|
875
|
+
*
|
|
876
|
+
* function syncThemeToDOM(update: ValueTransition<'light' | 'dark' | null>): void {
|
|
877
|
+
* const newTheme = update.to;
|
|
878
|
+
* document.documentElement.style.colorScheme = newTheme ?? 'light dark';
|
|
879
|
+
*
|
|
880
|
+
* if (newTheme === 'dark') {
|
|
881
|
+
* document.documentElement.classList.add('dark-theme');
|
|
882
|
+
* document.documentElement.classList.remove('light-theme');
|
|
883
|
+
* } else if (newTheme === 'light') {
|
|
884
|
+
* document.documentElement.classList.add('light-theme');
|
|
885
|
+
* document.documentElement.classList.remove('dark-theme');
|
|
886
|
+
* } else {
|
|
887
|
+
* document.documentElement.classList.remove('light-theme');
|
|
888
|
+
* document.documentElement.classList.remove('dark-theme');
|
|
889
|
+
* }
|
|
890
|
+
* }
|
|
891
|
+
* ```
|
|
892
|
+
*/
|
|
893
|
+
function effect(fn, type) {
|
|
894
|
+
const overrideType = type === "local" ? "local-storage" : type === "session" ? "session-storage" : null;
|
|
895
|
+
return function effectField(target, key, _descriptor) {
|
|
896
|
+
const meta = initMeta(target);
|
|
897
|
+
meta.fields.set(key, fn);
|
|
898
|
+
if (meta.pkFn === null) installEffect(meta, key);
|
|
899
|
+
return {
|
|
900
|
+
configurable: true,
|
|
901
|
+
enumerable: true,
|
|
902
|
+
get() {
|
|
903
|
+
return getField(this, useMeta(meta, this), key, overrideType);
|
|
904
|
+
},
|
|
905
|
+
set(value) {
|
|
906
|
+
setField(useMeta(meta, this), key, value, overrideType);
|
|
907
|
+
}
|
|
908
|
+
};
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
//#endregion
|
|
913
|
+
export { CacheResource, CacheStorage, DEFAULT_CACHE_ID, LocalResource, SessionResource, getParamCompanion as _getParamCompanion, initMeta as _initMeta, configureLocalStorage, configureSessionStorage, effect, field, getCacheStorage, getLocalStorage, getSessionStorage, input };
|
|
914
|
+
//# sourceMappingURL=storage.js.map
|