@telperion/reactive-storage 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +172 -1
- package/index.cjs +1 -0
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/index.js.map +1 -1
- package/json-parse.cjs +16 -0
- package/json-parse.d.ts +6 -0
- package/json-parse.js +15 -0
- package/json-parse.js.map +1 -0
- package/package.json +28 -1
- package/reactive-cookie-storage.cjs +212 -0
- package/reactive-cookie-storage.d.ts +69 -0
- package/reactive-cookie-storage.js +210 -0
- package/reactive-cookie-storage.js.map +1 -0
- package/reactive-web-storage.cjs +4 -8
- package/reactive-web-storage.d.ts +0 -1
- package/reactive-web-storage.js +4 -8
- package/reactive-web-storage.js.map +1 -1
package/README.md
CHANGED
|
@@ -84,6 +84,78 @@ const storage = new ReactiveWebStorage(
|
|
|
84
84
|
);
|
|
85
85
|
```
|
|
86
86
|
|
|
87
|
+
#### `ReactiveCookieStorage<S extends string>`
|
|
88
|
+
|
|
89
|
+
Reactive wrapper for browser cookies. Provides cookie-specific features including expiration control and optional polling for external changes.
|
|
90
|
+
|
|
91
|
+
```typescript
|
|
92
|
+
const storage = new ReactiveCookieStorage(
|
|
93
|
+
appName?: string,
|
|
94
|
+
options?: ReactiveCookieStorageOptions
|
|
95
|
+
);
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
**Parameters:**
|
|
99
|
+
- `appName` (optional): Application namespace (default: `'app'`). Used to prefix cookie names.
|
|
100
|
+
- `options` (optional): Cookie configuration options
|
|
101
|
+
|
|
102
|
+
**Options:**
|
|
103
|
+
- `path` (string): URL path where cookie is valid. Default: `'/'`
|
|
104
|
+
- `domain` (string): Domain where cookie is valid. Default: current domain
|
|
105
|
+
- `maxAge` (number): Cookie lifetime in seconds. Default: `undefined` (session cookie)
|
|
106
|
+
- `expires` (Date): Absolute expiration date. Default: `undefined`
|
|
107
|
+
- `secure` (boolean): HTTPS only flag. Default: `false`
|
|
108
|
+
- `sameSite` ('strict' | 'lax' | 'none'): CSRF protection level. Default: `'lax'`
|
|
109
|
+
|
|
110
|
+
**Third Parameter (optional):**
|
|
111
|
+
- `linker` (any): Value to link multiple instances for cross-instance synchronization. Can be a Symbol, string, number, object, or any other value.
|
|
112
|
+
|
|
113
|
+
**Important Limitations:**
|
|
114
|
+
- **Size Limit**: Cookies are limited to ~4KB each. The library enforces a 4000 byte limit and throws an error if exceeded.
|
|
115
|
+
- **Change Detection**: Cookies have no native change events. By default, only changes made through this instance are detected. Use a linker to synchronize multiple instances.
|
|
116
|
+
- **httpOnly Cookies**: Cannot access cookies set by the server with the httpOnly flag.
|
|
117
|
+
|
|
118
|
+
**Example:**
|
|
119
|
+
```typescript
|
|
120
|
+
import { ReactiveCookieStorage } from '@telperion/reactive-storage';
|
|
121
|
+
|
|
122
|
+
// Single instance
|
|
123
|
+
const storage = new ReactiveCookieStorage('my-app', {
|
|
124
|
+
path: '/',
|
|
125
|
+
maxAge: 86400, // 1 day
|
|
126
|
+
secure: true,
|
|
127
|
+
sameSite: 'strict'
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
// Subscribe to changes
|
|
131
|
+
storage.get('preferences', 'theme').subscribe(theme => {
|
|
132
|
+
console.log('Theme:', theme);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
// Set with default options
|
|
136
|
+
await storage.set('preferences', '', { theme: 'dark' });
|
|
137
|
+
|
|
138
|
+
// Multiple linked instances for cross-instance sync
|
|
139
|
+
const linker = Symbol('cookie-sync'); // Can also use strings, numbers, objects, etc.
|
|
140
|
+
const storageOne = new ReactiveCookieStorage('my-app', {
|
|
141
|
+
path: '/',
|
|
142
|
+
maxAge: 86400,
|
|
143
|
+
secure: true,
|
|
144
|
+
sameSite: 'strict'
|
|
145
|
+
}, linker);
|
|
146
|
+
|
|
147
|
+
const storageTwo = new ReactiveCookieStorage('my-app', {
|
|
148
|
+
path: '/',
|
|
149
|
+
maxAge: 86400,
|
|
150
|
+
secure: false,
|
|
151
|
+
sameSite: 'lax'
|
|
152
|
+
}, linker);
|
|
153
|
+
|
|
154
|
+
// Changes in storageOne will automatically notify storageTwo
|
|
155
|
+
await storageOne.set('user', '', { name: 'John' });
|
|
156
|
+
// storageTwo subscribers will be notified
|
|
157
|
+
```
|
|
158
|
+
|
|
87
159
|
### Methods
|
|
88
160
|
|
|
89
161
|
All methods are available on storage instances:
|
|
@@ -268,6 +340,91 @@ storage.get<User>('user').subscribe(user => {
|
|
|
268
340
|
// storage.get('invalid-store'); ❌
|
|
269
341
|
```
|
|
270
342
|
|
|
343
|
+
### Working with Cookies
|
|
344
|
+
|
|
345
|
+
Cookies provide unique features like expiration control and HTTP transmission. Cookie options are configured at instance creation time.
|
|
346
|
+
|
|
347
|
+
```typescript
|
|
348
|
+
import { ReactiveCookieStorage } from '@telperion/reactive-storage';
|
|
349
|
+
|
|
350
|
+
// Session cookie (no expiration)
|
|
351
|
+
const sessionStorage = new ReactiveCookieStorage('my-app', {
|
|
352
|
+
path: '/',
|
|
353
|
+
secure: true,
|
|
354
|
+
sameSite: 'strict'
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
await sessionStorage.set('session', '', {
|
|
358
|
+
userId: '123',
|
|
359
|
+
token: 'abc'
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
// Persistent cookie with 1 week expiration
|
|
363
|
+
const persistentStorage = new ReactiveCookieStorage('my-app', {
|
|
364
|
+
path: '/',
|
|
365
|
+
maxAge: 604800, // 7 days in seconds
|
|
366
|
+
secure: true,
|
|
367
|
+
sameSite: 'strict'
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
await persistentStorage.set('remember', '', { username: 'john' });
|
|
371
|
+
|
|
372
|
+
// Cookie with absolute expiration date
|
|
373
|
+
const tempStorage = new ReactiveCookieStorage('my-app', {
|
|
374
|
+
path: '/',
|
|
375
|
+
expires: new Date('2026-12-31'),
|
|
376
|
+
secure: true,
|
|
377
|
+
sameSite: 'strict'
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
await tempStorage.set('temp', '', { data: 'value' });
|
|
381
|
+
|
|
382
|
+
// Cross-instance synchronization using linker (any value works)
|
|
383
|
+
const linker = Symbol('my-app-sync'); // Symbols, strings, objects, etc.
|
|
384
|
+
|
|
385
|
+
const storageOne = new ReactiveCookieStorage('my-app', {
|
|
386
|
+
path: '/',
|
|
387
|
+
secure: true,
|
|
388
|
+
sameSite: 'strict'
|
|
389
|
+
}, linker);
|
|
390
|
+
|
|
391
|
+
const storageTwo = new ReactiveCookieStorage('my-app', {
|
|
392
|
+
path: '/',
|
|
393
|
+
secure: false,
|
|
394
|
+
sameSite: 'lax'
|
|
395
|
+
}, linker);
|
|
396
|
+
|
|
397
|
+
// Subscribe in second instance
|
|
398
|
+
storageTwo.get('preferences', 'theme').subscribe(theme => {
|
|
399
|
+
// Will receive updates from both storageOne and storageTwo
|
|
400
|
+
console.log('Theme changed:', theme);
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
// Set in first instance - will notify second instance
|
|
404
|
+
await storageOne.set('preferences', '', { theme: 'dark' });
|
|
405
|
+
|
|
406
|
+
// Size limit handling
|
|
407
|
+
try {
|
|
408
|
+
const largeData = { items: new Array(1000).fill('data') };
|
|
409
|
+
await storage.set('large', '', largeData);
|
|
410
|
+
} catch (error) {
|
|
411
|
+
console.error('Cookie too large:', error.message);
|
|
412
|
+
// Use localStorage for large data instead
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// Cleanup when done
|
|
416
|
+
storageOne.destroy(); // Unregisters from linker group
|
|
417
|
+
storageTwo.destroy(); // Unregisters from linker group
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
**Cookie Best Practices:**
|
|
421
|
+
- Use cookies for small, security-sensitive data (auth tokens, preferences)
|
|
422
|
+
- Use `secure: true` in production for HTTPS
|
|
423
|
+
- Use `sameSite: 'strict'` for CSRF protection
|
|
424
|
+
- Use a linker (symbol, string, etc.) when you need multiple instances with different configurations
|
|
425
|
+
- Call `destroy()` when disposing instances to prevent memory leaks
|
|
426
|
+
- Use localStorage for data > 4KB
|
|
427
|
+
|
|
271
428
|
### Integration with Framework-Specific Wrappers
|
|
272
429
|
|
|
273
430
|
This library serves as the foundation for framework-specific integrations:
|
|
@@ -277,16 +434,30 @@ This library serves as the foundation for framework-specific integrations:
|
|
|
277
434
|
|
|
278
435
|
## How It Works
|
|
279
436
|
|
|
437
|
+
### Web Storage (localStorage/sessionStorage)
|
|
438
|
+
|
|
280
439
|
1. **Storage Namespacing**: Data is stored with app-prefixed keys (e.g., `my-app/user`)
|
|
281
440
|
2. **JSON Serialization**: All data is serialized to JSON for storage compatibility
|
|
282
441
|
3. **Change Tracking**: Internal Subject emits changes that update all subscribers
|
|
283
442
|
4. **FIFO Queue**: Write operations are queued using `@FifoPromise` decorator to prevent race conditions
|
|
284
443
|
5. **Immutability**: All emitted values are deep-frozen to prevent accidental mutations
|
|
444
|
+
6. **Native Events**: localStorage uses the storage event for automatic cross-tab synchronization
|
|
445
|
+
|
|
446
|
+
### Cookie Storage
|
|
447
|
+
|
|
448
|
+
1. **Cookie Namespacing**: Cookie names are prefixed with app name (e.g., `my-app_user`)
|
|
449
|
+
2. **JSON Serialization + Encoding**: Data is JSON-stringified then URL-encoded for cookie compatibility
|
|
450
|
+
3. **Change Tracking**: RxJS Subject emits changes to this instance and linked instances
|
|
451
|
+
4. **FIFO Queue**: Write operations are queued using `@FifoPromise` decorator to prevent race conditions
|
|
452
|
+
5. **Immutability**: All emitted values are deep-frozen to prevent accidental mutations
|
|
453
|
+
6. **Size Validation**: Enforces 4KB limit before setting cookies
|
|
454
|
+
7. **Cross-Instance Sync**: Optional linker (any value) enables synchronous change notification between instances
|
|
285
455
|
|
|
286
456
|
## Browser Compatibility
|
|
287
457
|
|
|
288
458
|
Works in all modern browsers that support:
|
|
289
|
-
- Web Storage API (localStorage/sessionStorage)
|
|
459
|
+
- Web Storage API (localStorage/sessionStorage) - for web storage classes
|
|
460
|
+
- Cookie API (document.cookie) - for cookie storage class
|
|
290
461
|
- ES2015+ features
|
|
291
462
|
- RxJS 7+
|
|
292
463
|
|
package/index.cjs
CHANGED
|
@@ -5,3 +5,4 @@ tslib_1.__exportStar(require("./reactive-storage"), exports);
|
|
|
5
5
|
tslib_1.__exportStar(require("./reactive-web-storage"), exports);
|
|
6
6
|
tslib_1.__exportStar(require("./reactive-web-local-storage"), exports);
|
|
7
7
|
tslib_1.__exportStar(require("./reactive-web-session-storage"), exports);
|
|
8
|
+
tslib_1.__exportStar(require("./reactive-cookie-storage"), exports);
|
package/index.d.ts
CHANGED
package/index.js
CHANGED
package/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../libs/reactive-storage/src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,wBAAwB,CAAC;AACvC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,gCAAgC,CAAC","file":"index.js","sourcesContent":["export * from './reactive-storage';\nexport * from './reactive-web-storage';\nexport * from './reactive-web-local-storage';\nexport * from './reactive-web-session-storage';\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../../../libs/reactive-storage/src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,wBAAwB,CAAC;AACvC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,2BAA2B,CAAC","file":"index.js","sourcesContent":["export * from './reactive-storage';\nexport * from './reactive-web-storage';\nexport * from './reactive-web-local-storage';\nexport * from './reactive-web-session-storage';\nexport * from './reactive-cookie-storage';\n"]}
|
package/json-parse.cjs
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.jsonParse = jsonParse;
|
|
4
|
+
/**
|
|
5
|
+
* Safely parse JSON string, returning undefined on failure.
|
|
6
|
+
* @param value - JSON string to parse
|
|
7
|
+
* @returns Parsed value or undefined if parsing fails
|
|
8
|
+
*/
|
|
9
|
+
function jsonParse(value) {
|
|
10
|
+
try {
|
|
11
|
+
return JSON.parse(value);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
}
|
package/json-parse.d.ts
ADDED
package/json-parse.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Safely parse JSON string, returning undefined on failure.
|
|
3
|
+
* @param value - JSON string to parse
|
|
4
|
+
* @returns Parsed value or undefined if parsing fails
|
|
5
|
+
*/
|
|
6
|
+
export function jsonParse(value) {
|
|
7
|
+
try {
|
|
8
|
+
return JSON.parse(value);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=json-parse.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../libs/reactive-storage/src/json-parse.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,UAAU,SAAS,CAAI,KAAa;IACxC,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAU,CAAC;IACpB,CAAC;AACH,CAAC","file":"json-parse.js","sourcesContent":["/**\r\n * Safely parse JSON string, returning undefined on failure.\r\n * @param value - JSON string to parse\r\n * @returns Parsed value or undefined if parsing fails\r\n */\r\nexport function jsonParse<T>(value: string): T {\r\n try {\r\n return JSON.parse(value);\r\n } catch {\r\n return undefined!;\r\n }\r\n}\r\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@telperion/reactive-storage",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "RxJS-based reactive storage library for browser environments. Provides Observable-based wrappers for localStorage, sessionStorage, and cookies with immutability, type safety, and cross-instance synchronization support. Built with TypeScript and RxJS for reactive data management.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"rxjs",
|
|
7
|
+
"reactive",
|
|
8
|
+
"storage",
|
|
9
|
+
"localstorage",
|
|
10
|
+
"sessionstorage",
|
|
11
|
+
"cookies",
|
|
12
|
+
"observable",
|
|
13
|
+
"browser-storage",
|
|
14
|
+
"typescript",
|
|
15
|
+
"immutable",
|
|
16
|
+
"web-storage",
|
|
17
|
+
"reactive-programming",
|
|
18
|
+
"state-management",
|
|
19
|
+
"async-storage",
|
|
20
|
+
"cookie-storage",
|
|
21
|
+
"storage-sync"
|
|
22
|
+
],
|
|
4
23
|
"dependencies": {
|
|
5
24
|
"tslib": "^2.3.0",
|
|
6
25
|
"rxjs": "^7.8.1",
|
|
@@ -12,6 +31,7 @@
|
|
|
12
31
|
"module": "./index.js",
|
|
13
32
|
"main": "./index.cjs",
|
|
14
33
|
"typings": "./index.d.ts",
|
|
34
|
+
"sideEffects": false,
|
|
15
35
|
"bugs": "https://github.com/telperiontech/telperion/issues",
|
|
16
36
|
"license": "MIT",
|
|
17
37
|
"homepage": "https://open-source.telperion.tr",
|
|
@@ -63,6 +83,13 @@
|
|
|
63
83
|
"node": "./reactive-web-session-storage.cjs",
|
|
64
84
|
"require": "./reactive-web-session-storage.cjs",
|
|
65
85
|
"types": "./reactive-web-session-storage.d.ts"
|
|
86
|
+
},
|
|
87
|
+
"./reactive-cookie-storage": {
|
|
88
|
+
"default": "./reactive-cookie-storage.cjs",
|
|
89
|
+
"import": "./reactive-cookie-storage.js",
|
|
90
|
+
"node": "./reactive-cookie-storage.cjs",
|
|
91
|
+
"require": "./reactive-cookie-storage.cjs",
|
|
92
|
+
"types": "./reactive-cookie-storage.d.ts"
|
|
66
93
|
}
|
|
67
94
|
}
|
|
68
95
|
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var _a;
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.ReactiveCookieStorage = void 0;
|
|
5
|
+
const rxjs_1 = require("rxjs");
|
|
6
|
+
const reactive_storage_1 = require("./reactive-storage");
|
|
7
|
+
const async_iterator_polyfill_1 = require("./async-iterator.polyfill");
|
|
8
|
+
const json_parse_1 = require("./json-parse");
|
|
9
|
+
/**
|
|
10
|
+
* Reactive wrapper for browser cookies.
|
|
11
|
+
* Provides RxJS-based reactive API for cookie storage with automatic change detection.
|
|
12
|
+
*
|
|
13
|
+
* **Important Limitations:**
|
|
14
|
+
* - Cookies have a ~4KB size limit per cookie
|
|
15
|
+
* - No native change events - use linker to sync multiple instances
|
|
16
|
+
* - Cannot access httpOnly cookies set by the server
|
|
17
|
+
*
|
|
18
|
+
* **Cross-Instance Synchronization:**
|
|
19
|
+
* Link multiple instances using any shared value (symbol, string, object, etc.) to automatically sync changes between them.
|
|
20
|
+
*
|
|
21
|
+
* @template S - Storage store name type
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```typescript
|
|
25
|
+
* // Single instance
|
|
26
|
+
* const storage = new ReactiveCookieStorage('my-app', {
|
|
27
|
+
* path: '/',
|
|
28
|
+
* maxAge: 86400,
|
|
29
|
+
* secure: true,
|
|
30
|
+
* sameSite: 'strict'
|
|
31
|
+
* });
|
|
32
|
+
*
|
|
33
|
+
* // Multiple linked instances using a symbol
|
|
34
|
+
* const linker = Symbol('cookie-sync');
|
|
35
|
+
* const storageOne = new ReactiveCookieStorage('my-app', { secure: true }, linker);
|
|
36
|
+
* const storageTwo = new ReactiveCookieStorage('my-app', { secure: false }, linker);
|
|
37
|
+
* // Changes in storageOne will notify storageTwo and vice versa
|
|
38
|
+
*
|
|
39
|
+
* // Or use any other value type
|
|
40
|
+
* const storageA = new ReactiveCookieStorage('my-app', { secure: true }, 'my-linker');
|
|
41
|
+
* const storageB = new ReactiveCookieStorage('my-app', { secure: false }, 'my-linker');
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
class ReactiveCookieStorage extends reactive_storage_1.ReactiveStorage {
|
|
45
|
+
appName;
|
|
46
|
+
options;
|
|
47
|
+
static #MAX_COOKIE_SIZE = 4000; // Conservative 4KB limit
|
|
48
|
+
static #LINKERS = new Map();
|
|
49
|
+
/**
|
|
50
|
+
* Safely parse JSON with error handling.
|
|
51
|
+
* Returns undefined if parsing fails.
|
|
52
|
+
*/
|
|
53
|
+
static #parse(value) {
|
|
54
|
+
return (0, json_parse_1.jsonParse)(value);
|
|
55
|
+
}
|
|
56
|
+
#changes$ = new rxjs_1.Subject();
|
|
57
|
+
#linker;
|
|
58
|
+
constructor(appName = 'app', options = {}, linker) {
|
|
59
|
+
super();
|
|
60
|
+
this.appName = appName;
|
|
61
|
+
this.options = options;
|
|
62
|
+
// Register to linker group if provided
|
|
63
|
+
if (linker) {
|
|
64
|
+
this.#linker = linker;
|
|
65
|
+
if (!_a.#LINKERS.has(linker)) {
|
|
66
|
+
_a.#LINKERS.set(linker, new Set());
|
|
67
|
+
}
|
|
68
|
+
_a.#LINKERS.get(linker).add(this);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Destroy the storage instance and cleanup resources.
|
|
73
|
+
* Unregisters from linker group and completes the changes subject.
|
|
74
|
+
* Call this when you're done using the storage to prevent memory leaks.
|
|
75
|
+
*/
|
|
76
|
+
destroy() {
|
|
77
|
+
// Unregister from linker group
|
|
78
|
+
if (this.#linker) {
|
|
79
|
+
const linkedInstances = _a.#LINKERS.get(this.#linker);
|
|
80
|
+
if (linkedInstances) {
|
|
81
|
+
linkedInstances.delete(this);
|
|
82
|
+
if (linkedInstances.size === 0) {
|
|
83
|
+
_a.#LINKERS.delete(this.#linker);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
this.#changes$.complete();
|
|
88
|
+
}
|
|
89
|
+
async [reactive_storage_1.ReactiveStorage.Props.GET_ALL]() {
|
|
90
|
+
const cookies = this.#getAppCookies();
|
|
91
|
+
return Object.fromEntries(Object.entries(cookies).map(([storeName, value]) => [storeName, _a.#parse(value)]));
|
|
92
|
+
}
|
|
93
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
94
|
+
[reactive_storage_1.ReactiveStorage.Props.CHANGES] = this.#changes$[Symbol.asyncIterator] ?? (0, async_iterator_polyfill_1.toAsyncIterator)(this.#changes$);
|
|
95
|
+
async [reactive_storage_1.ReactiveStorage.Props.SET](storeName, value) {
|
|
96
|
+
const serialized = JSON.stringify(value);
|
|
97
|
+
const cookieName = this.#getCookieName(storeName);
|
|
98
|
+
// Validate size before setting
|
|
99
|
+
const cookieString = `${cookieName}=${encodeURIComponent(serialized)}`;
|
|
100
|
+
this.#validateSize(cookieString);
|
|
101
|
+
this.#setCookie(cookieName, serialized); // Uses instance options
|
|
102
|
+
const event = { storeName, value };
|
|
103
|
+
this.#changes$.next(event);
|
|
104
|
+
this.#notifyLinkedInstances(event);
|
|
105
|
+
}
|
|
106
|
+
async [reactive_storage_1.ReactiveStorage.Props.REMOVE](storeName) {
|
|
107
|
+
const cookieName = this.#getCookieName(storeName);
|
|
108
|
+
// Delete cookie by setting max-age to 0
|
|
109
|
+
this.#setCookie(cookieName, '', { maxAge: 0 });
|
|
110
|
+
const event = { storeName, value: undefined };
|
|
111
|
+
this.#changes$.next(event);
|
|
112
|
+
this.#notifyLinkedInstances(event);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Convert store name to cookie name by prefixing with app name.
|
|
116
|
+
* Sanitizes to only allow alphanumeric, underscore, and hyphen.
|
|
117
|
+
*/
|
|
118
|
+
#getCookieName(storeName) {
|
|
119
|
+
return `${this.appName}_${storeName}`.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Parse document.cookie string into key-value object.
|
|
123
|
+
* Handles decoding of cookie values.
|
|
124
|
+
*/
|
|
125
|
+
#parseCookies() {
|
|
126
|
+
if (!document.cookie) {
|
|
127
|
+
return {};
|
|
128
|
+
}
|
|
129
|
+
return Object.fromEntries(document.cookie
|
|
130
|
+
.split('; ')
|
|
131
|
+
.filter(Boolean)
|
|
132
|
+
.map((cookie) => {
|
|
133
|
+
const separatorIndex = cookie.indexOf('=');
|
|
134
|
+
if (separatorIndex === -1) {
|
|
135
|
+
return [cookie, ''];
|
|
136
|
+
}
|
|
137
|
+
const name = cookie.slice(0, separatorIndex);
|
|
138
|
+
const value = cookie.slice(separatorIndex + 1);
|
|
139
|
+
try {
|
|
140
|
+
return [name, decodeURIComponent(value)];
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
return [name, value]; // Return raw value if decode fails
|
|
144
|
+
}
|
|
145
|
+
}));
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Get all cookies that belong to this app (matching appName prefix).
|
|
149
|
+
* Returns object with storeName -> encoded value.
|
|
150
|
+
*/
|
|
151
|
+
#getAppCookies() {
|
|
152
|
+
const allCookies = this.#parseCookies();
|
|
153
|
+
const prefix = `${this.appName}_`;
|
|
154
|
+
const appCookies = {};
|
|
155
|
+
for (const [cookieName, value] of Object.entries(allCookies)) {
|
|
156
|
+
if (cookieName.startsWith(prefix)) {
|
|
157
|
+
const storeName = cookieName.slice(prefix.length);
|
|
158
|
+
appCookies[storeName] = value;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return appCookies;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Build and set a cookie with the instance's configured options.
|
|
165
|
+
* Pass options parameter to override specific settings (e.g., maxAge: 0 to delete).
|
|
166
|
+
*/
|
|
167
|
+
#setCookie(name, value, overrides = {}) {
|
|
168
|
+
const opts = { ...this.options, ...overrides };
|
|
169
|
+
let cookie = `${name}=${encodeURIComponent(value)}`;
|
|
170
|
+
if (opts.path !== undefined)
|
|
171
|
+
cookie += `; path=${opts.path}`;
|
|
172
|
+
if (opts.domain)
|
|
173
|
+
cookie += `; domain=${opts.domain}`;
|
|
174
|
+
if (opts.maxAge !== undefined)
|
|
175
|
+
cookie += `; max-age=${opts.maxAge}`;
|
|
176
|
+
if (opts.expires)
|
|
177
|
+
cookie += `; expires=${opts.expires.toUTCString()}`;
|
|
178
|
+
if (opts.secure)
|
|
179
|
+
cookie += '; secure';
|
|
180
|
+
if (opts.sameSite)
|
|
181
|
+
cookie += `; samesite=${opts.sameSite}`;
|
|
182
|
+
document.cookie = cookie;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Validate that a cookie string doesn't exceed size limits.
|
|
186
|
+
* Throws an error if the cookie is too large.
|
|
187
|
+
*/
|
|
188
|
+
#validateSize(cookieString) {
|
|
189
|
+
if (cookieString.length > _a.#MAX_COOKIE_SIZE) {
|
|
190
|
+
throw new Error(`Cookie size (${cookieString.length} bytes) exceeds ${_a.#MAX_COOKIE_SIZE} byte limit. ` +
|
|
191
|
+
`Consider using localStorage for larger data or splitting across multiple stores.`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Notify all other linked storage instances about a change.
|
|
196
|
+
* This instance will not be notified (to prevent infinite loops).
|
|
197
|
+
*/
|
|
198
|
+
#notifyLinkedInstances(event) {
|
|
199
|
+
if (!this.#linker)
|
|
200
|
+
return;
|
|
201
|
+
const linkedInstances = _a.#LINKERS.get(this.#linker);
|
|
202
|
+
if (!linkedInstances)
|
|
203
|
+
return;
|
|
204
|
+
for (const instance of linkedInstances) {
|
|
205
|
+
if (instance !== this) {
|
|
206
|
+
instance.#changes$.next(event);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
exports.ReactiveCookieStorage = ReactiveCookieStorage;
|
|
212
|
+
_a = ReactiveCookieStorage;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { ReactiveStorage } from './reactive-storage';
|
|
2
|
+
/**
|
|
3
|
+
* Options for configuring cookie behavior in ReactiveCookieStorage.
|
|
4
|
+
*/
|
|
5
|
+
export interface ReactiveCookieStorageOptions {
|
|
6
|
+
/** URL path where the cookie is valid. Default: '/' */
|
|
7
|
+
path?: string;
|
|
8
|
+
/** Domain where the cookie is valid. Default: current domain */
|
|
9
|
+
domain?: string;
|
|
10
|
+
/** Cookie lifetime in seconds. Default: undefined (session cookie) */
|
|
11
|
+
maxAge?: number;
|
|
12
|
+
/** Absolute expiration date. Default: undefined */
|
|
13
|
+
expires?: Date;
|
|
14
|
+
/** HTTPS only flag. Default: false */
|
|
15
|
+
secure?: boolean;
|
|
16
|
+
/** CSRF protection level. Default: 'lax' */
|
|
17
|
+
sameSite?: 'strict' | 'lax' | 'none';
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Reactive wrapper for browser cookies.
|
|
21
|
+
* Provides RxJS-based reactive API for cookie storage with automatic change detection.
|
|
22
|
+
*
|
|
23
|
+
* **Important Limitations:**
|
|
24
|
+
* - Cookies have a ~4KB size limit per cookie
|
|
25
|
+
* - No native change events - use linker to sync multiple instances
|
|
26
|
+
* - Cannot access httpOnly cookies set by the server
|
|
27
|
+
*
|
|
28
|
+
* **Cross-Instance Synchronization:**
|
|
29
|
+
* Link multiple instances using any shared value (symbol, string, object, etc.) to automatically sync changes between them.
|
|
30
|
+
*
|
|
31
|
+
* @template S - Storage store name type
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```typescript
|
|
35
|
+
* // Single instance
|
|
36
|
+
* const storage = new ReactiveCookieStorage('my-app', {
|
|
37
|
+
* path: '/',
|
|
38
|
+
* maxAge: 86400,
|
|
39
|
+
* secure: true,
|
|
40
|
+
* sameSite: 'strict'
|
|
41
|
+
* });
|
|
42
|
+
*
|
|
43
|
+
* // Multiple linked instances using a symbol
|
|
44
|
+
* const linker = Symbol('cookie-sync');
|
|
45
|
+
* const storageOne = new ReactiveCookieStorage('my-app', { secure: true }, linker);
|
|
46
|
+
* const storageTwo = new ReactiveCookieStorage('my-app', { secure: false }, linker);
|
|
47
|
+
* // Changes in storageOne will notify storageTwo and vice versa
|
|
48
|
+
*
|
|
49
|
+
* // Or use any other value type
|
|
50
|
+
* const storageA = new ReactiveCookieStorage('my-app', { secure: true }, 'my-linker');
|
|
51
|
+
* const storageB = new ReactiveCookieStorage('my-app', { secure: false }, 'my-linker');
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export declare class ReactiveCookieStorage<S extends string = string> extends ReactiveStorage<S> {
|
|
55
|
+
#private;
|
|
56
|
+
readonly appName: string;
|
|
57
|
+
private readonly options;
|
|
58
|
+
constructor(appName?: string, options?: ReactiveCookieStorageOptions, linker?: any);
|
|
59
|
+
/**
|
|
60
|
+
* Destroy the storage instance and cleanup resources.
|
|
61
|
+
* Unregisters from linker group and completes the changes subject.
|
|
62
|
+
* Call this when you're done using the storage to prevent memory leaks.
|
|
63
|
+
*/
|
|
64
|
+
destroy(): void;
|
|
65
|
+
protected [ReactiveStorage.Props.GET_ALL](): Promise<any>;
|
|
66
|
+
protected [ReactiveStorage.Props.CHANGES]: any;
|
|
67
|
+
protected [ReactiveStorage.Props.SET](storeName: S, value: unknown): Promise<void>;
|
|
68
|
+
protected [ReactiveStorage.Props.REMOVE](storeName: S): Promise<void>;
|
|
69
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
var _a;
|
|
2
|
+
import { Subject } from 'rxjs';
|
|
3
|
+
import { ReactiveStorage } from './reactive-storage';
|
|
4
|
+
import { toAsyncIterator } from './async-iterator.polyfill';
|
|
5
|
+
import { jsonParse } from './json-parse';
|
|
6
|
+
/**
|
|
7
|
+
* Reactive wrapper for browser cookies.
|
|
8
|
+
* Provides RxJS-based reactive API for cookie storage with automatic change detection.
|
|
9
|
+
*
|
|
10
|
+
* **Important Limitations:**
|
|
11
|
+
* - Cookies have a ~4KB size limit per cookie
|
|
12
|
+
* - No native change events - use linker to sync multiple instances
|
|
13
|
+
* - Cannot access httpOnly cookies set by the server
|
|
14
|
+
*
|
|
15
|
+
* **Cross-Instance Synchronization:**
|
|
16
|
+
* Link multiple instances using any shared value (symbol, string, object, etc.) to automatically sync changes between them.
|
|
17
|
+
*
|
|
18
|
+
* @template S - Storage store name type
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```typescript
|
|
22
|
+
* // Single instance
|
|
23
|
+
* const storage = new ReactiveCookieStorage('my-app', {
|
|
24
|
+
* path: '/',
|
|
25
|
+
* maxAge: 86400,
|
|
26
|
+
* secure: true,
|
|
27
|
+
* sameSite: 'strict'
|
|
28
|
+
* });
|
|
29
|
+
*
|
|
30
|
+
* // Multiple linked instances using a symbol
|
|
31
|
+
* const linker = Symbol('cookie-sync');
|
|
32
|
+
* const storageOne = new ReactiveCookieStorage('my-app', { secure: true }, linker);
|
|
33
|
+
* const storageTwo = new ReactiveCookieStorage('my-app', { secure: false }, linker);
|
|
34
|
+
* // Changes in storageOne will notify storageTwo and vice versa
|
|
35
|
+
*
|
|
36
|
+
* // Or use any other value type
|
|
37
|
+
* const storageA = new ReactiveCookieStorage('my-app', { secure: true }, 'my-linker');
|
|
38
|
+
* const storageB = new ReactiveCookieStorage('my-app', { secure: false }, 'my-linker');
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
export class ReactiveCookieStorage extends ReactiveStorage {
|
|
42
|
+
appName;
|
|
43
|
+
options;
|
|
44
|
+
static #MAX_COOKIE_SIZE = 4000; // Conservative 4KB limit
|
|
45
|
+
static #LINKERS = new Map();
|
|
46
|
+
/**
|
|
47
|
+
* Safely parse JSON with error handling.
|
|
48
|
+
* Returns undefined if parsing fails.
|
|
49
|
+
*/
|
|
50
|
+
static #parse(value) {
|
|
51
|
+
return jsonParse(value);
|
|
52
|
+
}
|
|
53
|
+
#changes$ = new Subject();
|
|
54
|
+
#linker;
|
|
55
|
+
constructor(appName = 'app', options = {}, linker) {
|
|
56
|
+
super();
|
|
57
|
+
this.appName = appName;
|
|
58
|
+
this.options = options;
|
|
59
|
+
// Register to linker group if provided
|
|
60
|
+
if (linker) {
|
|
61
|
+
this.#linker = linker;
|
|
62
|
+
if (!_a.#LINKERS.has(linker)) {
|
|
63
|
+
_a.#LINKERS.set(linker, new Set());
|
|
64
|
+
}
|
|
65
|
+
_a.#LINKERS.get(linker).add(this);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Destroy the storage instance and cleanup resources.
|
|
70
|
+
* Unregisters from linker group and completes the changes subject.
|
|
71
|
+
* Call this when you're done using the storage to prevent memory leaks.
|
|
72
|
+
*/
|
|
73
|
+
destroy() {
|
|
74
|
+
// Unregister from linker group
|
|
75
|
+
if (this.#linker) {
|
|
76
|
+
const linkedInstances = _a.#LINKERS.get(this.#linker);
|
|
77
|
+
if (linkedInstances) {
|
|
78
|
+
linkedInstances.delete(this);
|
|
79
|
+
if (linkedInstances.size === 0) {
|
|
80
|
+
_a.#LINKERS.delete(this.#linker);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
this.#changes$.complete();
|
|
85
|
+
}
|
|
86
|
+
async [ReactiveStorage.Props.GET_ALL]() {
|
|
87
|
+
const cookies = this.#getAppCookies();
|
|
88
|
+
return Object.fromEntries(Object.entries(cookies).map(([storeName, value]) => [storeName, _a.#parse(value)]));
|
|
89
|
+
}
|
|
90
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
91
|
+
[ReactiveStorage.Props.CHANGES] = this.#changes$[Symbol.asyncIterator] ?? toAsyncIterator(this.#changes$);
|
|
92
|
+
async [ReactiveStorage.Props.SET](storeName, value) {
|
|
93
|
+
const serialized = JSON.stringify(value);
|
|
94
|
+
const cookieName = this.#getCookieName(storeName);
|
|
95
|
+
// Validate size before setting
|
|
96
|
+
const cookieString = `${cookieName}=${encodeURIComponent(serialized)}`;
|
|
97
|
+
this.#validateSize(cookieString);
|
|
98
|
+
this.#setCookie(cookieName, serialized); // Uses instance options
|
|
99
|
+
const event = { storeName, value };
|
|
100
|
+
this.#changes$.next(event);
|
|
101
|
+
this.#notifyLinkedInstances(event);
|
|
102
|
+
}
|
|
103
|
+
async [ReactiveStorage.Props.REMOVE](storeName) {
|
|
104
|
+
const cookieName = this.#getCookieName(storeName);
|
|
105
|
+
// Delete cookie by setting max-age to 0
|
|
106
|
+
this.#setCookie(cookieName, '', { maxAge: 0 });
|
|
107
|
+
const event = { storeName, value: undefined };
|
|
108
|
+
this.#changes$.next(event);
|
|
109
|
+
this.#notifyLinkedInstances(event);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Convert store name to cookie name by prefixing with app name.
|
|
113
|
+
* Sanitizes to only allow alphanumeric, underscore, and hyphen.
|
|
114
|
+
*/
|
|
115
|
+
#getCookieName(storeName) {
|
|
116
|
+
return `${this.appName}_${storeName}`.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Parse document.cookie string into key-value object.
|
|
120
|
+
* Handles decoding of cookie values.
|
|
121
|
+
*/
|
|
122
|
+
#parseCookies() {
|
|
123
|
+
if (!document.cookie) {
|
|
124
|
+
return {};
|
|
125
|
+
}
|
|
126
|
+
return Object.fromEntries(document.cookie
|
|
127
|
+
.split('; ')
|
|
128
|
+
.filter(Boolean)
|
|
129
|
+
.map((cookie) => {
|
|
130
|
+
const separatorIndex = cookie.indexOf('=');
|
|
131
|
+
if (separatorIndex === -1) {
|
|
132
|
+
return [cookie, ''];
|
|
133
|
+
}
|
|
134
|
+
const name = cookie.slice(0, separatorIndex);
|
|
135
|
+
const value = cookie.slice(separatorIndex + 1);
|
|
136
|
+
try {
|
|
137
|
+
return [name, decodeURIComponent(value)];
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return [name, value]; // Return raw value if decode fails
|
|
141
|
+
}
|
|
142
|
+
}));
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Get all cookies that belong to this app (matching appName prefix).
|
|
146
|
+
* Returns object with storeName -> encoded value.
|
|
147
|
+
*/
|
|
148
|
+
#getAppCookies() {
|
|
149
|
+
const allCookies = this.#parseCookies();
|
|
150
|
+
const prefix = `${this.appName}_`;
|
|
151
|
+
const appCookies = {};
|
|
152
|
+
for (const [cookieName, value] of Object.entries(allCookies)) {
|
|
153
|
+
if (cookieName.startsWith(prefix)) {
|
|
154
|
+
const storeName = cookieName.slice(prefix.length);
|
|
155
|
+
appCookies[storeName] = value;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return appCookies;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Build and set a cookie with the instance's configured options.
|
|
162
|
+
* Pass options parameter to override specific settings (e.g., maxAge: 0 to delete).
|
|
163
|
+
*/
|
|
164
|
+
#setCookie(name, value, overrides = {}) {
|
|
165
|
+
const opts = { ...this.options, ...overrides };
|
|
166
|
+
let cookie = `${name}=${encodeURIComponent(value)}`;
|
|
167
|
+
if (opts.path !== undefined)
|
|
168
|
+
cookie += `; path=${opts.path}`;
|
|
169
|
+
if (opts.domain)
|
|
170
|
+
cookie += `; domain=${opts.domain}`;
|
|
171
|
+
if (opts.maxAge !== undefined)
|
|
172
|
+
cookie += `; max-age=${opts.maxAge}`;
|
|
173
|
+
if (opts.expires)
|
|
174
|
+
cookie += `; expires=${opts.expires.toUTCString()}`;
|
|
175
|
+
if (opts.secure)
|
|
176
|
+
cookie += '; secure';
|
|
177
|
+
if (opts.sameSite)
|
|
178
|
+
cookie += `; samesite=${opts.sameSite}`;
|
|
179
|
+
document.cookie = cookie;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Validate that a cookie string doesn't exceed size limits.
|
|
183
|
+
* Throws an error if the cookie is too large.
|
|
184
|
+
*/
|
|
185
|
+
#validateSize(cookieString) {
|
|
186
|
+
if (cookieString.length > _a.#MAX_COOKIE_SIZE) {
|
|
187
|
+
throw new Error(`Cookie size (${cookieString.length} bytes) exceeds ${_a.#MAX_COOKIE_SIZE} byte limit. ` +
|
|
188
|
+
`Consider using localStorage for larger data or splitting across multiple stores.`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Notify all other linked storage instances about a change.
|
|
193
|
+
* This instance will not be notified (to prevent infinite loops).
|
|
194
|
+
*/
|
|
195
|
+
#notifyLinkedInstances(event) {
|
|
196
|
+
if (!this.#linker)
|
|
197
|
+
return;
|
|
198
|
+
const linkedInstances = _a.#LINKERS.get(this.#linker);
|
|
199
|
+
if (!linkedInstances)
|
|
200
|
+
return;
|
|
201
|
+
for (const instance of linkedInstances) {
|
|
202
|
+
if (instance !== this) {
|
|
203
|
+
instance.#changes$.next(event);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
_a = ReactiveCookieStorage;
|
|
209
|
+
|
|
210
|
+
//# sourceMappingURL=reactive-cookie-storage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../libs/reactive-storage/src/reactive-cookie-storage.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,OAAO,EAAE,eAAe,EAA8B,MAAM,oBAAoB,CAAC;AACjF,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAoBzC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,OAAO,qBAAiD,SAAQ,eAAkB;IAgBpE;IACC;IAhBnB,MAAM,CAAU,gBAAgB,GAAG,IAAI,CAAC,CAAC,yBAAyB;IAClE,MAAM,CAAU,QAAQ,GAAG,IAAI,GAAG,EAAwC,CAAC;IAE3E;;;OAGG;IACH,MAAM,CAAC,MAAM,CAAC,KAAa;QACzB,OAAO,SAAS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,IAAI,cAAc,IAAI,CAAC,QAAQ,EAAE,CAAC;QAE3D,QAAQ,CAAC,MAAM,GAAG,MAAM,CAAC;IAC3B,CAAC;IAED;;;OAGG;IACH,aAAa,CAAC,YAAoB;QAChC,IAAI,YAAY,CAAC,MAAM,GAAG,EAAqB,CAAC,gBAAgB,EAAE,CAAC;YACjE,MAAM,IAAI,KAAK,CACb,gBAAgB,YAAY,CAAC,MAAM,mBAAmB,EAAqB,CAAC,gBAAgB,eAAe;gBACzG,kFAAkF,CACrF,CAAC;QACJ,CAAC;IACH,CAAC;IAED;;;OAGG;IACH,sBAAsB,CAAC,KAAoC;QACzD,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO;QAE1B,MAAM,eAAe,GAAG,EAAqB,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACzE,IAAI,CAAC,eAAe;YAAE,OAAO;QAE7B,KAAK,MAAM,QAAQ,IAAI,eAAe,EAAE,CAAC;YACvC,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;gBACtB,QAAQ,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACjC,CAAC;QACH,CAAC;IACH,CAAC","file":"reactive-cookie-storage.js","sourcesContent":["import { Subject } from 'rxjs';\r\n\r\nimport { ReactiveStorage, ReactiveStorageChangeEvent } from './reactive-storage';\r\nimport { toAsyncIterator } from './async-iterator.polyfill';\r\nimport { jsonParse } from './json-parse';\r\n\r\n/**\r\n * Options for configuring cookie behavior in ReactiveCookieStorage.\r\n */\r\nexport interface ReactiveCookieStorageOptions {\r\n /** URL path where the cookie is valid. Default: '/' */\r\n path?: string;\r\n /** Domain where the cookie is valid. Default: current domain */\r\n domain?: string;\r\n /** Cookie lifetime in seconds. Default: undefined (session cookie) */\r\n maxAge?: number;\r\n /** Absolute expiration date. Default: undefined */\r\n expires?: Date;\r\n /** HTTPS only flag. Default: false */\r\n secure?: boolean;\r\n /** CSRF protection level. Default: 'lax' */\r\n sameSite?: 'strict' | 'lax' | 'none';\r\n}\r\n\r\n/**\r\n * Reactive wrapper for browser cookies.\r\n * Provides RxJS-based reactive API for cookie storage with automatic change detection.\r\n *\r\n * **Important Limitations:**\r\n * - Cookies have a ~4KB size limit per cookie\r\n * - No native change events - use linker to sync multiple instances\r\n * - Cannot access httpOnly cookies set by the server\r\n *\r\n * **Cross-Instance Synchronization:**\r\n * Link multiple instances using any shared value (symbol, string, object, etc.) to automatically sync changes between them.\r\n *\r\n * @template S - Storage store name type\r\n *\r\n * @example\r\n * ```typescript\r\n * // Single instance\r\n * const storage = new ReactiveCookieStorage('my-app', {\r\n * path: '/',\r\n * maxAge: 86400,\r\n * secure: true,\r\n * sameSite: 'strict'\r\n * });\r\n *\r\n * // Multiple linked instances using a symbol\r\n * const linker = Symbol('cookie-sync');\r\n * const storageOne = new ReactiveCookieStorage('my-app', { secure: true }, linker);\r\n * const storageTwo = new ReactiveCookieStorage('my-app', { secure: false }, linker);\r\n * // Changes in storageOne will notify storageTwo and vice versa\r\n *\r\n * // Or use any other value type\r\n * const storageA = new ReactiveCookieStorage('my-app', { secure: true }, 'my-linker');\r\n * const storageB = new ReactiveCookieStorage('my-app', { secure: false }, 'my-linker');\r\n * ```\r\n */\r\nexport class ReactiveCookieStorage<S extends string = string> extends ReactiveStorage<S> {\r\n static readonly #MAX_COOKIE_SIZE = 4000; // Conservative 4KB limit\r\n static readonly #LINKERS = new Map<any, Set<ReactiveCookieStorage<any>>>();\r\n\r\n /**\r\n * Safely parse JSON with error handling.\r\n * Returns undefined if parsing fails.\r\n */\r\n static #parse(value: string): any {\r\n return jsonParse(value);\r\n }\r\n\r\n readonly #changes$ = new Subject<ReactiveStorageChangeEvent<S>>();\r\n readonly #linker?: any;\r\n\r\n constructor(\r\n public readonly appName: string = 'app',\r\n private readonly options: ReactiveCookieStorageOptions = {},\r\n linker?: any\r\n ) {\r\n super();\r\n\r\n // Register to linker group if provided\r\n if (linker) {\r\n this.#linker = linker;\r\n if (!ReactiveCookieStorage.#LINKERS.has(linker)) {\r\n ReactiveCookieStorage.#LINKERS.set(linker, new Set());\r\n }\r\n ReactiveCookieStorage.#LINKERS.get(linker)!.add(this);\r\n }\r\n }\r\n\r\n /**\r\n * Destroy the storage instance and cleanup resources.\r\n * Unregisters from linker group and completes the changes subject.\r\n * Call this when you're done using the storage to prevent memory leaks.\r\n */\r\n destroy(): void {\r\n // Unregister from linker group\r\n if (this.#linker) {\r\n const linkedInstances = ReactiveCookieStorage.#LINKERS.get(this.#linker);\r\n if (linkedInstances) {\r\n linkedInstances.delete(this);\r\n if (linkedInstances.size === 0) {\r\n ReactiveCookieStorage.#LINKERS.delete(this.#linker);\r\n }\r\n }\r\n }\r\n\r\n this.#changes$.complete();\r\n }\r\n\r\n protected async [ReactiveStorage.Props.GET_ALL](): Promise<any> {\r\n const cookies = this.#getAppCookies();\r\n\r\n return Object.fromEntries(\r\n Object.entries(cookies).map(([storeName, value]) => [storeName, ReactiveCookieStorage.#parse(value)])\r\n );\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n protected [ReactiveStorage.Props.CHANGES] = (this.#changes$ as any)[Symbol.asyncIterator] ?? toAsyncIterator(this.#changes$);\r\n\r\n protected async [ReactiveStorage.Props.SET](storeName: S, value: unknown): Promise<void> {\r\n const serialized = JSON.stringify(value);\r\n const cookieName = this.#getCookieName(storeName);\r\n\r\n // Validate size before setting\r\n const cookieString = `${cookieName}=${encodeURIComponent(serialized)}`;\r\n this.#validateSize(cookieString);\r\n\r\n this.#setCookie(cookieName, serialized); // Uses instance options\r\n\r\n const event = { storeName, value };\r\n this.#changes$.next(event);\r\n this.#notifyLinkedInstances(event);\r\n }\r\n\r\n protected async [ReactiveStorage.Props.REMOVE](storeName: S): Promise<void> {\r\n const cookieName = this.#getCookieName(storeName);\r\n\r\n // Delete cookie by setting max-age to 0\r\n this.#setCookie(cookieName, '', { maxAge: 0 });\r\n\r\n const event = { storeName, value: undefined };\r\n this.#changes$.next(event);\r\n this.#notifyLinkedInstances(event);\r\n }\r\n\r\n /**\r\n * Convert store name to cookie name by prefixing with app name.\r\n * Sanitizes to only allow alphanumeric, underscore, and hyphen.\r\n */\r\n #getCookieName(storeName: S): string {\r\n return `${this.appName}_${storeName}`.replace(/[^a-zA-Z0-9_-]/g, '_');\r\n }\r\n\r\n /**\r\n * Parse document.cookie string into key-value object.\r\n * Handles decoding of cookie values.\r\n */\r\n #parseCookies(): Record<string, string> {\r\n if (!document.cookie) {\r\n return {};\r\n }\r\n\r\n return Object.fromEntries(\r\n document.cookie\r\n .split('; ')\r\n .filter(Boolean)\r\n .map((cookie) => {\r\n const separatorIndex = cookie.indexOf('=');\r\n if (separatorIndex === -1) {\r\n return [cookie, ''];\r\n }\r\n const name = cookie.slice(0, separatorIndex);\r\n const value = cookie.slice(separatorIndex + 1);\r\n try {\r\n return [name, decodeURIComponent(value)];\r\n } catch {\r\n return [name, value]; // Return raw value if decode fails\r\n }\r\n })\r\n );\r\n }\r\n\r\n /**\r\n * Get all cookies that belong to this app (matching appName prefix).\r\n * Returns object with storeName -> encoded value.\r\n */\r\n #getAppCookies(): Record<string, string> {\r\n const allCookies = this.#parseCookies();\r\n const prefix = `${this.appName}_`;\r\n const appCookies: Record<string, string> = {};\r\n\r\n for (const [cookieName, value] of Object.entries(allCookies)) {\r\n if (cookieName.startsWith(prefix)) {\r\n const storeName = cookieName.slice(prefix.length);\r\n appCookies[storeName] = value;\r\n }\r\n }\r\n\r\n return appCookies;\r\n }\r\n\r\n /**\r\n * Build and set a cookie with the instance's configured options.\r\n * Pass options parameter to override specific settings (e.g., maxAge: 0 to delete).\r\n */\r\n #setCookie(name: string, value: string, overrides: Partial<ReactiveCookieStorageOptions> = {}): void {\r\n const opts = { ...this.options, ...overrides };\r\n let cookie = `${name}=${encodeURIComponent(value)}`;\r\n\r\n if (opts.path !== undefined) cookie += `; path=${opts.path}`;\r\n if (opts.domain) cookie += `; domain=${opts.domain}`;\r\n if (opts.maxAge !== undefined) cookie += `; max-age=${opts.maxAge}`;\r\n if (opts.expires) cookie += `; expires=${opts.expires.toUTCString()}`;\r\n if (opts.secure) cookie += '; secure';\r\n if (opts.sameSite) cookie += `; samesite=${opts.sameSite}`;\r\n\r\n document.cookie = cookie;\r\n }\r\n\r\n /**\r\n * Validate that a cookie string doesn't exceed size limits.\r\n * Throws an error if the cookie is too large.\r\n */\r\n #validateSize(cookieString: string): void {\r\n if (cookieString.length > ReactiveCookieStorage.#MAX_COOKIE_SIZE) {\r\n throw new Error(\r\n `Cookie size (${cookieString.length} bytes) exceeds ${ReactiveCookieStorage.#MAX_COOKIE_SIZE} byte limit. ` +\r\n `Consider using localStorage for larger data or splitting across multiple stores.`\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Notify all other linked storage instances about a change.\r\n * This instance will not be notified (to prevent infinite loops).\r\n */\r\n #notifyLinkedInstances(event: ReactiveStorageChangeEvent<S>): void {\r\n if (!this.#linker) return;\r\n\r\n const linkedInstances = ReactiveCookieStorage.#LINKERS.get(this.#linker);\r\n if (!linkedInstances) return;\r\n\r\n for (const instance of linkedInstances) {\r\n if (instance !== this) {\r\n instance.#changes$.next(event);\r\n }\r\n }\r\n }\r\n}\r\n"]}
|
package/reactive-web-storage.cjs
CHANGED
|
@@ -5,6 +5,7 @@ const rxjs_1 = require("rxjs");
|
|
|
5
5
|
const reactive_storage_1 = require("./reactive-storage");
|
|
6
6
|
const regex_parser_1 = require("./regex-parser");
|
|
7
7
|
const async_iterator_polyfill_1 = require("./async-iterator.polyfill");
|
|
8
|
+
const json_parse_1 = require("./json-parse");
|
|
8
9
|
/**
|
|
9
10
|
* Abstract implementation of ReactiveStorage for browser Web Storage API.
|
|
10
11
|
* Stores data as JSON in localStorage or sessionStorage with app namespacing.
|
|
@@ -13,13 +14,8 @@ const async_iterator_polyfill_1 = require("./async-iterator.polyfill");
|
|
|
13
14
|
*/
|
|
14
15
|
class AbstractReactiveWebStorage extends reactive_storage_1.ReactiveStorage {
|
|
15
16
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
16
|
-
static
|
|
17
|
-
|
|
18
|
-
return JSON.parse(string);
|
|
19
|
-
}
|
|
20
|
-
catch {
|
|
21
|
-
return undefined;
|
|
22
|
-
}
|
|
17
|
+
static #parse(string) {
|
|
18
|
+
return (0, json_parse_1.jsonParse)(string);
|
|
23
19
|
}
|
|
24
20
|
get #keyNameRegex() {
|
|
25
21
|
return (0, regex_parser_1.RegexParser)(`^${this.appName}\\/\\w+$`);
|
|
@@ -29,7 +25,7 @@ class AbstractReactiveWebStorage extends reactive_storage_1.ReactiveStorage {
|
|
|
29
25
|
const keys = Object.keys(this.storage).filter(key => this.#keyNameRegex.test(key));
|
|
30
26
|
return Object.fromEntries(keys.map(key => [
|
|
31
27
|
key.split('/')[1],
|
|
32
|
-
AbstractReactiveWebStorage
|
|
28
|
+
AbstractReactiveWebStorage.#parse(this.storage.getItem(key))
|
|
33
29
|
]));
|
|
34
30
|
}
|
|
35
31
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
@@ -7,7 +7,6 @@ import { ReactiveStorage } from "./reactive-storage";
|
|
|
7
7
|
*/
|
|
8
8
|
export declare abstract class AbstractReactiveWebStorage<S extends string = string> extends ReactiveStorage<S> {
|
|
9
9
|
#private;
|
|
10
|
-
static JsonParse(string: string): any;
|
|
11
10
|
protected abstract readonly appName: string;
|
|
12
11
|
abstract readonly storage: Storage;
|
|
13
12
|
protected [ReactiveStorage.Props.GET_ALL](): Promise<{
|
package/reactive-web-storage.js
CHANGED
|
@@ -2,6 +2,7 @@ import { Subject } from 'rxjs';
|
|
|
2
2
|
import { ReactiveStorage } from "./reactive-storage";
|
|
3
3
|
import { RegexParser } from './regex-parser';
|
|
4
4
|
import { toAsyncIterator } from './async-iterator.polyfill';
|
|
5
|
+
import { jsonParse } from './json-parse';
|
|
5
6
|
/**
|
|
6
7
|
* Abstract implementation of ReactiveStorage for browser Web Storage API.
|
|
7
8
|
* Stores data as JSON in localStorage or sessionStorage with app namespacing.
|
|
@@ -10,13 +11,8 @@ import { toAsyncIterator } from './async-iterator.polyfill';
|
|
|
10
11
|
*/
|
|
11
12
|
export class AbstractReactiveWebStorage extends ReactiveStorage {
|
|
12
13
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
13
|
-
static
|
|
14
|
-
|
|
15
|
-
return JSON.parse(string);
|
|
16
|
-
}
|
|
17
|
-
catch {
|
|
18
|
-
return undefined;
|
|
19
|
-
}
|
|
14
|
+
static #parse(string) {
|
|
15
|
+
return jsonParse(string);
|
|
20
16
|
}
|
|
21
17
|
get #keyNameRegex() {
|
|
22
18
|
return RegexParser(`^${this.appName}\\/\\w+$`);
|
|
@@ -26,7 +22,7 @@ export class AbstractReactiveWebStorage extends ReactiveStorage {
|
|
|
26
22
|
const keys = Object.keys(this.storage).filter(key => this.#keyNameRegex.test(key));
|
|
27
23
|
return Object.fromEntries(keys.map(key => [
|
|
28
24
|
key.split('/')[1],
|
|
29
|
-
AbstractReactiveWebStorage
|
|
25
|
+
AbstractReactiveWebStorage.#parse(this.storage.getItem(key))
|
|
30
26
|
]));
|
|
31
27
|
}
|
|
32
28
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../libs/reactive-storage/src/reactive-web-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,OAAO,EAAE,eAAe,EAA8B,MAAM,oBAAoB,CAAC;AACjF,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;
|
|
1
|
+
{"version":3,"sources":["../../../../../libs/reactive-storage/src/reactive-web-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,OAAO,EAAE,eAAe,EAA8B,MAA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E,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,OAAO,IAAI,SAAS,EAAE,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;QAC5E,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAC;IAC7C,CAAC;IAEU,KAAK,CAAC,CAAC,eAAe,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,SAAY;QACzD,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,OAAO,IAAI,SAAS,EAAE,CAAC,CAAC;QACxD,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;IACvD,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,OAAO,kBAA8C,SAAQ,0BAA6B;IAE1E;IACA;IAFpB,YACoB,OAAgB,EAChB,UAAU,KAAK;QAEjC,KAAK,EAAE,CAAC;QAHU,YAAO,GAAP,OAAO,CAAS;QAChB,YAAO,GAAP,OAAO,CAAQ;IAGnC,CAAC;CACF","file":"reactive-web-storage.js","sourcesContent":["import { Subject } from 'rxjs';\n\nimport { ReactiveStorage, ReactiveStorageChangeEvent } from \"./reactive-storage\";\nimport { RegexParser } from './regex-parser';\nimport { toAsyncIterator } from './async-iterator.polyfill';\nimport { jsonParse } from './json-parse';\n\n/**\n * Abstract implementation of ReactiveStorage for browser Web Storage API.\n * Stores data as JSON in localStorage or sessionStorage with app namespacing.\n *\n * @template S - Storage store name type\n */\nexport abstract class AbstractReactiveWebStorage<S extends string = string> extends ReactiveStorage<S> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static #parse(string: string): any {\n return jsonParse(string);\n }\n\n protected abstract readonly appName: string;\n abstract readonly storage: Storage;\n\n get #keyNameRegex() {\n return RegexParser(`^${this.appName}\\\\/\\\\w+$`);\n }\n\n #changes$ = new Subject<ReactiveStorageChangeEvent<S>>();\n\n\tprotected async [ReactiveStorage.Props.GET_ALL]() {\n\t\tconst keys = Object.keys(this.storage).filter(key => this.#keyNameRegex.test(key));\n\n return Object.fromEntries(keys.map(key => [\n key.split('/')[1],\n AbstractReactiveWebStorage.#parse(this.storage.getItem(key)!)\n ]));\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprotected [ReactiveStorage.Props.CHANGES] = (this.#changes$ as any)[Symbol.asyncIterator] ?? toAsyncIterator(this.#changes$);\n\n\tprotected async [ReactiveStorage.Props.SET](storeName: S, value: unknown) {\n this.storage.setItem(`${this.appName}/${storeName}`, JSON.stringify(value));\n this.#changes$.next({ storeName, value });\n\t}\n\n protected async [ReactiveStorage.Props.REMOVE](storeName: S) {\n this.storage.removeItem(`${this.appName}/${storeName}`);\n this.#changes$.next({ storeName, value: undefined });\n }\n}\n\n/**\n * Generic reactive web storage wrapper.\n * Allows using any Storage implementation (localStorage, sessionStorage, or custom).\n *\n * @template S - Storage store name type\n */\nexport class ReactiveWebStorage<S extends string = string> extends AbstractReactiveWebStorage<S> {\n constructor(\n override readonly storage: Storage,\n override readonly appName = 'app',\n ) {\n super();\n }\n}\n"]}
|