react-native-nitro-storage 0.5.7 → 0.5.9

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.
@@ -0,0 +1,1501 @@
1
+ "use strict";
2
+
3
+ import { assertAccessControlLevel, assertBiometricLevel, canUseRawBatchPath, canUseSecureRawBatchPath, createKeyChange, defaultDeserialize, defaultSerialize, isUpdater, notifyAllListeners, notifyKeyListeners, now, redactSecureKeyChange, runMicrotask, typedKeys } from "./shared";
4
+ import { StorageScope, AccessControl, BiometricLevel } from "./Storage.types";
5
+ import { MIGRATION_VERSION_KEY, isStoredEnvelope, assertBatchScope, assertValidScope, toVersionToken, prefixKey, isNamespaced } from "./internal";
6
+ import { StorageEventRegistry } from "./storage-events";
7
+ function asInternal(item) {
8
+ return item;
9
+ }
10
+ export function createStorageCore(buildAdapter) {
11
+ const registeredMigrations = new Map();
12
+ const memoryStore = new Map();
13
+ const memoryListeners = new Map();
14
+ const scopedListeners = new Map([[StorageScope.Disk, new Map()], [StorageScope.Secure, new Map()]]);
15
+ const scopedRawCache = new Map([[StorageScope.Disk, new Map()], [StorageScope.Secure, new Map()]]);
16
+ const pendingDiskWrites = new Map();
17
+ let diskFlushScheduled = false;
18
+ let diskWritesAsync = false;
19
+ const pendingSecureWrites = new Map();
20
+ let secureFlushScheduled = false;
21
+ let secureDefaultAccessControl = AccessControl.WhenUnlocked;
22
+ let metricsObserver;
23
+ let eventObserver;
24
+ let eventObserverRedactSecureValues = true;
25
+ const metricsCounters = new Map();
26
+ const storageEvents = new StorageEventRegistry();
27
+ function recordMetric(operation, scope, durationMs, keysCount = 1) {
28
+ const existing = metricsCounters.get(operation);
29
+ if (!existing) {
30
+ metricsCounters.set(operation, {
31
+ count: 1,
32
+ totalDurationMs: durationMs,
33
+ maxDurationMs: durationMs
34
+ });
35
+ } else {
36
+ existing.count += 1;
37
+ existing.totalDurationMs += durationMs;
38
+ existing.maxDurationMs = Math.max(existing.maxDurationMs, durationMs);
39
+ }
40
+ metricsObserver?.({
41
+ operation,
42
+ scope,
43
+ durationMs,
44
+ keysCount
45
+ });
46
+ }
47
+ function measureOperation(operation, scope, fn, keysCount = 1) {
48
+ if (!metricsObserver) {
49
+ return fn();
50
+ }
51
+ const start = now();
52
+ try {
53
+ return fn();
54
+ } finally {
55
+ recordMetric(operation, scope, now() - start, keysCount);
56
+ }
57
+ }
58
+ function getScopedListeners(scope) {
59
+ return scopedListeners.get(scope);
60
+ }
61
+ function getScopeRawCache(scope) {
62
+ return scopedRawCache.get(scope);
63
+ }
64
+ function cacheRawValue(scope, key, value) {
65
+ getScopeRawCache(scope).set(key, value);
66
+ }
67
+ function readCachedRawValue(scope, key) {
68
+ return getScopeRawCache(scope).get(key);
69
+ }
70
+ function clearScopeRawCache(scope) {
71
+ getScopeRawCache(scope).clear();
72
+ }
73
+ function addKeyListener(registry, key, listener) {
74
+ let listeners = registry.get(key);
75
+ if (!listeners) {
76
+ listeners = new Set();
77
+ registry.set(key, listeners);
78
+ }
79
+ listeners.add(listener);
80
+ return () => {
81
+ const keyListeners = registry.get(key);
82
+ if (!keyListeners) {
83
+ return;
84
+ }
85
+ keyListeners.delete(listener);
86
+ if (keyListeners.size === 0) {
87
+ registry.delete(key);
88
+ }
89
+ };
90
+ }
91
+ function getEventRawValue(scope, key) {
92
+ if (scope === StorageScope.Memory) {
93
+ const value = memoryStore.get(key);
94
+ return typeof value === "string" ? value : undefined;
95
+ }
96
+ return getRawValue(key, scope);
97
+ }
98
+ function shouldReadPreviousEventValues(scope) {
99
+ if (storageEvents.hasListeners(scope)) {
100
+ return true;
101
+ }
102
+ if (!eventObserver) {
103
+ return false;
104
+ }
105
+ return scope !== StorageScope.Secure || !eventObserverRedactSecureValues;
106
+ }
107
+ function eventForGlobalObserver(event) {
108
+ if (!eventObserverRedactSecureValues || event.scope !== StorageScope.Secure) {
109
+ return event;
110
+ }
111
+ if (event.type === "key") {
112
+ return redactSecureKeyChange(event);
113
+ }
114
+ return {
115
+ ...event,
116
+ changes: event.changes.map(redactSecureKeyChange)
117
+ };
118
+ }
119
+ function emitKeyChange(scope, key, oldValue, newValue, operation, source) {
120
+ adapter.onWillEmitChanges(scope, [key], operation, source);
121
+ const event = createKeyChange(scope, key, oldValue, newValue, operation, source);
122
+ storageEvents.emitKey(event);
123
+ eventObserver?.(eventForGlobalObserver(event));
124
+ }
125
+ function emitBatchChange(scope, operation, source, changes) {
126
+ if (changes.length === 0) {
127
+ return;
128
+ }
129
+ adapter.onWillEmitChanges(scope, changes.map(change => change.key), operation, source);
130
+ const event = {
131
+ type: "batch",
132
+ scope,
133
+ operation,
134
+ source,
135
+ changes
136
+ };
137
+ storageEvents.emitBatch(event);
138
+ eventObserver?.(eventForGlobalObserver(event));
139
+ }
140
+ function readPendingSecureWrite(key) {
141
+ return pendingSecureWrites.get(key)?.value;
142
+ }
143
+ function readPendingDiskWrite(key) {
144
+ return pendingDiskWrites.get(key)?.value;
145
+ }
146
+ function hasPendingDiskWrite(key) {
147
+ return pendingDiskWrites.has(key);
148
+ }
149
+ function hasPendingSecureWrite(key) {
150
+ return pendingSecureWrites.has(key);
151
+ }
152
+ function clearPendingDiskWrite(key) {
153
+ pendingDiskWrites.delete(key);
154
+ }
155
+ function clearPendingSecureWrite(key) {
156
+ pendingSecureWrites.delete(key);
157
+ }
158
+ function flushDiskWrites() {
159
+ diskFlushScheduled = false;
160
+ if (pendingDiskWrites.size === 0) {
161
+ return;
162
+ }
163
+ const writes = Array.from(pendingDiskWrites.values());
164
+ pendingDiskWrites.clear();
165
+ const keysToSet = [];
166
+ const valuesToSet = [];
167
+ const keysToRemove = [];
168
+ writes.forEach(({
169
+ key,
170
+ value
171
+ }) => {
172
+ if (value === undefined) {
173
+ keysToRemove.push(key);
174
+ return;
175
+ }
176
+ keysToSet.push(key);
177
+ valuesToSet.push(value);
178
+ });
179
+ if (keysToSet.length > 0) {
180
+ adapter.backend.setBatch(keysToSet, valuesToSet, StorageScope.Disk);
181
+ }
182
+ if (keysToRemove.length > 0) {
183
+ adapter.backend.removeBatch(keysToRemove, StorageScope.Disk);
184
+ }
185
+ }
186
+ function flushSecureWrites() {
187
+ secureFlushScheduled = false;
188
+ if (pendingSecureWrites.size === 0) {
189
+ return;
190
+ }
191
+ const writes = Array.from(pendingSecureWrites.values());
192
+ pendingSecureWrites.clear();
193
+ const groupedSetWrites = new Map();
194
+ const keysToRemove = [];
195
+ writes.forEach(({
196
+ key,
197
+ value,
198
+ accessControl
199
+ }) => {
200
+ if (value === undefined) {
201
+ keysToRemove.push(key);
202
+ } else {
203
+ const resolvedAccessControl = accessControl ?? secureDefaultAccessControl;
204
+ const existingGroup = groupedSetWrites.get(resolvedAccessControl);
205
+ const group = existingGroup ?? {
206
+ keys: [],
207
+ values: []
208
+ };
209
+ group.keys.push(key);
210
+ group.values.push(value);
211
+ if (!existingGroup) {
212
+ groupedSetWrites.set(resolvedAccessControl, group);
213
+ }
214
+ }
215
+ });
216
+ groupedSetWrites.forEach((group, accessControl) => {
217
+ adapter.backend.setSecureAccessControl(accessControl);
218
+ adapter.backend.setBatch(group.keys, group.values, StorageScope.Secure);
219
+ });
220
+ if (keysToRemove.length > 0) {
221
+ adapter.backend.removeBatch(keysToRemove, StorageScope.Secure);
222
+ }
223
+ }
224
+ function scheduleDiskWrite(key, value) {
225
+ pendingDiskWrites.set(key, {
226
+ key,
227
+ value
228
+ });
229
+ if (diskFlushScheduled) {
230
+ return;
231
+ }
232
+ diskFlushScheduled = true;
233
+ runMicrotask(flushDiskWrites);
234
+ }
235
+ function scheduleSecureWrite(key, value, accessControl) {
236
+ const pendingWrite = {
237
+ key,
238
+ value
239
+ };
240
+ if (accessControl !== undefined) {
241
+ pendingWrite.accessControl = accessControl;
242
+ }
243
+ pendingSecureWrites.set(key, pendingWrite);
244
+ if (secureFlushScheduled) {
245
+ return;
246
+ }
247
+ secureFlushScheduled = true;
248
+ runMicrotask(flushSecureWrites);
249
+ }
250
+ function getRawValue(key, scope) {
251
+ assertValidScope(scope);
252
+ if (scope === StorageScope.Memory) {
253
+ const value = memoryStore.get(key);
254
+ return typeof value === "string" ? value : undefined;
255
+ }
256
+ if (scope === StorageScope.Disk && hasPendingDiskWrite(key)) {
257
+ return readPendingDiskWrite(key);
258
+ }
259
+ if (scope === StorageScope.Secure && hasPendingSecureWrite(key)) {
260
+ return readPendingSecureWrite(key);
261
+ }
262
+ return adapter.backend.get(key, scope);
263
+ }
264
+ function setRawValue(key, value, scope) {
265
+ assertValidScope(scope);
266
+ const oldValue = scope === StorageScope.Memory ? getEventRawValue(scope, key) : undefined;
267
+ if (scope === StorageScope.Memory) {
268
+ memoryStore.set(key, value);
269
+ notifyKeyListeners(memoryListeners, key);
270
+ emitKeyChange(scope, key, oldValue, value, "set", "memory");
271
+ return;
272
+ }
273
+ if (scope === StorageScope.Disk) {
274
+ cacheRawValue(scope, key, value);
275
+ if (diskWritesAsync) {
276
+ scheduleDiskWrite(key, value);
277
+ emitKeyChange(scope, key, oldValue, value, "set", adapter.changeSource);
278
+ return;
279
+ }
280
+ flushDiskWrites();
281
+ clearPendingDiskWrite(key);
282
+ }
283
+ if (scope === StorageScope.Secure) {
284
+ flushSecureWrites();
285
+ clearPendingSecureWrite(key);
286
+ if (adapter.applyAccessControlOnSecureRawWrite) {
287
+ adapter.backend.setSecureAccessControl(secureDefaultAccessControl);
288
+ }
289
+ }
290
+ adapter.backend.set(key, value, scope);
291
+ cacheRawValue(scope, key, value);
292
+ emitKeyChange(scope, key, oldValue, value, "set", adapter.changeSource);
293
+ }
294
+ function removeRawValue(key, scope) {
295
+ assertValidScope(scope);
296
+ const oldValue = getEventRawValue(scope, key);
297
+ if (scope === StorageScope.Memory) {
298
+ memoryStore.delete(key);
299
+ notifyKeyListeners(memoryListeners, key);
300
+ emitKeyChange(scope, key, oldValue, undefined, "remove", "memory");
301
+ return;
302
+ }
303
+ if (scope === StorageScope.Disk) {
304
+ cacheRawValue(scope, key, undefined);
305
+ if (diskWritesAsync) {
306
+ scheduleDiskWrite(key, undefined);
307
+ emitKeyChange(scope, key, oldValue, undefined, "remove", adapter.changeSource);
308
+ return;
309
+ }
310
+ flushDiskWrites();
311
+ clearPendingDiskWrite(key);
312
+ }
313
+ if (scope === StorageScope.Secure) {
314
+ flushSecureWrites();
315
+ clearPendingSecureWrite(key);
316
+ }
317
+ adapter.backend.remove(key, scope);
318
+ cacheRawValue(scope, key, undefined);
319
+ emitKeyChange(scope, key, oldValue, undefined, "remove", adapter.changeSource);
320
+ }
321
+ function readMigrationVersion(scope) {
322
+ const raw = getRawValue(MIGRATION_VERSION_KEY, scope);
323
+ if (raw === undefined) {
324
+ return 0;
325
+ }
326
+ const parsed = Number.parseInt(raw, 10);
327
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
328
+ }
329
+ function writeMigrationVersion(scope, version) {
330
+ setRawValue(MIGRATION_VERSION_KEY, String(version), scope);
331
+ }
332
+ const internals = {
333
+ getScopedListeners,
334
+ cacheRawValue,
335
+ readCachedRawValue,
336
+ clearScopeRawCache,
337
+ clearPendingDiskWrite,
338
+ clearPendingSecureWrite,
339
+ clearAllPendingDiskWrites: () => {
340
+ pendingDiskWrites.clear();
341
+ },
342
+ clearAllPendingSecureWrites: () => {
343
+ pendingSecureWrites.clear();
344
+ },
345
+ flushDiskWrites,
346
+ flushSecureWrites,
347
+ emitKeyChange,
348
+ hasEventObserver: () => eventObserver !== undefined,
349
+ hasScopeEventListeners: scope => storageEvents.hasListeners(scope),
350
+ measureOperation,
351
+ recordMetric,
352
+ getSecureDefaultAccessControl: () => secureDefaultAccessControl,
353
+ setSecureDefaultAccessControl: level => {
354
+ secureDefaultAccessControl = level;
355
+ }
356
+ };
357
+ const adapter = buildAdapter(internals);
358
+ const storage = {
359
+ subscribe: (scope, listener) => {
360
+ assertValidScope(scope);
361
+ if (scope !== StorageScope.Memory) {
362
+ adapter.ensureScopeSubscription(scope);
363
+ const unsubscribe = storageEvents.subscribe(scope, listener);
364
+ return () => {
365
+ unsubscribe();
366
+ adapter.maybeCleanupScopeSubscription(scope);
367
+ };
368
+ }
369
+ return storageEvents.subscribe(scope, listener);
370
+ },
371
+ subscribeKey: (scope, key, listener) => {
372
+ assertValidScope(scope);
373
+ if (scope !== StorageScope.Memory) {
374
+ adapter.ensureScopeSubscription(scope);
375
+ const unsubscribe = storageEvents.subscribeKey(scope, key, listener);
376
+ return () => {
377
+ unsubscribe();
378
+ adapter.maybeCleanupScopeSubscription(scope);
379
+ };
380
+ }
381
+ return storageEvents.subscribeKey(scope, key, listener);
382
+ },
383
+ subscribePrefix: (scope, prefix, listener) => {
384
+ assertValidScope(scope);
385
+ if (scope !== StorageScope.Memory) {
386
+ adapter.ensureScopeSubscription(scope);
387
+ const unsubscribe = storageEvents.subscribePrefix(scope, prefix, listener);
388
+ return () => {
389
+ unsubscribe();
390
+ adapter.maybeCleanupScopeSubscription(scope);
391
+ };
392
+ }
393
+ return storageEvents.subscribePrefix(scope, prefix, listener);
394
+ },
395
+ subscribeNamespace: (namespace, scope, listener) => {
396
+ return storage.subscribePrefix(scope, prefixKey(namespace, ""), listener);
397
+ },
398
+ setEventObserver: (observer, options = {}) => {
399
+ eventObserver = observer;
400
+ eventObserverRedactSecureValues = options.redactSecureValues !== false;
401
+ if (observer) {
402
+ adapter.ensureScopeSubscription(StorageScope.Disk);
403
+ adapter.ensureScopeSubscription(StorageScope.Secure);
404
+ return;
405
+ }
406
+ adapter.maybeCleanupScopeSubscription(StorageScope.Disk);
407
+ adapter.maybeCleanupScopeSubscription(StorageScope.Secure);
408
+ },
409
+ clear: scope => {
410
+ measureOperation("storage:clear", scope, () => {
411
+ const previousValues = shouldReadPreviousEventValues(scope) ? storage.getAll(scope) : {};
412
+ if (scope === StorageScope.Memory) {
413
+ memoryStore.clear();
414
+ notifyAllListeners(memoryListeners);
415
+ emitBatchChange(scope, "clear", "memory", Object.keys(previousValues).map(key => createKeyChange(scope, key, previousValues[key], undefined, "clear", "memory")));
416
+ return;
417
+ }
418
+ if (scope === StorageScope.Disk) {
419
+ flushDiskWrites();
420
+ pendingDiskWrites.clear();
421
+ }
422
+ if (scope === StorageScope.Secure) {
423
+ flushSecureWrites();
424
+ pendingSecureWrites.clear();
425
+ }
426
+ clearScopeRawCache(scope);
427
+ adapter.backend.clear(scope);
428
+ emitBatchChange(scope, "clear", adapter.changeSource, Object.keys(previousValues).map(key => createKeyChange(scope, key, previousValues[key], undefined, "clear", adapter.changeSource)));
429
+ });
430
+ },
431
+ clearAll: () => {
432
+ measureOperation("storage:clearAll", StorageScope.Memory, () => {
433
+ storage.clear(StorageScope.Memory);
434
+ storage.clear(StorageScope.Disk);
435
+ storage.clear(StorageScope.Secure);
436
+ }, 3);
437
+ },
438
+ clearNamespace: (namespace, scope) => {
439
+ measureOperation("storage:clearNamespace", scope, () => {
440
+ assertValidScope(scope);
441
+ if (scope === StorageScope.Memory) {
442
+ const affectedKeys = Array.from(memoryStore.keys()).filter(key => isNamespaced(key, namespace));
443
+ const previousValues = affectedKeys.map(key => ({
444
+ key,
445
+ value: getEventRawValue(scope, key)
446
+ }));
447
+ if (affectedKeys.length === 0) {
448
+ return;
449
+ }
450
+ affectedKeys.forEach(key => {
451
+ memoryStore.delete(key);
452
+ });
453
+ affectedKeys.forEach(key => notifyKeyListeners(memoryListeners, key));
454
+ emitBatchChange(scope, "clearNamespace", "memory", previousValues.map(({
455
+ key,
456
+ value
457
+ }) => createKeyChange(scope, key, value, undefined, "clearNamespace", "memory")));
458
+ return;
459
+ }
460
+ const keyPrefix = prefixKey(namespace, "");
461
+ const previousValues = shouldReadPreviousEventValues(scope) ? storage.getByPrefix(keyPrefix, scope) : {};
462
+ if (scope === StorageScope.Disk) {
463
+ flushDiskWrites();
464
+ }
465
+ if (scope === StorageScope.Secure) {
466
+ flushSecureWrites();
467
+ }
468
+ const scopeCache = getScopeRawCache(scope);
469
+ for (const key of scopeCache.keys()) {
470
+ if (isNamespaced(key, namespace)) {
471
+ scopeCache.delete(key);
472
+ }
473
+ }
474
+ adapter.backend.removeByPrefix(keyPrefix, scope);
475
+ emitBatchChange(scope, "clearNamespace", adapter.changeSource, Object.keys(previousValues).map(key => createKeyChange(scope, key, previousValues[key], undefined, "clearNamespace", adapter.changeSource)));
476
+ });
477
+ },
478
+ clearBiometric: () => {
479
+ measureOperation("storage:clearBiometric", StorageScope.Secure, () => {
480
+ adapter.backend.clearSecureBiometric();
481
+ });
482
+ },
483
+ has: (key, scope) => {
484
+ return measureOperation("storage:has", scope, () => {
485
+ assertValidScope(scope);
486
+ if (scope === StorageScope.Memory) {
487
+ return memoryStore.has(key);
488
+ }
489
+ if (scope === StorageScope.Disk) {
490
+ flushDiskWrites();
491
+ }
492
+ if (scope === StorageScope.Secure) {
493
+ flushSecureWrites();
494
+ }
495
+ return adapter.backend.has(key, scope);
496
+ });
497
+ },
498
+ getAllKeys: scope => {
499
+ return measureOperation("storage:getAllKeys", scope, () => {
500
+ assertValidScope(scope);
501
+ if (scope === StorageScope.Memory) {
502
+ return Array.from(memoryStore.keys());
503
+ }
504
+ if (scope === StorageScope.Disk) {
505
+ flushDiskWrites();
506
+ }
507
+ if (scope === StorageScope.Secure) {
508
+ flushSecureWrites();
509
+ }
510
+ return adapter.backend.getAllKeys(scope);
511
+ });
512
+ },
513
+ getKeysByPrefix: (prefix, scope) => {
514
+ return measureOperation("storage:getKeysByPrefix", scope, () => {
515
+ assertValidScope(scope);
516
+ if (scope === StorageScope.Memory) {
517
+ return Array.from(memoryStore.keys()).filter(key => key.startsWith(prefix));
518
+ }
519
+ if (scope === StorageScope.Disk) {
520
+ flushDiskWrites();
521
+ }
522
+ if (scope === StorageScope.Secure) {
523
+ flushSecureWrites();
524
+ }
525
+ return adapter.backend.getKeysByPrefix(prefix, scope);
526
+ });
527
+ },
528
+ getByPrefix: (prefix, scope) => {
529
+ return measureOperation("storage:getByPrefix", scope, () => {
530
+ const result = {};
531
+ const keys = storage.getKeysByPrefix(prefix, scope);
532
+ if (keys.length === 0) {
533
+ return result;
534
+ }
535
+ if (scope === StorageScope.Memory) {
536
+ keys.forEach(key => {
537
+ const value = memoryStore.get(key);
538
+ if (typeof value === "string") {
539
+ result[key] = value;
540
+ }
541
+ });
542
+ return result;
543
+ }
544
+ if (scope === StorageScope.Disk) {
545
+ flushDiskWrites();
546
+ }
547
+ if (scope === StorageScope.Secure) {
548
+ flushSecureWrites();
549
+ }
550
+ const values = adapter.backend.getBatch(keys, scope);
551
+ keys.forEach((key, idx) => {
552
+ const value = values[idx];
553
+ if (value !== undefined) {
554
+ result[key] = value;
555
+ }
556
+ });
557
+ return result;
558
+ });
559
+ },
560
+ getAll: scope => {
561
+ return measureOperation("storage:getAll", scope, () => {
562
+ assertValidScope(scope);
563
+ const result = {};
564
+ if (scope === StorageScope.Memory) {
565
+ for (const key of memoryStore.keys()) {
566
+ const value = memoryStore.get(key);
567
+ if (typeof value === "string") result[key] = value;
568
+ }
569
+ return result;
570
+ }
571
+ if (scope === StorageScope.Disk) {
572
+ flushDiskWrites();
573
+ }
574
+ if (scope === StorageScope.Secure) {
575
+ flushSecureWrites();
576
+ }
577
+ const keys = adapter.backend.getAllKeys(scope);
578
+ if (keys.length === 0) return result;
579
+ const values = adapter.backend.getBatch(keys, scope);
580
+ keys.forEach((key, idx) => {
581
+ const val = values[idx];
582
+ if (val !== undefined) result[key] = val;
583
+ });
584
+ return result;
585
+ });
586
+ },
587
+ export: (scope, options = {}) => {
588
+ if (scope === StorageScope.Secure && options.includeSecureValues !== true) {
589
+ throw new Error("NitroStorage: exporting Secure scope exposes raw secret values. Pass { includeSecureValues: true } or use exportSecureUnsafe().");
590
+ }
591
+ return measureOperation("storage:export", scope, () => storage.getAll(scope));
592
+ },
593
+ exportSecureUnsafe: () => {
594
+ return measureOperation("storage:exportSecureUnsafe", StorageScope.Secure, () => storage.getAll(StorageScope.Secure));
595
+ },
596
+ size: scope => {
597
+ return measureOperation("storage:size", scope, () => {
598
+ assertValidScope(scope);
599
+ if (scope === StorageScope.Memory) {
600
+ return memoryStore.size;
601
+ }
602
+ if (scope === StorageScope.Disk) {
603
+ flushDiskWrites();
604
+ }
605
+ if (scope === StorageScope.Secure) {
606
+ flushSecureWrites();
607
+ }
608
+ return adapter.backend.size(scope);
609
+ });
610
+ },
611
+ setDiskWritesAsync: enabled => {
612
+ measureOperation("storage:setDiskWritesAsync", StorageScope.Disk, () => {
613
+ diskWritesAsync = enabled;
614
+ if (!enabled) {
615
+ flushDiskWrites();
616
+ }
617
+ });
618
+ },
619
+ flushDiskWrites: () => {
620
+ measureOperation("storage:flushDiskWrites", StorageScope.Disk, () => {
621
+ flushDiskWrites();
622
+ });
623
+ },
624
+ flushSecureWrites: () => {
625
+ measureOperation("storage:flushSecureWrites", StorageScope.Secure, () => {
626
+ flushSecureWrites();
627
+ });
628
+ },
629
+ setMetricsObserver: observer => {
630
+ metricsObserver = observer;
631
+ },
632
+ getMetricsSnapshot: () => {
633
+ const snapshot = {};
634
+ metricsCounters.forEach((value, key) => {
635
+ snapshot[key] = {
636
+ count: value.count,
637
+ totalDurationMs: value.totalDurationMs,
638
+ avgDurationMs: value.count === 0 ? 0 : value.totalDurationMs / value.count,
639
+ maxDurationMs: value.maxDurationMs
640
+ };
641
+ });
642
+ return snapshot;
643
+ },
644
+ resetMetrics: () => {
645
+ metricsCounters.clear();
646
+ },
647
+ getSecureMetadata: key => {
648
+ return measureOperation("storage:getSecureMetadata", StorageScope.Secure, () => {
649
+ flushSecureWrites();
650
+ const profile = adapter.getSecureMetadataProfile();
651
+ const biometricProtected = adapter.backend.hasSecureBiometric(key);
652
+ const exists = biometricProtected || adapter.backend.has(key, StorageScope.Secure);
653
+ let kind = "missing";
654
+ if (exists) {
655
+ kind = biometricProtected ? "biometric" : "secure";
656
+ }
657
+ return {
658
+ key,
659
+ exists,
660
+ kind,
661
+ backend: profile.backend,
662
+ encrypted: profile.encrypted,
663
+ hardwareBacked: profile.hardwareBacked,
664
+ biometricProtected,
665
+ valueExposed: false
666
+ };
667
+ });
668
+ },
669
+ getAllSecureMetadata: () => {
670
+ return measureOperation("storage:getAllSecureMetadata", StorageScope.Secure, () => {
671
+ flushSecureWrites();
672
+ return adapter.backend.getAllKeys(StorageScope.Secure).map(key => storage.getSecureMetadata(key));
673
+ });
674
+ },
675
+ getString: (key, scope) => {
676
+ return measureOperation("storage:getString", scope, () => {
677
+ return getRawValue(key, scope);
678
+ });
679
+ },
680
+ setString: (key, value, scope) => {
681
+ measureOperation("storage:setString", scope, () => {
682
+ setRawValue(key, value, scope);
683
+ });
684
+ },
685
+ deleteString: (key, scope) => {
686
+ measureOperation("storage:deleteString", scope, () => {
687
+ removeRawValue(key, scope);
688
+ });
689
+ },
690
+ import: (data, scope) => {
691
+ const keys = Object.keys(data);
692
+ measureOperation("storage:import", scope, () => {
693
+ assertValidScope(scope);
694
+ if (keys.length === 0) return;
695
+ const values = keys.map(k => data[k]);
696
+ const changes = keys.map((key, index) => createKeyChange(scope, key, getEventRawValue(scope, key), values[index], "import", scope === StorageScope.Memory ? "memory" : adapter.changeSource));
697
+ if (scope === StorageScope.Memory) {
698
+ keys.forEach((key, index) => {
699
+ memoryStore.set(key, values[index]);
700
+ });
701
+ keys.forEach(key => notifyKeyListeners(memoryListeners, key));
702
+ emitBatchChange(scope, "import", "memory", changes);
703
+ return;
704
+ }
705
+ if (scope === StorageScope.Secure) {
706
+ flushSecureWrites();
707
+ adapter.backend.setSecureAccessControl(secureDefaultAccessControl);
708
+ }
709
+ if (scope === StorageScope.Disk && adapter.flushDiskWritesOnImport) {
710
+ flushDiskWrites();
711
+ }
712
+ adapter.backend.setBatch(keys, values, scope);
713
+ keys.forEach((key, index) => cacheRawValue(scope, key, values[index]));
714
+ emitBatchChange(scope, "import", adapter.changeSource, changes);
715
+ }, keys.length);
716
+ }
717
+ };
718
+ function createStorageItem(config) {
719
+ const storageKey = prefixKey(config.namespace, config.key);
720
+ const serialize = config.serialize ?? defaultSerialize;
721
+ const deserialize = config.deserialize ?? defaultDeserialize;
722
+ const isMemory = config.scope === StorageScope.Memory;
723
+ const resolvedBiometricLevel = config.scope === StorageScope.Secure ? config.biometricLevel ?? (config.biometric === true ? BiometricLevel.BiometryOnly : BiometricLevel.None) : BiometricLevel.None;
724
+ const isBiometric = resolvedBiometricLevel !== BiometricLevel.None;
725
+ const secureAccessControl = config.accessControl;
726
+ const validate = config.validate;
727
+ const onValidationError = config.onValidationError;
728
+ const expiration = config.expiration;
729
+ const onExpired = config.onExpired;
730
+ const expirationTtlMs = expiration?.ttlMs;
731
+ const memoryExpiration = expiration && isMemory ? new Map() : null;
732
+ const readCache = !isMemory && config.readCache === true;
733
+ const coalesceDiskWrites = config.scope === StorageScope.Disk && config.coalesceDiskWrites === true;
734
+ const coalesceSecureWrites = config.scope === StorageScope.Secure && config.coalesceSecureWrites === true && !isBiometric;
735
+ const defaultValue = config.defaultValue;
736
+ const nonMemoryScope = config.scope === StorageScope.Disk ? StorageScope.Disk : config.scope === StorageScope.Secure ? StorageScope.Secure : null;
737
+ if (expiration && expiration.ttlMs <= 0) {
738
+ throw new Error("expiration.ttlMs must be greater than 0.");
739
+ }
740
+ if (config.scope === StorageScope.Secure) {
741
+ assertBiometricLevel(resolvedBiometricLevel);
742
+ if (secureAccessControl !== undefined) {
743
+ assertAccessControlLevel(secureAccessControl);
744
+ }
745
+ }
746
+ const listeners = new Set();
747
+ let unsubscribe = null;
748
+ let lastRaw = undefined;
749
+ let lastValue;
750
+ let hasLastValue = false;
751
+ let lastExpiresAt = undefined;
752
+ const invalidateParsedCache = () => {
753
+ lastRaw = undefined;
754
+ lastValue = undefined;
755
+ hasLastValue = false;
756
+ lastExpiresAt = undefined;
757
+ };
758
+ const ensureSubscription = () => {
759
+ if (unsubscribe) {
760
+ return;
761
+ }
762
+ const listener = () => {
763
+ invalidateParsedCache();
764
+ listeners.forEach(callback => callback());
765
+ };
766
+ if (isMemory) {
767
+ unsubscribe = addKeyListener(memoryListeners, storageKey, listener);
768
+ return;
769
+ }
770
+ adapter.ensureScopeSubscription(nonMemoryScope);
771
+ unsubscribe = addKeyListener(getScopedListeners(nonMemoryScope), storageKey, listener);
772
+ };
773
+ const readStoredRaw = () => {
774
+ if (isMemory) {
775
+ if (memoryExpiration) {
776
+ const expiresAt = memoryExpiration.get(storageKey);
777
+ if (expiresAt !== undefined && expiresAt <= Date.now()) {
778
+ memoryExpiration.delete(storageKey);
779
+ memoryStore.delete(storageKey);
780
+ notifyKeyListeners(memoryListeners, storageKey);
781
+ onExpired?.(storageKey);
782
+ return undefined;
783
+ }
784
+ }
785
+ return memoryStore.get(storageKey);
786
+ }
787
+ if (nonMemoryScope === StorageScope.Disk) {
788
+ const pending = pendingDiskWrites.get(storageKey);
789
+ if (pending !== undefined) {
790
+ return pending.value;
791
+ }
792
+ }
793
+ if (nonMemoryScope === StorageScope.Secure && !isBiometric) {
794
+ const pending = pendingSecureWrites.get(storageKey);
795
+ if (pending !== undefined) {
796
+ return pending.value;
797
+ }
798
+ }
799
+ if (readCache) {
800
+ const cache = getScopeRawCache(nonMemoryScope);
801
+ const cached = cache.get(storageKey);
802
+ if (cached !== undefined || cache.has(storageKey)) {
803
+ return cached;
804
+ }
805
+ }
806
+ if (isBiometric) {
807
+ return adapter.backend.getSecureBiometric(storageKey);
808
+ }
809
+ const raw = adapter.backend.get(storageKey, config.scope);
810
+ cacheRawValue(nonMemoryScope, storageKey, raw);
811
+ return raw;
812
+ };
813
+ const writeStoredRaw = rawValue => {
814
+ const oldValue = undefined;
815
+ if (isBiometric) {
816
+ adapter.backend.setSecureBiometricWithLevel(storageKey, rawValue, resolvedBiometricLevel);
817
+ emitKeyChange(config.scope, storageKey, oldValue, rawValue, "set", adapter.changeSource);
818
+ return;
819
+ }
820
+ cacheRawValue(nonMemoryScope, storageKey, rawValue);
821
+ if (nonMemoryScope === StorageScope.Disk) {
822
+ if (coalesceDiskWrites || diskWritesAsync) {
823
+ scheduleDiskWrite(storageKey, rawValue);
824
+ emitKeyChange(config.scope, storageKey, oldValue, rawValue, "set", adapter.changeSource);
825
+ return;
826
+ }
827
+ clearPendingDiskWrite(storageKey);
828
+ }
829
+ if (coalesceSecureWrites) {
830
+ scheduleSecureWrite(storageKey, rawValue, secureAccessControl ?? secureDefaultAccessControl);
831
+ emitKeyChange(config.scope, storageKey, oldValue, rawValue, "set", adapter.changeSource);
832
+ return;
833
+ }
834
+ if (nonMemoryScope === StorageScope.Secure) {
835
+ clearPendingSecureWrite(storageKey);
836
+ if (adapter.applyAccessControlOnSecureRawWrite) {
837
+ adapter.backend.setSecureAccessControl(secureAccessControl ?? secureDefaultAccessControl);
838
+ }
839
+ }
840
+ adapter.backend.set(storageKey, rawValue, config.scope);
841
+ emitKeyChange(config.scope, storageKey, oldValue, rawValue, "set", adapter.changeSource);
842
+ };
843
+ const removeStoredRaw = () => {
844
+ const oldValue = getEventRawValue(config.scope, storageKey);
845
+ if (isBiometric) {
846
+ adapter.backend.deleteSecureBiometric(storageKey);
847
+ emitKeyChange(config.scope, storageKey, oldValue, undefined, "remove", adapter.changeSource);
848
+ return;
849
+ }
850
+ cacheRawValue(nonMemoryScope, storageKey, undefined);
851
+ if (nonMemoryScope === StorageScope.Disk) {
852
+ if (coalesceDiskWrites || diskWritesAsync) {
853
+ scheduleDiskWrite(storageKey, undefined);
854
+ emitKeyChange(config.scope, storageKey, oldValue, undefined, "remove", adapter.changeSource);
855
+ return;
856
+ }
857
+ clearPendingDiskWrite(storageKey);
858
+ }
859
+ if (coalesceSecureWrites) {
860
+ scheduleSecureWrite(storageKey, undefined, secureAccessControl ?? secureDefaultAccessControl);
861
+ emitKeyChange(config.scope, storageKey, oldValue, undefined, "remove", adapter.changeSource);
862
+ return;
863
+ }
864
+ if (nonMemoryScope === StorageScope.Secure) {
865
+ clearPendingSecureWrite(storageKey);
866
+ }
867
+ adapter.backend.remove(storageKey, config.scope);
868
+ emitKeyChange(config.scope, storageKey, oldValue, undefined, "remove", adapter.changeSource);
869
+ };
870
+ const writeValueWithoutValidation = value => {
871
+ if (isMemory) {
872
+ const oldValue = getEventRawValue(config.scope, storageKey);
873
+ if (memoryExpiration) {
874
+ memoryExpiration.set(storageKey, Date.now() + (expirationTtlMs ?? 0));
875
+ }
876
+ memoryStore.set(storageKey, value);
877
+ notifyKeyListeners(memoryListeners, storageKey);
878
+ emitKeyChange(config.scope, storageKey, oldValue, typeof value === "string" ? value : undefined, "set", "memory");
879
+ return;
880
+ }
881
+ const serialized = serialize(value);
882
+ if (expiration) {
883
+ const envelope = {
884
+ __nitroStorageEnvelope: true,
885
+ expiresAt: Date.now() + expiration.ttlMs,
886
+ payload: serialized
887
+ };
888
+ writeStoredRaw(JSON.stringify(envelope));
889
+ return;
890
+ }
891
+ writeStoredRaw(serialized);
892
+ };
893
+ const resolveInvalidValue = invalidValue => {
894
+ if (onValidationError) {
895
+ return onValidationError(invalidValue);
896
+ }
897
+ return defaultValue;
898
+ };
899
+ const ensureValidatedValue = (candidate, hadStoredValue) => {
900
+ if (!validate || validate(candidate)) {
901
+ return candidate;
902
+ }
903
+ const resolved = resolveInvalidValue(candidate);
904
+ if (validate && !validate(resolved)) {
905
+ return defaultValue;
906
+ }
907
+ if (hadStoredValue) {
908
+ writeValueWithoutValidation(resolved);
909
+ }
910
+ return resolved;
911
+ };
912
+ const getInternal = () => {
913
+ const raw = readStoredRaw();
914
+ if (!memoryExpiration && raw === lastRaw && hasLastValue) {
915
+ if (!expiration || lastExpiresAt === null) {
916
+ return lastValue;
917
+ }
918
+ if (typeof lastExpiresAt === "number") {
919
+ if (lastExpiresAt > Date.now()) {
920
+ return lastValue;
921
+ }
922
+ removeStoredRaw();
923
+ invalidateParsedCache();
924
+ onExpired?.(storageKey);
925
+ lastValue = ensureValidatedValue(defaultValue, false);
926
+ hasLastValue = true;
927
+ listeners.forEach(cb => cb());
928
+ return lastValue;
929
+ }
930
+ }
931
+ lastRaw = raw;
932
+ if (raw === undefined) {
933
+ lastExpiresAt = undefined;
934
+ lastValue = ensureValidatedValue(defaultValue, false);
935
+ hasLastValue = true;
936
+ return lastValue;
937
+ }
938
+ if (isMemory) {
939
+ lastExpiresAt = undefined;
940
+ lastValue = ensureValidatedValue(raw, true);
941
+ hasLastValue = true;
942
+ return lastValue;
943
+ }
944
+ if (typeof raw !== "string") {
945
+ lastExpiresAt = undefined;
946
+ lastValue = ensureValidatedValue(defaultValue, false);
947
+ hasLastValue = true;
948
+ return lastValue;
949
+ }
950
+ let deserializableRaw = raw;
951
+ if (expiration) {
952
+ let envelopeExpiresAt = null;
953
+ try {
954
+ const parsed = JSON.parse(raw);
955
+ if (isStoredEnvelope(parsed)) {
956
+ envelopeExpiresAt = parsed.expiresAt;
957
+ if (parsed.expiresAt <= Date.now()) {
958
+ removeStoredRaw();
959
+ invalidateParsedCache();
960
+ onExpired?.(storageKey);
961
+ lastValue = ensureValidatedValue(defaultValue, false);
962
+ hasLastValue = true;
963
+ listeners.forEach(cb => cb());
964
+ return lastValue;
965
+ }
966
+ deserializableRaw = parsed.payload;
967
+ }
968
+ } catch {
969
+ // Keep backward compatibility with legacy raw values.
970
+ }
971
+ lastExpiresAt = envelopeExpiresAt;
972
+ } else {
973
+ lastExpiresAt = undefined;
974
+ }
975
+ lastValue = ensureValidatedValue(deserialize(deserializableRaw), true);
976
+ hasLastValue = true;
977
+ return lastValue;
978
+ };
979
+ const getCurrentVersion = () => {
980
+ const raw = readStoredRaw();
981
+ return toVersionToken(raw);
982
+ };
983
+ const get = () => measureOperation("item:get", config.scope, () => getInternal());
984
+ const getWithVersion = () => measureOperation("item:getWithVersion", config.scope, () => ({
985
+ value: getInternal(),
986
+ version: getCurrentVersion()
987
+ }));
988
+ const set = valueOrFn => {
989
+ measureOperation("item:set", config.scope, () => {
990
+ const newValue = isUpdater(valueOrFn) ? valueOrFn(getInternal()) : valueOrFn;
991
+ if (validate && !validate(newValue)) {
992
+ throw new Error(`Validation failed for key "${storageKey}" in scope "${StorageScope[config.scope]}".`);
993
+ }
994
+ invalidateParsedCache();
995
+ writeValueWithoutValidation(newValue);
996
+ });
997
+ };
998
+ const setIfVersion = (version, valueOrFn) => measureOperation("item:setIfVersion", config.scope, () => {
999
+ const currentVersion = getCurrentVersion();
1000
+ if (currentVersion !== version) {
1001
+ return false;
1002
+ }
1003
+ set(valueOrFn);
1004
+ return true;
1005
+ });
1006
+ const deleteItem = () => {
1007
+ measureOperation("item:delete", config.scope, () => {
1008
+ invalidateParsedCache();
1009
+ if (isMemory) {
1010
+ const oldValue = getEventRawValue(config.scope, storageKey);
1011
+ if (memoryExpiration) {
1012
+ memoryExpiration.delete(storageKey);
1013
+ }
1014
+ memoryStore.delete(storageKey);
1015
+ notifyKeyListeners(memoryListeners, storageKey);
1016
+ emitKeyChange(config.scope, storageKey, oldValue, undefined, "remove", "memory");
1017
+ return;
1018
+ }
1019
+ removeStoredRaw();
1020
+ });
1021
+ };
1022
+ const hasItem = () => measureOperation("item:has", config.scope, () => {
1023
+ if (isMemory) return memoryStore.has(storageKey);
1024
+ if (isBiometric) return adapter.backend.hasSecureBiometric(storageKey);
1025
+ if (nonMemoryScope === StorageScope.Disk) {
1026
+ const pending = pendingDiskWrites.get(storageKey);
1027
+ if (pending !== undefined) {
1028
+ return pending.value !== undefined;
1029
+ }
1030
+ }
1031
+ if (nonMemoryScope === StorageScope.Secure) {
1032
+ const pending = pendingSecureWrites.get(storageKey);
1033
+ if (pending !== undefined) {
1034
+ return pending.value !== undefined;
1035
+ }
1036
+ }
1037
+ return adapter.backend.has(storageKey, config.scope);
1038
+ });
1039
+ const subscribe = callback => {
1040
+ ensureSubscription();
1041
+ listeners.add(callback);
1042
+ return () => {
1043
+ listeners.delete(callback);
1044
+ if (listeners.size === 0 && unsubscribe) {
1045
+ unsubscribe();
1046
+ if (!isMemory) {
1047
+ adapter.maybeCleanupScopeSubscription(nonMemoryScope);
1048
+ }
1049
+ unsubscribe = null;
1050
+ }
1051
+ };
1052
+ };
1053
+ const subscribeSelector = (selector, listener, options = {}) => {
1054
+ const isEqual = options.isEqual ?? Object.is;
1055
+ let currentValue = selector(getInternal());
1056
+ if (options.fireImmediately === true) {
1057
+ listener(currentValue, currentValue);
1058
+ }
1059
+ return subscribe(() => {
1060
+ const nextValue = selector(getInternal());
1061
+ if (isEqual(currentValue, nextValue)) {
1062
+ return;
1063
+ }
1064
+ const previousValue = currentValue;
1065
+ currentValue = nextValue;
1066
+ listener(nextValue, previousValue);
1067
+ });
1068
+ };
1069
+ const storageItem = {
1070
+ get,
1071
+ getWithVersion,
1072
+ set,
1073
+ setIfVersion,
1074
+ delete: deleteItem,
1075
+ has: hasItem,
1076
+ subscribe,
1077
+ subscribeSelector,
1078
+ serialize,
1079
+ deserialize,
1080
+ _triggerListeners: () => {
1081
+ invalidateParsedCache();
1082
+ listeners.forEach(listener => listener());
1083
+ },
1084
+ _invalidateParsedCacheOnly: () => {
1085
+ invalidateParsedCache();
1086
+ },
1087
+ _hasValidation: validate !== undefined,
1088
+ _hasExpiration: expiration !== undefined,
1089
+ _readCacheEnabled: readCache,
1090
+ _isBiometric: isBiometric,
1091
+ _biometricLevel: resolvedBiometricLevel,
1092
+ _defaultValue: defaultValue,
1093
+ ...(secureAccessControl !== undefined ? {
1094
+ _secureAccessControl: secureAccessControl
1095
+ } : {}),
1096
+ scope: config.scope,
1097
+ key: storageKey
1098
+ };
1099
+ return storageItem;
1100
+ }
1101
+ function getBatch(items, scope) {
1102
+ return measureOperation("batch:get", scope, () => {
1103
+ assertBatchScope(items, scope);
1104
+ if (scope === StorageScope.Memory) {
1105
+ return items.map(item => item.get());
1106
+ }
1107
+ const useRawBatchPath = items.every(item => scope === StorageScope.Secure ? canUseSecureRawBatchPath(item) : canUseRawBatchPath(item));
1108
+ if (!useRawBatchPath) {
1109
+ return items.map(item => item.get());
1110
+ }
1111
+ const rawValues = new Array(items.length);
1112
+ const keysToFetch = [];
1113
+ const keyIndexes = [];
1114
+ items.forEach((item, index) => {
1115
+ if (scope === StorageScope.Disk) {
1116
+ const pending = pendingDiskWrites.get(item.key);
1117
+ if (pending !== undefined) {
1118
+ rawValues[index] = pending.value;
1119
+ return;
1120
+ }
1121
+ }
1122
+ if (scope === StorageScope.Secure) {
1123
+ const pending = pendingSecureWrites.get(item.key);
1124
+ if (pending !== undefined) {
1125
+ rawValues[index] = pending.value;
1126
+ return;
1127
+ }
1128
+ }
1129
+ if (item._readCacheEnabled === true) {
1130
+ const cache = getScopeRawCache(scope);
1131
+ const cached = cache.get(item.key);
1132
+ if (cached !== undefined || cache.has(item.key)) {
1133
+ rawValues[index] = cached;
1134
+ return;
1135
+ }
1136
+ }
1137
+ keysToFetch.push(item.key);
1138
+ keyIndexes.push(index);
1139
+ });
1140
+ if (keysToFetch.length > 0) {
1141
+ const fetchedValues = adapter.backend.getBatch(keysToFetch, scope);
1142
+ fetchedValues.forEach((value, index) => {
1143
+ const key = keysToFetch[index];
1144
+ const targetIndex = keyIndexes[index];
1145
+ if (key === undefined || targetIndex === undefined) {
1146
+ return;
1147
+ }
1148
+ rawValues[targetIndex] = value;
1149
+ cacheRawValue(scope, key, value);
1150
+ });
1151
+ }
1152
+ return items.map((item, index) => {
1153
+ const raw = rawValues[index];
1154
+ if (raw === undefined) {
1155
+ return asInternal(item)._defaultValue;
1156
+ }
1157
+ return item.deserialize(raw);
1158
+ });
1159
+ }, items.length);
1160
+ }
1161
+ function setBatch(items, scope) {
1162
+ measureOperation("batch:set", scope, () => {
1163
+ assertBatchScope(items.map(batchEntry => batchEntry.item), scope);
1164
+ if (scope === StorageScope.Memory) {
1165
+ // Determine if any item needs per-item handling (validation or TTL)
1166
+ const needsIndividualSets = items.some(({
1167
+ item
1168
+ }) => {
1169
+ const internal = asInternal(item);
1170
+ return internal._hasValidation || internal._hasExpiration;
1171
+ });
1172
+ if (needsIndividualSets) {
1173
+ // Fall back to individual sets to preserve validation and TTL semantics
1174
+ items.forEach(({
1175
+ item,
1176
+ value
1177
+ }) => item.set(value));
1178
+ return;
1179
+ }
1180
+ const changes = items.map(({
1181
+ item,
1182
+ value
1183
+ }) => createKeyChange(scope, item.key, getEventRawValue(scope, item.key), typeof value === "string" ? value : undefined, "setBatch", "memory"));
1184
+
1185
+ // Atomic write: update all values in memoryStore, invalidate caches, then batch-notify
1186
+ items.forEach(({
1187
+ item,
1188
+ value
1189
+ }) => {
1190
+ memoryStore.set(item.key, value);
1191
+ asInternal(item)._invalidateParsedCacheOnly();
1192
+ });
1193
+ items.forEach(({
1194
+ item
1195
+ }) => notifyKeyListeners(memoryListeners, item.key));
1196
+ emitBatchChange(scope, "setBatch", "memory", changes);
1197
+ return;
1198
+ }
1199
+ if (scope === StorageScope.Secure) {
1200
+ const secureEntries = items.map(({
1201
+ item,
1202
+ value
1203
+ }) => ({
1204
+ item,
1205
+ value,
1206
+ internal: asInternal(item)
1207
+ }));
1208
+ const canUseSecureBatchPath = secureEntries.every(({
1209
+ internal
1210
+ }) => canUseSecureRawBatchPath(internal));
1211
+ if (!canUseSecureBatchPath) {
1212
+ items.forEach(({
1213
+ item,
1214
+ value
1215
+ }) => item.set(value));
1216
+ return;
1217
+ }
1218
+ flushSecureWrites();
1219
+ const keys = secureEntries.map(({
1220
+ item
1221
+ }) => item.key);
1222
+ const oldValues = shouldReadPreviousEventValues(scope) ? adapter.backend.getBatch(keys, scope) : [];
1223
+ const groupedByAccessControl = new Map();
1224
+ secureEntries.forEach(({
1225
+ item,
1226
+ value,
1227
+ internal
1228
+ }) => {
1229
+ const accessControl = internal._secureAccessControl ?? secureDefaultAccessControl;
1230
+ const existingGroup = groupedByAccessControl.get(accessControl);
1231
+ const group = existingGroup ?? {
1232
+ keys: [],
1233
+ values: []
1234
+ };
1235
+ group.keys.push(item.key);
1236
+ group.values.push(item.serialize(value));
1237
+ if (!existingGroup) {
1238
+ groupedByAccessControl.set(accessControl, group);
1239
+ }
1240
+ });
1241
+ groupedByAccessControl.forEach((group, accessControl) => {
1242
+ adapter.backend.setSecureAccessControl(accessControl);
1243
+ adapter.backend.setBatch(group.keys, group.values, scope);
1244
+ group.keys.forEach((key, index) => cacheRawValue(scope, key, group.values[index]));
1245
+ });
1246
+ emitBatchChange(scope, "setBatch", adapter.changeSource, secureEntries.map(({
1247
+ item,
1248
+ value
1249
+ }, index) => createKeyChange(scope, item.key, oldValues[index], item.serialize(value), "setBatch", adapter.changeSource)));
1250
+ return;
1251
+ }
1252
+ flushDiskWrites();
1253
+ const useRawBatchPath = items.every(({
1254
+ item
1255
+ }) => canUseRawBatchPath(asInternal(item)));
1256
+ if (!useRawBatchPath) {
1257
+ items.forEach(({
1258
+ item,
1259
+ value
1260
+ }) => item.set(value));
1261
+ return;
1262
+ }
1263
+ const keys = items.map(entry => entry.item.key);
1264
+ const values = items.map(entry => entry.item.serialize(entry.value));
1265
+ const oldValues = shouldReadPreviousEventValues(scope) ? adapter.backend.getBatch(keys, scope) : [];
1266
+ adapter.backend.setBatch(keys, values, scope);
1267
+ keys.forEach((key, index) => cacheRawValue(scope, key, values[index]));
1268
+ emitBatchChange(scope, "setBatch", adapter.changeSource, keys.map((key, index) => createKeyChange(scope, key, oldValues[index], values[index], "setBatch", adapter.changeSource)));
1269
+ }, items.length);
1270
+ }
1271
+ function removeBatch(items, scope) {
1272
+ measureOperation("batch:remove", scope, () => {
1273
+ assertBatchScope(items, scope);
1274
+ if (scope === StorageScope.Memory) {
1275
+ const changes = items.map(item => createKeyChange(scope, item.key, getEventRawValue(scope, item.key), undefined, "removeBatch", "memory"));
1276
+ items.forEach(item => item.delete());
1277
+ emitBatchChange(scope, "removeBatch", "memory", changes);
1278
+ return;
1279
+ }
1280
+ const keys = items.map(item => item.key);
1281
+ if (scope === StorageScope.Disk) {
1282
+ flushDiskWrites();
1283
+ }
1284
+ if (scope === StorageScope.Secure) {
1285
+ flushSecureWrites();
1286
+ }
1287
+ const oldValues = shouldReadPreviousEventValues(scope) ? adapter.backend.getBatch(keys, scope) : [];
1288
+ adapter.backend.removeBatch(keys, scope);
1289
+ keys.forEach(key => cacheRawValue(scope, key, undefined));
1290
+ emitBatchChange(scope, "removeBatch", adapter.changeSource, keys.map((key, index) => createKeyChange(scope, key, oldValues[index], undefined, "removeBatch", adapter.changeSource)));
1291
+ }, items.length);
1292
+ }
1293
+ function registerMigration(version, migration) {
1294
+ if (!Number.isInteger(version) || version <= 0) {
1295
+ throw new Error("Migration version must be a positive integer.");
1296
+ }
1297
+ if (registeredMigrations.has(version)) {
1298
+ throw new Error(`Migration version ${version} is already registered.`);
1299
+ }
1300
+ registeredMigrations.set(version, migration);
1301
+ }
1302
+ function migrateToLatest(scope = StorageScope.Disk) {
1303
+ return measureOperation("migration:run", scope, () => {
1304
+ assertValidScope(scope);
1305
+ const currentVersion = readMigrationVersion(scope);
1306
+ const versions = Array.from(registeredMigrations.keys()).filter(version => version > currentVersion).sort((a, b) => a - b);
1307
+ let appliedVersion = currentVersion;
1308
+ const context = {
1309
+ scope,
1310
+ getRaw: key => getRawValue(key, scope),
1311
+ setRaw: (key, value) => setRawValue(key, value, scope),
1312
+ removeRaw: key => removeRawValue(key, scope)
1313
+ };
1314
+ versions.forEach(version => {
1315
+ const migration = registeredMigrations.get(version);
1316
+ if (!migration) {
1317
+ return;
1318
+ }
1319
+ migration(context);
1320
+ appliedVersion = version;
1321
+ });
1322
+ if (appliedVersion !== currentVersion) {
1323
+ writeMigrationVersion(scope, appliedVersion);
1324
+ }
1325
+ return appliedVersion;
1326
+ });
1327
+ }
1328
+ function runTransaction(scope, transaction) {
1329
+ return measureOperation("transaction:run", scope, () => {
1330
+ assertValidScope(scope);
1331
+ if (scope === StorageScope.Disk) {
1332
+ flushDiskWrites();
1333
+ }
1334
+ if (scope === StorageScope.Secure) {
1335
+ flushSecureWrites();
1336
+ }
1337
+ const NOT_SET = Symbol();
1338
+ const rollback = new Map();
1339
+ const rememberRollback = (key, item) => {
1340
+ if (rollback.has(key)) {
1341
+ return;
1342
+ }
1343
+ if (scope === StorageScope.Memory) {
1344
+ rollback.set(key, {
1345
+ kind: "memory",
1346
+ value: memoryStore.has(key) ? memoryStore.get(key) : NOT_SET
1347
+ });
1348
+ } else {
1349
+ const internal = item ? item : undefined;
1350
+ if (scope === StorageScope.Secure && internal?._isBiometric === true) {
1351
+ rollback.set(key, {
1352
+ kind: "biometric",
1353
+ value: adapter.backend.getSecureBiometric(key),
1354
+ level: internal._biometricLevel
1355
+ });
1356
+ return;
1357
+ }
1358
+ rollback.set(key, {
1359
+ kind: "raw",
1360
+ value: getRawValue(key, scope),
1361
+ ...(scope === StorageScope.Secure && internal?._secureAccessControl !== undefined ? {
1362
+ accessControl: internal._secureAccessControl
1363
+ } : {})
1364
+ });
1365
+ }
1366
+ };
1367
+ const tx = {
1368
+ scope,
1369
+ getRaw: key => getRawValue(key, scope),
1370
+ setRaw: (key, value) => {
1371
+ rememberRollback(key);
1372
+ setRawValue(key, value, scope);
1373
+ },
1374
+ removeRaw: key => {
1375
+ rememberRollback(key);
1376
+ removeRawValue(key, scope);
1377
+ },
1378
+ getItem: item => {
1379
+ assertBatchScope([item], scope);
1380
+ return item.get();
1381
+ },
1382
+ setItem: (item, value) => {
1383
+ assertBatchScope([item], scope);
1384
+ rememberRollback(item.key, item);
1385
+ item.set(value);
1386
+ },
1387
+ removeItem: item => {
1388
+ assertBatchScope([item], scope);
1389
+ rememberRollback(item.key, item);
1390
+ item.delete();
1391
+ }
1392
+ };
1393
+ try {
1394
+ return transaction(tx);
1395
+ } catch (error) {
1396
+ const rollbackEntries = Array.from(rollback.entries()).reverse();
1397
+ if (scope === StorageScope.Memory) {
1398
+ rollbackEntries.forEach(([key, record]) => {
1399
+ if (record.value === NOT_SET) {
1400
+ memoryStore.delete(key);
1401
+ } else {
1402
+ memoryStore.set(key, record.value);
1403
+ }
1404
+ notifyKeyListeners(memoryListeners, key);
1405
+ });
1406
+ } else {
1407
+ const groupedKeysToSet = new Map();
1408
+ const keysToRemove = [];
1409
+ rollbackEntries.forEach(([key, record]) => {
1410
+ if (record.kind === "biometric") {
1411
+ if (record.value === undefined) {
1412
+ adapter.backend.deleteSecureBiometric(key);
1413
+ } else {
1414
+ adapter.backend.setSecureBiometricWithLevel(key, record.value, record.level);
1415
+ }
1416
+ return;
1417
+ }
1418
+ if (record.kind !== "raw") {
1419
+ return;
1420
+ }
1421
+ if (record.value === undefined) {
1422
+ keysToRemove.push(key);
1423
+ } else {
1424
+ const accessControl = record.accessControl ?? secureDefaultAccessControl;
1425
+ const existingGroup = groupedKeysToSet.get(accessControl);
1426
+ const group = existingGroup ?? {
1427
+ keys: [],
1428
+ values: []
1429
+ };
1430
+ group.keys.push(key);
1431
+ group.values.push(record.value);
1432
+ if (!existingGroup) {
1433
+ groupedKeysToSet.set(accessControl, group);
1434
+ }
1435
+ }
1436
+ });
1437
+ if (scope === StorageScope.Disk) {
1438
+ flushDiskWrites();
1439
+ }
1440
+ if (scope === StorageScope.Secure) {
1441
+ flushSecureWrites();
1442
+ }
1443
+ groupedKeysToSet.forEach((group, accessControl) => {
1444
+ if (scope === StorageScope.Secure) {
1445
+ adapter.backend.setSecureAccessControl(accessControl);
1446
+ }
1447
+ adapter.backend.setBatch(group.keys, group.values, scope);
1448
+ group.keys.forEach((key, index) => cacheRawValue(scope, key, group.values[index]));
1449
+ });
1450
+ if (keysToRemove.length > 0) {
1451
+ adapter.backend.removeBatch(keysToRemove, scope);
1452
+ keysToRemove.forEach(key => cacheRawValue(scope, key, undefined));
1453
+ }
1454
+ }
1455
+ throw error;
1456
+ }
1457
+ });
1458
+ }
1459
+ function createSecureAuthStorage(config, options) {
1460
+ const ns = options?.namespace ?? "auth";
1461
+ const result = {};
1462
+ for (const key of typedKeys(config)) {
1463
+ const itemConfig = config[key];
1464
+ const expirationConfig = itemConfig.ttlMs !== undefined ? {
1465
+ ttlMs: itemConfig.ttlMs
1466
+ } : undefined;
1467
+ result[key] = createStorageItem({
1468
+ key,
1469
+ scope: StorageScope.Secure,
1470
+ defaultValue: "",
1471
+ namespace: ns,
1472
+ ...(itemConfig.biometric !== undefined ? {
1473
+ biometric: itemConfig.biometric
1474
+ } : {}),
1475
+ ...(itemConfig.biometricLevel !== undefined ? {
1476
+ biometricLevel: itemConfig.biometricLevel
1477
+ } : {}),
1478
+ ...(itemConfig.accessControl !== undefined ? {
1479
+ accessControl: itemConfig.accessControl
1480
+ } : {}),
1481
+ ...(expirationConfig !== undefined ? {
1482
+ expiration: expirationConfig
1483
+ } : {})
1484
+ });
1485
+ }
1486
+ return result;
1487
+ }
1488
+ return {
1489
+ storage,
1490
+ createStorageItem,
1491
+ getBatch,
1492
+ setBatch,
1493
+ removeBatch,
1494
+ registerMigration,
1495
+ migrateToLatest,
1496
+ runTransaction,
1497
+ createSecureAuthStorage,
1498
+ internals
1499
+ };
1500
+ }
1501
+ //# sourceMappingURL=storage-core.js.map