@ad-execute-manager/storage 2.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 singcl
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,276 @@
1
+ # @ad-execute-manager/storage
2
+
3
+ A flexible storage utility for JavaScript applications with expiration support, user-specific storage, and customizable prefixes.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @ad-execute-manager/storage
9
+ ```
10
+
11
+ ## Features
12
+
13
+ - **Expiration Support**: Set expiration times for stored items, including 'today' option for day-bound data
14
+ - **User-specific Storage**: Store data per user with automatic userId prefixing
15
+ - **Customizable Prefix**: Add a prefix to identify the source of storage items
16
+ - **Synchronous Operations**: Uses synchronous storage methods for simple integration
17
+ - **Error Handling**: Built-in error handling for storage operations
18
+ - **TypeScript Support**: Includes TypeScript type definitions
19
+ - **Logger Integration**: Uses @ad-execute-manager/logger for logging storage operations
20
+
21
+ ## Usage
22
+
23
+ ### Basic Usage
24
+
25
+ ```javascript
26
+ import { Storage } from '@ad-execute-manager/storage';
27
+
28
+ // Create a storage instance
29
+ const storage = new Storage({
30
+ prefix: 'myapp_',
31
+ expire: null // Default expiration (null = never expire)
32
+ });
33
+
34
+ // Set data with different expiration options
35
+
36
+ // Set data that expires today
37
+ storage.setItem('dailyTask', { completed: false }, 'today');
38
+
39
+ // Set data with custom expiration (2 hours)
40
+ storage.setItem('tempData', { value: 123 }, 2 * 60 * 60 * 1000);
41
+
42
+ // Set permanent data
43
+ storage.setItem('userSettings', { theme: 'dark' });
44
+
45
+ // Get data
46
+ const dailyTask = storage.getItem('dailyTask');
47
+ const tempData = storage.getItem('tempData');
48
+ const userSettings = storage.getItem('userSettings');
49
+
50
+ console.log('Daily Task:', dailyTask);
51
+ console.log('Temp Data:', tempData);
52
+ console.log('User Settings:', userSettings);
53
+ ```
54
+
55
+ ### User-specific Storage
56
+
57
+ ```javascript
58
+ import { Storage } from '@ad-execute-manager/storage';
59
+
60
+ // Create storage instance with userId
61
+ const userStorage = new Storage({
62
+ prefix: 'app_',
63
+ userId: 'user123'
64
+ });
65
+
66
+ // Set user-specific data
67
+ userStorage.setUserItem('preferences', { theme: 'light', language: 'en' });
68
+ userStorage.setUserItem('lastLogin', new Date().toISOString());
69
+
70
+ // Get user-specific data
71
+ const preferences = userStorage.getUserItem('preferences');
72
+ const lastLogin = userStorage.getUserItem('lastLogin');
73
+
74
+ console.log('User Preferences:', preferences);
75
+ console.log('Last Login:', lastLogin);
76
+ ```
77
+
78
+ ### Advanced Usage
79
+
80
+ ```javascript
81
+ import { Storage } from '@ad-execute-manager/storage';
82
+
83
+ // Create storage instance
84
+ const storage = new Storage({
85
+ prefix: 'app_',
86
+ expire: 24 * 60 * 60 * 1000 // Default to 24 hours
87
+ });
88
+
89
+ // Set data
90
+ storage.setItem('session', { token: 'abc123' });
91
+
92
+ // Get all keys
93
+ const allKeys = storage.keys();
94
+ console.log('All stored keys:', allKeys);
95
+
96
+ // Remove an item
97
+ storage.removeItem('tempData');
98
+
99
+ // Clear all storage
100
+ // storage.clear(); // Uncomment to clear all storage
101
+
102
+ // Using the static new method
103
+ const anotherStorage = Storage.new({
104
+ prefix: 'another_'
105
+ });
106
+
107
+ anotherStorage.setItem('test', { value: 'hello' });
108
+ ```
109
+
110
+ ## API
111
+
112
+ ### Constructor
113
+
114
+ ```javascript
115
+ new Storage(options)
116
+ ```
117
+
118
+ - **options** (Object): Configuration options
119
+ - **prefix** (String): Storage key prefix, defaults to 'storage_'
120
+ - **expire** (Number|null): Default expiration time in milliseconds, null for never expire, defaults to null
121
+ - **userId** (String|Number): User ID for user-specific storage
122
+
123
+ ### Methods
124
+
125
+ #### Basic Storage
126
+
127
+ - **setItem(key, value, expire)**: Set a storage item
128
+ - **key** (String): Storage key
129
+ - **value** (Any): Value to store (will be JSON stringified)
130
+ - **expire** (Number|'today'|null): Expiration time in milliseconds, 'today' for day-bound, or null for no expiration
131
+
132
+ - **getItem(key)**: Get a storage item
133
+ - **key** (String): Storage key
134
+ - **returns** (Any|null): Stored value or null if expired/non-existent
135
+
136
+ - **removeItem(key)**: Remove a storage item
137
+ - **key** (String): Storage key
138
+
139
+ - **clear()**: Clear all storage items
140
+
141
+ - **keys()**: Get all non-expired storage keys
142
+ - **returns** (Array): Array of storage keys without prefix
143
+
144
+ #### User-specific Storage
145
+
146
+ - **setUserItem(key, value, expire)**: Set a user-specific storage item
147
+ - **key** (String): Storage key
148
+ - **value** (Any): Value to store
149
+ - **expire** (Number|'today'|null): Expiration time
150
+
151
+ - **getUserItem(key)**: Get a user-specific storage item
152
+ - **key** (String): Storage key
153
+ - **returns** (Any|null): Stored value or null if expired/non-existent
154
+
155
+ #### Static Methods
156
+
157
+ - **Storage.new(options)**: Create a new Storage instance
158
+ - **options** (Object): Same as constructor options
159
+ - **returns** (Storage): New Storage instance
160
+
161
+ ## Examples
162
+
163
+ ### Example 1: Daily Task Management
164
+
165
+ ```javascript
166
+ import { Storage } from '@ad-execute-manager/storage';
167
+
168
+ // Create storage for daily tasks
169
+ const taskStorage = new Storage({
170
+ prefix: 'tasks_',
171
+ expire: null
172
+ });
173
+
174
+ // Set daily task (expires today)
175
+ taskStorage.setItem('dailyTask', {
176
+ id: 1,
177
+ title: 'Complete tutorial',
178
+ completed: false
179
+ }, 'today');
180
+
181
+ // Get daily task
182
+ const dailyTask = taskStorage.getItem('dailyTask');
183
+
184
+ if (dailyTask) {
185
+ console.log('Daily task:', dailyTask);
186
+
187
+ // Mark task as completed
188
+ dailyTask.completed = true;
189
+ taskStorage.setItem('dailyTask', dailyTask, 'today');
190
+
191
+ console.log('Task marked as completed');
192
+ } else {
193
+ console.log('No active daily task');
194
+ }
195
+ ```
196
+
197
+ ### Example 2: User Preferences
198
+
199
+ ```javascript
200
+ import { Storage } from '@ad-execute-manager/storage';
201
+
202
+ // Create user-specific storage
203
+ const userStorage = new Storage({
204
+ prefix: 'user_',
205
+ userId: 'user123',
206
+ expire: null
207
+ });
208
+
209
+ // Set user preferences
210
+ userStorage.setUserItem('preferences', {
211
+ theme: 'dark',
212
+ language: 'en',
213
+ notifications: true
214
+ });
215
+
216
+ // Get user preferences
217
+ const preferences = userStorage.getUserItem('preferences');
218
+ console.log('User preferences:', preferences);
219
+
220
+ // Update preferences
221
+ if (preferences) {
222
+ preferences.theme = 'light';
223
+ userStorage.setUserItem('preferences', preferences);
224
+ console.log('Preferences updated');
225
+ }
226
+ ```
227
+
228
+ ### Example 3: Session Management
229
+
230
+ ```javascript
231
+ import { Storage } from '@ad-execute-manager/storage';
232
+
233
+ // Create session storage with 1-hour expiration
234
+ const sessionStorage = new Storage({
235
+ prefix: 'session_',
236
+ expire: 60 * 60 * 1000 // 1 hour
237
+ });
238
+
239
+ // Set session data
240
+ sessionStorage.setItem('session', {
241
+ token: 'abc123xyz789',
242
+ userId: 'user123',
243
+ timestamp: Date.now()
244
+ });
245
+
246
+ // Check if session is valid
247
+ function checkSession() {
248
+ const session = sessionStorage.getItem('session');
249
+
250
+ if (session) {
251
+ console.log('Session is valid:', session);
252
+ return true;
253
+ } else {
254
+ console.log('Session expired or not found');
255
+ return false;
256
+ }
257
+ }
258
+
259
+ // Refresh session
260
+ sessionStorage.setItem('session', {
261
+ token: 'newToken123',
262
+ userId: 'user123',
263
+ timestamp: Date.now()
264
+ });
265
+
266
+ console.log('Session refreshed');
267
+ checkSession();
268
+ ```
269
+
270
+ ## Dependencies
271
+
272
+ - **@ad-execute-manager/logger**: For logging storage operations
273
+
274
+ ## License
275
+
276
+ MIT
@@ -0,0 +1,124 @@
1
+ export default Storage;
2
+ export type StorageOptions = {
3
+ /**
4
+ * 存储key的前缀
5
+ */
6
+ prefix?: string;
7
+ /**
8
+ * 默认过期时间(毫秒),null表示永不过期
9
+ */
10
+ expire?: number | null;
11
+ /**
12
+ * 用户ID
13
+ */
14
+ userId?: string | number;
15
+ };
16
+ /**
17
+ * @example
18
+ const storage = new Storage({
19
+ prefix: 'myapp_',
20
+ });
21
+
22
+ // 设置当天有效的数据
23
+ *storage.setItem('dailyTask', { completed: false }, 'today');
24
+
25
+ // 设置普通带过期时间的数据(2小时)
26
+ storage.setItem('tempData', { value: 123 }, 2 * 60 * 60 * 1000);
27
+
28
+ // 设置永久有效的数据
29
+ storage.setItem('userSettings', { theme: 'dark' });
30
+
31
+ // 获取数据
32
+ const dailyTask = storage.getStorageSync('dailyTask');
33
+ const tempData = storage.getStorageSync('tempData');
34
+ const userSettings = storage.getStorageSync('userSettings');
35
+
36
+ console.log('Daily Task:', dailyTask);
37
+ console.log('Temp Data:', tempData);
38
+ console.log('User Settings:', userSettings);
39
+ */
40
+ declare class Storage {
41
+ /**
42
+ * @param {StorageOptions=} args
43
+ * @returns
44
+ */
45
+ static "new"(args?: StorageOptions | undefined): Storage;
46
+ /**
47
+ * @param {StorageOptions} [options]
48
+ */
49
+ constructor(options?: StorageOptions);
50
+ config: {
51
+ /**
52
+ * 存储key的前缀
53
+ */
54
+ prefix: string;
55
+ /**
56
+ * 默认过期时间(毫秒),null表示永不过期
57
+ */
58
+ expire: number | null;
59
+ /**
60
+ * 用户ID
61
+ */
62
+ userId?: string | number;
63
+ };
64
+ logger: Logger;
65
+ /**
66
+ * 获取当天结束时间的时间戳
67
+ * @returns {number} 当天23:59:59的时间戳
68
+ */
69
+ getTodayEndTimestamp(): number;
70
+ /**
71
+ * 设置存储项 - 内部使用
72
+ * @param {string} key 存储键
73
+ * @param {any} value 存储值
74
+ * @param {number|'today'} expire 过期时间(毫秒)或'today'表示当天有效,可选
75
+ */
76
+ _setItem(storageKey: any, value: any, expire: number | "today"): void;
77
+ /**
78
+ * 获取存储项 - 内部使用
79
+ * @param {string} key 存储键
80
+ * @returns {any} 存储的值,如果过期或不存在则返回null
81
+ */
82
+ _getItem(storageKey: any): any;
83
+ /**
84
+ * 设置存储项
85
+ * @param {string} key 存储键
86
+ * @param {any} value 存储值
87
+ * @param {number|'today'} expire 过期时间(毫秒)或'today'表示当天有效,可选
88
+ */
89
+ setItem(key: string, value: any, expire: number | "today"): void;
90
+ /**
91
+ * 获取存储项
92
+ * @param {string} key 存储键
93
+ * @returns {any} 存储的值,如果过期或不存在则返回null
94
+ */
95
+ getItem(key: string): any;
96
+ /**
97
+ * 获取存储项 - 用户维度
98
+ * @param {string} key 存储键
99
+ * @returns {any} 存储的值,如果过期或不存在则返回null
100
+ */
101
+ getUserItem(key: string): any;
102
+ /**
103
+ * 设置存储项 - 用户维度
104
+ * @param {string} key 存储键
105
+ * @param {any} value 存储值
106
+ * @param {number|'today'} expire 过期时间(毫秒)或'today'表示当天有效,可选
107
+ */
108
+ setUserItem(key: string, value: any, expire: number | "today"): void;
109
+ /**
110
+ * 删除存储项
111
+ * @param {string} key 存储键
112
+ */
113
+ removeItem(key: string): void;
114
+ /**
115
+ * 清空所有存储项
116
+ */
117
+ clear(): void;
118
+ /**
119
+ * 获取所有未过期的存储键
120
+ * @returns {string[]} 键数组
121
+ */
122
+ keys(): string[];
123
+ }
124
+ import { Logger } from '@ad-execute-manager/logger';
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";const __rslib_import_meta_url__="u"<typeof document?new(require("url".replace("",""))).URL("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href;var __webpack_require__={};__webpack_require__.d=(e,r)=>{for(var t in r)__webpack_require__.o(r,t)&&!__webpack_require__.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},__webpack_require__.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),__webpack_require__.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{Storage:()=>src_Storage});const logger_namespaceObject=require("@ad-execute-manager/logger");class Storage{constructor(e={}){this.config={prefix:"storage_",expire:null,...e},this.logger=new logger_namespaceObject.Logger({prefix:"Storage"})}getTodayEndTimestamp(){let e=new Date;return new Date(e.getFullYear(),e.getMonth(),e.getDate(),23,59,59,999).getTime()}_setItem(e,r,t){let o=void 0!==t?t:this.config.expire;"today"===o&&(o=this.getTodayEndTimestamp()-Date.now());let _={value:r,expire:o,timestamp:Date.now()};try{tt.setStorageSync(e,JSON.stringify(_))}catch(e){console.error("Storage setItem error:",e)}}_getItem(e){try{let r=tt.getStorageSync(e);if(!r)return null;let t=JSON.parse(r);if(t.expire&&Date.now()-t.timestamp>t.expire)return this.removeItem(e),null;return t.value}catch(e){return console.error("Storage getItem error:",e),null}}setItem(e,r,t){let o=this.config.prefix+e;return this._setItem(o,r,t)}getItem(e){let r=this.config.prefix+e;return this._getItem(r)}getUserItem(e){let r=this.config.userId??"null";if("null"===r)return this.logger.error("userId is required"),null;let t=`${this.config.prefix}_${r}_${e}`;return this._getItem(t)}setUserItem(e,r,t){let o=this.config.userId??"null";if("null"===o)return void this.logger.error("userId is required");let _=`${this.config.prefix}_${o}_${e}`;return this._setItem(_,r,t)}removeItem(e){try{tt.removeStorageSync(e)}catch(e){console.error("Storage removeItem error:",e)}}clear(){try{tt.clearStorageSync()}catch(e){console.error("Storage clear error:",e)}}keys(){try{let e=[];return(tt.getStorageInfoSync().keys??[]).forEach(r=>{if(r.startsWith(this.config.prefix)){let t=JSON.parse(tt.getStorageSync(r));(!t.expire||Date.now()-t.timestamp<=t.expire)&&e.push(r.replace(this.config.prefix,""))}}),e}catch(e){return console.error("Storage keys error:",e),[]}}static new(e){return new Storage(e)}}const src_Storage=Storage;for(var __rspack_i in exports.Storage=__webpack_exports__.Storage,__webpack_exports__)-1===["Storage"].indexOf(__rspack_i)&&(exports[__rspack_i]=__webpack_exports__[__rspack_i]);Object.defineProperty(exports,"__esModule",{value:!0});
@@ -0,0 +1 @@
1
+ export { default as Storage } from "./Storage.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{Logger as e}from"@ad-execute-manager/logger";class t{constructor(t={}){this.config={prefix:"storage_",expire:null,...t},this.logger=new e({prefix:"Storage"})}getTodayEndTimestamp(){let e=new Date;return new Date(e.getFullYear(),e.getMonth(),e.getDate(),23,59,59,999).getTime()}_setItem(e,t,r){let o=void 0!==r?r:this.config.expire;"today"===o&&(o=this.getTodayEndTimestamp()-Date.now());let i={value:t,expire:o,timestamp:Date.now()};try{tt.setStorageSync(e,JSON.stringify(i))}catch(e){console.error("Storage setItem error:",e)}}_getItem(e){try{let t=tt.getStorageSync(e);if(!t)return null;let r=JSON.parse(t);if(r.expire&&Date.now()-r.timestamp>r.expire)return this.removeItem(e),null;return r.value}catch(e){return console.error("Storage getItem error:",e),null}}setItem(e,t,r){let o=this.config.prefix+e;return this._setItem(o,t,r)}getItem(e){let t=this.config.prefix+e;return this._getItem(t)}getUserItem(e){let t=this.config.userId??"null";if("null"===t)return this.logger.error("userId is required"),null;let r=`${this.config.prefix}_${t}_${e}`;return this._getItem(r)}setUserItem(e,t,r){let o=this.config.userId??"null";if("null"===o)return void this.logger.error("userId is required");let i=`${this.config.prefix}_${o}_${e}`;return this._setItem(i,t,r)}removeItem(e){try{tt.removeStorageSync(e)}catch(e){console.error("Storage removeItem error:",e)}}clear(){try{tt.clearStorageSync()}catch(e){console.error("Storage clear error:",e)}}keys(){try{let e=[];return(tt.getStorageInfoSync().keys??[]).forEach(t=>{if(t.startsWith(this.config.prefix)){let r=JSON.parse(tt.getStorageSync(t));(!r.expire||Date.now()-r.timestamp<=r.expire)&&e.push(t.replace(this.config.prefix,""))}}),e}catch(e){return console.error("Storage keys error:",e),[]}}static new(e){return new t(e)}}let r=t;export{r as Storage};
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@ad-execute-manager/storage",
3
+ "version": "2.0.1",
4
+ "description": "A flexible storage utility for JavaScript applications with expiration support, user-specific storage, and customizable prefixes.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "import": "./dist/index.js",
9
+ "require": "./dist/index.cjs",
10
+ "types": "./dist/index.d.ts"
11
+ }
12
+ },
13
+ "main": "./dist/index.cjs",
14
+ "types": "./dist/index.d.ts",
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "author": {
19
+ "name": "singcl",
20
+ "email": "iambabyer@gmail.com",
21
+ "url": "https://github.com/singcl"
22
+ },
23
+ "license": "MIT",
24
+ "homepage": "https://npmjs.com/package/@ad-execute-manager/storage",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/singcl/ad-execute-manager.git",
28
+ "directory": "packages/storage"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/singcl/ad-execute-manager/issues"
32
+ },
33
+ "engines": {
34
+ "node": ">=14.0.0"
35
+ },
36
+ "keywords": [
37
+ "storage",
38
+ "localstorage",
39
+ "expiration",
40
+ "user-storage",
41
+ "javascript",
42
+ "nodejs",
43
+ "typescript",
44
+ "prefix",
45
+ "session",
46
+ "cache"
47
+ ],
48
+ "scripts": {
49
+ "build": "rslib build && tsc",
50
+ "dev": "rslib build --watch",
51
+ "format": "prettier --write .",
52
+ "lint": "eslint .",
53
+ "test": "rstest",
54
+ "prepublishOnly": "npm run build"
55
+ },
56
+ "peerDependencies": {
57
+ "@ad-execute-manager/logger": "^2.0.1"
58
+ },
59
+ "devDependencies": {
60
+ "@babel/eslint-parser": "^7.28.5",
61
+ "@babel/preset-env": "^7.28.5",
62
+ "@eslint/js": "^9.39.1",
63
+ "@rslib/core": "^0.18.5",
64
+ "@rstest/core": "^0.7.2",
65
+ "eslint": "^9.39.2",
66
+ "eslint-plugin-import": "^2.32.0",
67
+ "globals": "^16.5.0",
68
+ "prettier": "^3.7.3",
69
+ "typescript": "^5.9.3"
70
+ }
71
+ }