Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e0776a56b0 | |||
| ba38d4377b | |||
| 6ac04e2069 | |||
| 6fe5112bfb | |||
| acf8cea099 | |||
| bd67581b75 |
@@ -1,8 +1,5 @@
|
||||
{
|
||||
"npmci": {
|
||||
"npmAccessLevel": "public"
|
||||
},
|
||||
"gitzone": {
|
||||
"@git.zone/cli": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
"githost": "code.foss.global",
|
||||
@@ -24,9 +21,19 @@
|
||||
"data encoding",
|
||||
"data decoding"
|
||||
]
|
||||
},
|
||||
"release": {
|
||||
"registries": [
|
||||
"https://verdaccio.lossless.digital",
|
||||
"https://registry.npmjs.org"
|
||||
],
|
||||
"accessLevel": "public"
|
||||
}
|
||||
},
|
||||
"tsdoc": {
|
||||
"@git.zone/tsdoc": {
|
||||
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
|
||||
},
|
||||
"@ship.zone/szci": {
|
||||
"npmGlobalTools": []
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,31 @@
|
||||
# Changelog
|
||||
|
||||
## 2026-04-30 - 6.0.1 - fix(build,json)
|
||||
replace lodash.clonedeep with structuredClone and migrate package metadata to smartconfig
|
||||
|
||||
- removes the lodash.clonedeep dependency by using structuredClone when folding saveable properties
|
||||
- improves cross-platform buffer handling by resolving Buffer from globalThis instead of relying on ts-ignore checks
|
||||
- migrates project metadata from npmextra.json to .smartconfig.json and updates packaged files accordingly
|
||||
- updates build tooling versions and drops the allowimplicitany build flag
|
||||
|
||||
## 2025-12-10 - 6.0.0 - BREAKING CHANGE(Smartjson)
|
||||
Require TC39 Stage 3 decorators for @foldDec (use accessor), switch foldDec to initializer-based implementation, improve buffer encode/decode handling, bump dependencies and update docs/tests.
|
||||
|
||||
- foldDec now implements TC39 Stage 3 accessor decorators and must be used with the 'accessor' keyword (e.g. '@foldDec() accessor prop: T'). The decorator registers saveable properties via context.addInitializer so properties are tracked per-instance.
|
||||
- Buffer handling rewritten: replacer/reviver handle Uint8Array and Buffer cross-platform; EncodedBuffer.data now uses a 'base64:' prefix and reviver returns a Uint8Array. This changes the serialized representation of buffers.
|
||||
- tsconfig updated to remove experimentalDecorators and useDefineForClassFields overrides — project now targets modern TypeScript decorator support (ensure your toolchain supports Stage 3 decorators).
|
||||
- Documentation (readme and hints) and tests updated to reflect accessor-based decorators and new buffer handling.
|
||||
- Dependencies bumped: @push.rocks/smartenv -> ^6.0.0, dev deps @git.zone/tsbuild, @git.zone/tsrun, @git.zone/tstest upgraded, and @types/node -> ^24.0.0.
|
||||
- Removed pnpm-workspace.yaml onlyBuiltDependencies entries.
|
||||
|
||||
## 2025-09-12 - 5.2.0 - feat(smartjson)
|
||||
Implement stableOneWayStringify: deterministic, cycle-safe JSON for hashing/comparisons; update docs and tests
|
||||
|
||||
- Implement stableOneWayStringify in ts/index.ts: produces deterministic JSON, encodes buffers, replaces circular references with "__cycle__" and marks unserializable values as "__unserializable__".
|
||||
- Update README: add documentation and examples for stableOneWayStringify, clarify JSONL wording, and update performance/migration notes.
|
||||
- Add unit test to verify stableOneWayStringify handles circular references without throwing.
|
||||
- Add .claude/settings.local.json (local settings/config) as part of the change set.
|
||||
|
||||
## 2025-09-12 - 5.1.0 - feat(smartjson)
|
||||
Add JSONL stringify and ordering comparator; fix empty buffer handling; refactor Smartjson folding/enfolding
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2026 Task Venture Capital GmbH
|
||||
|
||||
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:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
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.
|
||||
+12
-13
@@ -1,36 +1,35 @@
|
||||
{
|
||||
"name": "@push.rocks/smartjson",
|
||||
"version": "5.1.0",
|
||||
"version": "6.0.1",
|
||||
"private": false,
|
||||
"description": "A library for handling typed JSON data, providing functionalities for parsing, stringifying, and working with JSON objects, including support for encoding and decoding buffers.",
|
||||
"main": "dist_ts/index.js",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
"scripts": {
|
||||
"test": "(tstest test/ --web)",
|
||||
"build": "(tsbuild --web --allowimplicitany)",
|
||||
"build": "(tsbuild --web)",
|
||||
"buildDocs": "tsdoc"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://code.foss.global/push.rocks/smartjson.git"
|
||||
},
|
||||
"author": "Lossless GmbH",
|
||||
"author": "Task Venture Capital GmbH",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://gitlab.com/pushrocks/smartjson/issues"
|
||||
"url": "https://code.foss.global/push.rocks/smartjson/issues"
|
||||
},
|
||||
"homepage": "https://code.foss.global/push.rocks/smartjson",
|
||||
"devDependencies": {
|
||||
"@git.zone/tsbuild": "^2.6.8",
|
||||
"@git.zone/tsrun": "^1.3.3",
|
||||
"@git.zone/tstest": "^2.3.8",
|
||||
"@types/node": "^22"
|
||||
"@git.zone/tsbuild": "^4.4.0",
|
||||
"@git.zone/tsrun": "^2.0.2",
|
||||
"@git.zone/tstest": "^3.6.3",
|
||||
"@types/node": "^25.6.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@push.rocks/smartenv": "^5.0.13",
|
||||
"@push.rocks/smartenv": "^6.0.0",
|
||||
"@push.rocks/smartstring": "^4.1.0",
|
||||
"fast-json-stable-stringify": "^2.1.0",
|
||||
"lodash.clonedeep": "^4.5.0"
|
||||
"fast-json-stable-stringify": "^2.1.0"
|
||||
},
|
||||
"files": [
|
||||
"ts/**/*",
|
||||
@@ -41,7 +40,7 @@
|
||||
"dist_ts_web/**/*",
|
||||
"assets/**/*",
|
||||
"cli.js",
|
||||
"npmextra.json",
|
||||
".smartconfig.json",
|
||||
"readme.md"
|
||||
],
|
||||
"browserslist": [
|
||||
@@ -61,5 +60,5 @@
|
||||
"data encoding",
|
||||
"data decoding"
|
||||
],
|
||||
"packageManager": "pnpm@10.14.0+sha512.ad27a79641b49c3e481a16a805baa71817a04bbe06a38d17e60e2eaee83f6a146c6a688125f5792e48dd5ba30e7da52a5cda4c3992b9ccf333f9ce223af84748"
|
||||
"packageManager": "pnpm@10.28.2"
|
||||
}
|
||||
|
||||
Generated
+3110
-3058
File diff suppressed because it is too large
Load Diff
@@ -1,3 +0,0 @@
|
||||
onlyBuiltDependencies:
|
||||
- esbuild
|
||||
- puppeteer
|
||||
@@ -1 +1,11 @@
|
||||
# Project Hints
|
||||
|
||||
## Decorators
|
||||
- Uses TC39 Stage 3 decorators (not legacy `experimentalDecorators`)
|
||||
- The `@foldDec()` decorator requires the `accessor` keyword on properties
|
||||
- Example: `@foldDec() accessor myProp: string = 'value';`
|
||||
|
||||
## Dependencies
|
||||
- Last upgraded: December 2024
|
||||
- Uses @push.rocks/smartenv v6.x
|
||||
- Uses @git.zone/tstest v3.x for testing
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
|
||||
A powerful library for working with JSON in TypeScript, providing type-safe serialization, advanced buffer handling, deep object comparison, and support for complex class instances. Perfect for applications that need reliable JSON manipulation with full TypeScript support.
|
||||
|
||||
## Issue Reporting and Security
|
||||
|
||||
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
@@ -21,9 +25,10 @@ pnpm add @push.rocks/smartjson
|
||||
✨ **Type-Safe JSON Operations** - Full TypeScript support with proper typing
|
||||
🎯 **Class Instance Serialization** - Fold and unfold class instances to/from JSON
|
||||
🔐 **Buffer & Binary Support** - Seamless handling of Buffers and Typed Arrays
|
||||
📊 **JSON Lines Support** - Parse and compare JSONL data streams
|
||||
📊 **JSON Lines Support** - Parse, stringify and compare JSONL data streams
|
||||
🎨 **Pretty Printing** - Beautiful formatted JSON output
|
||||
⚡ **Stable Stringification** - Consistent key ordering for reliable comparisons
|
||||
♻️ **Circular Reference Handling** - Safe one-way stringify for objects with cycles
|
||||
🔍 **Deep Equality Checks** - Compare complex objects and JSON structures
|
||||
🌐 **Base64 Encoding** - Built-in base64 JSON encoding/decoding
|
||||
|
||||
@@ -67,6 +72,40 @@ const prettyJson = smartjson.stringifyPretty({
|
||||
});
|
||||
```
|
||||
|
||||
### Safe One-Way Stringification (New in v5.1.0)
|
||||
|
||||
Handle circular references and unserializable values safely for hashing and comparisons:
|
||||
|
||||
```typescript
|
||||
// Create objects with circular references
|
||||
const objA = { name: 'A' };
|
||||
const objB = { name: 'B', ref: objA };
|
||||
objA['ref'] = objB; // Circular reference!
|
||||
|
||||
// Normal stringify would throw, but stableOneWayStringify handles it
|
||||
const safeJson = smartjson.stableOneWayStringify(objA);
|
||||
// Circular references are replaced with "__cycle__"
|
||||
|
||||
// Perfect for object hashing
|
||||
const hash1 = crypto.createHash('sha256')
|
||||
.update(smartjson.stableOneWayStringify(complexObject))
|
||||
.digest('hex');
|
||||
|
||||
// Handles unserializable values gracefully
|
||||
const objWithGetter = {
|
||||
normal: 'value',
|
||||
get throwing() { throw new Error('Cannot serialize!'); }
|
||||
};
|
||||
const safe = smartjson.stableOneWayStringify(objWithGetter);
|
||||
// Throwing getters are replaced with "__unserializable__"
|
||||
|
||||
// Custom key ordering for consistent hashes
|
||||
const ordered = smartjson.stableOneWayStringify(
|
||||
{ z: 1, a: 2 },
|
||||
['a', 'z'] // Specify key order
|
||||
);
|
||||
```
|
||||
|
||||
### Base64 JSON Encoding
|
||||
|
||||
Encode JSON data as base64 for safe transmission:
|
||||
@@ -122,9 +161,9 @@ Transform class instances to JSON and back while preserving type safety:
|
||||
import { Smartjson, foldDec } from '@push.rocks/smartjson';
|
||||
|
||||
class User extends Smartjson {
|
||||
@foldDec() public username: string;
|
||||
@foldDec() public email: string;
|
||||
@foldDec() public settings: UserSettings;
|
||||
@foldDec() accessor username: string;
|
||||
@foldDec() accessor email: string;
|
||||
@foldDec() accessor settings: UserSettings;
|
||||
|
||||
// Properties without @foldDec won't be serialized
|
||||
private internalId: string;
|
||||
@@ -139,8 +178,8 @@ class User extends Smartjson {
|
||||
}
|
||||
|
||||
class UserSettings extends Smartjson {
|
||||
@foldDec() public theme: 'light' | 'dark' = 'light';
|
||||
@foldDec() public notifications: boolean = true;
|
||||
@foldDec() accessor theme: 'light' | 'dark' = 'light';
|
||||
@foldDec() accessor notifications: boolean = true;
|
||||
}
|
||||
|
||||
// Create and serialize
|
||||
@@ -162,8 +201,8 @@ console.log(restoredUser.settings instanceof UserSettings); // true
|
||||
|
||||
```typescript
|
||||
class Company extends Smartjson {
|
||||
@foldDec() public name: string;
|
||||
@foldDec() public employees: Employee[] = [];
|
||||
@foldDec() accessor name: string;
|
||||
@foldDec() accessor employees: Employee[] = [];
|
||||
|
||||
addEmployee(employee: Employee) {
|
||||
this.employees.push(employee);
|
||||
@@ -171,9 +210,9 @@ class Company extends Smartjson {
|
||||
}
|
||||
|
||||
class Employee extends Smartjson {
|
||||
@foldDec() public name: string;
|
||||
@foldDec() public role: string;
|
||||
@foldDec() public salary: number;
|
||||
@foldDec() accessor name: string;
|
||||
@foldDec() accessor role: string;
|
||||
@foldDec() accessor salary: number;
|
||||
|
||||
constructor(name: string, role: string, salary: number) {
|
||||
super();
|
||||
@@ -247,9 +286,9 @@ const isEqual = smartjson.deepEqualObjects(obj1, obj2); // true
|
||||
|
||||
```typescript
|
||||
class CachedAPIResponse extends Smartjson {
|
||||
@foldDec() public data: any;
|
||||
@foldDec() public timestamp: number;
|
||||
@foldDec() public endpoint: string;
|
||||
@foldDec() accessor data: any;
|
||||
@foldDec() accessor timestamp: number;
|
||||
@foldDec() accessor endpoint: string;
|
||||
|
||||
isExpired(maxAge: number = 3600000): boolean {
|
||||
return Date.now() - this.timestamp > maxAge;
|
||||
@@ -283,9 +322,9 @@ if (stored) {
|
||||
|
||||
```typescript
|
||||
class AppConfig extends Smartjson {
|
||||
@foldDec() public apiUrl: string;
|
||||
@foldDec() public features: Map<string, boolean> = new Map();
|
||||
@foldDec() public limits: {
|
||||
@foldDec() accessor apiUrl: string;
|
||||
@foldDec() accessor features: Map<string, boolean> = new Map();
|
||||
@foldDec() accessor limits: {
|
||||
maxUploadSize: number;
|
||||
maxConcurrentRequests: number;
|
||||
};
|
||||
@@ -311,6 +350,7 @@ class AppConfig extends Smartjson {
|
||||
|
||||
- `parse(jsonString: string): any` - Parse JSON with automatic buffer handling
|
||||
- `stringify(obj: any, simpleOrderArray?: string[], options?: Options): string` - Convert to JSON with stable ordering
|
||||
- `stableOneWayStringify(obj: any, simpleOrderArray?: string[], options?: Options): string` - Safe stringify with circular reference handling (one-way, for hashing/comparison)
|
||||
- `stringifyPretty(obj: any): string` - Pretty print JSON with 2-space indentation
|
||||
- `stringifyBase64(obj: any): string` - Encode JSON as base64
|
||||
- `parseBase64(base64String: string): any` - Decode base64 JSON
|
||||
@@ -328,7 +368,7 @@ class AppConfig extends Smartjson {
|
||||
|
||||
### Decorators
|
||||
|
||||
- `@foldDec()` - Mark class property for serialization
|
||||
- `@foldDec()` - Mark class property for serialization (use with `accessor` keyword)
|
||||
|
||||
## Performance Tips
|
||||
|
||||
@@ -336,7 +376,8 @@ class AppConfig extends Smartjson {
|
||||
2. **Enable pretty printing** only for debugging (it's slower)
|
||||
3. **Cache base64 encodings** when repeatedly sending the same data
|
||||
4. **Use JSON Lines** for streaming large datasets
|
||||
5. **Avoid circular references** in objects being serialized
|
||||
5. **Use stableOneWayStringify** for objects with circular references (for hashing/caching)
|
||||
6. **Prefer regular stringify** for round-trip serialization without cycles
|
||||
|
||||
## Migration Guide
|
||||
|
||||
@@ -358,19 +399,21 @@ This library supports modern browsers and Node.js environments. For older browse
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
||||
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
|
||||
|
||||
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
||||
|
||||
### Trademarks
|
||||
|
||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
|
||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
|
||||
|
||||
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
|
||||
|
||||
### Company Information
|
||||
|
||||
Task Venture Capital GmbH
|
||||
Registered at District court Bremen HRB 35230 HB, Germany
|
||||
Registered at District Court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||
For any legal inquiries or further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||
|
||||
+12
-1
@@ -3,7 +3,7 @@ import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartjson from '../ts/index.js';
|
||||
|
||||
class SomeClass extends smartjson.Smartjson {
|
||||
@smartjson.foldDec() thisis: string = 'test';
|
||||
@smartjson.foldDec() accessor thisis: string = 'test';
|
||||
constructor() {
|
||||
super();
|
||||
console.log(this.saveableProperties);
|
||||
@@ -104,4 +104,15 @@ tap.test('should respect simpleOrderArray comparator', async () => {
|
||||
expect(ordered.indexOf('"a"')).toBeLessThan(ordered.indexOf('"c"'));
|
||||
});
|
||||
|
||||
tap.test('stableOneWayStringify should handle circular references without throwing', async () => {
|
||||
const a: any = { name: 'x' };
|
||||
a.self = a;
|
||||
const b: any = { name: 'x' };
|
||||
b.self = b;
|
||||
const s1 = smartjson.stableOneWayStringify(a);
|
||||
const s2 = smartjson.stableOneWayStringify(b);
|
||||
expect(typeof s1).toEqual('string');
|
||||
expect(s1).toEqual(s2);
|
||||
});
|
||||
|
||||
tap.start();
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartjson',
|
||||
version: '5.1.0',
|
||||
version: '6.0.1',
|
||||
description: 'A library for handling typed JSON data, providing functionalities for parsing, stringifying, and working with JSON objects, including support for encoding and decoding buffers.'
|
||||
}
|
||||
|
||||
+20
-8
@@ -14,22 +14,34 @@ interface IEncodedBuffer {
|
||||
type TParseReviver = (this: any, key: string, value: any) => any;
|
||||
type TParseReplacer = (this: any, key: string, value: any) => any;
|
||||
|
||||
interface INodeBufferLike extends Uint8Array {
|
||||
toString(): string;
|
||||
toString(encoding: 'base64'): string;
|
||||
}
|
||||
|
||||
interface INodeBufferConstructor {
|
||||
from(data: Uint8Array): INodeBufferLike;
|
||||
from(data: string, encoding: 'base64'): INodeBufferLike;
|
||||
}
|
||||
|
||||
const getNodeBuffer = (): INodeBufferConstructor | undefined => {
|
||||
return (globalThis as typeof globalThis & { Buffer?: INodeBufferConstructor }).Buffer;
|
||||
};
|
||||
|
||||
// Utility functions to handle base64 encoding/decoding in a cross-platform way
|
||||
function base64Encode(data: Uint8Array): string {
|
||||
// Prefer Node's Buffer when available
|
||||
if (typeof Buffer !== 'undefined') {
|
||||
// @ts-ignore Buffer might not exist in browser builds
|
||||
return Buffer.from(data).toString('base64');
|
||||
const NodeBuffer = getNodeBuffer();
|
||||
if (NodeBuffer) {
|
||||
return NodeBuffer.from(data).toString('base64');
|
||||
}
|
||||
// Fallback for browsers
|
||||
return btoa(String.fromCharCode(...data));
|
||||
}
|
||||
|
||||
function base64Decode(str: string): Uint8Array {
|
||||
// Prefer Node's Buffer when available
|
||||
if (typeof Buffer !== 'undefined') {
|
||||
// @ts-ignore Buffer might not exist in browser builds
|
||||
const buf = Buffer.from(str, 'base64');
|
||||
const NodeBuffer = getNodeBuffer();
|
||||
if (NodeBuffer) {
|
||||
const buf = NodeBuffer.from(str, 'base64');
|
||||
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
}
|
||||
// Fallback for browsers
|
||||
|
||||
+80
-8
@@ -26,6 +26,69 @@ export const stringifyJsonL = (items: any[]): string => {
|
||||
return items.map((item) => stringify(item)).join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* stableOneWayStringify
|
||||
* - Produces a stable, deterministic JSON string
|
||||
* - Handles circular references without throwing (replaces cycles)
|
||||
* - Safe for hashing/comparisons ("one-way"; not intended for round-trips)
|
||||
*/
|
||||
export const stableOneWayStringify = (
|
||||
objArg: any,
|
||||
simpleOrderArray?: string[],
|
||||
optionsArg: plugins.IStableJsonTypes['Options'] = {}
|
||||
): string => {
|
||||
// Prepare object without throwing on circular references, and encode buffers
|
||||
const visited = new WeakSet<object>();
|
||||
const sanitize = (val: any): any => {
|
||||
// primitives
|
||||
if (val === null || typeof val !== 'object') {
|
||||
return val;
|
||||
}
|
||||
// Encode buffers/typed arrays via existing replacer
|
||||
const replaced = (bufferhandling.replacer as any)('', val);
|
||||
if (replaced && replaced.type === 'EncodedBuffer' && typeof replaced.data === 'string') {
|
||||
return replaced;
|
||||
}
|
||||
// Handle circular references
|
||||
if (visited.has(val)) {
|
||||
return '__cycle__';
|
||||
}
|
||||
visited.add(val);
|
||||
// Arrays
|
||||
if (Array.isArray(val)) {
|
||||
return val.map((item) => sanitize(item));
|
||||
}
|
||||
// Plain objects and class instances: copy enumerable own props
|
||||
const out: Record<string, any> = {};
|
||||
for (const key of Object.keys(val)) {
|
||||
try {
|
||||
out[key] = sanitize((val as any)[key]);
|
||||
} catch (e) {
|
||||
// In case of getters throwing or non-serializable, mark
|
||||
out[key] = '__unserializable__';
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const obj = sanitize(objArg);
|
||||
const options: plugins.IStableJsonTypes['Options'] = {
|
||||
...optionsArg,
|
||||
cycles: true,
|
||||
};
|
||||
if (simpleOrderArray && !options.cmp) {
|
||||
const order = new Map<string, number>();
|
||||
simpleOrderArray.forEach((key, idx) => order.set(key, idx));
|
||||
options.cmp = (a, b) => {
|
||||
const aIdx = order.has(a.key) ? (order.get(a.key) as number) : Number.POSITIVE_INFINITY;
|
||||
const bIdx = order.has(b.key) ? (order.get(b.key) as number) : Number.POSITIVE_INFINITY;
|
||||
if (aIdx !== bIdx) return aIdx - bIdx;
|
||||
return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
|
||||
};
|
||||
}
|
||||
return plugins.stableJson(obj, options);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param objArg
|
||||
@@ -100,7 +163,7 @@ export class Smartjson {
|
||||
// INSTANCE
|
||||
// ========
|
||||
|
||||
public saveableProperties: string[];
|
||||
public saveableProperties: string[] = [];
|
||||
|
||||
/**
|
||||
* folds a class into an object
|
||||
@@ -124,11 +187,11 @@ export class Smartjson {
|
||||
if (Array.isArray(val)) {
|
||||
return val.map((item) => foldValue(item));
|
||||
}
|
||||
return plugins.lodashCloneDeep(val);
|
||||
return structuredClone(val);
|
||||
};
|
||||
const props: string[] = (this as any).saveableProperties || [];
|
||||
for (const keyName of props) {
|
||||
const value = this[keyName];
|
||||
const value = (this as unknown as Record<string, unknown>)[keyName];
|
||||
result[keyName] = foldValue(value);
|
||||
}
|
||||
return result;
|
||||
@@ -144,14 +207,23 @@ export class Smartjson {
|
||||
}
|
||||
|
||||
/**
|
||||
* Decorator that marks a property as foldable
|
||||
* Decorator that marks a property as foldable (TC39 Stage 3 decorator)
|
||||
* Use with the `accessor` keyword: @foldDec() accessor myProp: string;
|
||||
*/
|
||||
export const foldDec = () => {
|
||||
return (target: any, key: string) => {
|
||||
if (!target.saveableProperties) {
|
||||
target.saveableProperties = [];
|
||||
return <This extends Smartjson, Value>(
|
||||
_value: ClassAccessorDecoratorTarget<This, Value>,
|
||||
context: ClassAccessorDecoratorContext<This, Value>
|
||||
): ClassAccessorDecoratorResult<This, Value> | void => {
|
||||
const propertyName = String(context.name);
|
||||
context.addInitializer(function (this: This) {
|
||||
if (!this.saveableProperties) {
|
||||
this.saveableProperties = [];
|
||||
}
|
||||
target.saveableProperties.push(key);
|
||||
if (!this.saveableProperties.includes(propertyName)) {
|
||||
this.saveableProperties.push(propertyName);
|
||||
}
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -5,12 +5,11 @@ import * as smartstring from '@push.rocks/smartstring';
|
||||
export { smartenv, smartstring };
|
||||
|
||||
// third party scope
|
||||
import lodashCloneDeep from 'lodash.clonedeep';
|
||||
import stableJson2 from 'fast-json-stable-stringify';
|
||||
|
||||
const stableJson = stableJson2 as any;
|
||||
|
||||
export { lodashCloneDeep, stableJson };
|
||||
export { stableJson };
|
||||
|
||||
export interface IStableJsonTypes {
|
||||
Comparator: (
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
|
||||
Reference in New Issue
Block a user