schema-storage 0.1.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/LICENSE +22 -0
- package/README.md +258 -0
- package/dist/drivers.d.ts +12 -0
- package/dist/drivers.d.ts.map +1 -0
- package/dist/drivers.js +30 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/storage.d.ts +11 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +113 -0
- package/dist/types.d.ts +27 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/dist/validation.d.ts +12 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +70 -0
- package/package.json +37 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024
|
|
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.
|
|
22
|
+
|
package/README.md
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
# schema-storage
|
|
2
|
+
|
|
3
|
+
TypeScript-first wrapper around localStorage that provides typed keys, schema validation, and automatic data migrations — so persisted client-side data never breaks your app.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install schema-storage zod
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { createStorage } from "schema-storage";
|
|
15
|
+
import { z } from "zod";
|
|
16
|
+
|
|
17
|
+
const storage = createStorage({
|
|
18
|
+
user: z.object({
|
|
19
|
+
id: z.string(),
|
|
20
|
+
email: z.string().email(),
|
|
21
|
+
}),
|
|
22
|
+
theme: z.enum(["light", "dark"]),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
// Fully typed!
|
|
26
|
+
storage.set("theme", "dark"); // ✅
|
|
27
|
+
storage.set("theme", "blue"); // ❌ Type error
|
|
28
|
+
|
|
29
|
+
const user = storage.get("user"); // { id: string; email: string } | null
|
|
30
|
+
const theme = storage.getOrDefault("theme", "light"); // "light" | "dark"
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Features
|
|
34
|
+
|
|
35
|
+
### 1. Typed Keys
|
|
36
|
+
|
|
37
|
+
No more magic strings. All keys are typed and autocompleted.
|
|
38
|
+
|
|
39
|
+
```typescript
|
|
40
|
+
const storage = createStorage({
|
|
41
|
+
settings: z.object({
|
|
42
|
+
language: z.string(),
|
|
43
|
+
notifications: z.boolean(),
|
|
44
|
+
}),
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
storage.get("settings"); // Typed return
|
|
48
|
+
storage.get("unknown"); // ❌ Type error
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### 2. Schema Validation
|
|
52
|
+
|
|
53
|
+
Every read operation validates data against your schema. Invalid or corrupted data is safely rejected.
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
const storage = createStorage({
|
|
57
|
+
count: z.number(),
|
|
58
|
+
}, {
|
|
59
|
+
onInvalid: "reset", // or "throw" | "ignore"
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// If localStorage contains invalid JSON or wrong shape:
|
|
63
|
+
const count = storage.get("count"); // null (or throws if onInvalid: "throw")
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### 3. Versioned Migrations
|
|
67
|
+
|
|
68
|
+
Safely evolve your data models without breaking existing users.
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
const storage = createStorage({
|
|
72
|
+
user: {
|
|
73
|
+
version: 2,
|
|
74
|
+
schema: z.object({
|
|
75
|
+
id: z.string(),
|
|
76
|
+
email: z.string().email(),
|
|
77
|
+
name: z.string(),
|
|
78
|
+
}),
|
|
79
|
+
migrate: {
|
|
80
|
+
1: (oldData) => ({
|
|
81
|
+
id: oldData.id,
|
|
82
|
+
email: "unknown@example.com",
|
|
83
|
+
name: "User",
|
|
84
|
+
}),
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
When `get("user")` is called:
|
|
91
|
+
1. Detects stored version (1)
|
|
92
|
+
2. Applies migration from 1 → 2
|
|
93
|
+
3. Validates final result
|
|
94
|
+
4. Persists upgraded version automatically
|
|
95
|
+
|
|
96
|
+
### 4. Storage-Agnostic
|
|
97
|
+
|
|
98
|
+
Use any storage backend with the same API.
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
import { createStorage, MemoryStorage } from "schema-storage";
|
|
102
|
+
|
|
103
|
+
// Default: localStorage
|
|
104
|
+
const storage1 = createStorage({ ... });
|
|
105
|
+
|
|
106
|
+
// sessionStorage
|
|
107
|
+
const storage2 = createStorage({ ... }, { driver: sessionStorage });
|
|
108
|
+
|
|
109
|
+
// Memory (SSR-safe, testing)
|
|
110
|
+
const storage3 = createStorage({ ... }, { driver: new MemoryStorage() });
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## API
|
|
114
|
+
|
|
115
|
+
### `createStorage<T>(schema, options?)`
|
|
116
|
+
|
|
117
|
+
Creates a typed storage instance.
|
|
118
|
+
|
|
119
|
+
**Parameters:**
|
|
120
|
+
- `schema`: Object mapping keys to Zod schemas or versioned schemas
|
|
121
|
+
- `options`:
|
|
122
|
+
- `driver?: StorageDriver` - Storage backend (default: localStorage)
|
|
123
|
+
- `onInvalid?: "throw" | "reset" | "ignore"` - Behavior for invalid data (default: "ignore")
|
|
124
|
+
- `prefix?: string` - Key prefix for namespacing
|
|
125
|
+
|
|
126
|
+
**Returns:** `SafeStorage<T>`
|
|
127
|
+
|
|
128
|
+
### Storage Methods
|
|
129
|
+
|
|
130
|
+
#### `get<K>(key: K): T[K] | null`
|
|
131
|
+
|
|
132
|
+
Reads and validates a value. Returns `null` if missing or invalid.
|
|
133
|
+
|
|
134
|
+
#### `set<K>(key: K, value: T[K]): void`
|
|
135
|
+
|
|
136
|
+
Writes a value with validation. Throws if validation fails and `onInvalid: "throw"`.
|
|
137
|
+
|
|
138
|
+
#### `remove(key: keyof T): void`
|
|
139
|
+
|
|
140
|
+
Removes a key and its metadata.
|
|
141
|
+
|
|
142
|
+
#### `clear(): void`
|
|
143
|
+
|
|
144
|
+
Clears all storage (or all prefixed keys if using a prefix).
|
|
145
|
+
|
|
146
|
+
#### `has(key: keyof T): boolean`
|
|
147
|
+
|
|
148
|
+
Checks if a key exists.
|
|
149
|
+
|
|
150
|
+
#### `getOrDefault<K>(key: K, defaultValue: T[K]): T[K]`
|
|
151
|
+
|
|
152
|
+
Gets a value or returns the default if missing/invalid.
|
|
153
|
+
|
|
154
|
+
## Examples
|
|
155
|
+
|
|
156
|
+
### Basic Usage
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
import { createStorage } from "schema-storage";
|
|
160
|
+
import { z } from "zod";
|
|
161
|
+
|
|
162
|
+
const storage = createStorage({
|
|
163
|
+
todos: z.array(z.object({
|
|
164
|
+
id: z.string(),
|
|
165
|
+
text: z.string(),
|
|
166
|
+
completed: z.boolean(),
|
|
167
|
+
})),
|
|
168
|
+
filter: z.enum(["all", "active", "completed"]),
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
storage.set("todos", [
|
|
172
|
+
{ id: "1", text: "Learn schema-storage", completed: false },
|
|
173
|
+
]);
|
|
174
|
+
|
|
175
|
+
const todos = storage.get("todos"); // Fully typed!
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### With Migrations
|
|
179
|
+
|
|
180
|
+
```typescript
|
|
181
|
+
const storage = createStorage({
|
|
182
|
+
preferences: {
|
|
183
|
+
version: 3,
|
|
184
|
+
schema: z.object({
|
|
185
|
+
theme: z.enum(["light", "dark", "auto"]),
|
|
186
|
+
fontSize: z.number().min(12).max(24),
|
|
187
|
+
language: z.string(),
|
|
188
|
+
}),
|
|
189
|
+
migrate: {
|
|
190
|
+
1: (old) => ({
|
|
191
|
+
theme: old.theme ?? "light",
|
|
192
|
+
fontSize: 16,
|
|
193
|
+
language: "en",
|
|
194
|
+
}),
|
|
195
|
+
2: (old) => ({
|
|
196
|
+
...old,
|
|
197
|
+
theme: old.theme === "system" ? "auto" : old.theme,
|
|
198
|
+
}),
|
|
199
|
+
},
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
### Custom Storage Driver
|
|
205
|
+
|
|
206
|
+
```typescript
|
|
207
|
+
import { createStorage, type StorageDriver } from "schema-storage";
|
|
208
|
+
|
|
209
|
+
class CustomStorage implements StorageDriver {
|
|
210
|
+
private data = new Map<string, string>();
|
|
211
|
+
|
|
212
|
+
getItem(key: string): string | null {
|
|
213
|
+
return this.data.get(key) ?? null;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
setItem(key: string, value: string): void {
|
|
217
|
+
this.data.set(key, value);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
removeItem(key: string): void {
|
|
221
|
+
this.data.delete(key);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
clear(): void {
|
|
225
|
+
this.data.clear();
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
key(index: number): string | null {
|
|
229
|
+
return Array.from(this.data.keys())[index] ?? null;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
get length(): number {
|
|
233
|
+
return this.data.size;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const storage = createStorage({ ... }, { driver: new CustomStorage() });
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
## Why schema-storage?
|
|
241
|
+
|
|
242
|
+
**localStorage problems:**
|
|
243
|
+
- Everything is a string (manual JSON parsing)
|
|
244
|
+
- No type safety
|
|
245
|
+
- No validation
|
|
246
|
+
- No migration strategy
|
|
247
|
+
|
|
248
|
+
**schema-storage solves:**
|
|
249
|
+
- ✅ Typed keys with autocomplete
|
|
250
|
+
- ✅ Automatic JSON handling
|
|
251
|
+
- ✅ Runtime validation with Zod
|
|
252
|
+
- ✅ Versioned migrations
|
|
253
|
+
- ✅ Storage-agnostic design
|
|
254
|
+
|
|
255
|
+
## License
|
|
256
|
+
|
|
257
|
+
MIT
|
|
258
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { StorageDriver } from "./types";
|
|
2
|
+
export declare class MemoryStorage implements StorageDriver {
|
|
3
|
+
private store;
|
|
4
|
+
getItem(key: string): string | null;
|
|
5
|
+
setItem(key: string, value: string): void;
|
|
6
|
+
removeItem(key: string): void;
|
|
7
|
+
clear(): void;
|
|
8
|
+
key(index: number): string | null;
|
|
9
|
+
get length(): number;
|
|
10
|
+
}
|
|
11
|
+
export declare function getDefaultDriver(): StorageDriver;
|
|
12
|
+
//# sourceMappingURL=drivers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"drivers.d.ts","sourceRoot":"","sources":["../src/drivers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAExC,qBAAa,aAAc,YAAW,aAAa;IACjD,OAAO,CAAC,KAAK,CAAkC;IAE/C,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;IAInC,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAIzC,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAI7B,KAAK,IAAI,IAAI;IAIb,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;IAKjC,IAAI,MAAM,IAAI,MAAM,CAEnB;CACF;AAED,wBAAgB,gBAAgB,IAAI,aAAa,CAKhD"}
|
package/dist/drivers.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export class MemoryStorage {
|
|
2
|
+
constructor() {
|
|
3
|
+
this.store = new Map();
|
|
4
|
+
}
|
|
5
|
+
getItem(key) {
|
|
6
|
+
return this.store.get(key) ?? null;
|
|
7
|
+
}
|
|
8
|
+
setItem(key, value) {
|
|
9
|
+
this.store.set(key, value);
|
|
10
|
+
}
|
|
11
|
+
removeItem(key) {
|
|
12
|
+
this.store.delete(key);
|
|
13
|
+
}
|
|
14
|
+
clear() {
|
|
15
|
+
this.store.clear();
|
|
16
|
+
}
|
|
17
|
+
key(index) {
|
|
18
|
+
const keys = Array.from(this.store.keys());
|
|
19
|
+
return keys[index] ?? null;
|
|
20
|
+
}
|
|
21
|
+
get length() {
|
|
22
|
+
return this.store.size;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export function getDefaultDriver() {
|
|
26
|
+
if (typeof window !== "undefined" && window.localStorage) {
|
|
27
|
+
return window.localStorage;
|
|
28
|
+
}
|
|
29
|
+
return new MemoryStorage();
|
|
30
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,KAAK,aAAa,EAAE,KAAK,gBAAgB,EAAE,KAAK,cAAc,EAAE,MAAM,SAAS,CAAC;AACzF,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { SchemaDefinition, StorageOptions } from "./types";
|
|
2
|
+
export interface SafeStorage<T extends Record<string, unknown>> {
|
|
3
|
+
get<K extends keyof T>(key: K): T[K] | null;
|
|
4
|
+
set<K extends keyof T>(key: K, value: T[K]): void;
|
|
5
|
+
remove(key: keyof T): void;
|
|
6
|
+
clear(): void;
|
|
7
|
+
has(key: keyof T): boolean;
|
|
8
|
+
getOrDefault<K extends keyof T>(key: K, defaultValue: T[K]): T[K];
|
|
9
|
+
}
|
|
10
|
+
export declare function createStorage<T extends Record<string, unknown>>(schema: SchemaDefinition<T>, options?: StorageOptions): SafeStorage<T>;
|
|
11
|
+
//# sourceMappingURL=storage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,gBAAgB,EAChB,cAAc,EAEf,MAAM,SAAS,CAAC;AASjB,MAAM,WAAW,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC5D,GAAG,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAC5C,GAAG,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAClD,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,GAAG,IAAI,CAAC;IAC3B,KAAK,IAAI,IAAI,CAAC;IACd,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC;IAC3B,YAAY,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;CACnE;AAQD,wBAAgB,aAAa,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7D,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC,EAC3B,OAAO,GAAE,cAAmB,GAC3B,WAAW,CAAC,CAAC,CAAC,CAmIhB"}
|
package/dist/storage.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { getDefaultDriver } from "./drivers";
|
|
2
|
+
import { parseStoredValue, serializeValue, serializeMetadata, getMetadataKey, } from "./validation";
|
|
3
|
+
function isVersioned(schema) {
|
|
4
|
+
return typeof schema === "object" && "version" in schema && "schema" in schema;
|
|
5
|
+
}
|
|
6
|
+
export function createStorage(schema, options = {}) {
|
|
7
|
+
const driver = options.driver ?? getDefaultDriver();
|
|
8
|
+
const onInvalid = options.onInvalid ?? "ignore";
|
|
9
|
+
const prefix = options.prefix ?? "";
|
|
10
|
+
function getStorageKey(key) {
|
|
11
|
+
return prefix ? `${prefix}:${key}` : key;
|
|
12
|
+
}
|
|
13
|
+
function get(key) {
|
|
14
|
+
const storageKey = getStorageKey(String(key));
|
|
15
|
+
const raw = driver.getItem(storageKey);
|
|
16
|
+
const schemaDef = schema[key];
|
|
17
|
+
if (!schemaDef) {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
const metadataKey = getMetadataKey(storageKey);
|
|
21
|
+
const result = parseStoredValue(raw, schemaDef, metadataKey, driver);
|
|
22
|
+
if (result.value === null && onInvalid === "throw") {
|
|
23
|
+
throw new Error(`Invalid or missing data for key: ${String(key)}`);
|
|
24
|
+
}
|
|
25
|
+
if (result.needsWrite && result.value !== null) {
|
|
26
|
+
const serialized = serializeValue(result.value);
|
|
27
|
+
driver.setItem(storageKey, serialized);
|
|
28
|
+
if (isVersioned(schemaDef)) {
|
|
29
|
+
const metadataSerialized = serializeMetadata(schemaDef.version);
|
|
30
|
+
driver.setItem(metadataKey, metadataSerialized);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return result.value;
|
|
34
|
+
}
|
|
35
|
+
function set(key, value) {
|
|
36
|
+
const storageKey = getStorageKey(String(key));
|
|
37
|
+
const schemaDef = schema[key];
|
|
38
|
+
if (!schemaDef) {
|
|
39
|
+
throw new Error(`Unknown key: ${String(key)}`);
|
|
40
|
+
}
|
|
41
|
+
let actualSchema;
|
|
42
|
+
if (isVersioned(schemaDef)) {
|
|
43
|
+
actualSchema = schemaDef.schema;
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
actualSchema = schemaDef;
|
|
47
|
+
}
|
|
48
|
+
const validated = actualSchema.safeParse(value);
|
|
49
|
+
if (!validated.success) {
|
|
50
|
+
if (onInvalid === "throw") {
|
|
51
|
+
throw new Error(`Validation failed for key ${String(key)}: ${validated.error.message}`);
|
|
52
|
+
}
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const serialized = serializeValue(validated.data);
|
|
56
|
+
driver.setItem(storageKey, serialized);
|
|
57
|
+
if (isVersioned(schemaDef)) {
|
|
58
|
+
const metadataSerialized = serializeMetadata(schemaDef.version);
|
|
59
|
+
const metadataKey = getMetadataKey(storageKey);
|
|
60
|
+
driver.setItem(metadataKey, metadataSerialized);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function remove(key) {
|
|
64
|
+
const storageKey = getStorageKey(String(key));
|
|
65
|
+
driver.removeItem(storageKey);
|
|
66
|
+
const metadataKey = getMetadataKey(storageKey);
|
|
67
|
+
driver.removeItem(metadataKey);
|
|
68
|
+
}
|
|
69
|
+
function clear() {
|
|
70
|
+
if (prefix) {
|
|
71
|
+
const keysToRemove = [];
|
|
72
|
+
const prefixWithColon = `${prefix}:`;
|
|
73
|
+
const metadataPrefix = getMetadataKey(prefixWithColon);
|
|
74
|
+
for (let i = 0; i < driver.length; i++) {
|
|
75
|
+
const key = driver.key(i);
|
|
76
|
+
if (key) {
|
|
77
|
+
if (key.startsWith(prefixWithColon) || key.startsWith(metadataPrefix)) {
|
|
78
|
+
keysToRemove.push(key);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
keysToRemove.forEach((key) => driver.removeItem(key));
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
const keysToRemove = [];
|
|
86
|
+
const metadataPrefix = getMetadataKey("");
|
|
87
|
+
for (let i = 0; i < driver.length; i++) {
|
|
88
|
+
const key = driver.key(i);
|
|
89
|
+
if (key && key.startsWith(metadataPrefix)) {
|
|
90
|
+
keysToRemove.push(key);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
keysToRemove.forEach((key) => driver.removeItem(key));
|
|
94
|
+
driver.clear();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function has(key) {
|
|
98
|
+
const storageKey = getStorageKey(String(key));
|
|
99
|
+
return driver.getItem(storageKey) !== null;
|
|
100
|
+
}
|
|
101
|
+
function getOrDefault(key, defaultValue) {
|
|
102
|
+
const value = get(key);
|
|
103
|
+
return value !== null ? value : defaultValue;
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
get,
|
|
107
|
+
set,
|
|
108
|
+
remove,
|
|
109
|
+
clear,
|
|
110
|
+
has,
|
|
111
|
+
getOrDefault,
|
|
112
|
+
};
|
|
113
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export interface StorageDriver {
|
|
3
|
+
getItem(key: string): string | null;
|
|
4
|
+
setItem(key: string, value: string): void;
|
|
5
|
+
removeItem(key: string): void;
|
|
6
|
+
clear(): void;
|
|
7
|
+
key(index: number): string | null;
|
|
8
|
+
readonly length: number;
|
|
9
|
+
}
|
|
10
|
+
export interface VersionedSchema<T> {
|
|
11
|
+
version: number;
|
|
12
|
+
schema: z.ZodType<T>;
|
|
13
|
+
migrate?: Record<number, (data: unknown) => T>;
|
|
14
|
+
}
|
|
15
|
+
export type SchemaDefinition<T extends Record<string, unknown>> = {
|
|
16
|
+
[K in keyof T]: z.ZodType<T[K]> | VersionedSchema<T[K]>;
|
|
17
|
+
};
|
|
18
|
+
export interface StorageOptions {
|
|
19
|
+
driver?: StorageDriver;
|
|
20
|
+
onInvalid?: "throw" | "reset" | "ignore";
|
|
21
|
+
prefix?: string;
|
|
22
|
+
}
|
|
23
|
+
export interface StorageMetadata {
|
|
24
|
+
version: number;
|
|
25
|
+
data: unknown;
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,MAAM,WAAW,aAAa;IAC5B,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;IACpC,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1C,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,KAAK,IAAI,IAAI,CAAC;IACd,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;IAClC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,eAAe,CAAC,CAAC;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC;CAChD;AAED,MAAM,MAAM,gBAAgB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI;KAC/D,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CACxD,CAAC;AAEF,MAAM,WAAW,cAAc;IAC7B,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB,SAAS,CAAC,EAAE,OAAO,GAAG,OAAO,GAAG,QAAQ,CAAC;IACzC,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,OAAO,CAAC;CACf"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { VersionedSchema } from "./types";
|
|
3
|
+
export declare function getMetadataKey(key: string): string;
|
|
4
|
+
export declare function parseStoredValue<T>(raw: string | null, schema: z.ZodType<T> | VersionedSchema<T>, metadataKey: string, driver: {
|
|
5
|
+
getItem(key: string): string | null;
|
|
6
|
+
}): {
|
|
7
|
+
value: T | null;
|
|
8
|
+
needsWrite: boolean;
|
|
9
|
+
};
|
|
10
|
+
export declare function serializeValue<T>(value: T): string;
|
|
11
|
+
export declare function serializeMetadata(version: number): string;
|
|
12
|
+
//# sourceMappingURL=validation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,eAAe,EAAmB,MAAM,SAAS,CAAC;AAI3D,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAgB,gBAAgB,CAAC,CAAC,EAChC,GAAG,EAAE,MAAM,GAAG,IAAI,EAClB,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,EACzC,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE;IAAE,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAA;CAAE,GAC9C;IAAE,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC;IAAC,UAAU,EAAE,OAAO,CAAA;CAAE,CAqD1C;AAsBD,wBAAgB,cAAc,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,CAElD;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAGzD"}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
const METADATA_PREFIX = "__safe_storage_meta__";
|
|
2
|
+
export function getMetadataKey(key) {
|
|
3
|
+
return `${METADATA_PREFIX}${key}`;
|
|
4
|
+
}
|
|
5
|
+
export function parseStoredValue(raw, schema, metadataKey, driver) {
|
|
6
|
+
if (raw === null) {
|
|
7
|
+
return { value: null, needsWrite: false };
|
|
8
|
+
}
|
|
9
|
+
let parsed;
|
|
10
|
+
try {
|
|
11
|
+
parsed = JSON.parse(raw);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return { value: null, needsWrite: false };
|
|
15
|
+
}
|
|
16
|
+
const isVersioned = (s) => {
|
|
17
|
+
return typeof s === "object" && "version" in s && "schema" in s;
|
|
18
|
+
};
|
|
19
|
+
if (isVersioned(schema)) {
|
|
20
|
+
const metadataRaw = driver.getItem(metadataKey);
|
|
21
|
+
let storedVersion = 1;
|
|
22
|
+
if (metadataRaw) {
|
|
23
|
+
try {
|
|
24
|
+
const metadata = JSON.parse(metadataRaw);
|
|
25
|
+
storedVersion = metadata.version;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
storedVersion = 1;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (storedVersion < schema.version) {
|
|
32
|
+
const migrated = migrateData(parsed, storedVersion, schema);
|
|
33
|
+
const validated = schema.schema.safeParse(migrated);
|
|
34
|
+
if (validated.success) {
|
|
35
|
+
return { value: validated.data, needsWrite: true };
|
|
36
|
+
}
|
|
37
|
+
return { value: null, needsWrite: false };
|
|
38
|
+
}
|
|
39
|
+
const validated = schema.schema.safeParse(parsed);
|
|
40
|
+
if (validated.success) {
|
|
41
|
+
return { value: validated.data, needsWrite: false };
|
|
42
|
+
}
|
|
43
|
+
return { value: null, needsWrite: false };
|
|
44
|
+
}
|
|
45
|
+
const validated = schema.safeParse(parsed);
|
|
46
|
+
if (validated.success) {
|
|
47
|
+
return { value: validated.data, needsWrite: false };
|
|
48
|
+
}
|
|
49
|
+
return { value: null, needsWrite: false };
|
|
50
|
+
}
|
|
51
|
+
function migrateData(data, fromVersion, schema) {
|
|
52
|
+
let current = data;
|
|
53
|
+
let currentVersion = fromVersion;
|
|
54
|
+
while (currentVersion < schema.version && schema.migrate) {
|
|
55
|
+
const migration = schema.migrate[currentVersion];
|
|
56
|
+
if (!migration) {
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
current = migration(current);
|
|
60
|
+
currentVersion++;
|
|
61
|
+
}
|
|
62
|
+
return current;
|
|
63
|
+
}
|
|
64
|
+
export function serializeValue(value) {
|
|
65
|
+
return JSON.stringify(value);
|
|
66
|
+
}
|
|
67
|
+
export function serializeMetadata(version) {
|
|
68
|
+
const metadata = { version, data: null };
|
|
69
|
+
return JSON.stringify(metadata);
|
|
70
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "schema-storage",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "TypeScript-first localStorage wrapper with typed keys, schema validation, and automatic migrations",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist"
|
|
9
|
+
],
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "tsc",
|
|
12
|
+
"prepublishOnly": "npm run build"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"localStorage",
|
|
16
|
+
"storage",
|
|
17
|
+
"typescript",
|
|
18
|
+
"validation",
|
|
19
|
+
"migration",
|
|
20
|
+
"schema",
|
|
21
|
+
"zod"
|
|
22
|
+
],
|
|
23
|
+
"author": "Justinkarso",
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "https://github.com/Justinkarso/schema-storage"
|
|
28
|
+
},
|
|
29
|
+
"peerDependencies": {
|
|
30
|
+
"zod": "^4.2.1"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@types/node": "^25.0.3",
|
|
34
|
+
"typescript": "^5.9.3",
|
|
35
|
+
"zod": "^4.2.1"
|
|
36
|
+
}
|
|
37
|
+
}
|