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