@philiprehberger/safe-json 0.1.5

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) 2026 philiprehberger
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,83 @@
1
+ # @philiprehberger/safe-json
2
+
3
+ [![CI](https://github.com/philiprehberger/ts-safe-json/actions/workflows/ci.yml/badge.svg)](https://github.com/philiprehberger/ts-safe-json/actions/workflows/ci.yml)
4
+ [![npm version](https://img.shields.io/npm/v/@philiprehberger/safe-json.svg)](https://www.npmjs.com/package/@philiprehberger/safe-json)
5
+ [![License](https://img.shields.io/github/license/philiprehberger/ts-safe-json)](LICENSE)
6
+
7
+ Safe JSON parsing and serialization with circular detection and depth limiting
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @philiprehberger/safe-json
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ### Safe Parse
18
+
19
+ ```ts
20
+ import { safeParse } from '@philiprehberger/safe-json';
21
+
22
+ const { ok, data, error } = safeParse<User>(jsonString);
23
+ if (ok) {
24
+ console.log(data.name); // typed as User
25
+ } else {
26
+ console.error(error.message);
27
+ }
28
+ ```
29
+
30
+ ### Safe Stringify
31
+
32
+ ```ts
33
+ import { safeStringify } from '@philiprehberger/safe-json';
34
+
35
+ // Handles circular references
36
+ const obj: any = { name: 'test' };
37
+ obj.self = obj;
38
+ safeStringify(obj);
39
+ // {"name":"test","self":"[Circular]"}
40
+
41
+ // Depth limiting
42
+ safeStringify(deeplyNested, { maxDepth: 3 });
43
+ // Objects beyond depth 3 become "[MaxDepth]"
44
+
45
+ // Pretty print
46
+ safeStringify(data, { space: 2 });
47
+ ```
48
+
49
+ ## API
50
+
51
+ | Export | Description |
52
+ |--------|-------------|
53
+ | `safeParse<T>(input)` | Parse JSON string, returns `{ ok, data?, error? }` |
54
+ | `safeStringify(value, options?)` | Stringify with circular/depth protection |
55
+
56
+ ### `SafeParseResult<T>`
57
+
58
+ | Property | Type | Description |
59
+ |----------|------|-------------|
60
+ | `ok` | `boolean` | Whether parsing succeeded |
61
+ | `data` | `T` | Parsed value (if ok) |
62
+ | `error` | `Error` | Parse error (if not ok) |
63
+
64
+ ### `StringifyOptions`
65
+
66
+ | Option | Type | Default | Description |
67
+ |--------|------|---------|-------------|
68
+ | `maxDepth` | `number` | — | Max nesting depth before `"[MaxDepth]"` |
69
+ | `replacer` | `(key, value) => unknown` | — | Custom replacer function |
70
+ | `space` | `number` | — | Indentation spaces |
71
+
72
+
73
+ ## Development
74
+
75
+ ```bash
76
+ npm install
77
+ npm run build
78
+ npm test
79
+ ```
80
+
81
+ ## License
82
+
83
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ // src/parse.ts
4
+ function safeParse(input) {
5
+ try {
6
+ const data = JSON.parse(input);
7
+ return { ok: true, data };
8
+ } catch (error) {
9
+ return {
10
+ ok: false,
11
+ error: error instanceof Error ? error : new Error(String(error))
12
+ };
13
+ }
14
+ }
15
+ function safeStringify(value, options = {}) {
16
+ const { maxDepth, replacer, space } = options;
17
+ const seen = /* @__PURE__ */ new WeakSet();
18
+ function serialize(val, depth) {
19
+ if (val === null || typeof val !== "object") return val;
20
+ if (seen.has(val)) return "[Circular]";
21
+ seen.add(val);
22
+ if (maxDepth !== void 0 && depth >= maxDepth) return "[MaxDepth]";
23
+ if (Array.isArray(val)) {
24
+ const arr = [];
25
+ for (const item of val) {
26
+ arr.push(serialize(item, depth + 1));
27
+ }
28
+ seen.delete(val);
29
+ return arr;
30
+ }
31
+ const obj = {};
32
+ for (const [key, v] of Object.entries(val)) {
33
+ obj[key] = serialize(v, depth + 1);
34
+ }
35
+ seen.delete(val);
36
+ return obj;
37
+ }
38
+ try {
39
+ const safe = serialize(value, 0);
40
+ return JSON.stringify(safe, replacer, space);
41
+ } catch (error) {
42
+ return JSON.stringify({ error: "Failed to stringify value" });
43
+ }
44
+ }
45
+
46
+ exports.safeParse = safeParse;
47
+ exports.safeStringify = safeStringify;
48
+ //# sourceMappingURL=index.cjs.map
49
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/parse.ts"],"names":[],"mappings":";;;AAEO,SAAS,UAAuB,KAAA,EAAmC;AACxE,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,KAAA,CAAM,KAAK,CAAA;AAC7B,IAAA,OAAO,EAAE,EAAA,EAAI,IAAA,EAAM,IAAA,EAAK;AAAA,EAC1B,SAAS,KAAA,EAAO;AACd,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,KAAA,EAAO,iBAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC;AAAA,KACjE;AAAA,EACF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A,CAAK,SAAA,CAAU,IAAA,EAAM,QAAA,EAAsD,KAAK,CAAA;AAAA,EACzF,SAAS,KAAA,EAAO;AACd,IAAA,OAAO,IAAA,CAAK,SAAA,CAAU,EAAE,KAAA,EAAO,6BAA6B,CAAA;AAAA,EAC9D;AACF","file":"index.cjs","sourcesContent":["import type { SafeParseResult, StringifyOptions } from './types.js';\n\nexport function safeParse<T = unknown>(input: string): SafeParseResult<T> {\n try {\n const data = JSON.parse(input) as T;\n return { ok: true, data };\n } catch (error) {\n return {\n ok: false,\n error: error instanceof Error ? error : new Error(String(error)),\n };\n }\n}\n\nexport function safeStringify(\n value: unknown,\n options: StringifyOptions = {},\n): string {\n const { maxDepth, replacer, space } = options;\n const seen = new WeakSet<object>();\n\n function serialize(val: unknown, depth: number): unknown {\n if (val === null || typeof val !== 'object') return val;\n\n if (seen.has(val as object)) return '[Circular]';\n seen.add(val as object);\n\n if (maxDepth !== undefined && depth >= maxDepth) return '[MaxDepth]';\n\n if (Array.isArray(val)) {\n const arr: unknown[] = [];\n for (const item of val) {\n arr.push(serialize(item, depth + 1));\n }\n seen.delete(val as object);\n return arr;\n }\n\n const obj: Record<string, unknown> = {};\n for (const [key, v] of Object.entries(val as Record<string, unknown>)) {\n obj[key] = serialize(v, depth + 1);\n }\n seen.delete(val as object);\n return obj;\n }\n\n try {\n const safe = serialize(value, 0);\n return JSON.stringify(safe, replacer as (key: string, value: unknown) => unknown, space);\n } catch (error) {\n return JSON.stringify({ error: 'Failed to stringify value' });\n }\n}\n"]}
@@ -0,0 +1,15 @@
1
+ interface SafeParseResult<T> {
2
+ ok: boolean;
3
+ data?: T;
4
+ error?: Error;
5
+ }
6
+ interface StringifyOptions {
7
+ maxDepth?: number;
8
+ replacer?: (key: string, value: unknown) => unknown;
9
+ space?: number;
10
+ }
11
+
12
+ declare function safeParse<T = unknown>(input: string): SafeParseResult<T>;
13
+ declare function safeStringify(value: unknown, options?: StringifyOptions): string;
14
+
15
+ export { type SafeParseResult, type StringifyOptions, safeParse, safeStringify };
@@ -0,0 +1,15 @@
1
+ interface SafeParseResult<T> {
2
+ ok: boolean;
3
+ data?: T;
4
+ error?: Error;
5
+ }
6
+ interface StringifyOptions {
7
+ maxDepth?: number;
8
+ replacer?: (key: string, value: unknown) => unknown;
9
+ space?: number;
10
+ }
11
+
12
+ declare function safeParse<T = unknown>(input: string): SafeParseResult<T>;
13
+ declare function safeStringify(value: unknown, options?: StringifyOptions): string;
14
+
15
+ export { type SafeParseResult, type StringifyOptions, safeParse, safeStringify };
package/dist/index.js ADDED
@@ -0,0 +1,46 @@
1
+ // src/parse.ts
2
+ function safeParse(input) {
3
+ try {
4
+ const data = JSON.parse(input);
5
+ return { ok: true, data };
6
+ } catch (error) {
7
+ return {
8
+ ok: false,
9
+ error: error instanceof Error ? error : new Error(String(error))
10
+ };
11
+ }
12
+ }
13
+ function safeStringify(value, options = {}) {
14
+ const { maxDepth, replacer, space } = options;
15
+ const seen = /* @__PURE__ */ new WeakSet();
16
+ function serialize(val, depth) {
17
+ if (val === null || typeof val !== "object") return val;
18
+ if (seen.has(val)) return "[Circular]";
19
+ seen.add(val);
20
+ if (maxDepth !== void 0 && depth >= maxDepth) return "[MaxDepth]";
21
+ if (Array.isArray(val)) {
22
+ const arr = [];
23
+ for (const item of val) {
24
+ arr.push(serialize(item, depth + 1));
25
+ }
26
+ seen.delete(val);
27
+ return arr;
28
+ }
29
+ const obj = {};
30
+ for (const [key, v] of Object.entries(val)) {
31
+ obj[key] = serialize(v, depth + 1);
32
+ }
33
+ seen.delete(val);
34
+ return obj;
35
+ }
36
+ try {
37
+ const safe = serialize(value, 0);
38
+ return JSON.stringify(safe, replacer, space);
39
+ } catch (error) {
40
+ return JSON.stringify({ error: "Failed to stringify value" });
41
+ }
42
+ }
43
+
44
+ export { safeParse, safeStringify };
45
+ //# sourceMappingURL=index.js.map
46
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/parse.ts"],"names":[],"m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AC;AACtC,IAAA,KAAA,MAAW,CAAC,GAAA,EAAK,CAAC,KAAK,MAAA,CAAO,OAAA,CAAQ,GAA8B,CAAA,EAAG;AACrE,MAAA,GAAA,CAAI,GAAG,CAAA,GAAI,SAAA,CAAU,CAAA,EAAG,QAAQ,CAAC,CAAA;AAAA,IACnC;AACA,IAAA,IAAA,CAAK,OAAO,GAAa,CAAA;AACzB,IAAA,OAAO,GAAA;AAAA,EACT;AAEA,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,SAAA,CAAU,KAAA,EAAO,CAAC,CAAA;AAC/B,IAAA,OAAO,IAAA,CAAK,SAAA,CAAU,IAAA,EAAM,QAAA,EAAsD,KAAK,CAAA;AAAA,EACzF,SAAS,KAAA,EAAO;AACd,IAAA,OAAO,IAAA,CAAK,SAAA,CAAU,EAAE,KAAA,EAAO,6BAA6B,CAAA;AAAA,EAC9D;AACF","file":"index.js","sourcesContent":["import type { SafeParseResult, StringifyOptions } from './types.js';\n\nexport function safeParse<T = unknown>(input: string): SafeParseResult<T> {\n try {\n const data = JSON.parse(input) as T;\n return { ok: true, data };\n } catch (error) {\n return {\n ok: false,\n error: error instanceof Error ? error : new Error(String(error)),\n };\n }\n}\n\nexport function safeStringify(\n value: unknown,\n options: StringifyOptions = {},\n): string {\n const { maxDepth, replacer, space } = options;\n const seen = new WeakSet<object>();\n\n function serialize(val: unknown, depth: number): unknown {\n if (val === null || typeof val !== 'object') return val;\n\n if (seen.has(val as object)) return '[Circular]';\n seen.add(val as object);\n\n if (maxDepth !== undefined && depth >= maxDepth) return '[MaxDepth]';\n\n if (Array.isArray(val)) {\n const arr: unknown[] = [];\n for (const item of val) {\n arr.push(serialize(item, depth + 1));\n }\n seen.delete(val as object);\n return arr;\n }\n\n const obj: Record<string, unknown> = {};\n for (const [key, v] of Object.entries(val as Record<string, unknown>)) {\n obj[key] = serialize(v, depth + 1);\n }\n seen.delete(val as object);\n return obj;\n }\n\n try {\n const safe = serialize(value, 0);\n return JSON.stringify(safe, replacer as (key: string, value: unknown) => unknown, space);\n } catch (error) {\n return JSON.stringify({ error: 'Failed to stringify value' });\n }\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@philiprehberger/safe-json",
3
+ "version": "0.1.5",
4
+ "description": "Safe JSON parsing and serialization with circular detection and depth limiting",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ }
19
+ }
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "scripts": {
25
+ "build": "tsup",
26
+ "dev": "tsup --watch",
27
+ "typecheck": "tsc --noEmit",
28
+ "prepublishOnly": "npm run build",
29
+ "test": "node --test"
30
+ },
31
+ "devDependencies": {
32
+ "tsup": "^8.0.0",
33
+ "typescript": "^5.0.0"
34
+ },
35
+ "keywords": [
36
+ "json",
37
+ "parse",
38
+ "safe",
39
+ "circular",
40
+ "stringify",
41
+ "validation"
42
+ ],
43
+ "license": "MIT",
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/philiprehberger/ts-safe-json.git"
47
+ },
48
+ "homepage": "https://github.com/philiprehberger/ts-safe-json#readme",
49
+ "bugs": {
50
+ "url": "https://github.com/philiprehberger/ts-safe-json/issues"
51
+ },
52
+ "author": "Philip Rehberger",
53
+ "engines": {
54
+ "node": ">=18.0.0"
55
+ },
56
+ "sideEffects": false
57
+ }