dex-jstore 1.1.10

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/LICENCE ADDED
@@ -0,0 +1,8 @@
1
+
2
+ MIT © Lavender Incognito
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/lib/index.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ import type { FilterFn, JstoreEventName, JstoreListener, JsonObject, JsonValue, LoadOptions, MapFn, Result, Transaction, Validator } from "./types.js";
2
+ export declare class Jstore {
3
+ #private;
4
+ constructor(fp: string, options?: LoadOptions);
5
+ get filePath(): string;
6
+ close(): void;
7
+ reload(): void;
8
+ all(): JsonObject;
9
+ clear(): void;
10
+ get size(): number;
11
+ on<E extends JstoreEventName>(event: E, listener: JstoreListener<E>): this;
12
+ once<E extends JstoreEventName>(event: E, listener: JstoreListener<E>): this;
13
+ off<E extends JstoreEventName>(event: E, listener: JstoreListener<E>): this;
14
+ addValidator<T extends JsonValue>(key: string, validator: Validator<T>): this;
15
+ removeValidator(key: string): this;
16
+ get<T extends JsonValue = JsonValue>(key: string): T | undefined;
17
+ tryGet<T extends JsonValue = JsonValue>(key: string): Result<T>;
18
+ set(key: string, value: JsonValue): this;
19
+ setIfAbsent(key: string, value: JsonValue): boolean;
20
+ has(key: string): boolean;
21
+ del(key: string): boolean;
22
+ rename(from: string, to: string): boolean;
23
+ bool(key: string): boolean;
24
+ toggle(key: string): boolean;
25
+ increment(key: string, amount?: number): number;
26
+ decrement(key: string, amount?: number): number;
27
+ push(key: string, ...values: JsonValue[]): this;
28
+ pull(key: string, predicate: (item: JsonValue) => boolean): this;
29
+ merge(key: string, value: JsonObject): this;
30
+ forEach(fn: (value: JsonValue, key: string) => void): void;
31
+ filter<T extends JsonValue>(predicate: FilterFn<T>): JsonObject;
32
+ map<T extends JsonValue, R extends JsonValue>(fn: MapFn<T, R>): JsonObject;
33
+ findKeys(predicate: FilterFn): string[];
34
+ getPath<T extends JsonValue = JsonValue>(dotPath: string): T | undefined;
35
+ tryGetPath<T extends JsonValue = JsonValue>(dotPath: string): Result<T>;
36
+ setPath(dotPath: string, value: JsonValue): this;
37
+ hasPath(dotPath: string): boolean;
38
+ delPath(dotPath: string): boolean;
39
+ mergePath(dotPath: string, value: JsonObject): this;
40
+ boolPath(dotPath: string): boolean;
41
+ togglePath(dotPath: string): boolean;
42
+ incrementPath(dotPath: string, amount?: number): number;
43
+ pushPath(dotPath: string, ...values: JsonValue[]): this;
44
+ transaction(): Transaction;
45
+ toJSON(indent?: number): string;
46
+ fromJSON(raw: string): this;
47
+ absorb(other: Jstore, overwrite?: boolean): this;
48
+ }
49
+ export { ok, err } from "./types.js";
50
+ export type { AllowedSeparators, FilterFn, JstoreEventMap, JstoreEventName, JstoreListener, JsonArray, JsonObject, JsonValue, JsonPrimitive, LoadOptions, MapFn, Result, SchemaMap, Transaction, Validator, } from "./types.js";
package/lib/index.js ADDED
@@ -0,0 +1,396 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { EventEmitter } from "node:events";
4
+ import { err, ok } from "./types.js";
5
+ function isObject(v) {
6
+ return v !== null && typeof v === "object" && !Array.isArray(v);
7
+ }
8
+ function deepClone(v) {
9
+ return JSON.parse(JSON.stringify(v));
10
+ }
11
+ function deepMerge(target, source) {
12
+ const result = { ...target };
13
+ for (const key of Object.keys(source)) {
14
+ if (isObject(source[key]) && isObject(target[key])) {
15
+ result[key] = deepMerge(target[key], source[key]);
16
+ }
17
+ else {
18
+ result[key] = source[key];
19
+ }
20
+ }
21
+ return result;
22
+ }
23
+ export class Jstore {
24
+ #fp;
25
+ #sep;
26
+ #createOnMissing;
27
+ #indent;
28
+ #encode;
29
+ #emitter;
30
+ #schema;
31
+ #data;
32
+ #watcher = null;
33
+ constructor(fp, options = {}) {
34
+ this.#fp = path.resolve(fp);
35
+ this.#sep = options.separator ?? ".";
36
+ this.#createOnMissing = options.createOnMissing ?? true;
37
+ this.#indent = options.indent ?? 2;
38
+ this.#encode = options.encode ?? false;
39
+ this.#emitter = new EventEmitter();
40
+ this.#schema = {};
41
+ this.#data = this.#loadFile();
42
+ if (options.watch)
43
+ this.#startWatcher();
44
+ }
45
+ #loadFile() {
46
+ if (!fs.existsSync(this.#fp)) {
47
+ if (!this.#createOnMissing) {
48
+ throw new Error(`[jstore] File not found: ${this.#fp}`);
49
+ }
50
+ fs.mkdirSync(path.dirname(this.#fp), { recursive: true });
51
+ fs.writeFileSync(this.#fp, this.#encode ? btoa("{}") : "{}", "utf-8");
52
+ return {};
53
+ }
54
+ const raw = fs.readFileSync(this.#fp, "utf-8").trim();
55
+ try {
56
+ return JSON.parse(this.#encode ? atob(raw) : raw);
57
+ }
58
+ catch {
59
+ this.#emit("error", { message: `Failed to parse JSON at ${this.#fp}` });
60
+ throw new Error(`[jstore] Invalid JSON in file: ${this.#fp}`);
61
+ }
62
+ }
63
+ #save() {
64
+ const content = JSON.stringify(this.#data, null, this.#indent);
65
+ fs.writeFileSync(this.#fp, this.#encode ? btoa(content) : content, "utf-8");
66
+ this.#emit("save", {});
67
+ }
68
+ #resolvePath(dotPath) {
69
+ if (!dotPath)
70
+ throw new Error("[jstore] Path must be a non-empty string");
71
+ return dotPath.split(this.#sep);
72
+ }
73
+ #emit(event, payload) {
74
+ this.#emitter.emit(event, payload);
75
+ }
76
+ #startWatcher() {
77
+ this.#watcher = fs.watch(this.#fp, () => {
78
+ try {
79
+ this.#data = this.#loadFile();
80
+ this.#emit("reload", {});
81
+ }
82
+ catch {
83
+ }
84
+ });
85
+ this.#watcher.unref();
86
+ }
87
+ get filePath() {
88
+ return this.#fp;
89
+ }
90
+ close() {
91
+ this.#watcher?.close();
92
+ this.#watcher = null;
93
+ }
94
+ reload() {
95
+ this.#data = this.#loadFile();
96
+ this.#emit("reload", {});
97
+ }
98
+ all() {
99
+ return deepClone(this.#data);
100
+ }
101
+ clear() {
102
+ this.#data = {};
103
+ this.#save();
104
+ this.#emit("clear", {});
105
+ }
106
+ get size() {
107
+ return Object.keys(this.#data).length;
108
+ }
109
+ on(event, listener) {
110
+ this.#emitter.on(event, listener);
111
+ return this;
112
+ }
113
+ once(event, listener) {
114
+ this.#emitter.once(event, listener);
115
+ return this;
116
+ }
117
+ off(event, listener) {
118
+ this.#emitter.off(event, listener);
119
+ return this;
120
+ }
121
+ addValidator(key, validator) {
122
+ this.#schema[key] = validator;
123
+ return this;
124
+ }
125
+ removeValidator(key) {
126
+ delete this.#schema[key];
127
+ return this;
128
+ }
129
+ get(key) {
130
+ const val = this.#data[key];
131
+ return val !== undefined ? deepClone(val) : undefined;
132
+ }
133
+ tryGet(key) {
134
+ const val = this.get(key);
135
+ return val !== undefined
136
+ ? ok(val)
137
+ : err(`Key "${key}" not found`);
138
+ }
139
+ set(key, value) {
140
+ const validator = this.#schema[key];
141
+ if (validator && !validator(value)) {
142
+ throw new Error(`[jstore] Validation failed for key "${key}"`);
143
+ }
144
+ this.#data[key] = deepClone(value);
145
+ this.#save();
146
+ this.#emit("set", { key, value });
147
+ return this;
148
+ }
149
+ setIfAbsent(key, value) {
150
+ if (this.has(key))
151
+ return false;
152
+ this.set(key, value);
153
+ return true;
154
+ }
155
+ has(key) {
156
+ return Object.hasOwn(this.#data, key);
157
+ }
158
+ del(key) {
159
+ if (!this.has(key))
160
+ return false;
161
+ delete this.#data[key];
162
+ this.#save();
163
+ this.#emit("del", { key });
164
+ return true;
165
+ }
166
+ rename(from, to) {
167
+ if (!this.has(from))
168
+ return false;
169
+ this.#data[to] = this.#data[from];
170
+ delete this.#data[from];
171
+ this.#save();
172
+ return true;
173
+ }
174
+ bool(key) {
175
+ const val = this.get(key);
176
+ if (typeof val === "boolean")
177
+ return val;
178
+ if (val === 1)
179
+ return true;
180
+ if (val === 0)
181
+ return false;
182
+ throw new Error(`[jstore] bool() expects boolean or 0/1 for key "${key}", got: ${JSON.stringify(val)}`);
183
+ }
184
+ toggle(key) {
185
+ const current = this.bool(key);
186
+ this.set(key, !current);
187
+ return !current;
188
+ }
189
+ increment(key, amount = 1) {
190
+ const current = this.get(key) ?? 0;
191
+ if (typeof current !== "number") {
192
+ throw new Error(`[jstore] increment() requires a numeric value for key "${key}"`);
193
+ }
194
+ const next = current + amount;
195
+ this.set(key, next);
196
+ return next;
197
+ }
198
+ decrement(key, amount = 1) {
199
+ return this.increment(key, -amount);
200
+ }
201
+ push(key, ...values) {
202
+ const current = this.get(key);
203
+ if (current !== undefined && !Array.isArray(current)) {
204
+ throw new Error(`[jstore] push() requires an array value for key "${key}"`);
205
+ }
206
+ this.set(key, [...(current ?? []), ...values]);
207
+ return this;
208
+ }
209
+ pull(key, predicate) {
210
+ const current = this.get(key);
211
+ if (!Array.isArray(current)) {
212
+ throw new Error(`[jstore] pull() requires an array value for key "${key}"`);
213
+ }
214
+ this.set(key, current.filter((item) => !predicate(item)));
215
+ return this;
216
+ }
217
+ merge(key, value) {
218
+ const current = this.get(key) ?? {};
219
+ if (!isObject(current)) {
220
+ throw new Error(`[jstore] merge() requires an object value for key "${key}"`);
221
+ }
222
+ this.set(key, deepMerge(current, value));
223
+ return this;
224
+ }
225
+ forEach(fn) {
226
+ for (const [k, v] of Object.entries(this.#data)) {
227
+ fn(deepClone(v), k);
228
+ }
229
+ }
230
+ filter(predicate) {
231
+ return Object.fromEntries(Object.entries(this.#data).filter(([k, v]) => predicate(v, k)));
232
+ }
233
+ map(fn) {
234
+ return Object.fromEntries(Object.entries(this.#data).map(([k, v]) => [k, fn(v, k)]));
235
+ }
236
+ findKeys(predicate) {
237
+ return Object.keys(this.#data).filter((k) => predicate(this.#data[k], k));
238
+ }
239
+ getPath(dotPath) {
240
+ const keys = this.#resolvePath(dotPath);
241
+ let current = this.#data;
242
+ for (const key of keys) {
243
+ if (!isObject(current))
244
+ return undefined;
245
+ current = current[key];
246
+ if (current === undefined)
247
+ return undefined;
248
+ }
249
+ return deepClone(current);
250
+ }
251
+ tryGetPath(dotPath) {
252
+ const val = this.getPath(dotPath);
253
+ return val !== undefined
254
+ ? ok(val)
255
+ : err(`Path "${dotPath}" not found`);
256
+ }
257
+ setPath(dotPath, value) {
258
+ const keys = this.#resolvePath(dotPath);
259
+ let current = this.#data;
260
+ for (let i = 0; i < keys.length - 1; i++) {
261
+ const key = keys[i];
262
+ if (!isObject(current[key])) {
263
+ current[key] = {};
264
+ }
265
+ current = current[key];
266
+ }
267
+ current[keys.at(-1)] = deepClone(value);
268
+ this.#save();
269
+ this.#emit("setPath", { path: dotPath, value });
270
+ return this;
271
+ }
272
+ hasPath(dotPath) {
273
+ return this.getPath(dotPath) !== undefined;
274
+ }
275
+ delPath(dotPath) {
276
+ const keys = this.#resolvePath(dotPath);
277
+ let current = this.#data;
278
+ for (let i = 0; i < keys.length - 1; i++) {
279
+ if (!isObject(current))
280
+ return false;
281
+ current = current[keys[i]];
282
+ if (current === undefined)
283
+ return false;
284
+ }
285
+ const parent = current;
286
+ const lastKey = keys.at(-1);
287
+ if (!Object.hasOwn(parent, lastKey))
288
+ return false;
289
+ delete parent[lastKey];
290
+ this.#save();
291
+ this.#emit("delPath", { path: dotPath });
292
+ return true;
293
+ }
294
+ mergePath(dotPath, value) {
295
+ const current = this.getPath(dotPath) ?? {};
296
+ if (!isObject(current)) {
297
+ throw new Error(`[jstore] mergePath() requires an object at "${dotPath}"`);
298
+ }
299
+ this.setPath(dotPath, deepMerge(current, value));
300
+ return this;
301
+ }
302
+ boolPath(dotPath) {
303
+ const val = this.getPath(dotPath);
304
+ if (typeof val === "boolean")
305
+ return val;
306
+ if (val === 1)
307
+ return true;
308
+ if (val === 0)
309
+ return false;
310
+ throw new Error(`[jstore] boolPath() expects boolean or 0/1 at "${dotPath}", got: ${JSON.stringify(val)}`);
311
+ }
312
+ togglePath(dotPath) {
313
+ const current = this.boolPath(dotPath);
314
+ this.setPath(dotPath, !current);
315
+ return !current;
316
+ }
317
+ incrementPath(dotPath, amount = 1) {
318
+ const current = this.getPath(dotPath) ?? 0;
319
+ if (typeof current !== "number") {
320
+ throw new Error(`[jstore] incrementPath() requires a numeric value at "${dotPath}"`);
321
+ }
322
+ const next = current + amount;
323
+ this.setPath(dotPath, next);
324
+ return next;
325
+ }
326
+ pushPath(dotPath, ...values) {
327
+ const current = this.getPath(dotPath);
328
+ if (current !== undefined && !Array.isArray(current)) {
329
+ throw new Error(`[jstore] pushPath() requires an array at "${dotPath}"`);
330
+ }
331
+ this.setPath(dotPath, [...(current ?? []), ...values]);
332
+ return this;
333
+ }
334
+ transaction() {
335
+ const snapshot = deepClone(this.#data);
336
+ let draft = deepClone(this.#data);
337
+ const tx = {
338
+ set: (key, value) => {
339
+ draft[key] = deepClone(value);
340
+ return tx;
341
+ },
342
+ del: (key) => {
343
+ delete draft[key];
344
+ return tx;
345
+ },
346
+ setPath: (dotPath, value) => {
347
+ const keys = dotPath.split(this.#sep);
348
+ let current = draft;
349
+ for (let i = 0; i < keys.length - 1; i++) {
350
+ if (!isObject(current[keys[i]]))
351
+ current[keys[i]] = {};
352
+ current = current[keys[i]];
353
+ }
354
+ current[keys.at(-1)] = deepClone(value);
355
+ return tx;
356
+ },
357
+ delPath: (dotPath) => {
358
+ const keys = dotPath.split(this.#sep);
359
+ let current = draft;
360
+ for (let i = 0; i < keys.length - 1; i++) {
361
+ if (!isObject(current))
362
+ return tx;
363
+ current = current[keys[i]];
364
+ }
365
+ if (isObject(current))
366
+ delete current[keys.at(-1)];
367
+ return tx;
368
+ },
369
+ commit: () => {
370
+ this.#data = draft;
371
+ this.#save();
372
+ },
373
+ rollback: () => {
374
+ draft = snapshot;
375
+ },
376
+ };
377
+ return tx;
378
+ }
379
+ toJSON(indent = this.#indent) {
380
+ return JSON.stringify(this.#data, null, indent);
381
+ }
382
+ fromJSON(raw) {
383
+ this.#data = JSON.parse(raw);
384
+ this.#save();
385
+ return this;
386
+ }
387
+ absorb(other, overwrite = true) {
388
+ for (const [k, v] of Object.entries(other.all())) {
389
+ if (overwrite || !this.has(k))
390
+ this.#data[k] = v;
391
+ }
392
+ this.#save();
393
+ return this;
394
+ }
395
+ }
396
+ export { ok, err } from "./types.js";
package/lib/types.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ export type AllowedSeparators = "/" | ">" | "." | "?" | "::" | "->";
2
+ export type JsonPrimitive = string | number | boolean | null;
3
+ export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
4
+ export type JsonArray = JsonValue[];
5
+ export interface JsonObject {
6
+ [key: string]: JsonValue;
7
+ }
8
+ export type Paths<T, Sep extends string = "."> = T extends JsonObject ? {
9
+ [K in keyof T & string]: K | (T[K] extends JsonObject ? `${K}${Sep}${Paths<T[K], Sep> & string}` : never);
10
+ }[keyof T & string] : never;
11
+ export type PathValue<T, P extends string, Sep extends string = "."> = P extends `${infer K}${Sep}${infer Rest}` ? K extends keyof T ? PathValue<T[K], Rest, Sep> : never : P extends keyof T ? T[P] : never;
12
+ export interface LoadOptions {
13
+ separator?: AllowedSeparators;
14
+ createOnMissing?: boolean;
15
+ indent?: number;
16
+ watch?: boolean;
17
+ encode?: boolean;
18
+ }
19
+ export type JstoreEventMap = {
20
+ set: {
21
+ key: string;
22
+ value: JsonValue;
23
+ };
24
+ del: {
25
+ key: string;
26
+ };
27
+ setPath: {
28
+ path: string;
29
+ value: JsonValue;
30
+ };
31
+ delPath: {
32
+ path: string;
33
+ };
34
+ clear: Record<string, never>;
35
+ reload: Record<string, never>;
36
+ save: Record<string, never>;
37
+ error: {
38
+ message: string;
39
+ cause?: unknown;
40
+ };
41
+ };
42
+ export type JstoreEventName = keyof JstoreEventMap;
43
+ export type JstoreListener<E extends JstoreEventName> = (payload: JstoreEventMap[E]) => void;
44
+ export type FilterFn<T extends JsonValue = JsonValue> = (value: T, key: string) => boolean;
45
+ export type MapFn<T extends JsonValue = JsonValue, R extends JsonValue = JsonValue> = (value: T, key: string) => R;
46
+ export interface Transaction {
47
+ set(key: string, value: JsonValue): Transaction;
48
+ del(key: string): Transaction;
49
+ setPath(dotPath: string, value: JsonValue): Transaction;
50
+ delPath(dotPath: string): Transaction;
51
+ commit(): void;
52
+ rollback(): void;
53
+ }
54
+ export type Validator<T extends JsonValue = JsonValue> = (value: unknown) => value is T;
55
+ export type SchemaMap = Record<string, Validator>;
56
+ export type Ok<T> = {
57
+ ok: true;
58
+ value: T;
59
+ };
60
+ export type Err = {
61
+ ok: false;
62
+ error: string;
63
+ };
64
+ export type Result<T> = Ok<T> | Err;
65
+ export declare const ok: <T>(value: T) => Ok<T>;
66
+ export declare const err: (error: string) => Err;
package/lib/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export const ok = (value) => ({ ok: true, value });
2
+ export const err = (error) => ({ ok: false, error });
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "dex-jstore",
3
+ "version": "1.1.10",
4
+ "description": "Mini-json lib to control json files",
5
+ "license": "MIT",
6
+ "author": "lavender-incognito",
7
+ "type": "module",
8
+ "main": "lib/index.js",
9
+ "readme": "README.md",
10
+ "scripts": {
11
+ "test": "node tests/test.js",
12
+ "build": "tsc",
13
+ "prepublishOnly": "npm run build",
14
+ "publish": "npm run prepublishOnly && npm publish"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "import": "./lib/index.js",
19
+ "types": "./lib/index.d.ts"
20
+ }
21
+ },
22
+ "files": [
23
+ "lib"
24
+ ],
25
+ "devDependencies": {
26
+ "@types/node": "^25.6.0",
27
+ "typescript": "^6.0.3"
28
+ }
29
+ }
package/readme.md ADDED
@@ -0,0 +1,734 @@
1
+ # dex-jstore
2
+
3
+ > A production-grade, type-safe JSON flat-file store — zero dependencies, zero ceremony.
4
+
5
+ ```ts
6
+ import { Jstore } from "dex-jstore";
7
+
8
+ const db = new Jstore("./store.json");
9
+ db.set("user.theme", "dark");
10
+ db.increment("visits");
11
+ console.log(db.getPath("user.theme")); // "dark"
12
+ ```
13
+
14
+ Made by **Lavender Incognito** · MIT License
15
+
16
+ ---
17
+
18
+ ## Table of Contents
19
+
20
+ - [Why dex-jstore](#why-dex-jstore)
21
+ - [Installation](#installation)
22
+ - [Quick Start](#quick-start)
23
+ - [Constructor & Options](#constructor--options)
24
+ - [API Reference](#api-reference)
25
+ - [Lifecycle](#lifecycle)
26
+ - [Flat Key Operations](#flat-key-operations)
27
+ - [Boolean Helpers](#boolean-helpers)
28
+ - [Numeric Helpers](#numeric-helpers)
29
+ - [Array Helpers](#array-helpers)
30
+ - [Object Merge](#object-merge)
31
+ - [Dot-Path Operations](#dot-path-operations)
32
+ - [Functional Iteration](#functional-iteration)
33
+ - [Transactions](#transactions)
34
+ - [Events](#events)
35
+ - [Schema Validation](#schema-validation)
36
+ - [Import / Export](#import--export)
37
+ - [Type System](#type-system)
38
+ - [Result Type](#result-type)
39
+ - [Recipes](#recipes)
40
+ - [FAQ](#faq)
41
+ - [License](#license)
42
+
43
+ ---
44
+
45
+ ## Why dex-jstore
46
+
47
+ Most projects don't need a database. They need a place to persist a handful of settings, counters, or lightweight records without spinning up Postgres or bundling SQLite. `dex-jstore` is that place.
48
+
49
+ - **Zero runtime dependencies** — only Node's built-in `node:fs`, `node:path`, and `node:events`
50
+ - **True private fields** — class internals use `#` syntax; no accidental access through casts
51
+ - **Deep TypeScript inference** — `Paths<T>` and `PathValue<T, P>` give you autocomplete on nested keys at compile time
52
+ - **Railway-oriented errors** — every read has a `try*` variant that returns `Result<T>` instead of throwing
53
+ - **Atomic transactions** — group multiple writes into a single commit; roll back cleanly on failure
54
+ - **Typed event emitter** — subscribe to `set`, `del`, `clear`, `reload`, `save`, `error`, and more
55
+ - **Runtime schema validation** — attach validators per key; bad data is rejected before it ever hits disk
56
+ - **File watcher** — optionally auto-reload when the file is edited externally
57
+ - **Fluent, chainable API** — every mutation returns `this`
58
+
59
+ ---
60
+
61
+ ## Installation
62
+
63
+ ```bash
64
+ npm install dex-jstore
65
+ # or
66
+ pnpm add dex-jstore
67
+ # or
68
+ yarn add dex-jstore
69
+ ```
70
+
71
+ Requires **Node.js ≥ 22** and **TypeScript ≥ 5.4** (for `using` / `Paths` support). ESM-only package.
72
+
73
+ ---
74
+
75
+ ## Quick Start
76
+
77
+ ```ts
78
+ import { Jstore } from "dex-jstore";
79
+
80
+ const db = new Jstore("./data.json");
81
+
82
+ // Flat keys
83
+ db.set("app.name", "my-app");
84
+ db.set("visits", 0);
85
+
86
+ // Dot-path access
87
+ db.setPath("user.prefs.theme", "dark");
88
+ console.log(db.getPath("user.prefs.theme")); // "dark"
89
+
90
+ // Numeric helpers
91
+ db.increment("visits"); // 1
92
+ db.increment("visits", 5); // 6
93
+ db.decrement("visits"); // 5
94
+
95
+ // Boolean helpers
96
+ db.set("debug", false);
97
+ db.toggle("debug"); // true
98
+
99
+ // Array helpers
100
+ db.set("tags", []);
101
+ db.push("tags", "typescript", "json");
102
+ db.pull("tags", (t) => t === "json");
103
+
104
+ // Transactions
105
+ const tx = db.transaction();
106
+ tx.set("version", 2).setPath("user.role", "admin");
107
+ tx.commit(); // single disk write
108
+
109
+ // Events
110
+ db.on("set", ({ key, value }) => console.log(`${key} →`, value));
111
+
112
+ // Safe reads
113
+ const result = db.tryGet("missing-key");
114
+ if (!result.ok) console.error(result.error); // "Key "missing-key" not found"
115
+ ```
116
+
117
+ ---
118
+
119
+ ## Constructor & Options
120
+
121
+ ```ts
122
+ new Jstore(filePath: string, options?: LoadOptions)
123
+ ```
124
+
125
+ | Option | Type | Default | Description |
126
+ |---|---|---|---|
127
+ | `separator` | `AllowedSeparators` | `"."` | Delimiter used to split dot-paths |
128
+ | `createOnMissing` | `boolean` | `true` | Create the file (and parent dirs) if absent |
129
+ | `indent` | `number` | `2` | JSON pretty-print spaces; set `0` for minified output |
130
+ | `watch` | `boolean` | `false` | Auto-reload on external file changes |
131
+ | `encode` | `boolean` | `false` | Base64-obfuscate the stored content |
132
+
133
+ ```ts
134
+ // Custom separator
135
+ const db = new Jstore("./cfg.json", { separator: "/" });
136
+ db.setPath("user/prefs/lang", "fr");
137
+
138
+ // Minified storage
139
+ const db = new Jstore("./prod.json", { indent: 0 });
140
+
141
+ // File watcher
142
+ const db = new Jstore("./shared.json", { watch: true });
143
+ db.on("reload", () => console.log("Store reloaded from disk"));
144
+ ```
145
+
146
+ ### Allowed separators
147
+
148
+ ```ts
149
+ type AllowedSeparators = "." | "/" | ">" | "?" | "::" | "->";
150
+ ```
151
+
152
+ ---
153
+
154
+ ## API Reference
155
+
156
+ ### Lifecycle
157
+
158
+ #### `filePath` *(getter)*
159
+ ```ts
160
+ db.filePath // "/absolute/path/to/store.json"
161
+ ```
162
+ The resolved absolute path of the backing file.
163
+
164
+ #### `size` *(getter)*
165
+ ```ts
166
+ db.size // number of top-level keys
167
+ ```
168
+
169
+ #### `all()`
170
+ ```ts
171
+ db.all(): JsonObject
172
+ ```
173
+ Returns a deep clone of the entire store. Mutations to the returned object do not affect the store.
174
+
175
+ #### `reload()`
176
+ ```ts
177
+ db.reload(): void
178
+ ```
179
+ Re-reads the file from disk, discarding any in-memory state. Fires the `reload` event.
180
+
181
+ #### `clear()`
182
+ ```ts
183
+ db.clear(): void
184
+ ```
185
+ Removes all keys and persists an empty object. Fires the `clear` event.
186
+
187
+ #### `close()`
188
+ ```ts
189
+ db.close(): void
190
+ ```
191
+ Stops the file watcher (if `watch: true` was set). Safe to call multiple times. Should be called on graceful shutdown.
192
+
193
+ ---
194
+
195
+ ### Flat Key Operations
196
+
197
+ #### `get<T>(key)`
198
+ ```ts
199
+ db.get<T>(key: string): T | undefined
200
+ ```
201
+ Returns a deep clone of the value at `key`, or `undefined` if absent.
202
+
203
+ #### `tryGet<T>(key)`
204
+ ```ts
205
+ db.tryGet<T>(key: string): Result<T>
206
+ ```
207
+ Like `get`, but returns `{ ok: true, value }` or `{ ok: false, error }` instead of `undefined`. See [Result Type](#result-type).
208
+
209
+ #### `set(key, value)`
210
+ ```ts
211
+ db.set(key: string, value: JsonValue): this
212
+ ```
213
+ Stores `value` at `key` and writes to disk. Runs the registered validator for `key` if one exists. Fires the `set` event. Returns `this` for chaining.
214
+
215
+ #### `setIfAbsent(key, value)`
216
+ ```ts
217
+ db.setIfAbsent(key: string, value: JsonValue): boolean
218
+ ```
219
+ Sets `value` only if `key` does not already exist. Returns `true` if the value was set, `false` if it was skipped.
220
+
221
+ #### `has(key)`
222
+ ```ts
223
+ db.has(key: string): boolean
224
+ ```
225
+
226
+ #### `del(key)`
227
+ ```ts
228
+ db.del(key: string): boolean
229
+ ```
230
+ Deletes `key`. Returns `true` if it existed and was deleted. Fires the `del` event.
231
+
232
+ #### `rename(from, to)`
233
+ ```ts
234
+ db.rename(from: string, to: string): boolean
235
+ ```
236
+ Atomically renames a key. Returns `false` if `from` does not exist.
237
+
238
+ ---
239
+
240
+ ### Boolean Helpers
241
+
242
+ #### `bool(key)`
243
+ ```ts
244
+ db.bool(key: string): boolean
245
+ ```
246
+ Interprets the value at `key` as a boolean. Accepts `true`/`false` and `1`/`0`. Throws on anything else.
247
+
248
+ #### `toggle(key)`
249
+ ```ts
250
+ db.toggle(key: string): boolean
251
+ ```
252
+ Flips the boolean at `key` and persists. Returns the new value.
253
+
254
+ ---
255
+
256
+ ### Numeric Helpers
257
+
258
+ #### `increment(key, amount?)`
259
+ ```ts
260
+ db.increment(key: string, amount?: number): number
261
+ ```
262
+ Increments the numeric value at `key` by `amount` (default `1`). Creates the key at `0` if absent. Returns the new value.
263
+
264
+ #### `decrement(key, amount?)`
265
+ ```ts
266
+ db.decrement(key: string, amount?: number): number
267
+ ```
268
+ Equivalent to `increment(key, -amount)`.
269
+
270
+ ```ts
271
+ db.set("score", 10);
272
+ db.increment("score"); // 11
273
+ db.increment("score", 4); // 15
274
+ db.decrement("score", 5); // 10
275
+ ```
276
+
277
+ ---
278
+
279
+ ### Array Helpers
280
+
281
+ #### `push(key, ...values)`
282
+ ```ts
283
+ db.push(key: string, ...values: JsonValue[]): this
284
+ ```
285
+ Appends values to the array at `key`. Creates an empty array if the key is absent.
286
+
287
+ #### `pull(key, predicate)`
288
+ ```ts
289
+ db.pull(key: string, predicate: (item: JsonValue) => boolean): this
290
+ ```
291
+ Removes all elements matching `predicate` from the array at `key`.
292
+
293
+ ```ts
294
+ db.set("roles", ["viewer", "editor", "admin"]);
295
+ db.pull("roles", (r) => r === "admin");
296
+ db.get("roles"); // ["viewer", "editor"]
297
+ ```
298
+
299
+ ---
300
+
301
+ ### Object Merge
302
+
303
+ #### `merge(key, value)`
304
+ ```ts
305
+ db.merge(key: string, value: JsonObject): this
306
+ ```
307
+ Deep-merges `value` into the existing object at `key`. Does not overwrite nested keys not present in `value`.
308
+
309
+ ```ts
310
+ db.set("config", { a: 1, b: { x: 10 } });
311
+ db.merge("config", { b: { y: 20 }, c: 3 });
312
+ db.get("config"); // { a: 1, b: { x: 10, y: 20 }, c: 3 }
313
+ ```
314
+
315
+ ---
316
+
317
+ ### Dot-Path Operations
318
+
319
+ All flat key methods have a `*Path` variant that accepts a separator-delimited path string to traverse nested objects.
320
+
321
+ #### `getPath<T>(dotPath)`
322
+ ```ts
323
+ db.getPath<T>(dotPath: string): T | undefined
324
+ ```
325
+
326
+ #### `tryGetPath<T>(dotPath)`
327
+ ```ts
328
+ db.tryGetPath<T>(dotPath: string): Result<T>
329
+ ```
330
+
331
+ #### `setPath(dotPath, value)`
332
+ ```ts
333
+ db.setPath(dotPath: string, value: JsonValue): this
334
+ ```
335
+ Intermediate objects are created automatically if absent.
336
+
337
+ #### `hasPath(dotPath)`
338
+ ```ts
339
+ db.hasPath(dotPath: string): boolean
340
+ ```
341
+
342
+ #### `delPath(dotPath)`
343
+ ```ts
344
+ db.delPath(dotPath: string): boolean
345
+ ```
346
+
347
+ #### `mergePath(dotPath, value)`
348
+ ```ts
349
+ db.mergePath(dotPath: string, value: JsonObject): this
350
+ ```
351
+
352
+ #### `boolPath(dotPath)` / `togglePath(dotPath)`
353
+ ```ts
354
+ db.boolPath(dotPath: string): boolean
355
+ db.togglePath(dotPath: string): boolean
356
+ ```
357
+
358
+ #### `incrementPath(dotPath, amount?)`
359
+ ```ts
360
+ db.incrementPath(dotPath: string, amount?: number): number
361
+ ```
362
+
363
+ #### `pushPath(dotPath, ...values)`
364
+ ```ts
365
+ db.pushPath(dotPath: string, ...values: JsonValue[]): this
366
+ ```
367
+
368
+ ```ts
369
+ db.setPath("metrics.requests.total", 0);
370
+ db.incrementPath("metrics.requests.total", 100);
371
+ db.getPath("metrics.requests.total"); // 100
372
+ ```
373
+
374
+ ---
375
+
376
+ ### Functional Iteration
377
+
378
+ These methods operate on top-level entries and **never mutate** the store.
379
+
380
+ #### `forEach(fn)`
381
+ ```ts
382
+ db.forEach((value: JsonValue, key: string) => void): void
383
+ ```
384
+
385
+ #### `filter<T>(predicate)`
386
+ ```ts
387
+ db.filter<T>(predicate: FilterFn<T>): JsonObject
388
+ ```
389
+ Returns a new plain object containing only the entries for which `predicate` returns `true`.
390
+
391
+ #### `map<T, R>(fn)`
392
+ ```ts
393
+ db.map<T, R>(fn: MapFn<T, R>): JsonObject
394
+ ```
395
+ Returns a new plain object with each value transformed by `fn`.
396
+
397
+ #### `findKeys(predicate)`
398
+ ```ts
399
+ db.findKeys(predicate: FilterFn): string[]
400
+ ```
401
+ Returns all top-level keys for which `predicate` returns `true`.
402
+
403
+ ```ts
404
+ db.set("a", 1);
405
+ db.set("b", "hello");
406
+ db.set("c", 42);
407
+
408
+ db.filter<number>((v) => typeof v === "number"); // { a: 1, c: 42 }
409
+ db.findKeys((v) => typeof v === "string"); // ["b"]
410
+ db.map<number, number>((v) => (v as number) * 2); // { a: 2, c: 84 } (b NaN-safe)
411
+ ```
412
+
413
+ ---
414
+
415
+ ### Transactions
416
+
417
+ A transaction lets you group multiple operations into a single atomic write. Changes are staged in memory and only flushed to disk on `commit()`. Calling `rollback()` discards all staged changes.
418
+
419
+ ```ts
420
+ transaction(): Transaction
421
+ ```
422
+
423
+ ```ts
424
+ interface Transaction {
425
+ set(key: string, value: JsonValue): Transaction;
426
+ del(key: string): Transaction;
427
+ setPath(dotPath: string, value: JsonValue): Transaction;
428
+ delPath(dotPath: string): Transaction;
429
+ commit(): void;
430
+ rollback(): void;
431
+ }
432
+ ```
433
+
434
+ ```ts
435
+ const tx = db.transaction();
436
+
437
+ try {
438
+ tx
439
+ .set("status", "migrating")
440
+ .setPath("user.role", "admin")
441
+ .del("legacy_flag");
442
+
443
+ tx.commit(); // ← one single write to disk
444
+ } catch (e) {
445
+ tx.rollback(); // ← no disk write occurred
446
+ }
447
+ ```
448
+
449
+ > **Note:** Transactions do not fire individual `set` / `del` events. Only the `save` event fires on `commit()`.
450
+
451
+ ---
452
+
453
+ ### Events
454
+
455
+ `Jstore` extends `EventEmitter` with fully typed events.
456
+
457
+ ```ts
458
+ db.on(event, listener): this
459
+ db.once(event, listener): this
460
+ db.off(event, listener): this
461
+ ```
462
+
463
+ | Event | Payload | Fired when |
464
+ |---|---|---|
465
+ | `set` | `{ key, value }` | A flat key is written |
466
+ | `del` | `{ key }` | A flat key is deleted |
467
+ | `setPath` | `{ path, value }` | A dot-path is written |
468
+ | `delPath` | `{ path }` | A dot-path is deleted |
469
+ | `clear` | `{}` | The store is cleared |
470
+ | `reload` | `{}` | The store is reloaded from disk |
471
+ | `save` | `{}` | Any write reaches disk |
472
+ | `error` | `{ message, cause? }` | A parse or I/O error occurs |
473
+
474
+ ```ts
475
+ db.on("set", ({ key, value }) => {
476
+ console.log(`[store] SET ${key} =`, value);
477
+ });
478
+
479
+ db.on("error", ({ message }) => {
480
+ console.error("[store] Error:", message);
481
+ });
482
+
483
+ // One-time listener
484
+ db.once("reload", () => console.log("Reloaded from external edit"));
485
+ ```
486
+
487
+ ---
488
+
489
+ ### Schema Validation
490
+
491
+ Register a type guard per key. Any `set()` or `setPath()` call whose value fails validation will throw before touching the store.
492
+
493
+ ```ts
494
+ db.addValidator(key: string, validator: Validator<T>): this
495
+ db.removeValidator(key: string): this
496
+ ```
497
+
498
+ ```ts
499
+ // Zod-compatible — any (value: unknown) => value is T works
500
+ db.addValidator("port", (v): v is number =>
501
+ typeof v === "number" && Number.isInteger(v) && v > 0 && v < 65536
502
+ );
503
+
504
+ db.addValidator("theme", (v): v is "light" | "dark" =>
505
+ v === "light" || v === "dark"
506
+ );
507
+
508
+ db.set("port", 3000); // ✓
509
+ db.set("port", 99999); // ✗ throws: [jstore] Validation failed for key "port"
510
+ db.set("theme", "dim"); // ✗ throws: [jstore] Validation failed for key "theme"
511
+ ```
512
+
513
+ ---
514
+
515
+ ### Import / Export
516
+
517
+ #### `toJSON(indent?)`
518
+ ```ts
519
+ db.toJSON(indent?: number): string
520
+ ```
521
+ Serializes the store to a JSON string. Uses the instance's `indent` setting by default.
522
+
523
+ #### `fromJSON(raw)`
524
+ ```ts
525
+ db.fromJSON(raw: string): this
526
+ ```
527
+ Overwrites the entire store with a parsed JSON string and persists.
528
+
529
+ #### `absorb(other, overwrite?)`
530
+ ```ts
531
+ db.absorb(other: Jstore, overwrite?: boolean): this
532
+ ```
533
+ Merges all top-level entries from `other` into this store. Set `overwrite` to `false` to preserve existing keys.
534
+
535
+ ```ts
536
+ const defaults = new Jstore("./defaults.json");
537
+ const user = new Jstore("./user.json");
538
+
539
+ // Apply defaults without overwriting user values
540
+ user.absorb(defaults, false);
541
+ ```
542
+
543
+ ---
544
+
545
+ ## Type System
546
+
547
+ `dex-jstore` ships a rich set of utility types in `types.ts`.
548
+
549
+ ### `Paths<T, Sep>`
550
+
551
+ Produces a union of all valid dot-separated key paths into `T`, up to 4 levels deep.
552
+
553
+ ```ts
554
+ type Config = {
555
+ server: { host: string; port: number };
556
+ debug: boolean;
557
+ };
558
+
559
+ type ConfigPaths = Paths<Config>;
560
+ // "server" | "server.host" | "server.port" | "debug"
561
+ ```
562
+
563
+ ### `PathValue<T, P, Sep>`
564
+
565
+ Resolves the value type at a given path.
566
+
567
+ ```ts
568
+ type PortType = PathValue<Config, "server.port">;
569
+ // number
570
+ ```
571
+
572
+ ### `JsonValue`
573
+
574
+ ```ts
575
+ type JsonValue = string | number | boolean | null | JsonObject | JsonArray;
576
+ ```
577
+
578
+ ### `Result<T>`
579
+
580
+ ```ts
581
+ type Result<T> = { ok: true; value: T } | { ok: false; error: string };
582
+ ```
583
+
584
+ ### `AllowedSeparators`
585
+
586
+ ```ts
587
+ type AllowedSeparators = "." | "/" | ">" | "?" | "::" | "->";
588
+ ```
589
+
590
+ ---
591
+
592
+ ## Result Type
593
+
594
+ Every read method has a safe `try*` variant that returns a `Result<T>` instead of `undefined` or throwing. This enables clean, exhaustive error handling without `try/catch`.
595
+
596
+ ```ts
597
+ import { Jstore, ok, err } from "dex-jstore";
598
+ import type { Result } from "dex-jstore";
599
+
600
+ const result: Result<number> = db.tryGet<number>("hits");
601
+
602
+ if (result.ok) {
603
+ console.log("Hits:", result.value);
604
+ } else {
605
+ console.warn("Not found:", result.error);
606
+ }
607
+ ```
608
+
609
+ You can also construct results directly:
610
+
611
+ ```ts
612
+ import { ok, err } from "dex-jstore";
613
+
614
+ function safeRead(key: string): Result<string> {
615
+ const val = db.get<string>(key);
616
+ return val !== undefined ? ok(val) : err(`Missing key: ${key}`);
617
+ }
618
+ ```
619
+
620
+ ---
621
+
622
+ ## Recipes
623
+
624
+ ### App configuration store
625
+
626
+ ```ts
627
+ const cfg = new Jstore("./app.config.json", { createOnMissing: true });
628
+
629
+ cfg.setIfAbsent("port", 3000);
630
+ cfg.setIfAbsent("host", "localhost");
631
+ cfg.setIfAbsent("debug", false);
632
+
633
+ export const port = cfg.get<number>("port")!;
634
+ export const debug = cfg.bool("debug");
635
+ ```
636
+
637
+ ### Session / request counter
638
+
639
+ ```ts
640
+ const stats = new Jstore("./stats.json");
641
+
642
+ // In your request handler:
643
+ stats.increment("requests.total");
644
+ stats.incrementPath("requests.by_method.GET");
645
+ ```
646
+
647
+ ### Feature flags
648
+
649
+ ```ts
650
+ const flags = new Jstore("./flags.json");
651
+ flags.addValidator("beta", (v): v is boolean => typeof v === "boolean");
652
+
653
+ flags.set("beta", false);
654
+ flags.toggle("beta"); // true
655
+
656
+ if (flags.bool("beta")) {
657
+ // enable beta features
658
+ }
659
+ ```
660
+
661
+ ### Shared store with auto-reload
662
+
663
+ ```ts
664
+ // In a multi-process scenario where another process may write the file:
665
+ const shared = new Jstore("./shared.json", { watch: true });
666
+
667
+ shared.on("reload", () => {
668
+ console.log("Shared store updated:", shared.all());
669
+ });
670
+ ```
671
+
672
+ ### Atomic multi-step migration
673
+
674
+ ```ts
675
+ const db = new Jstore("./store.json");
676
+ const tx = db.transaction();
677
+
678
+ try {
679
+ tx.del("old_user_id")
680
+ .set("user_id", generateNewId())
681
+ .setPath("migration.v2", true)
682
+ .set("schema_version", 2);
683
+ tx.commit();
684
+ } catch (e) {
685
+ tx.rollback();
686
+ throw e;
687
+ }
688
+ ```
689
+
690
+ ### Absorbing defaults
691
+
692
+ ```ts
693
+ const defaults = new Jstore("./defaults.json");
694
+ const config = new Jstore("./config.json");
695
+
696
+ // Load defaults first, then overlay user config
697
+ const merged = new Jstore("./merged.json");
698
+ merged.absorb(defaults).absorb(config, true);
699
+ ```
700
+
701
+ ---
702
+
703
+ ## FAQ
704
+
705
+ **Does dex-jstore work in the browser?**
706
+ No — it uses `node:fs` for persistence. For browser use, consider wrapping `localStorage` with a compatible interface.
707
+
708
+ **Is it safe to use from multiple processes simultaneously?**
709
+ Not without external coordination. File writes are synchronous and not locked. For multi-process scenarios, use the `watch: true` option on readers and designate a single writer process.
710
+
711
+ **Can I use it without TypeScript?**
712
+ Yes. It's standard ESM JavaScript at runtime. You just lose the compile-time path inference.
713
+
714
+ **What happens if the JSON file is corrupted?**
715
+ The constructor throws an error with the file path. An `error` event is also emitted before the throw. Consider wrapping the constructor in a try/catch and falling back to `fromJSON("{}")`.
716
+
717
+ **Does `transaction()` support `setPath` / `delPath`?**
718
+ Yes — the `Transaction` interface exposes all four core mutators: `set`, `del`, `setPath`, and `delPath`.
719
+
720
+ **Can I use Zod validators?**
721
+ Yes. Zod's `.parse` throws, but `.safeParse` returns a result you can use to build a `Validator<T>`:
722
+
723
+ ```ts
724
+ import { z } from "zod";
725
+
726
+ const UserSchema = z.object({ name: z.string(), age: z.number().min(0) });
727
+
728
+ db.addValidator("user", (v): v is z.infer<typeof UserSchema> =>
729
+ UserSchema.safeParse(v).success
730
+ );
731
+ ```
732
+
733
+ ---
734
+