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