@ngx-pwa/local-storage 12.1.0 → 13.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +6 -18
  2. package/{esm2015/lib/databases/exceptions.js → esm2020/lib/databases/exceptions.mjs} +1 -1
  3. package/esm2020/lib/databases/indexeddb-database.mjs +326 -0
  4. package/{esm2015/lib/databases/local-database.js → esm2020/lib/databases/local-database.mjs} +7 -7
  5. package/{esm2015/lib/databases/localstorage-database.js → esm2020/lib/databases/localstorage-database.mjs} +3 -3
  6. package/{esm2015/lib/databases/memory-database.js → esm2020/lib/databases/memory-database.mjs} +3 -3
  7. package/{esm2015/lib/storage.module.js → esm2020/lib/storage.module.mjs} +4 -4
  8. package/{esm2015/lib/storages/exceptions.js → esm2020/lib/storages/exceptions.mjs} +1 -1
  9. package/esm2020/lib/storages/local-storage.service.mjs +83 -0
  10. package/{esm2015/lib/storages/storage-map.service.js → esm2020/lib/storages/storage-map.service.mjs} +5 -5
  11. package/{esm2015/lib/tokens.js → esm2020/lib/tokens.mjs} +0 -0
  12. package/{esm2015/lib/validation/json-schema.js → esm2020/lib/validation/json-schema.mjs} +0 -0
  13. package/esm2020/lib/validation/json-validator.mjs +243 -0
  14. package/{esm2015/ngx-pwa-local-storage.js → esm2020/ngx-pwa-local-storage.mjs} +0 -0
  15. package/{esm2015/public-api.js → esm2020/public-api.mjs} +0 -0
  16. package/fesm2015/ngx-pwa-local-storage.mjs +1389 -0
  17. package/fesm2015/ngx-pwa-local-storage.mjs.map +1 -0
  18. package/{fesm2015/ngx-pwa-local-storage.js → fesm2020/ngx-pwa-local-storage.mjs} +40 -38
  19. package/fesm2020/ngx-pwa-local-storage.mjs.map +1 -0
  20. package/package.json +25 -12
  21. package/schematics/migration.json +5 -0
  22. package/schematics/ng-add/index.js +14 -3
  23. package/schematics/ng-add/index.js.map +1 -1
  24. package/schematics/ng-add/schema.json +1 -1
  25. package/schematics/ng-update/index.d.ts +1 -0
  26. package/schematics/ng-update/index.js +18 -5
  27. package/schematics/ng-update/index.js.map +1 -1
  28. package/schematics/utility/config.d.ts +1 -1
  29. package/schematics/utility/config.js +11 -11
  30. package/schematics/utility/config.js.map +1 -1
  31. package/schematics/utility/module.js +3 -3
  32. package/schematics/utility/module.js.map +1 -1
  33. package/bundles/ngx-pwa-local-storage.umd.js +0 -1846
  34. package/bundles/ngx-pwa-local-storage.umd.js.map +0 -1
  35. package/esm2015/lib/databases/indexeddb-database.js +0 -327
  36. package/esm2015/lib/storages/local-storage.service.js +0 -80
  37. package/esm2015/lib/validation/json-validator.js +0 -242
  38. package/fesm2015/ngx-pwa-local-storage.js.map +0 -1
