@qlover/fe-corekit 1.4.0 → 1.5.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/dist/index.d.ts CHANGED
@@ -1770,9 +1770,9 @@ declare abstract class RequestManager<Config extends RequestAdapterConfig> {
1770
1770
  * getConfig(): any {
1771
1771
  * return this.config;
1772
1772
  * }
1773
- * async request<Request, Response>(
1773
+ * async request<Response, Request>(
1774
1774
  * config: any
1775
- * ): Promise<RequestAdapterResponse<Response, Request>> {
1775
+ * ): Promise<RequestAdapterResponse<Request, Response>> {
1776
1776
  * const sendConfig = { ...this.config, ...config };
1777
1777
  * await new Promise((resolve) => setTimeout(resolve, 1000));
1778
1778
  *
@@ -1811,70 +1811,70 @@ declare class RequestScheduler<Config extends RequestAdapterConfig> extends Requ
1811
1811
  * @param config - The configuration for the request.
1812
1812
  * @returns A promise that resolves to the response of the request.
1813
1813
  */
1814
- request<Request, Response>(config: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Response, Request>>;
1814
+ request<Response, Request>(config: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Request, Response>>;
1815
1815
  /**
1816
1816
  * Executes a GET request.
1817
1817
  *
1818
1818
  * @param config - The configuration for the GET request.
1819
1819
  * @returns A promise that resolves to the response of the GET request.
1820
1820
  */
1821
- get<Request, Response>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Response, Request>>;
1821
+ get<Response, Request>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Request, Response>>;
1822
1822
  /**
1823
1823
  * Executes a POST request.
1824
1824
  *
1825
1825
  * @param config - The configuration for the POST request.
1826
1826
  * @returns A promise that resolves to the response of the POST request.
1827
1827
  */
1828
- post<Request, Response>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Response, Request>>;
1828
+ post<Response, Request>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Request, Response>>;
1829
1829
  /**
1830
1830
  * Executes a PUT request.
1831
1831
  *
1832
1832
  * @param config - The configuration for the PUT request.
1833
1833
  * @returns A promise that resolves to the response of the PUT request.
1834
1834
  */
1835
- put<Request, Response>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Response, Request>>;
1835
+ put<Response, Request>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Request, Response>>;
1836
1836
  /**
1837
1837
  * Executes a DELETE request.
1838
1838
  *
1839
1839
  * @param config - The configuration for the DELETE request.
1840
1840
  * @returns A promise that resolves to the response of the DELETE request.
1841
1841
  */
1842
- delete<Request, Response>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Response, Request>>;
1842
+ delete<Response, Request>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Request, Response>>;
1843
1843
  /**
1844
1844
  * Executes a PATCH request.
1845
1845
  *
1846
1846
  * @param config - The configuration for the PATCH request.
1847
1847
  * @returns A promise that resolves to the response of the PATCH request.
1848
1848
  */
1849
- patch<Request, Response>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Response, Request>>;
1849
+ patch<Response, Request>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Request, Response>>;
1850
1850
  /**
1851
1851
  * Executes a HEAD request.
1852
1852
  *
1853
1853
  * @param config - The configuration for the HEAD request.
1854
1854
  * @returns A promise that resolves to the response of the HEAD request.
1855
1855
  */
1856
- head<Request, Response>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Response, Request>>;
1856
+ head<Response, Request>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Request, Response>>;
1857
1857
  /**
1858
1858
  * Executes an OPTIONS request.
1859
1859
  *
1860
1860
  * @param config - The configuration for the OPTIONS request.
1861
1861
  * @returns A promise that resolves to the response of the OPTIONS request.
1862
1862
  */
1863
- options<Request, Response>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Response, Request>>;
1863
+ options<Response, Request>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Request, Response>>;
1864
1864
  /**
1865
1865
  * Executes a TRACE request.
1866
1866
  *
1867
1867
  * @param config - The configuration for the TRACE request.
1868
1868
  * @returns A promise that resolves to the response of the TRACE request.
1869
1869
  */
1870
- trace<Request, Response>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Response, Request>>;
1870
+ trace<Response, Request>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Request, Response>>;
1871
1871
  /**
1872
1872
  * Executes a CONNECT request.
1873
1873
  *
1874
1874
  * @param config - The configuration for the CONNECT request.
1875
1875
  * @returns A promise that resolves to the response of the CONNECT request.
1876
1876
  */
1877
- connect<Request, Response>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Response, Request>>;
1877
+ connect<Response, Request>(url: string, config?: RequestAdapterConfig<Request>): Promise<RequestAdapterResponse<Request, Response>>;
1878
1878
  }
1879
1879
 
1880
1880
  /**
@@ -2098,7 +2098,7 @@ declare class RequestTransaction<Config extends RequestAdapterConfig<unknown>> e
2098
2098
  * @example
2099
2099
  * ```typescript
2100
2100
  * // JSON serialization implementation
2101
- * class JSONSerializer implements Serializer {
2101
+ * class JSONSerializer implements SerializerIneterface {
2102
2102
  * serialize(data: any): string {
2103
2103
  * return JSON.stringify(data);
2104
2104
  * }
@@ -2109,7 +2109,7 @@ declare class RequestTransaction<Config extends RequestAdapterConfig<unknown>> e
2109
2109
  * }
2110
2110
  * ```
2111
2111
  */
2112
- interface Serializer<T = unknown, R = string> {
2112
+ interface SerializerIneterface<T = unknown, R = string> {
2113
2113
  /**
2114
2114
  * Serializes data into a target format
2115
2115
  * @since 1.0.10
@@ -2127,6 +2127,32 @@ interface Serializer<T = unknown, R = string> {
2127
2127
  deserialize(data: R, defaultValue?: T): T;
2128
2128
  }
2129
2129
 
2130
+ interface JSONSerializerOptions {
2131
+ /**
2132
+ * Enable pretty printing of JSON output
2133
+ * Adds automatic indentation and line breaks for better readability
2134
+ *
2135
+ * @since 1.0.10
2136
+ * @default false
2137
+ */
2138
+ pretty?: boolean;
2139
+ /**
2140
+ * Number of spaces to use for indentation when pretty printing
2141
+ * Only used when pretty is true
2142
+ *
2143
+ * @since 1.0.10
2144
+ * @default 2
2145
+ */
2146
+ indent?: number;
2147
+ /**
2148
+ * Custom replacer function for JSON.stringify
2149
+ * Allows custom transformation during serialization
2150
+ * Note: Will be wrapped to handle line endings
2151
+ *
2152
+ * @since 1.0.10
2153
+ */
2154
+ replacer?: (this: unknown, key: string, value: unknown) => unknown;
2155
+ }
2130
2156
  /**
2131
2157
  * Enhanced JSON serialization implementation that combines standard JSON API with additional features
2132
2158
  *
@@ -2148,7 +2174,7 @@ interface Serializer<T = unknown, R = string> {
2148
2174
  * 3. Configuration file parsing with error handling
2149
2175
  * 4. Cross-platform data exchange
2150
2176
  *
2151
- * @implements {Serializer<unknown, string>} - Generic serialization interface
2177
+ * @implements {SerializerIneterface<unknown, string>} - Generic serialization interface
2152
2178
  * @implements {JSON} - Standard JSON interface compatibility
2153
2179
  * @todo - If circular reference is detected, the error message is not very friendly, can use [flatted](https://www.npmjs.com/package/flatted) to improve it
2154
2180
  * @since 1.0.10
@@ -2185,39 +2211,35 @@ interface Serializer<T = unknown, R = string> {
2185
2211
  * JSON.parse('{ "name": "test" }'); // same as JSON.parse('{ "name": "test" }')
2186
2212
  * ```
2187
2213
  */
2188
- declare class JSONSerializer implements Serializer<unknown, string>, JSON {
2189
- private options;
2214
+ declare class JSONSerializer<T = unknown, Opt extends JSONSerializerOptions = JSONSerializerOptions> implements SerializerIneterface<T, string>, JSON {
2215
+ /**
2216
+ * Options for JSONSerializer
2217
+ *
2218
+ * @since 1.5.0
2219
+ * @default `{}`
2220
+ */
2221
+ protected options: Opt;
2190
2222
  /**
2191
2223
  * Implements Symbol.toStringTag to properly identify this class
2192
2224
  * Required by JSON interface
2225
+ *
2226
+ * When this object calls toString, it returns this value
2227
+ *
2228
+ * @example
2229
+ * ```typescript
2230
+ * const serializer = new JSONSerializer();
2231
+ * serializer.toString(); // returns '[object JSONSerializer]'
2232
+ * ```
2193
2233
  */
2194
2234
  readonly [Symbol.toStringTag] = "JSONSerializer";
2195
- constructor(options?: {
2196
- /**
2197
- * Enable pretty printing of JSON output
2198
- * Adds automatic indentation and line breaks for better readability
2199
- *
2200
- * @since 1.0.10
2201
- * @default false
2202
- */
2203
- pretty?: boolean;
2204
- /**
2205
- * Number of spaces to use for indentation when pretty printing
2206
- * Only used when pretty is true
2207
- *
2208
- * @since 1.0.10
2209
- * @default 2
2210
- */
2211
- indent?: number;
2212
- /**
2213
- * Custom replacer function for JSON.stringify
2214
- * Allows custom transformation during serialization
2215
- * Note: Will be wrapped to handle line endings
2216
- *
2217
- * @since 1.0.10
2218
- */
2219
- replacer?: (this: unknown, key: string, value: unknown) => unknown;
2220
- });
2235
+ constructor(
2236
+ /**
2237
+ * Options for JSONSerializer
2238
+ *
2239
+ * @since 1.5.0
2240
+ * @default `{}`
2241
+ */
2242
+ options?: Opt);
2221
2243
  /**
2222
2244
  * Creates a replacer function that handles line endings normalization
2223
2245
  *
@@ -2231,12 +2253,11 @@ declare class JSONSerializer implements Serializer<unknown, string>, JSON {
2231
2253
  * 2. Function replacer - Wrapped to handle line endings
2232
2254
  * 3. Null/undefined - Creates default line ending handler
2233
2255
  *
2234
- * @private
2235
2256
  * @param replacer - Custom replacer function or array of properties to include
2236
2257
  * @returns Replacer function or array of properties to include
2237
2258
  * @since 1.0.10
2238
2259
  */
2239
- private createReplacer;
2260
+ protected createReplacer(replacer?: ((this: unknown, key: string, value: unknown) => unknown) | (number | string)[] | null): ((this: unknown, key: string, value: unknown) => unknown) | (number | string)[] | null;
2240
2261
  /**
2241
2262
  * Enhanced JSON.stringify with additional features
2242
2263
  *
@@ -2288,7 +2309,7 @@ declare class JSONSerializer implements Serializer<unknown, string>, JSON {
2288
2309
  * @since 1.0.10
2289
2310
  * @returns Parsed value
2290
2311
  */
2291
- deserialize(data: string, defaultValue?: unknown): unknown;
2312
+ deserialize(data: string, defaultValue?: T): T;
2292
2313
  /**
2293
2314
  * Optimized serialization for arrays of primitive values
2294
2315
  * Avoids object property enumeration
@@ -2302,14 +2323,21 @@ declare class JSONSerializer implements Serializer<unknown, string>, JSON {
2302
2323
 
2303
2324
  /**
2304
2325
  * Base64 serialization implementation
2305
- * Provides string-to-base64 encoding/decoding with optional compression
2326
+ * Cross-platform string-to-base64 encoding/decoding for both browser and Node.js
2327
+ *
2328
+ * Significance: Provides universal Base64 serialization across different JavaScript environments
2329
+ * Core idea: Environment-aware Base64 encoding with consistent API
2330
+ * Main function: Convert strings to/from Base64 with optional URL-safe encoding
2331
+ * Main purpose: Enable cross-platform data serialization with Base64 encoding
2306
2332
  *
2307
2333
  * Features:
2334
+ * - Cross-platform compatibility (Browser + Node.js)
2308
2335
  * - Base64 encoding/decoding
2309
2336
  * - UTF-8 support
2310
2337
  * - URL-safe encoding option
2338
+ * - Robust error handling
2311
2339
  *
2312
- * @implements {Serializer<string, string>}
2340
+ * @implements {SerializerIneterface<string, string>}
2313
2341
  *
2314
2342
  * @since 1.0.10
2315
2343
  *
@@ -2318,13 +2346,13 @@ declare class JSONSerializer implements Serializer<unknown, string>, JSON {
2318
2346
  * const serializer = new Base64Serializer({ urlSafe: true });
2319
2347
  *
2320
2348
  * // Encode string to base64
2321
- * const encoded = serializer.stringify("Hello World!");
2349
+ * const encoded = serializer.serialize("Hello World!");
2322
2350
  *
2323
2351
  * // Decode base64 back to string
2324
- * const decoded = serializer.parse(encoded);
2352
+ * const decoded = serializer.deserialize(encoded);
2325
2353
  * ```
2326
2354
  */
2327
- declare class Base64Serializer implements Serializer<string, string> {
2355
+ declare class Base64Serializer implements SerializerIneterface<string, string> {
2328
2356
  private options;
2329
2357
  constructor(options?: {
2330
2358
  /**
@@ -2336,7 +2364,20 @@ declare class Base64Serializer implements Serializer<string, string> {
2336
2364
  urlSafe?: boolean;
2337
2365
  });
2338
2366
  /**
2339
- * Serializes string to base64
2367
+ * Detects if running in Node.js environment
2368
+ * @private
2369
+ * @returns True if in Node.js, false if in browser
2370
+ */
2371
+ private isNodeEnvironment;
2372
+ /**
2373
+ * Validates if a string is a valid Base64 encoded string
2374
+ * @private
2375
+ * @param value - The string to validate
2376
+ * @returns True if valid Base64, false otherwise
2377
+ */
2378
+ private isValidBase64;
2379
+ /**
2380
+ * Serializes string to base64 using environment-appropriate method
2340
2381
  * @override
2341
2382
  * @since 1.0.10
2342
2383
  * @param data - String to encode
@@ -2344,7 +2385,7 @@ declare class Base64Serializer implements Serializer<string, string> {
2344
2385
  */
2345
2386
  serialize(data: string): string;
2346
2387
  /**
2347
- * Deserializes base64 string back to original
2388
+ * Deserializes base64 string back to original using environment-appropriate method
2348
2389
  * @override
2349
2390
  * @since 1.0.10
2350
2391
  * @param data - Base64 string to decode
@@ -2370,238 +2411,519 @@ declare class Base64Serializer implements Serializer<string, string> {
2370
2411
  }
2371
2412
 
2372
2413
  /**
2373
- * Interface representing a synchronous storage mechanism.
2414
+ * Interface representing an asynchronous storage mechanism.
2374
2415
  *
2375
2416
  * @template Key - The type of keys used to identify stored values.
2376
2417
  * @template ValueType - The type of values stored, defaults to unknown.
2377
2418
  *
2378
2419
  * @example
2420
+ *
2379
2421
  * ```typescript
2380
- * const storage: SyncStorage<string, number> = ...;
2381
- * storage.setItem('key', 123);
2382
- * const value = storage.getItem('key', 0);
2422
+ * const storage: AsyncStorage<string, number> = ...;
2423
+ * await storage.setItem('key', 123);
2424
+ * const value = await storage.getItem('key', 0);
2383
2425
  * ```
2426
+ *
2384
2427
  */
2385
- interface SyncStorage<Key, ValueType = unknown> {
2428
+ interface AsyncStorageInterface<Key, ValueType = unknown> {
2386
2429
  /**
2387
2430
  * The number of items stored.
2388
2431
  */
2389
2432
  readonly length: number;
2390
2433
  /**
2391
- * Stores a value with the specified key.
2434
+ * Asynchronously stores a value with the specified key.
2392
2435
  *
2393
2436
  * @param key - The key to identify the stored value.
2394
2437
  * @param value - The value to store.
2395
2438
  * @param options - Optional parameters for storage.
2439
+ * @returns A promise that resolves when the value is stored.
2396
2440
  */
2397
- setItem<T>(key: Key, value: T, options?: unknown): void;
2441
+ setItem<T>(key: Key, value: T, options?: unknown): Promise<void>;
2398
2442
  /**
2399
- * Retrieves a value by key.
2443
+ * Asynchronously retrieves a value by key.
2400
2444
  *
2401
2445
  * @param key - The key of the value to retrieve.
2402
2446
  * @param defaultValue - The default value to return if the key is not found.
2403
2447
  * @param options - Optional parameters for retrieval.
2404
- * @returns The value associated with the key, or the default value if not found.
2448
+ * @returns A promise that resolves to the value associated with the key, or the default value if not found.
2405
2449
  */
2406
- getItem<T extends ValueType>(key: Key, defaultValue?: T, options?: unknown): T | null;
2450
+ getItem<T extends ValueType>(key: Key, defaultValue?: T, options?: unknown): Promise<T | null>;
2407
2451
  /**
2408
- * Removes a value by key.
2452
+ * Asynchronously removes a value by key.
2409
2453
  *
2410
2454
  * @param key - The key of the value to remove.
2411
2455
  * @param options - Optional parameters for removal.
2456
+ * @returns A promise that resolves when the value is removed.
2412
2457
  */
2413
- removeItem(key: Key, options?: unknown): void;
2458
+ removeItem(key: Key, options?: unknown): Promise<void>;
2414
2459
  /**
2415
- * Clears all stored values.
2460
+ * Asynchronously clears all stored values.
2461
+ *
2462
+ * @returns A promise that resolves when all values are cleared.
2416
2463
  */
2417
- clear(): void;
2464
+ clear(): Promise<void>;
2418
2465
  }
2466
+
2467
+ interface ExpireOptions {
2468
+ /**
2469
+ * Expire time
2470
+ *
2471
+ * maybe is
2472
+ * - number: milliseconds
2473
+ * - string: time string, like '1d', '1h', '1m', '1s'
2474
+ * - object: {}
2475
+ * - ...
2476
+ *
2477
+ * Subclass implementation
2478
+ */
2479
+ expires?: unknown;
2480
+ }
2481
+
2419
2482
  /**
2420
- * Interface representing an asynchronous storage mechanism.
2483
+ * Interface representing a synchronous storage mechanism.
2421
2484
  *
2422
2485
  * @template Key - The type of keys used to identify stored values.
2423
2486
  * @template ValueType - The type of values stored, defaults to unknown.
2424
2487
  *
2425
2488
  * @example
2426
- *
2427
2489
  * ```typescript
2428
- * const storage: AsyncStorage<string, number> = ...;
2429
- * await storage.setItem('key', 123);
2430
- * const value = await storage.getItem('key', 0);
2490
+ * const storage: SyncStorage<string, number> = ...;
2491
+ * storage.setItem('key', 123);
2492
+ * const value = storage.getItem('key', 0);
2431
2493
  * ```
2432
- *
2433
2494
  */
2434
- interface AsyncStorage<Key, ValueType = unknown> {
2495
+ interface SyncStorageInterface<Key, Opt = unknown> {
2435
2496
  /**
2436
2497
  * The number of items stored.
2437
2498
  */
2438
2499
  readonly length: number;
2439
2500
  /**
2440
- * Asynchronously stores a value with the specified key.
2501
+ * Stores a value with the specified key.
2441
2502
  *
2442
2503
  * @param key - The key to identify the stored value.
2443
2504
  * @param value - The value to store.
2444
2505
  * @param options - Optional parameters for storage.
2445
- * @returns A promise that resolves when the value is stored.
2446
2506
  */
2447
- setItem<T>(key: Key, value: T, options?: unknown): Promise<void>;
2507
+ setItem<T>(key: Key, value: T, options?: Opt): void | unknown;
2448
2508
  /**
2449
- * Asynchronously retrieves a value by key.
2509
+ * Retrieves a value by key.
2450
2510
  *
2451
2511
  * @param key - The key of the value to retrieve.
2452
2512
  * @param defaultValue - The default value to return if the key is not found.
2453
2513
  * @param options - Optional parameters for retrieval.
2454
- * @returns A promise that resolves to the value associated with the key, or the default value if not found.
2514
+ * @returns The value associated with the key, or the default value if not found.
2455
2515
  */
2456
- getItem<T extends ValueType>(key: Key, defaultValue?: T, options?: unknown): Promise<T | null>;
2516
+ getItem<T>(key: Key, defaultValue?: T, options?: Opt): T | null;
2457
2517
  /**
2458
- * Asynchronously removes a value by key.
2518
+ * Removes a value by key.
2459
2519
  *
2460
2520
  * @param key - The key of the value to remove.
2461
2521
  * @param options - Optional parameters for removal.
2462
- * @returns A promise that resolves when the value is removed.
2463
2522
  */
2464
- removeItem(key: Key, options?: unknown): Promise<void>;
2523
+ removeItem(key: Key, options?: Opt): void;
2465
2524
  /**
2466
- * Asynchronously clears all stored values.
2525
+ * Clears all stored values.
2526
+ */
2527
+ clear(): void;
2528
+ /**
2529
+ * Get the raw value from the storage.
2467
2530
  *
2468
- * @returns A promise that resolves when all values are cleared.
2531
+ * 通过这个方法可以获取到内部原始的值
2532
+ *
2533
+ * @param value - The value to get the raw value from.
2534
+ * @returns The raw value.
2469
2535
  */
2470
- clear(): Promise<void>;
2536
+ getRawValue?<T>(value: unknown, defaultValue?: T, options?: Opt): T | null;
2537
+ }
2538
+
2539
+ interface KeyStorageOptions<Key, Sopt = unknown> extends ExpireOptions {
2540
+ /**
2541
+ * Persistent storage
2542
+ */
2543
+ storage?: SyncStorageInterface<Key, Sopt>;
2544
+ }
2545
+ declare abstract class KeyStorageInterface<Key, Value, Opt extends KeyStorageOptions<Key> = KeyStorageOptions<Key>> {
2546
+ readonly key: Key;
2547
+ protected options: Opt;
2548
+ protected value: Value | null;
2549
+ constructor(key: Key, options?: Opt);
2550
+ getKey(): Key;
2551
+ getValue(): Value | null;
2552
+ abstract get(options?: Opt): Value | null;
2553
+ abstract set(value: Value, options?: Opt): void;
2554
+ abstract remove(options?: Opt): void;
2471
2555
  }
2472
2556
 
2473
2557
  /**
2474
- * Represents a storage mechanism for JSON-serializable data.
2558
+ * KeyStorage is a storage that can be used to store a single value.
2475
2559
  *
2476
- * This class provides a way to store, retrieve, and manage JSON data
2477
- * with optional expiration times. It can operate with a provided
2478
- * synchronous storage backend or use an internal store.
2560
+ * Typical usage scenario: need to store a value and need to persist it:
2479
2561
  *
2480
- * The main purpose of this class is to facilitate the storage of
2481
- * complex data structures in a serialized JSON format, allowing
2482
- * for easy retrieval and management.
2562
+ * - token storage
2563
+ * - user info storage
2564
+ * - page theme, language
2565
+ * - ...
2483
2566
  *
2484
- * inner serializer is used by default, which is `JSONSerializer`.
2567
+ * And support for data encryption, there are times when reporting errors in the local data can easily be tampered with, this time you can use encryption to protect the data!
2485
2568
  *
2486
- * @since 1.0.17
2569
+ * @since 1.5.0
2487
2570
  *
2488
- * @example
2571
+ * @example basic usage
2489
2572
  *
2490
- * A simple example of how to use the JSONStorage class
2573
+ * use localStorage as storage, persist the value
2491
2574
  *
2492
2575
  * ```typescript
2493
- * const storage = new JSONStorage();
2494
- * storage.setItem('key', { data: 'value' }, 3600);
2495
- * const value = storage.getItem('key');
2496
- * // => { data: 'value' }
2497
- * ```
2498
- * @example
2576
+ * const tokenStorage = new KeyStorage('token', localStorage);
2499
2577
  *
2500
- * If need persistent storage, you can use `localStorage` or `sessionStorage`
2578
+ * tokenStorage.get(); // get from localStorage
2579
+ * tokenStorage.set('token-123123123'); // set to localStorage
2580
+ * tokenStorage.remove(); // remove from localStorage
2581
+ * ```
2501
2582
  *
2583
+ * @example with encrypt
2502
2584
  * ```typescript
2503
- * const storage = new JSONStorage(localStorage);
2504
- * storage.setItem('key', { data: 'value' }, 3600);
2505
- * const value = storage.getItem('key');
2506
- * // => { data: 'value' }
2585
+ * const tokenStorage = new KeyStorage('token', localStorage, {
2586
+ * encrypt: new Encryptor(new AESCipher('1234567890'))
2587
+ * });
2588
+ *
2589
+ * tokenStorage.get(); // get from localStorage
2590
+ * tokenStorage.set('token-123123123'); // set to localStorage
2591
+ * tokenStorage.remove(); // remove from localStorage
2507
2592
  * ```
2593
+ */
2594
+ declare class KeyStorage<Key, Value, Opt extends KeyStorageOptions<Key> = KeyStorageOptions<Key>> extends KeyStorageInterface<Key, Value, Opt> {
2595
+ protected value: Value | null;
2596
+ protected mergeOptions(options?: Opt): Opt;
2597
+ get(options?: Opt): Value | null;
2598
+ set(token: Value, options?: Opt): void;
2599
+ remove(options?: Opt): void;
2600
+ }
2601
+
2602
+ interface ObjectStorageOptions extends ExpireOptions {
2603
+ }
2604
+ /**
2605
+ * Storage value wrapper with expiration support
2508
2606
  *
2509
- * @example
2607
+ * Significance: Provides a standardized structure for stored values with metadata
2608
+ * Core idea: Encapsulate stored data with key, value, and optional expiration time
2609
+ * Main function: Wrap user data with storage metadata
2610
+ * Main purpose: Enable expiration-aware storage operations
2510
2611
  *
2511
- * Or use custom serializer and storage
2612
+ * @template Key - The type of the storage key
2613
+ * @template ValueType - The type of the stored value
2512
2614
  *
2615
+ * @example
2513
2616
  * ```typescript
2514
- * // use native JSON
2515
- * const customSerializer = {
2516
- * serialize: JSON.stringify,
2517
- * deserialize: JSON.parse,
2617
+ * const storageValue: StorageValue<string, number> = {
2618
+ * key: 'user-id',
2619
+ * value: 12345,
2620
+ * expires: Date.now() + 3600000 // 1 hour from now
2518
2621
  * };
2622
+ * ```
2623
+ */
2624
+ type StorageValue<Key, ValueType> = {
2625
+ /** The storage key */
2626
+ key: Key;
2627
+ /** The actual stored value */
2628
+ value: ValueType;
2629
+ /** Optional expiration timestamp in milliseconds */
2630
+ expires?: number;
2631
+ };
2632
+ /**
2633
+ * Object-based storage implementation with memory caching and optional persistence
2519
2634
  *
2520
- * // can use localStorage or sessionStorage
2521
- * const customStorage = {
2522
- * setItem: (key: string, value: string) => {
2523
- * localStorage.setItem(key, value);
2524
- * },
2525
- * getItem: (key: string) => {
2526
- * return localStorage.getItem(key);
2527
- * },
2528
- * removeItem: (key: string) => {
2529
- * localStorage.removeItem(key);
2530
- * },
2531
- * clear: () => {
2532
- * localStorage.clear();
2533
- * },
2534
- * };
2635
+ * Significance: Provides a high-performance storage solution with dual-layer architecture
2636
+ * Core idea: Combine in-memory caching with optional persistent storage for optimal performance
2637
+ * Main function: Store and retrieve data with expiration support and automatic cache management
2638
+ * Main purpose: Enable fast data access with persistence and expiration capabilities
2639
+ *
2640
+ * Features:
2641
+ * - In-memory caching for fast access
2642
+ * - Optional persistent storage backend
2643
+ * - Automatic expiration handling
2644
+ * - Type-safe operations with generics
2645
+ * - Serialization support for complex data types
2646
+ *
2647
+ * @template Key - The type of storage keys
2648
+ * @template ValueType - The type of stored values (defaults to string)
2649
+ *
2650
+ * @example
2651
+ * ```typescript
2652
+ * import { ObjectStorage } from './ObjectStorage';
2653
+ * import { JsonSerializer } from '../serializer';
2654
+ *
2655
+ * // Create storage with JSON serializer
2656
+ * const storage = new ObjectStorage(
2657
+ * new JsonSerializer(),
2658
+ * localStorage // optional persistent storage
2659
+ * );
2660
+ *
2661
+ * // Store data with expiration
2662
+ * storage.setItem('user-session', { userId: 123 }, Date.now() + 3600000);
2535
2663
  *
2536
- * const storage = new JSONStorage(customStorage, customSerializer);
2537
- * storage.setItem('key', { data: 'value' }, 3600);
2538
- * const value = storage.getItem('key');
2664
+ * // Retrieve data
2665
+ * const session = storage.getItem('user-session');
2539
2666
  * ```
2540
2667
  *
2668
+ * @since 1.5.0
2541
2669
  */
2542
- declare class JSONStorage implements SyncStorage<string> {
2670
+ declare class ObjectStorage<Key, ValueType = string, Opt extends ObjectStorageOptions = ObjectStorageOptions> implements SyncStorageInterface<Key, Opt> {
2543
2671
  /**
2544
- * The storage backend to use.
2672
+ * Serializer for data transformation
2673
+ *
2674
+ * Significance: Enables storage of complex data types
2675
+ * Core idea: Convert between runtime objects and storage format
2676
+ * Main function: Serialize/deserialize storage values
2677
+ * Main purpose: Support type-safe storage operations
2545
2678
  */
2546
- private readonly storage?;
2679
+ protected readonly serializer?: SerializerIneterface<unknown, ValueType> | undefined;
2547
2680
  /**
2548
- * The serializer used to serialize and deserialize the data.
2681
+ * In-memory storage map for fast data access
2549
2682
  *
2550
- * **serializer and deserialize is only support sync operation**
2683
+ * Significance: Primary storage layer for performance optimization
2684
+ * Core idea: Keep frequently accessed data in memory
2685
+ * Main function: Provide instant data access without I/O operations
2686
+ * Main purpose: Minimize latency for storage operations
2551
2687
  */
2552
- private readonly serializer;
2688
+ protected store: Map<Key, ValueType>;
2553
2689
  /**
2554
- * The internal store for the JSONStorage class.
2690
+ * Creates a new ObjectStorage instance
2691
+ *
2692
+ * @param serializer - Serializer for converting between storage values and stored format
2693
+ * @param persistent - Optional persistent storage backend for data durability
2555
2694
  *
2556
- * If `storage` is not provided, it is stored in memory by default.
2695
+ * @example
2696
+ * ```typescript
2697
+ * const storage = new ObjectStorage(
2698
+ * new JsonSerializer(),
2699
+ * localStorage
2700
+ * );
2701
+ * ```
2557
2702
  */
2558
- private store;
2703
+ constructor(
2559
2704
  /**
2560
- * Initializes a new instance of the JSONStorage class.
2705
+ * Serializer for data transformation
2561
2706
  *
2562
- * @param storage - An optional synchronous storage backend to use.
2707
+ * Significance: Enables storage of complex data types
2708
+ * Core idea: Convert between runtime objects and storage format
2709
+ * Main function: Serialize/deserialize storage values
2710
+ * Main purpose: Support type-safe storage operations
2563
2711
  */
2564
- constructor(
2712
+ serializer?: SerializerIneterface<unknown, ValueType> | undefined);
2565
2713
  /**
2566
- * The storage backend to use.
2714
+ * Gets the number of items stored in the memory cache
2715
+ *
2716
+ * @override
2717
+ * @returns The number of stored items in memory
2718
+ *
2719
+ * @example
2720
+ * ```typescript
2721
+ * console.log(`Storage contains ${storage.length} items`);
2722
+ * ```
2567
2723
  */
2568
- storage?: SyncStorage<string, string> | undefined,
2724
+ get length(): number;
2569
2725
  /**
2570
- * The serializer used to serialize and deserialize the data.
2726
+ * Stores a value with optional expiration time
2571
2727
  *
2572
- * **serializer and deserialize is only support sync operation**
2728
+ * Significance: Primary method for data storage operations
2729
+ * Core idea: Store data with metadata and optional expiration
2730
+ * Main function: Persist data to both memory and persistent storage
2731
+ * Main purpose: Enable reliable data storage with expiration support
2732
+ *
2733
+ * @override
2734
+ * @template T - The type of the value to store
2735
+ * @param key - The key under which the value is stored
2736
+ * @param value - The value to store (must be serializable)
2737
+ * @param expire - Optional expiration time in milliseconds from epoch
2738
+ *
2739
+ * @example
2740
+ * ```typescript
2741
+ * // Store without expiration
2742
+ * storage.setItem('username', 'john_doe');
2743
+ *
2744
+ * // Store with expiration (1 hour)
2745
+ * storage.setItem('session', sessionData, Date.now() + 3600000);
2746
+ * ```
2573
2747
  */
2574
- serializer?: Serializer<unknown, string>);
2748
+ setItem<T>(key: Key, value: T, options?: ObjectStorageOptions): unknown;
2575
2749
  /**
2576
- * Gets the number of items stored in the local storage.
2750
+ * Retrieves a stored value by key with fallback strategy
2751
+ *
2752
+ * Significance: Primary method for data retrieval operations
2753
+ * Core idea: Multi-layer retrieval with expiration checking
2754
+ * Main function: Get data from memory first, then persistent storage
2755
+ * Main purpose: Provide fast, reliable data access with automatic cleanup
2756
+ *
2757
+ * Retrieval strategy:
2758
+ * 1. Check memory cache first
2759
+ * 2. Fallback to persistent storage if not in memory
2760
+ * 3. Validate expiration and cleanup if expired
2761
+ * 4. Return default value if not found or expired
2762
+ *
2763
+ * @override
2764
+ * @template T - The expected type of the retrieved value
2765
+ * @param key - The key of the item to retrieve
2766
+ * @param defaultValue - Default value to return if item not found or expired
2767
+ * @returns The stored value or default value if not found/expired
2768
+ *
2769
+ * @example
2770
+ * ```typescript
2771
+ * // Get value with default
2772
+ * const username = storage.getItem('username', 'anonymous');
2577
2773
  *
2578
- * @returns The number of stored items.
2774
+ * // Get complex object
2775
+ * const config = storage.getItem<AppConfig>('app-config');
2776
+ * ```
2579
2777
  */
2580
- get length(): number;
2778
+ getItem<T>(key: Key, defaultValue?: T): T | null;
2779
+ getRawValue<T>(value: unknown, defaultValue?: T): T | null;
2581
2780
  /**
2582
- * Stores a value with an optional expiration time.
2781
+ * Removes a stored item by its key from both memory and persistent storage
2782
+ *
2783
+ * Significance: Essential cleanup method for storage management
2784
+ * Core idea: Synchronize removal across all storage layers
2785
+ * Main function: Delete data from memory and persistent storage
2786
+ * Main purpose: Maintain data consistency and free up storage space
2787
+ *
2788
+ * @override
2789
+ * @param key - The key of the item to remove
2583
2790
  *
2584
- * @param key - The key under which the value is stored.
2585
- * @param value - The value to store, which must be JSON-serializable.
2586
- * @param expire - Optional expiration time in milliseconds.
2791
+ * @example
2792
+ * ```typescript
2793
+ * storage.removeItem('expired-session');
2794
+ * ```
2587
2795
  */
2588
- setItem<T>(key: string, value: T, expire?: number): void;
2796
+ removeItem(key: Key): void;
2589
2797
  /**
2590
- * Retrieves a stored value by its key.
2798
+ * Clears all stored items from both memory and persistent storage
2591
2799
  *
2592
- * @param key - The key of the value to retrieve.
2593
- * @param defaultValue - An optional default value to return if the key is not found.
2594
- * @returns The stored value or the default value if the key is not found or expired.
2800
+ * Significance: Bulk cleanup method for complete storage reset
2801
+ * Core idea: Synchronize clearing across all storage layers
2802
+ * Main function: Remove all data from memory and persistent storage
2803
+ * Main purpose: Provide complete storage reset capability
2804
+ *
2805
+ * @override
2806
+ *
2807
+ * @example
2808
+ * ```typescript
2809
+ * storage.clear(); // Removes all stored data
2810
+ * ```
2811
+ */
2812
+ clear(): void;
2813
+ /**
2814
+ * Checks if a storage value has expired
2815
+ *
2816
+ * Significance: Core expiration validation logic
2817
+ * Core idea: Compare expiration timestamp with current time
2818
+ * Main function: Determine if stored data is still valid
2819
+ * Main purpose: Enable automatic cleanup of expired data
2820
+ *
2821
+ * @param value - The storage value to check for expiration
2822
+ * @returns True if the value has expired, false otherwise
2823
+ *
2824
+ * @example
2825
+ * ```typescript
2826
+ * const isExpired = this.isExpired(storageValue);
2827
+ * if (isExpired) {
2828
+ * this.removeItem(key);
2829
+ * }
2830
+ * ```
2831
+ */
2832
+ protected isExpired(value: StorageValue<Key, ValueType>): boolean;
2833
+ /**
2834
+ * Type guard to check if a value is a valid StorageValue
2835
+ *
2836
+ * Significance: Type safety validation for deserialized data
2837
+ * Core idea: Verify object structure matches expected StorageValue format
2838
+ * Main function: Validate deserialized data structure
2839
+ * Main purpose: Ensure type safety and prevent runtime errors
2840
+ *
2841
+ * @template Key - The type of the storage key
2842
+ * @template ValueType - The type of the stored value
2843
+ * @param value - The value to check
2844
+ * @returns True if the value is a valid StorageValue, false otherwise
2845
+ *
2846
+ * @example
2847
+ * ```typescript
2848
+ * if (this.isStorageValue(deserializedValue)) {
2849
+ * // Safe to access .key, .value, .expire properties
2850
+ * return deserializedValue.value;
2851
+ * }
2852
+ * ```
2595
2853
  */
2596
- getItem<T>(key: string, defaultValue?: T): T | null;
2854
+ protected isStorageValue(value: unknown): value is StorageValue<Key, ValueType>;
2855
+ /**
2856
+ * Gets the serializer instance
2857
+ *
2858
+ * Significance: Provides access to the serialization logic
2859
+ * Core idea: Expose serializer for advanced use cases
2860
+ * Main function: Return the serializer instance
2861
+ * Main purpose: Enable direct access to serialization when needed
2862
+ *
2863
+ * @returns The serializer instance
2864
+ *
2865
+ * @example
2866
+ * ```typescript
2867
+ * const serializer = storage.getSerializer();
2868
+ * if (serializer) {
2869
+ * // Direct access to serializer
2870
+ * }
2871
+ * ```
2872
+ */
2873
+ getSerializer(): SerializerIneterface<unknown, ValueType> | undefined;
2874
+ }
2875
+
2876
+ /**
2877
+ * Pipe processor type definition
2878
+ *
2879
+ * Significance: Define the type of components that can be used for data processing pipelines
2880
+ * Core idea: Unify the type definition of different processors, supporting data transformation and intermediate storage
2881
+ * Main function: Provide type-safe pipeline components
2882
+ * Main purpose: Support serialization, encryption, intermediate storage, and other data processing operations
2883
+ */
2884
+ type PipeType<Key> = SerializerIneterface<unknown, unknown> | Encryptor<unknown, unknown> | SyncStorageInterface<Key, unknown>;
2885
+ /**
2886
+ * Pipe value definition, containing the pipe processor and its type identifier
2887
+ *
2888
+ * Significance: Pre-determine the pipe type to avoid runtime type checks
2889
+ * Core idea: Bind the pipe processor with its type to improve execution efficiency
2890
+ * Main function: Store the pipe processor and its type information
2891
+ * Main purpose: Optimize pipe execution performance, simplify type judgment logic
2892
+ */
2893
+ type PipeValue<Key> = {
2894
+ type: 'serialize';
2895
+ pipe: SerializerIneterface<unknown, unknown>;
2896
+ } | {
2897
+ type: 'encrypt';
2898
+ pipe: Encryptor<unknown, unknown>;
2899
+ } | {
2900
+ type: 'storage';
2901
+ pipe: SyncStorageInterface<Key, unknown>;
2902
+ };
2903
+
2904
+ type PipeArg<Key> = PipeType<Key> | PipeValue<Key>;
2905
+ declare class SyncStorage<Key, Opt = unknown> implements SyncStorageInterface<Key, Opt> {
2906
+ protected readonly storage: SyncStorageInterface<Key, Opt>;
2907
+ /**
2908
+ * Internal pipe value list, pre-determined type
2909
+ */
2910
+ protected readonly pipes: PipeValue<Key>[];
2911
+ constructor(storage: SyncStorageInterface<Key, Opt>, pipes?: PipeArg<Key>[] | PipeArg<Key>);
2912
+ /**
2913
+ * Get the number of storage items
2914
+ */
2915
+ get length(): number;
2916
+ setItem<T>(key: Key, value: T, options?: Opt): void;
2917
+ getItem<T>(key: Key, defaultValue?: T, options?: Opt): T | null;
2597
2918
  /**
2598
- * Removes a stored item by its key.
2919
+ * Delete data items, delete from all storage layers
2599
2920
  *
2600
- * @param key - The key of the item to remove.
2921
+ * @param key - Storage key
2922
+ * @param options - Delete options
2601
2923
  */
2602
- removeItem(key: string): void;
2924
+ removeItem(key: Key, options?: Opt): void;
2603
2925
  /**
2604
- * Clears all stored items.
2926
+ * Clear all data, including storage in the pipeline
2605
2927
  */
2606
2928
  clear(): void;
2607
2929
  }
@@ -2634,5 +2956,4 @@ type Intersection<T1, T2> = {
2634
2956
  [P in keyof T1 & keyof T2]: T1[P] | T2[P];
2635
2957
  };
2636
2958
 
2637
- export { AsyncExecutor, Base64Serializer, Executor, ExecutorError, FetchAbortPlugin, FetchURLPlugin, JSONSerializer, JSONStorage, RequestAdapterAxios, RequestAdapterFetch, RequestError, RequestErrorID, RequestManager, RequestScheduler, RequestTransaction, RetryPlugin, SyncExecutor };
2638
- export type { AsyncStorage, Encryptor, ExecutorContext, ExecutorPlugin, HookRuntimes, Intersection, PromiseTask, RequestAdapterConfig, RequestAdapterFetchConfig, RequestAdapterInterface, RequestAdapterResponse, RequestTransactionInterface, RetryOptions, Serializer, SyncStorage, SyncTask, Task, ValueOf };
2959
+ export { AsyncExecutor, type AsyncStorageInterface, Base64Serializer, type Encryptor, Executor, type ExecutorContext, ExecutorError, type ExecutorPlugin, type ExpireOptions, FetchAbortPlugin, FetchURLPlugin, type HookRuntimes, type Intersection, JSONSerializer, type JSONSerializerOptions, KeyStorage, KeyStorageInterface, type KeyStorageOptions, ObjectStorage, type ObjectStorageOptions, type PipeArg, type PromiseTask, RequestAdapterAxios, type RequestAdapterConfig, RequestAdapterFetch, type RequestAdapterFetchConfig, type RequestAdapterInterface, type RequestAdapterResponse, RequestError, RequestErrorID, RequestManager, RequestScheduler, RequestTransaction, type RequestTransactionInterface, type RetryOptions, RetryPlugin, type SerializerIneterface, type StorageValue, SyncExecutor, SyncStorage, type SyncStorageInterface, type SyncTask, type Task, type ValueOf };