@@ -0,0 +1,1389 @@
1
+ import * as i0 from '@angular/core';
2
+ import { Injectable, InjectionToken, Inject, PLATFORM_ID, NgModule } from '@angular/core';
3
+ import { isPlatformBrowser } from '@angular/common';
4
+ import { ReplaySubject, fromEvent, race, throwError, of, Observable, asyncScheduler, from } from 'rxjs';
5
+ import { mergeMap, map, first, mapTo, takeWhile, tap, observeOn, catchError } from 'rxjs/operators';
6
+
7
+ class JSONValidator {
8
+ /**
9
+ * Validate a JSON data against a Jsubset of the JSON Schema standard.
10
+ * Types are enforced to validate everything: each schema must
11
+ * @param data JSON data to validate
12
+ * @param schema Subset of JSON Schema. Must have a `type`.
13
+ * @returns If data is valid: `true`, if it is invalid: `false`
14
+ * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/VALIDATION.md}
15
+ */
16
+ validate(data, schema) {
17
+ switch (schema.type) {
18
+ case 'string':
19
+ return this.validateString(data, schema);
20
+ case 'number':
21
+ case 'integer':
22
+ return this.validateNumber(data, schema);
23
+ case 'boolean':
24
+ return this.validateBoolean(data, schema);
25
+ case 'array':
26
+ return this.validateArray(data, schema);
27
+ case 'object':
28
+ return this.validateObject(data, schema);
29
+ }
30
+ }
31
+ /**
32
+ * Validate a string
33
+ * @param data Data to validate
34
+ * @param schema Schema describing the string
35
+ * @returns If data is valid: `true`, if it is invalid: `false`
36
+ */
37
+ validateString(data, schema) {
38
+ if (typeof data !== 'string') {
39
+ return false;
40
+ }
41
+ if (!this.validateConst(data, schema)) {
42
+ return false;
43
+ }
44
+ if (!this.validateEnum(data, schema)) {
45
+ return false;
46
+ }
47
+ if ((schema.maxLength !== undefined) && (data.length > schema.maxLength)) {
48
+ return false;
49
+ }
50
+ if ((schema.minLength !== undefined) && (data.length < schema.minLength)) {
51
+ return false;
52
+ }
53
+ if (schema.pattern) {
54
+ let regularExpression = null;
55
+ try {
56
+ regularExpression = new RegExp(schema.pattern);
57
+ }
58
+ catch (_a) {
59
+ // Nothing to do
60
+ }
61
+ if (regularExpression && !regularExpression.test(data)) {
62
+ return false;
63
+ }
64
+ }
65
+ return true;
66
+ }
67
+ /**
68
+ * Validate a number or an integer
69
+ * @param data Data to validate
70
+ * @param schema Schema describing the number or integer
71
+ * @returns If data is valid: `true`, if it is invalid: `false`
72
+ */
73
+ validateNumber(data, schema) {
74
+ if (typeof data !== 'number') {
75
+ return false;
76
+ }
77
+ if ((schema.type === 'integer') && !Number.isInteger(data)) {
78
+ return false;
79
+ }
80
+ if (!this.validateConst(data, schema)) {
81
+ return false;
82
+ }
83
+ if (!this.validateEnum(data, schema)) {
84
+ return false;
85
+ }
86
+ /* Test is done this way to not divide by 0 */
87
+ if (schema.multipleOf && !Number.isInteger(data / schema.multipleOf)) {
88
+ return false;
89
+ }
90
+ if ((schema.maximum !== undefined) && (data > schema.maximum)) {
91
+ return false;
92
+ }
93
+ if ((schema.exclusiveMaximum !== undefined) && (data >= schema.exclusiveMaximum)) {
94
+ return false;
95
+ }
96
+ if ((schema.minimum !== undefined) && (data < schema.minimum)) {
97
+ return false;
98
+ }
99
+ if ((schema.exclusiveMinimum !== undefined) && (data <= schema.exclusiveMinimum)) {
100
+ return false;
101
+ }
102
+ return true;
103
+ }
104
+ /**
105
+ * Validate a boolean
106
+ * @param data Data to validate
107
+ * @param schema Schema describing the boolean
108
+ * @returns If data is valid: `true`, if it is invalid: `false`
109
+ */
110
+ validateBoolean(data, schema) {
111
+ if (typeof data !== 'boolean') {
112
+ return false;
113
+ }
114
+ if (!this.validateConst(data, schema)) {
115
+ return false;
116
+ }
117
+ return true;
118
+ }
119
+ /**
120
+ * Validate an array
121
+ * @param data Data to validate
122
+ * @param schema Schema describing the array
123
+ * @returns If data is valid: `true`, if it is invalid: `false`
124
+ */
125
+ validateArray(data, schema) {
126
+ if (!Array.isArray(data)) {
127
+ return false;
128
+ }
129
+ if ((schema.maxItems !== undefined) && (data.length > schema.maxItems)) {
130
+ return false;
131
+ }
132
+ if ((schema.minItems !== undefined) && (data.length < schema.minItems)) {
133
+ return false;
134
+ }
135
+ if (schema.uniqueItems) {
136
+ /* Create a set to eliminate values with multiple occurences */
137
+ const dataSet = new Set(data);
138
+ if (data.length !== dataSet.size) {
139
+ return false;
140
+ }
141
+ }
142
+ /* Specific test for tuples */
143
+ if (Array.isArray(schema.items)) {
144
+ // TODO: cast should not be needed here
145
+ return this.validateTuple(data, schema.items);
146
+ }
147
+ /* Validate all the values in array */
148
+ for (const value of data) {
149
+ // TODO: remove when TypeScript 4.1 is available
150
+ // (currently the narrowed type from `Array.isArray()` is lost on readonly arrays)
151
+ if (!this.validate(value, schema.items)) {
152
+ return false;
153
+ }
154
+ }
155
+ return true;
156
+ }
157
+ /**
158
+ * Validate a tuple (array with fixed length and multiple types)
159
+ * @param data Data to validate
160
+ * @param schemas Schemas describing the tuple
161
+ * @returns If data is valid: `true`, if it is invalid: `false`
162
+ */
163
+ validateTuple(data, schemas) {
164
+ /* Tuples have a fixed length */
165
+ if (data.length !== schemas.length) {
166
+ return false;
167
+ }
168
+ for (let i = 0; i < schemas.length; i += 1) {
169
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
170
+ if (!this.validate(data[i], schemas[i])) {
171
+ return false;
172
+ }
173
+ }
174
+ return true;
175
+ }
176
+ /**
177
+ * Validate an object
178
+ * @param data Data to validate
179
+ * @param schema JSON schema describing the object
180
+ * @returns If data is valid: `true`, if it is invalid: `false`
181
+ */
182
+ validateObject(data, schema) {
183
+ /* Check the type and if not `null` as `null` also have the type `object` in old browsers */
184
+ if ((typeof data !== 'object') || (data === null)) {
185
+ return false;
186
+ }
187
+ /* Check if the object doesn't have more properties than expected
188
+ * Equivalent of `additionalProperties: false`
189
+ */
190
+ if (Object.keys(schema.properties).length < Object.keys(data).length) {
191
+ return false;
192
+ }
193
+ /* Validate required properties */
194
+ if (schema.required) {
195
+ for (const requiredProp of schema.required) {
196
+ if (!Object.prototype.hasOwnProperty.call(data, requiredProp)) {
197
+ return false;
198
+ }
199
+ }
200
+ }
201
+ /* Recursively validate all properties */
202
+ for (const property in schema.properties) {
203
+ /* Filter to keep only real properties (no internal JS stuff) and check if the data has the property too */
204
+ if (Object.prototype.hasOwnProperty.call(schema.properties, property) && Object.prototype.hasOwnProperty.call(data, property)) {
205
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
206
+ if (!this.validate(data[property], schema.properties[property])) {
207
+ return false;
208
+ }
209
+ }
210
+ }
211
+ return true;
212
+ }
213
+ /**
214
+ * Validate a constant
215
+ * @param data Data ta validate
216
+ * @param schema JSON schema describing the constant
217
+ * @returns If data is valid: `true`, if it is invalid: `false`
218
+ */
219
+ validateConst(data, schema) {
220
+ if (!schema.const) {
221
+ return true;
222
+ }
223
+ return (data === schema.const);
224
+ }
225
+ /**
226
+ * Validate an enum
227
+ * @param data Data ta validate
228
+ * @param schema JSON schema describing the enum
229
+ * @returns If data is valid: `true`, if it is invalid: `false`
230
+ */
231
+ validateEnum(data, schema) {
232
+ if (!schema.enum) {
233
+ return true;
234
+ }
235
+ /* Cast as the data can be of multiple types, and so TypeScript is lost */
236
+ return (schema.enum.includes(data));
237
+ }
238
+ }
239
+ JSONValidator.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: JSONValidator, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
240
+ JSONValidator.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: JSONValidator, providedIn: 'root' });
241
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: JSONValidator, decorators: [{
242
+ type: Injectable,
243
+ args: [{
244
+ providedIn: 'root'
245
+ }]
246
+ }] });
247
+
248
+ /**
249
+ * Token to provide a prefix to `localStorage` keys.
250
+ */
251
+ const LS_PREFIX = new InjectionToken('localStoragePrefix', {
252
+ providedIn: 'root',
253
+ factory: () => ''
254
+ });
255
+ /**
256
+ * Default name used for `indexedDB` database.
257
+ */
258
+ const DEFAULT_IDB_DB_NAME = 'ngStorage';
259
+ /**
260
+ * Token to provide `indexedDB` database name.
261
+ */
262
+ const IDB_DB_NAME = new InjectionToken('localStorageIDBDBName', {
263
+ providedIn: 'root',
264
+ factory: () => DEFAULT_IDB_DB_NAME
265
+ });
266
+ /**
267
+ * Default version used for `indexedDB` database.
268
+ */
269
+ const DEFAULT_IDB_DB_VERSION = 1;
270
+ /**
271
+ * Token to provide `indexedDB` database version.
272
+ * Must be an unsigned **integer**.
273
+ */
274
+ const IDB_DB_VERSION = new InjectionToken('localStorageIDBDBVersion', {
275
+ providedIn: 'root',
276
+ factory: () => DEFAULT_IDB_DB_VERSION
277
+ });
278
+ /**
279
+ * Default name used for `indexedDB` object store.
280
+ */
281
+ const DEFAULT_IDB_STORE_NAME = 'localStorage';
282
+ /**
283
+ * Token to provide `indexedDB` store name.
284
+ * For backward compatibility, the default can't be set now, `IndexedDBDatabase` will do it at runtime.
285
+ */
286
+ const IDB_STORE_NAME = new InjectionToken('localStorageIDBStoreName', {
287
+ providedIn: 'root',
288
+ factory: () => DEFAULT_IDB_STORE_NAME
289
+ });
290
+ /**
291
+ * Default value for interoperability with native `indexedDB` and other storage libs,
292
+ * by changing how values are stored in `indexedDB` database.
293
+ */
294
+ const DEFAULT_IDB_NO_WRAP = true;
295
+ /**
296
+ * Token to allow interoperability with native `indexedDB` and other storage libs,
297
+ * by changing how values are stored in `indexedDB` database.
298
+ * Defaults to `true`. Change to `false` for backward compatiblity in existing applications.
299
+ * **DO NOT CHANGE THIS BEHAVIOR ONCE IN PRODUCTION**, as it would break with existing data.
300
+ */
301
+ const IDB_NO_WRAP = new InjectionToken('localStorageIDBWrap', {
302
+ providedIn: 'root',
303
+ factory: () => DEFAULT_IDB_NO_WRAP
304
+ });
305
+
306
+ /**
307
+ * Exception message when `indexedDB` is not working
308
+ */
309
+ const IDB_BROKEN_ERROR = 'indexedDB is not working';
310
+ /**
311
+ * Exception raised when `indexedDB` is not working
312
+ */
313
+ class IDBBrokenError extends Error {
314
+ constructor() {
315
+ super(...arguments);
316
+ this.message = IDB_BROKEN_ERROR;
317
+ }
318
+ }
319
+ /**
320
+ * Exception message when a value can't be serialized for `localStorage`
321
+ */
322
+ const SERIALIZATION_ERROR = `The storage is currently localStorage,
323
+ where data must be serialized, and the provided data can't be serialized.`;
324
+ /**
325
+ * Exception raised when a value can't be serialized for `localStorage`
326
+ */
327
+ class SerializationError extends Error {
328
+ constructor() {
329
+ super(...arguments);
330
+ this.message = SERIALIZATION_ERROR;
331
+ }
332
+ }
333
+
334
+ class IndexedDBDatabase {
335
+ /**
336
+ * Constructor params are provided by Angular (but can also be passed manually in tests)
337
+ * @param dbName `indexedDB` database name
338
+ * @param storeName `indexedDB` store name
339
+ * @param dbVersion `indexedDB` database version
340
+ * @param noWrap Flag to not wrap `indexedDB` values for interoperability or to wrap for backward compatibility
341
+ */
342
+ constructor(dbName = DEFAULT_IDB_DB_NAME, storeName = DEFAULT_IDB_STORE_NAME, dbVersion = DEFAULT_IDB_DB_VERSION, noWrap = DEFAULT_IDB_NO_WRAP) {
343
+ /**
344
+ * `indexedDB` database connection, wrapped in a RxJS `ReplaySubject` to be able to access the connection
345
+ * even after the connection success event happened
346
+ */
347
+ this.database = new ReplaySubject(1);
348
+ /**
349
+ * Index used when wrapping value. *For backward compatibility only.*
350
+ */
351
+ this.wrapIndex = 'value';
352
+ this.dbName = dbName;
353
+ this.storeName = storeName;
354
+ this.dbVersion = dbVersion;
355
+ this.noWrap = noWrap;
356
+ /* Connect to `indexedDB`, with prefix if provided by the user */
357
+ this.connect();
358
+ }
359
+ /**
360
+ * Information about `indexedDB` connection. *Only useful for interoperability.*
361
+ * @returns `indexedDB` database name, store name and database version
362
+ */
363
+ get backingStore() {
364
+ return {
365
+ database: this.dbName,
366
+ store: this.storeName,
367
+ version: this.dbVersion,
368
+ };
369
+ }
370
+ /**
371
+ * Number of items in our `indexedDB` database and object store
372
+ */
373
+ get size() {
374
+ /* Open a transaction in read-only mode */
375
+ return this.transaction('readonly').pipe(mergeMap((transactionData) => {
376
+ const { store, events } = transactionData;
377
+ /* Request to know the number of items */
378
+ const request = store.count();
379
+ /* Return the result */
380
+ return events.pipe(map(() => request.result));
381
+ }),
382
+ /* The observable will complete after the first value */
383
+ first());
384
+ }
385
+ /**
386
+ * Gets an item value in our `indexedDB` store
387
+ * @param key The item's key
388
+ * @returns The item's value if the key exists, `undefined` otherwise, wrapped in an RxJS `Observable`
389
+ */
390
+ get(key) {
391
+ /* Open a transaction in read-only mode */
392
+ return this.transaction('readonly').pipe(mergeMap((transactionData) => {
393
+ const { store, events } = transactionData;
394
+ /* Request the value with the key provided by the user */
395
+ const request = store.get(key);
396
+ /* Listen events and return the result */
397
+ return events.pipe(map(() => {
398
+ if ((request.result !== undefined) && (request.result !== null)) {
399
+ /* Prior to v8, the value was wrapped in an `{ value: ...}` object */
400
+ if (!this.noWrap && (typeof request.result === 'object') && (this.wrapIndex in request.result) &&
401
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
402
+ (request.result[this.wrapIndex] !== undefined) && (request.result[this.wrapIndex] !== null)) {
403
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
404
+ return request.result[this.wrapIndex];
405
+ }
406
+ else {
407
+ /* Cast to the wanted type */
408
+ return request.result;
409
+ }
410
+ }
411
+ /* Return `undefined` if the value is empty */
412
+ return undefined;
413
+ }));
414
+ }),
415
+ /* The observable will complete after the first value */
416
+ first());
417
+ }
418
+ /**
419
+ * Sets an item in our `indexedDB` store
420
+ * @param key The item's key
421
+ * @param data The item's value
422
+ * @returns An RxJS `Observable` to wait the end of the operation
423
+ */
424
+ set(key, data) {
425
+ /* Storing `undefined` in `indexedDb` can cause issues in some browsers so removing item instead */
426
+ if (data === undefined) {
427
+ return this.delete(key);
428
+ }
429
+ /* Open a transaction in write mode */
430
+ return this.transaction('readwrite').pipe(mergeMap((transactionData) => {
431
+ const { store, events } = transactionData;
432
+ /* Prior to v8, data was wrapped in a `{ value: ... }` object */
433
+ const dataToStore = this.noWrap ? data : { [this.wrapIndex]: data };
434
+ /* Add if the item is not existing yet, or update otherwise */
435
+ store.put(dataToStore, key);
436
+ /* Listen to events and return `undefined` as no value is expected */
437
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
438
+ return events.pipe(mapTo(undefined));
439
+ }),
440
+ /* The observable will complete after the first value */
441
+ first());
442
+ }
443
+ /**
444
+ * Deletes an item in our `indexedDB` store
445
+ * @param key The item's key
446
+ * @returns An RxJS `Observable` to wait the end of the operation
447
+ */
448
+ delete(key) {
449
+ /* Open a transaction in write mode */
450
+ return this.transaction('readwrite').pipe(mergeMap((transactionData) => {
451
+ const { store, events } = transactionData;
452
+ /* Delete the item in store */
453
+ store.delete(key);
454
+ /* Listen to events and return `undefined` as no data is expected here */
455
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
456
+ return events.pipe(mapTo(undefined));
457
+ }),
458
+ /* The observable will complete after the first value */
459
+ first());
460
+ }
461
+ /**
462
+ * Deletes all items from our `indexedDB` objet store
463
+ * @returns An RxJS `Observable` to wait the end of the operation
464
+ */
465
+ clear() {
466
+ /* Open a transaction in write mode */
467
+ return this.transaction('readwrite').pipe(mergeMap((transactionData) => {
468
+ const { store, events } = transactionData;
469
+ /* Delete all items in object store */
470
+ store.clear();
471
+ /* Listen to events and return `undefined` as no data is expected here */
472
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
473
+ return events.pipe(mapTo(undefined));
474
+ }),
475
+ /* The observable will complete */
476
+ first());
477
+ }
478
+ /**
479
+ * Get all the keys in our `indexedDB` store
480
+ * @returns An RxJS `Observable` iterating on each key
481
+ */
482
+ keys() {
483
+ /* Open a transaction in read-only mode */
484
+ return this.transaction('readonly').pipe(
485
+ /* `first()` is used as the final operator in other methods to complete the `Observable`
486
+ * (as it all starts from a `ReplaySubject` which never ends),
487
+ * but as this method is iterating over multiple values, `first()` **must** be used here */
488
+ first(), mergeMap((transactionData) => {
489
+ const { store } = transactionData;
490
+ /* Open a cursor on the store
491
+ * Avoid issues like https://github.com/cyrilletuzi/angular-async-local-storage/issues/69 */
492
+ const request = store.openKeyCursor();
493
+ /* Listen to success event */
494
+ const success$ = fromEvent(request, 'success').pipe(
495
+ /* Stop the `Observable` when the cursor is `null` */
496
+ takeWhile(() => (request.result !== null)),
497
+ /* This lib only allows string keys, but user could have added other types of keys from outside
498
+ * It's OK to cast as the cursor as been tested in the previous operator */
499
+ map(() => request.result.key.toString()),
500
+ /* Iterate on the cursor */
501
+ tap(() => { request.result.continue(); }));
502
+ /* Listen to error event and if so, throw an error */
503
+ const error$ = this.listenError(request);
504
+ /* Choose the first event to occur */
505
+ return race([success$, error$]);
506
+ }));
507
+ }
508
+ /**
509
+ * Check if a key exists in our `indexedDB` store
510
+ * @returns An RxJS `Observable` telling if the key exists or not
511
+ */
512
+ has(key) {
513
+ /* Open a transaction in read-only mode */
514
+ return this.transaction('readonly').pipe(mergeMap((transactionData) => {
515
+ const { store, events } = transactionData;
516
+ /* Check if the key exists in the store
517
+ * Fixes https://github.com/cyrilletuzi/angular-async-local-storage/issues/69
518
+ */
519
+ const request = store.getKey(key);
520
+ /* Listen to events and return `true` or `false` */
521
+ return events.pipe(map(() => (request.result !== undefined) ? true : false));
522
+ }),
523
+ /* The observable will complete */
524
+ first());
525
+ }
526
+ /**
527
+ * Connects to `indexedDB` and creates the object store on first time
528
+ */
529
+ connect() {
530
+ let request;
531
+ /* Connect to `indexedDB`
532
+ * Will fail in Safari cross-origin iframes
533
+ * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/issues/42} */
534
+ try {
535
+ /* Do NOT explicit `window` here, as `indexedDB` could be used from a web worker too */
536
+ request = indexedDB.open(this.dbName, this.dbVersion);
537
+ }
538
+ catch (_a) {
539
+ this.database.error(new IDBBrokenError());
540
+ return;
541
+ }
542
+ /* Create store on first connection */
543
+ this.createStore(request);
544
+ /* Listen to success and error events */
545
+ const success$ = fromEvent(request, 'success');
546
+ const error$ = this.listenError(request);
547
+ /* Choose the first to occur */
548
+ race([success$, error$])
549
+ /* The observable will complete */
550
+ .pipe(first())
551
+ .subscribe({
552
+ next: () => {
553
+ /* Register the database connection in the `ReplaySubject` for further access */
554
+ this.database.next(request.result);
555
+ },
556
+ error: () => {
557
+ /* Firefox private mode issue: fallback storage if IndexedDb connection is failing
558
+ * @see {@link https://bugzilla.mozilla.org/show_bug.cgi?id=781982}
559
+ * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/issues/26} */
560
+ this.database.error(new IDBBrokenError());
561
+ },
562
+ });
563
+ }
564
+ /**
565
+ * Create store on first use of `indexedDB`
566
+ * @param request `indexedDB` database opening request
567
+ */
568
+ createStore(request) {
569
+ /* Listen to the event fired on first connection */
570
+ fromEvent(request, 'upgradeneeded')
571
+ /* The observable will complete */
572
+ .pipe(first())
573
+ .subscribe({
574
+ next: () => {
575
+ /* Check if the store already exists, to avoid error */
576
+ if (!request.result.objectStoreNames.contains(this.storeName)) {
577
+ /* Create the object store */
578
+ request.result.createObjectStore(this.storeName);
579
+ }
580
+ }
581
+ });
582
+ }
583
+ /**
584
+ * Open an `indexedDB` transaction and get our store
585
+ * @param mode `readonly` or `readwrite`
586
+ * @returns An `indexedDB` transaction store and events, wrapped in an RxJS `Observable`
587
+ */
588
+ transaction(mode) {
589
+ /* From the `indexedDB` connection, open a transaction and get the store */
590
+ return this.database
591
+ .pipe(mergeMap((database) => {
592
+ let transaction;
593
+ try {
594
+ transaction = database.transaction([this.storeName], mode);
595
+ }
596
+ catch (error) {
597
+ /* The store could have been deleted from outside */
598
+ return throwError(error);
599
+ }
600
+ /* Get the store from the transaction */
601
+ const store = transaction.objectStore(this.storeName);
602
+ /* Listen transaction `complete` and `error` events */
603
+ const events = this.listenTransactionEvents(transaction);
604
+ return of({ store, events });
605
+ }));
606
+ }
607
+ /**
608
+ * Listen errors on a transaction or request, and throw if trigerred
609
+ * @param transactionOrRequest `indexedDb` transaction or request to listen
610
+ * @returns An `Observable` listening to errors
611
+ */
612
+ listenError(transactionOrRequest) {
613
+ return fromEvent(transactionOrRequest, 'error').pipe(
614
+ /* Throw on error to be able to catch errors in RxJS way.
615
+ * Here `event.target` must be used, as `transactionOrRequest.error` will be `null`
616
+ * if we are on the request and the error is only triggered later by the transaction */
617
+ mergeMap((event) => throwError(event.target.error)));
618
+ }
619
+ /**
620
+ * Listen transaction `complete` and `error` events
621
+ * @param transaction Transaction to listen
622
+ * @returns An `Observable` listening to transaction `complete` and `error` events
623
+ */
624
+ listenTransactionEvents(transaction) {
625
+ /* Listen to the `complete` event */
626
+ const complete$ = fromEvent(transaction, 'complete');
627
+ /* Listen to the `error` event */
628
+ const error$ = this.listenError(transaction);
629
+ /* Choose the first event to occur */
630
+ return race([complete$, error$]);
631
+ }
632
+ }
633
+ IndexedDBDatabase.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: IndexedDBDatabase, deps: [{ token: IDB_DB_NAME }, { token: IDB_STORE_NAME }, { token: IDB_DB_VERSION }, { token: IDB_NO_WRAP }], target: i0.ɵɵFactoryTarget.Injectable });
634
+ IndexedDBDatabase.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: IndexedDBDatabase, providedIn: 'root' });
635
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: IndexedDBDatabase, decorators: [{
636
+ type: Injectable,
637
+ args: [{
638
+ providedIn: 'root'
639
+ }]
640
+ }], ctorParameters: function () {
641
+ return [{ type: undefined, decorators: [{
642
+ type: Inject,
643
+ args: [IDB_DB_NAME]
644
+ }] }, { type: undefined, decorators: [{
645
+ type: Inject,
646
+ args: [IDB_STORE_NAME]
647
+ }] }, { type: undefined, decorators: [{
648
+ type: Inject,
649
+ args: [IDB_DB_VERSION]
650
+ }] }, { type: undefined, decorators: [{
651
+ type: Inject,
652
+ args: [IDB_NO_WRAP]
653
+ }] }];
654
+ } });
655
+
656
+ class LocalStorageDatabase {
657
+ /**
658
+ * Constructor params are provided by Angular (but can also be passed manually in tests)
659
+ * @param prefix Prefix option to avoid collision for multiple apps on the same subdomain or for interoperability
660
+ */
661
+ constructor(prefix = '') {
662
+ /* Prefix if asked, or no prefix otherwise */
663
+ this.prefix = prefix || '';
664
+ }
665
+ /**
666
+ * Number of items in `localStorage`
667
+ */
668
+ get size() {
669
+ /* Wrap in a RxJS `Observable` to be consistent with other storages */
670
+ return of(localStorage.length);
671
+ }
672
+ /**
673
+ * Gets an item value in `localStorage`
674
+ * @param key The item's key
675
+ * @returns The item's value if the key exists, `undefined` otherwise, wrapped in a RxJS `Observable`
676
+ */
677
+ get(key) {
678
+ /* Get raw data */
679
+ const unparsedData = localStorage.getItem(this.prefixKey(key));
680
+ let parsedData;
681
+ /* No need to parse if data is `null` or `undefined` */
682
+ if ((unparsedData !== undefined) && (unparsedData !== null)) {
683
+ /* Try to parse */
684
+ try {
685
+ parsedData = JSON.parse(unparsedData);
686
+ }
687
+ catch (error) {
688
+ return throwError(error);
689
+ }
690
+ }
691
+ /* Wrap in a RxJS `Observable` to be consistent with other storages */
692
+ return of(parsedData);
693
+ }
694
+ /**
695
+ * Store an item in `localStorage`
696
+ * @param key The item's key
697
+ * @param data The item's value
698
+ * @returns A RxJS `Observable` to wait the end of the operation
699
+ */
700
+ set(key, data) {
701
+ let serializedData = null;
702
+ /* Check if data can be serialized */
703
+ const dataPrototype = Object.getPrototypeOf(data);
704
+ if ((typeof data === 'object') && (data !== null) && !Array.isArray(data) &&
705
+ !((dataPrototype === Object.prototype) || (dataPrototype === null))) {
706
+ return throwError(new SerializationError());
707
+ }
708
+ /* Try to stringify (can fail on circular references) */
709
+ try {
710
+ serializedData = JSON.stringify(data);
711
+ }
712
+ catch (error) {
713
+ return throwError(error);
714
+ }
715
+ /* Can fail if storage quota is exceeded */
716
+ try {
717
+ localStorage.setItem(this.prefixKey(key), serializedData);
718
+ }
719
+ catch (error) {
720
+ return throwError(error);
721
+ }
722
+ /* Wrap in a RxJS `Observable` to be consistent with other storages */
723
+ return of(undefined);
724
+ }
725
+ /**
726
+ * Deletes an item in `localStorage`
727
+ * @param key The item's key
728
+ * @returns A RxJS `Observable` to wait the end of the operation
729
+ */
730
+ delete(key) {
731
+ localStorage.removeItem(this.prefixKey(key));
732
+ /* Wrap in a RxJS `Observable` to be consistent with other storages */
733
+ return of(undefined);
734
+ }
735
+ /**
736
+ * Deletes all items in `localStorage`
737
+ * @returns A RxJS `Observable` to wait the end of the operation
738
+ */
739
+ clear() {
740
+ localStorage.clear();
741
+ /* Wrap in a RxJS `Observable` to be consistent with other storages */
742
+ return of(undefined);
743
+ }
744
+ /**
745
+ * Get all keys in `localStorage`
746
+ * Note the order of the keys may be inconsistent in Firefox
747
+ * @returns A RxJS `Observable` iterating on keys
748
+ */
749
+ keys() {
750
+ /* Create an `Observable` from keys */
751
+ return new Observable((subscriber) => {
752
+ /* Iteretate over all the indexes */
753
+ for (let index = 0; index < localStorage.length; index += 1) {
754
+ /* Cast as we are sure in this case the key is not `null` */
755
+ subscriber.next(this.getUnprefixedKey(index));
756
+ }
757
+ subscriber.complete();
758
+ }).pipe(
759
+ /* Required to work like other databases which are asynchronous */
760
+ observeOn(asyncScheduler));
761
+ }
762
+ /**
763
+ * Check if a key exists in `localStorage`
764
+ * @param key The item's key
765
+ * @returns A RxJS `Observable` telling if the key exists or not
766
+ */
767
+ has(key) {
768
+ /* Itérate over all indexes in storage */
769
+ for (let index = 0; index < localStorage.length; index += 1) {
770
+ if (key === this.getUnprefixedKey(index)) {
771
+ /* Wrap in a RxJS `Observable` to be consistent with other storages */
772
+ return of(true);
773
+ }
774
+ }
775
+ /* Wrap in a RxJS `Observable` to be consistent with other storages */
776
+ return of(false);
777
+ }
778
+ /**
779
+ * Get an unprefixed key
780
+ * @param index Index of the key
781
+ * @returns The unprefixed key name if exists, `null` otherwise
782
+ */
783
+ getUnprefixedKey(index) {
784
+ /* Get the key in storage: may have a prefix */
785
+ const prefixedKey = localStorage.key(index);
786
+ if (prefixedKey !== null) {
787
+ /* If no prefix, the key is already good, otherwrite strip the prefix */
788
+ return !this.prefix ? prefixedKey : prefixedKey.substr(this.prefix.length);
789
+ }
790
+ return null;
791
+ }
792
+ /**
793
+ * Add the prefix to a key
794
+ * @param key The key name
795
+ * @returns The prefixed key name
796
+ */
797
+ prefixKey(key) {
798
+ return `${this.prefix}${key}`;
799
+ }
800
+ }
801
+ LocalStorageDatabase.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LocalStorageDatabase, deps: [{ token: LS_PREFIX }], target: i0.ɵɵFactoryTarget.Injectable });
802
+ LocalStorageDatabase.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LocalStorageDatabase, providedIn: 'root' });
803
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LocalStorageDatabase, decorators: [{
804
+ type: Injectable,
805
+ args: [{
806
+ providedIn: 'root'
807
+ }]
808
+ }], ctorParameters: function () {
809
+ return [{ type: undefined, decorators: [{
810
+ type: Inject,
811
+ args: [LS_PREFIX]
812
+ }] }];
813
+ } });
814
+
815
+ class MemoryDatabase {
816
+ constructor() {
817
+ /**
818
+ * Memory storage
819
+ */
820
+ this.memoryStorage = new Map();
821
+ }
822
+ /**
823
+ * Number of items in memory
824
+ */
825
+ get size() {
826
+ /* Wrap in a RxJS `Observable` to be consistent with other storages */
827
+ return of(this.memoryStorage.size);
828
+ }
829
+ /**
830
+ * Gets an item value in memory
831
+ * @param key The item's key
832
+ * @returns The item's value if the key exists, `undefined` otherwise, wrapped in a RxJS `Observable`
833
+ */
834
+ get(key) {
835
+ /* Wrap in a RxJS `Observable` to be consistent with other storages */
836
+ return of(this.memoryStorage.get(key));
837
+ }
838
+ /**
839
+ * Sets an item in memory
840
+ * @param key The item's key
841
+ * @param data The item's value
842
+ * @returns A RxJS `Observable` to wait the end of the operation
843
+ */
844
+ set(key, data) {
845
+ this.memoryStorage.set(key, data);
846
+ /* Wrap in a RxJS `Observable` to be consistent with other storages */
847
+ return of(undefined);
848
+ }
849
+ /**
850
+ * Deletes an item in memory
851
+ * @param key The item's key
852
+ * @returns A RxJS `Observable` to wait the end of the operation
853
+ */
854
+ delete(key) {
855
+ this.memoryStorage.delete(key);
856
+ /* Wrap in a RxJS `Observable` to be consistent with other storages */
857
+ return of(undefined);
858
+ }
859
+ /**
860
+ * Deletes all items in memory
861
+ * @returns A RxJS `Observable` to wait the end of the operation
862
+ */
863
+ clear() {
864
+ this.memoryStorage.clear();
865
+ /* Wrap in a RxJS `Observable` to be consistent with other storages */
866
+ return of(undefined);
867
+ }
868
+ /**
869
+ * Get all keys in memory
870
+ * @returns A RxJS `Observable` iterating on keys
871
+ */
872
+ keys() {
873
+ /* Create an `Observable` from keys */
874
+ return from(this.memoryStorage.keys());
875
+ }
876
+ /**
877
+ * Check if a key exists in memory
878
+ * @param key Key name
879
+ * @returns a RxJS `Observable` telling if the key exists or not
880
+ */
881
+ has(key) {
882
+ /* Wrap in a RxJS `Observable` to be consistent with other storages */
883
+ return of(this.memoryStorage.has(key));
884
+ }
885
+ }
886
+ MemoryDatabase.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: MemoryDatabase, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
887
+ MemoryDatabase.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: MemoryDatabase, providedIn: 'root' });
888
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: MemoryDatabase, decorators: [{
889
+ type: Injectable,
890
+ args: [{
891
+ providedIn: 'root'
892
+ }]
893
+ }] });
894
+
895
+ /**
896
+ * Factory to create a storage according to browser support
897
+ * @param platformId Context about the platform (`browser`, `server`...)
898
+ * @param LSPrefix Prefix for `localStorage` keys to avoid collision for multiple apps on the same subdomain
899
+ * @param IDBDBName `indexedDB` database name
900
+ * @param IDBstoreName `indexedDB` storeName name
901
+ * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/BROWSERS_SUPPORT.md}
902
+ */
903
+ function localDatabaseFactory(platformId, LSPrefix, IDBDBName, IDBStoreName, IDBDBVersion, IDBNoWrap) {
904
+ /* When storage is fully disabled in browser (via the "Block all cookies" option),
905
+ * just trying to check `indexedDB` or `localStorage` variables causes a security exception.
906
+ * Prevents https://github.com/cyrilletuzi/angular-async-local-storage/issues/118
907
+ */
908
+ try {
909
+ // Do not explicit `window` here, as the global object is not the same in web workers
910
+ if (isPlatformBrowser(platformId) && (indexedDB !== undefined) && (indexedDB !== null) && ('open' in indexedDB)) {
911
+ /* Check:
912
+ * - if we are in a browser context (issue: server-side rendering)
913
+ * - it could exist but be `undefined` or `null`
914
+ * - it could exists but not having a working API
915
+ * Will be the case for:
916
+ * - All other browsers in normal mode
917
+ * - Chromium / Safari private mode, but in this case, data will be swiped when the user leaves the app */
918
+ return new IndexedDBDatabase(IDBDBName, IDBStoreName, IDBDBVersion, IDBNoWrap);
919
+ }
920
+ else if (isPlatformBrowser(platformId)
921
+ && (localStorage !== undefined) && (localStorage !== null) && ('getItem' in localStorage)) {
922
+ /* Check:
923
+ * - if we are in a browser context (issue: server-side rendering)
924
+ * - if `localStorage` exists (to be sure)
925
+ * - it could exists but not having a working API
926
+ * Will be the case for:
927
+ * - Safari cross-origin iframes, detected later in `IndexedDBDatabase.connect()`
928
+ * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/issues/42}
929
+ * - Firefox private mode, but in this case, data will be swiped when the user leaves the app
930
+ * For Firefox, can only be detected later in `IndexedDBDatabase.connect()`
931
+ * @see {@link https://bugzilla.mozilla.org/show_bug.cgi?id=781982}
932
+ */
933
+ return new LocalStorageDatabase(LSPrefix);
934
+ }
935
+ }
936
+ catch (_a) {
937
+ // Nothing to do
938
+ }
939
+ /* Will be the case for:
940
+ * - In browsers if storage has been fully disabled (via the "Block all cookies" option)
941
+ * - Server-side rendering
942
+ * - All other non-browser context
943
+ */
944
+ return new MemoryDatabase();
945
+ }
946
+ class LocalDatabase {
947
+ }
948
+ LocalDatabase.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LocalDatabase, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
949
+ LocalDatabase.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LocalDatabase, providedIn: 'root', useFactory: localDatabaseFactory, deps: [{ token: PLATFORM_ID }, { token: LS_PREFIX }, { token: IDB_DB_NAME }, { token: IDB_STORE_NAME }, { token: IDB_DB_VERSION }, { token: IDB_NO_WRAP }] });
950
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LocalDatabase, decorators: [{
951
+ type: Injectable,
952
+ args: [{
953
+ providedIn: 'root',
954
+ useFactory: localDatabaseFactory,
955
+ deps: [
956
+ PLATFORM_ID,
957
+ LS_PREFIX,
958
+ IDB_DB_NAME,
959
+ IDB_STORE_NAME,
960
+ IDB_DB_VERSION,
961
+ IDB_NO_WRAP,
962
+ ]
963
+ }]
964
+ }] });
965
+
966
+ /**
967
+ * Exception message when a value is not valid against the JSON schema
968
+ */
969
+ const VALIDATION_ERROR = `Data stored is not valid against the provided JSON schema.
970
+ Check your JSON schema, otherwise it means data has been corrupted.`;
971
+ /**
972
+ * Exception raised when a value is not valid against the JSON schema
973
+ */
974
+ class ValidationError extends Error {
975
+ constructor() {
976
+ super(...arguments);
977
+ this.message = VALIDATION_ERROR;
978
+ }
979
+ }
980
+
981
+ class StorageMap {
982
+ /**
983
+ * Constructor params are provided by Angular (but can also be passed manually in tests)
984
+ * @param database Storage to use
985
+ * @param jsonValidator Validator service
986
+ * @param LSPrefix Prefix for `localStorage` keys to avoid collision for multiple apps on the same subdomain or for interoperability
987
+ */
988
+ constructor(database, jsonValidator = new JSONValidator(), LSPrefix = '') {
989
+ this.database = database;
990
+ this.jsonValidator = jsonValidator;
991
+ this.LSPrefix = LSPrefix;
992
+ this.notifiers = new Map();
993
+ }
994
+ /**
995
+ * **Number of items** in storage, wrapped in an `Observable`.
996
+ *
997
+ * @example
998
+ * this.storageMap.size.subscribe((size) => {
999
+ * console.log(size);
1000
+ * });
1001
+ */
1002
+ get size() {
1003
+ return this.database.size
1004
+ /* Catch if `indexedDb` is broken */
1005
+ .pipe(this.catchIDBBroken(() => this.database.size));
1006
+ }
1007
+ /**
1008
+ * Tells you which storage engine is used. *Only useful for interoperability.*
1009
+ * Note that due to some browsers issues in some special contexts
1010
+ * (Firefox private mode and Safari cross-origin iframes),
1011
+ * **this information may be wrong at initialization,**
1012
+ * as the storage could fallback from `indexedDB` to `localStorage`
1013
+ * only after a first read or write operation.
1014
+ * @returns Storage engine used
1015
+ *
1016
+ * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/INTEROPERABILITY.md}
1017
+ *
1018
+ * @example
1019
+ * if (this.storageMap.backingEngine === 'indexedDB') {}
1020
+ */
1021
+ get backingEngine() {
1022
+ if (this.database instanceof IndexedDBDatabase) {
1023
+ return 'indexedDB';
1024
+ }
1025
+ else if (this.database instanceof LocalStorageDatabase) {
1026
+ return 'localStorage';
1027
+ }
1028
+ else if (this.database instanceof MemoryDatabase) {
1029
+ return 'memory';
1030
+ }
1031
+ else {
1032
+ return 'unknown';
1033
+ }
1034
+ }
1035
+ /**
1036
+ * Info about `indexedDB` database. *Only useful for interoperability.*
1037
+ * @returns `indexedDB` database name, store name and database version.
1038
+ * **Values will be empty if the storage is not `indexedDB`,**
1039
+ * **so it should be used after an engine check**.
1040
+ *
1041
+ * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/INTEROPERABILITY.md}
1042
+ *
1043
+ * @example
1044
+ * if (this.storageMap.backingEngine === 'indexedDB') {
1045
+ * const { database, store, version } = this.storageMap.backingStore;
1046
+ * }
1047
+ */
1048
+ get backingStore() {
1049
+ return (this.database instanceof IndexedDBDatabase) ?
1050
+ this.database.backingStore :
1051
+ { database: '', store: '', version: 0 };
1052
+ }
1053
+ /**
1054
+ * Info about `localStorage` fallback storage. *Only useful for interoperability.*
1055
+ * @returns `localStorage` prefix.
1056
+ * **Values will be empty if the storage is not `localStorage`,**
1057
+ * **so it should be used after an engine check**.
1058
+ *
1059
+ * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/INTEROPERABILITY.md}
1060
+ *
1061
+ * @example
1062
+ * if (this.storageMap.backingEngine === 'localStorage') {
1063
+ * const { prefix } = this.storageMap.fallbackBackingStore;
1064
+ * }
1065
+ */
1066
+ get fallbackBackingStore() {
1067
+ return (this.database instanceof LocalStorageDatabase) ?
1068
+ { prefix: this.database.prefix } :
1069
+ { prefix: '' };
1070
+ }
1071
+ get(key, schema) {
1072
+ /* Get the data in storage */
1073
+ return this.database.get(key).pipe(
1074
+ /* Check if `indexedDb` is broken */
1075
+ this.catchIDBBroken(() => this.database.get(key)), mergeMap((data) => {
1076
+ /* No need to validate if the data is empty */
1077
+ if ((data === undefined) || (data === null)) {
1078
+ return of(undefined);
1079
+ }
1080
+ else if (schema) {
1081
+ /* Validate data against a JSON schema if provided */
1082
+ if (!this.jsonValidator.validate(data, schema)) {
1083
+ return throwError(new ValidationError());
1084
+ }
1085
+ /* Data have been checked, so it's OK to cast */
1086
+ return of(data);
1087
+ }
1088
+ /* Cast to unknown as the data wasn't checked */
1089
+ return of(data);
1090
+ }));
1091
+ }
1092
+ /**
1093
+ * Set an item in storage.
1094
+ * Note that setting `null` or `undefined` will remove the item to avoid some browsers issues.
1095
+ * @param key The item's key
1096
+ * @param data The item's value
1097
+ * @param schema Optional JSON schema to validate the data
1098
+ * @returns A RxJS `Observable` to wait the end of the operation
1099
+ *
1100
+ * @example
1101
+ * this.storageMap.set('key', 'value').subscribe(() => {});
1102
+ */
1103
+ set(key, data, schema) {
1104
+ /* Storing `undefined` or `null` is useless and can cause issues in `indexedDb` in some browsers,
1105
+ * so removing item instead for all storages to have a consistent API */
1106
+ if ((data === undefined) || (data === null)) {
1107
+ return this.delete(key);
1108
+ }
1109
+ /* Validate data against a JSON schema if provided */
1110
+ if (schema && !this.jsonValidator.validate(data, schema)) {
1111
+ return throwError(new ValidationError());
1112
+ }
1113
+ return this.database.set(key, data).pipe(
1114
+ /* Catch if `indexedDb` is broken */
1115
+ this.catchIDBBroken(() => this.database.set(key, data)),
1116
+ /* Notify watchers (must be last because it should only happen if the operation succeeds) */
1117
+ tap(() => { this.notify(key, data); }));
1118
+ }
1119
+ /**
1120
+ * Delete an item in storage
1121
+ * @param key The item's key
1122
+ * @returns A RxJS `Observable` to wait the end of the operation
1123
+ *
1124
+ * @example
1125
+ * this.storageMap.delete('key').subscribe(() => {});
1126
+ */
1127
+ delete(key) {
1128
+ return this.database.delete(key).pipe(
1129
+ /* Catch if `indexedDb` is broken */
1130
+ this.catchIDBBroken(() => this.database.delete(key)),
1131
+ /* Notify watchers (must be last because it should only happen if the operation succeeds) */
1132
+ tap(() => { this.notify(key, undefined); }));
1133
+ }
1134
+ /**
1135
+ * Delete all items in storage
1136
+ * @returns A RxJS `Observable` to wait the end of the operation
1137
+ *
1138
+ * @example
1139
+ * this.storageMap.clear().subscribe(() => {});
1140
+ */
1141
+ clear() {
1142
+ return this.database.clear().pipe(
1143
+ /* Catch if `indexedDb` is broken */
1144
+ this.catchIDBBroken(() => this.database.clear()),
1145
+ /* Notify watchers (must be last because it should only happen if the operation succeeds) */
1146
+ tap(() => {
1147
+ for (const key of this.notifiers.keys()) {
1148
+ this.notify(key, undefined);
1149
+ }
1150
+ }));
1151
+ }
1152
+ /**
1153
+ * Get all keys stored in storage. Note **this is an *iterating* `Observable`**:
1154
+ * * if there is no key, the `next` callback will not be invoked,
1155
+ * * if you need to wait the whole operation to end, be sure to act in the `complete` callback,
1156
+ * as this `Observable` can emit several values and so will invoke the `next` callback several times.
1157
+ * @returns A list of the keys wrapped in a RxJS `Observable`
1158
+ *
1159
+ * @example
1160
+ * this.storageMap.keys().subscribe({
1161
+ * next: (key) => { console.log(key); },
1162
+ * complete: () => { console.log('Done'); },
1163
+ * });
1164
+ */
1165
+ keys() {
1166
+ return this.database.keys()
1167
+ /* Catch if `indexedDb` is broken */
1168
+ .pipe(this.catchIDBBroken(() => this.database.keys()));
1169
+ }
1170
+ /**
1171
+ * Tells if a key exists in storage
1172
+ * @returns A RxJS `Observable` telling if the key exists
1173
+ *
1174
+ * @example
1175
+ * this.storageMap.has('key').subscribe((hasKey) => {
1176
+ * if (hasKey) {}
1177
+ * });
1178
+ */
1179
+ has(key) {
1180
+ return this.database.has(key)
1181
+ /* Catch if `indexedDb` is broken */
1182
+ .pipe(this.catchIDBBroken(() => this.database.has(key)));
1183
+ }
1184
+ watch(key, schema) {
1185
+ /* Check if there is already a notifier */
1186
+ if (!this.notifiers.has(key)) {
1187
+ this.notifiers.set(key, new ReplaySubject(1));
1188
+ }
1189
+ /* Non-null assertion is required because TypeScript doesn't narrow `.has()` yet */
1190
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1191
+ const notifier = this.notifiers.get(key);
1192
+ /* Get the current item value */
1193
+ (schema ? this.get(key, schema) : this.get(key)).subscribe({
1194
+ next: (result) => notifier.next(result),
1195
+ error: (error) => notifier.error(error),
1196
+ });
1197
+ /* Only the public API of the `Observable` should be returned */
1198
+ return (schema ?
1199
+ notifier.asObservable() :
1200
+ notifier.asObservable());
1201
+ }
1202
+ /**
1203
+ * Notify when a value changes
1204
+ * @param key The item's key
1205
+ * @param data The new value
1206
+ */
1207
+ notify(key, value) {
1208
+ const notifier = this.notifiers.get(key);
1209
+ if (notifier) {
1210
+ notifier.next(value);
1211
+ }
1212
+ }
1213
+ /**
1214
+ * RxJS operator to catch if `indexedDB` is broken
1215
+ * @param operationCallback Callback with the operation to redo
1216
+ */
1217
+ catchIDBBroken(operationCallback) {
1218
+ return catchError((error) => {
1219
+ /* Check if `indexedDB` is broken based on error message (the specific error class seems to be lost in the process) */
1220
+ if ((error !== undefined) && (error !== null)
1221
+ && (typeof error === 'object') && ('message' in error)
1222
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1223
+ && (error.message === IDB_BROKEN_ERROR)) {
1224
+ /* When storage is fully disabled in browser (via the "Block all cookies" option),
1225
+ * just trying to check `localStorage` variable causes a security exception.
1226
+ * Prevents https://github.com/cyrilletuzi/angular-async-local-storage/issues/118
1227
+ */
1228
+ try {
1229
+ if ('getItem' in localStorage) {
1230
+ /* Fallback to `localStorage` if available */
1231
+ this.database = new LocalStorageDatabase(this.LSPrefix);
1232
+ }
1233
+ else {
1234
+ /* Fallback to memory storage otherwise */
1235
+ this.database = new MemoryDatabase();
1236
+ }
1237
+ }
1238
+ catch (_a) {
1239
+ /* Fallback to memory storage otherwise */
1240
+ this.database = new MemoryDatabase();
1241
+ }
1242
+ /* Redo the operation */
1243
+ return operationCallback();
1244
+ }
1245
+ else {
1246
+ /* Otherwise, rethrow the error */
1247
+ return throwError(error);
1248
+ }
1249
+ });
1250
+ }
1251
+ }
1252
+ StorageMap.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: StorageMap, deps: [{ token: LocalDatabase }, { token: JSONValidator }, { token: LS_PREFIX }], target: i0.ɵɵFactoryTarget.Injectable });
1253
+ StorageMap.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: StorageMap, providedIn: 'root' });
1254
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: StorageMap, decorators: [{
1255
+ type: Injectable,
1256
+ args: [{
1257
+ providedIn: 'root'
1258
+ }]
1259
+ }], ctorParameters: function () {
1260
+ return [{ type: LocalDatabase }, { type: JSONValidator }, { type: undefined, decorators: [{
1261
+ type: Inject,
1262
+ args: [LS_PREFIX]
1263
+ }] }];
1264
+ } });
1265
+
1266
+ class LocalStorage {
1267
+ /* Use the `StorageMap` service to avoid code duplication */
1268
+ constructor(storageMap) {
1269
+ this.storageMap = storageMap;
1270
+ }
1271
+ /**
1272
+ * Number of items in storage wrapped in an `Observable`
1273
+ *
1274
+ * @example
1275
+ * this.localStorage.length.subscribe((length) => {
1276
+ * console.log(length);
1277
+ * });
1278
+ */
1279
+ get length() {
1280
+ return this.storageMap.size;
1281
+ }
1282
+ getItem(key, schema) {
1283
+ if (schema) {
1284
+ /* Backward compatibility with version <= 7 */
1285
+ schema = ('schema' in schema) ? schema.schema : schema;
1286
+ }
1287
+ return (schema ? this.storageMap.get(key, schema) : this.storageMap.get(key)).pipe(
1288
+ /* Transform `undefined` into `null` to align with `localStorage` API */
1289
+ map((value) => (value !== undefined) ? value : null));
1290
+ }
1291
+ /**
1292
+ * Set an item in storage.
1293
+ * Note that setting `null` or `undefined` will remove the item to avoid some browsers issues.
1294
+ * @param key The item's key
1295
+ * @param data The item's value
1296
+ * @param schema Optional JSON schema to validate the data
1297
+ * @returns A RxJS `Observable` to wait the end of the operation
1298
+ *
1299
+ * @example
1300
+ * this.localStorage.set('key', 'value').subscribe(() => {});
1301
+ */
1302
+ setItem(key, data, schema) {
1303
+ return this.storageMap.set(key, data, schema).pipe(
1304
+ /* Transform `undefined` into `true` for backward compatibility with v7 */
1305
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
1306
+ mapTo(true));
1307
+ }
1308
+ /**
1309
+ * Delete an item in storage
1310
+ * @param key The item's key
1311
+ * @returns A RxJS `Observable` to wait the end of the operation
1312
+ *
1313
+ * @example
1314
+ * this.localStorage.delete('key').subscribe(() => {});
1315
+ */
1316
+ removeItem(key) {
1317
+ return this.storageMap.delete(key).pipe(
1318
+ /* Transform `undefined` into `true` for backward compatibility with v7 */
1319
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
1320
+ mapTo(true));
1321
+ }
1322
+ /**
1323
+ * Delete all items in storage
1324
+ * @returns A RxJS `Observable` to wait the end of the operation
1325
+ *
1326
+ * @example
1327
+ * this.localStorage.clear().subscribe(() => {});
1328
+ */
1329
+ clear() {
1330
+ return this.storageMap.clear().pipe(
1331
+ /* Transform `undefined` into `true` for backward compatibility with v7 */
1332
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
1333
+ mapTo(true));
1334
+ }
1335
+ }
1336
+ LocalStorage.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LocalStorage, deps: [{ token: StorageMap }], target: i0.ɵɵFactoryTarget.Injectable });
1337
+ LocalStorage.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LocalStorage, providedIn: 'root' });
1338
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LocalStorage, decorators: [{
1339
+ type: Injectable,
1340
+ args: [{
1341
+ providedIn: 'root'
1342
+ }]
1343
+ }], ctorParameters: function () { return [{ type: StorageMap }]; } });
1344
+
1345
+ /**
1346
+ * This module does not contain anything, it's only useful to provide options via `.forRoot()`.
1347
+ */
1348
+ class StorageModule {
1349
+ /**
1350
+ * Only useful to provide options, otherwise it does nothing.
1351
+ * **Must be used at initialization, ie. in `AppModule`, and must not be loaded again in another module.**
1352
+ *
1353
+ * @example
1354
+ * NgModule({
1355
+ * imports: [StorageModule.forRoot({
1356
+ * LSPrefix: 'custom_',
1357
+ * })]
1358
+ * })
1359
+ * export class AppModule
1360
+ */
1361
+ static forRoot(config) {
1362
+ return {
1363
+ ngModule: StorageModule,
1364
+ providers: [
1365
+ config.LSPrefix ? { provide: LS_PREFIX, useValue: config.LSPrefix } : [],
1366
+ config.IDBDBName ? { provide: IDB_DB_NAME, useValue: config.IDBDBName } : [],
1367
+ config.IDBStoreName ? { provide: IDB_STORE_NAME, useValue: config.IDBStoreName } : [],
1368
+ config.IDBDBVersion ? { provide: IDB_DB_VERSION, useValue: config.IDBDBVersion } : [],
1369
+ (config.IDBNoWrap === false) ? { provide: IDB_NO_WRAP, useValue: config.IDBNoWrap } : [],
1370
+ ],
1371
+ };
1372
+ }
1373
+ }
1374
+ StorageModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: StorageModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
1375
+ StorageModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: StorageModule });
1376
+ StorageModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: StorageModule });
1377
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: StorageModule, decorators: [{
1378
+ type: NgModule
1379
+ }] });
1380
+
1381
+ /*
1382
+ * Public API Surface of local-storage
1383
+ */
1384
+
1385
+ /**
1386
+ * Generated bundle index. Do not edit.
1387
+ */
1388
+
1389
+ export { JSONValidator, LocalDatabase, LocalStorage, SERIALIZATION_ERROR, SerializationError, StorageMap, StorageModule, VALIDATION_ERROR, ValidationError };