Compare commits

...

79 Commits

Author SHA1 Message Date
9bb6e0b497 update description 2024-05-29 14:13:49 +02:00
5275e13360 5.0.20 2024-05-28 00:50:30 +02:00
03fe2174d1 fix(core): update 2024-05-28 00:50:30 +02:00
7df82ce64d 5.0.19 2024-04-17 20:19:18 +02:00
09b74e4053 fix(core): update 2024-04-17 20:19:17 +02:00
096cd74773 5.0.18 2024-04-17 20:11:19 +02:00
e9a45ac993 fix(core): update 2024-04-17 20:11:18 +02:00
b3856cb94a 5.0.17 2024-04-17 20:10:59 +02:00
e44d014733 fix(core): update 2024-04-17 20:10:59 +02:00
777d7ae1b3 update tsconfig 2024-04-14 17:45:36 +02:00
f1f6b5fa79 update npmextra.json: githost 2024-04-01 21:35:43 +02:00
65673e9710 update npmextra.json: githost 2024-04-01 19:58:33 +02:00
66f1094cfe update npmextra.json: githost 2024-03-30 21:47:32 +01:00
8e93b8cb73 5.0.16 2024-03-19 13:50:07 +01:00
e38ccd221a fix(core): update 2024-03-19 13:50:06 +01:00
969b892ed8 5.0.15 2024-03-19 13:30:15 +01:00
d1d679ac34 fix(core): update 2024-03-19 13:30:15 +01:00
8937dfb553 5.0.14 2024-03-03 10:35:27 +01:00
09d45b1f45 fix(core): update 2024-03-03 10:35:26 +01:00
a897f01ec6 5.0.13 2024-03-03 10:30:12 +01:00
f951e0e70d fix(core): update 2024-03-03 10:30:11 +01:00
e79a2514ef 5.0.12 2024-03-03 10:29:19 +01:00
d77c104915 fix(core): update 2024-03-03 10:29:18 +01:00
45593168b0 5.0.11 2024-02-25 01:43:07 +01:00
0227f22ca6 fix(core): update 2024-02-25 01:43:07 +01:00
cece00a9b0 5.0.10 2023-08-24 12:01:21 +02:00
e90ae7649f fix(core): update 2023-08-24 12:01:21 +02:00
70e6150708 5.0.9 2023-08-24 10:48:52 +02:00
52928e0b9b fix(core): update 2023-08-24 10:48:51 +02:00
00ae980fa7 5.0.8 2023-08-19 09:45:22 +02:00
2cd2180788 fix(core): update 2023-08-19 09:45:22 +02:00
2a37a42ed0 5.0.7 2023-08-19 09:45:01 +02:00
e88deb1b5f fix(core): update 2023-08-19 09:45:00 +02:00
05f8e6812b switch to new org scheme 2023-07-10 02:56:36 +02:00
3affd81165 5.0.6 2023-06-03 16:28:41 +02:00
7a8f959cf4 fix(core): update 2023-06-03 16:28:41 +02:00
4df1d41cc7 5.0.5 2022-11-08 11:19:20 +01:00
fb83e41eb3 fix(core): update 2022-11-08 11:19:20 +01:00
27b67b63cc 5.0.4 2022-10-26 10:56:02 +02:00
697afbaf98 fix(core): update 2022-10-26 10:56:01 +02:00
ab3ae7ec90 5.0.3 2022-10-26 10:52:15 +02:00
b2bb918ee4 fix(core): update 2022-10-26 10:52:14 +02:00
606ff73f58 5.0.2 2022-09-13 21:37:42 +02:00
7ea17c792d fix(core): update 2022-09-13 21:37:42 +02:00
4478b7588a 5.0.1 2022-06-26 11:20:39 +02:00
9bac6e5809 fix(core): update 2022-06-26 11:20:39 +02:00
cbc7e4ebce 5.0.0 2022-06-09 19:55:12 +02:00
097f54a74c BREAKING CHANGE(core): update 2022-06-09 19:55:12 +02:00
807624d157 4.0.7 2022-06-09 19:54:44 +02:00
9d7e2e03d9 fix(core): update 2022-06-09 19:54:43 +02:00
9686caff18 4.0.6 2021-01-28 02:21:24 +00:00
9260d653a1 fix(core): update 2021-01-28 02:21:23 +00:00
28cd849d0d 4.0.5 2020-10-09 09:41:16 +00:00
89a399bf42 fix(core): update 2020-10-09 09:41:15 +00:00
16048fe96d 4.0.4 2020-10-05 16:20:27 +00:00
04d60333a9 fix(core): update 2020-10-05 16:20:27 +00:00
c30f1f4ab9 4.0.3 2020-10-05 15:28:30 +00:00
fc91dd3171 fix(core): update 2020-10-05 15:28:29 +00:00
55f8951732 4.0.2 2020-10-05 12:06:14 +00:00
92f212e9d3 fix(core): update 2020-10-05 12:06:13 +00:00
1a22db26da 4.0.1 2020-10-05 11:26:07 +00:00
0d3bcab40f fix(core): update 2020-10-05 11:26:06 +00:00
e11ace6a23 4.0.0 2020-10-05 11:22:17 +00:00
f29b632bd2 BREAKING CHANGE(core): update 2020-10-05 11:22:16 +00:00
25f80b6b59 3.0.12 2020-10-05 11:13:17 +00:00
176ac34504 fix(core): update 2020-10-05 11:13:17 +00:00
2707542234 3.0.11 2020-10-03 11:20:59 +00:00
ee025d094c fix(core): update 2020-10-03 11:20:58 +00:00
9bc1c4bf93 3.0.10 2019-12-15 19:27:19 +00:00
5176a34575 3.0.9 2019-12-15 19:05:21 +00:00
fe9f9299fc fix(core): update 2019-12-15 19:05:20 +00:00
62cf2fd262 3.0.8 2019-08-25 16:03:35 +02:00
65e581d48b fix(core): update 2019-08-25 16:03:34 +02:00
4ff97294bb 3.0.7 2019-08-09 10:55:54 +02:00
2d5bd6a2f0 fix(core): update 2019-08-09 10:55:54 +02:00
a2649b7854 3.0.6 2019-08-09 10:55:17 +02:00
b901f8604b fix(core): update 2019-08-09 10:55:17 +02:00
d70310ce8b 3.0.5 2019-07-04 17:04:24 +02:00
e0e9ceed31 fix(core): update 2019-07-04 17:04:24 +02:00
22 changed files with 7526 additions and 1983 deletions

View File

@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

18
.gitignore vendored
View File

@ -1,4 +1,20 @@
node_modules/ .nogit/
# artifacts
coverage/ coverage/
public/ public/
pages/ pages/
# installs
node_modules/
# caches
.yarn/
.cache/
.rpt2_cache
# builds
dist/
dist_*/
# custom

View File

@ -1,150 +0,0 @@
# gitzone standard
image: hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: "$CI_BUILD_STAGE"
stages:
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
tags:
- docker
- notpriv
snyk:
stage: security
script:
- npmci npm prepare
- npmci command npm install -g snyk
- npmci command npm install --ignore-scripts
- npmci command snyk test
tags:
- docker
- notpriv
sast:
stage: security
image: registry.gitlab.com/hosttoday/ht-docker-dbase:npmci
variables:
DOCKER_DRIVER: overlay2
allow_failure: true
services:
- docker:stable-dind
script:
- npmci npm prepare
- npmci npm install
- npmci command npm run build
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
- docker run
--env SAST_CONFIDENCE_LEVEL="${SAST_CONFIDENCE_LEVEL:-3}"
--volume "$PWD:/code"
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/sast:$SP_VERSION" /app/bin/run /code
artifacts:
reports:
sast: gl-sast-report.json
tags:
- docker
- priv
# ====================
# test stage
# ====================
testLTS:
stage: test
script:
- npmci npm prepare
- npmci node install lts
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
testSTABLE:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
image: docker:stable
allow_failure: true
services:
- docker:stable-dind
script:
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
- docker run
--env SOURCE_CODE="$PWD"
--volume "$PWD":/code
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
artifacts:
paths: [codeclimate.json]
tags:
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- docker
- notpriv
pages:
image: hosttoday/ht-docker-node:npmci
stage: metadata
script:
- npmci command npm install -g typedoc typescript
- npmci npm prepare
- npmci npm install
- npmci command typedoc --module "commonjs" --target "ES2016" --out public/ ts/
tags:
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

4
.snyk
View File

@ -1,4 +0,0 @@
# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities.
version: v1.13.3
ignore: {}
patch: {}

11
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"type": "node-terminal"
}
]
}

26
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,26 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}
}
}
}
]
}

View File

@ -1,54 +0,0 @@
# @pushrocks/smartjson
typed json handlers
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartjson)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartjson)
* [github.com (source mirror)](https://github.com/pushrocks/smartjson)
* [docs (typedoc)](https://pushrocks.gitlab.io/smartjson/)
## Status for master
[![build status](https://gitlab.com/pushrocks/smartjson/badges/master/build.svg)](https://gitlab.com/pushrocks/smartjson/commits/master)
[![coverage report](https://gitlab.com/pushrocks/smartjson/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smartjson/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/@pushrocks/smartjson.svg)](https://www.npmjs.com/package/@pushrocks/smartjson)
[![Known Vulnerabilities](https://snyk.io/test/npm/@pushrocks/smartjson/badge.svg)](https://snyk.io/test/npm/@pushrocks/smartjson)
[![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
## Usage
Use TypeScript for best in class instellisense.
### Classes
SmartJson makes it easy to fold and enfold classes into and from JSON
```javascript
import { Smartjson, foldDec } from 'smartjson';
class AwesomeClass extends Smartjson {
static stringify
computedValue: string;
@foldDec() // mark anotherValueToStore as foldable
anotherValueToStore: string = null;
constructor() {
super(); // this is important
}
}
let myAwesomeInstance = new AwesomeClass();
let foldedObject = myAwesomeInstance.foldToObject(); // will return {anotherValueToStore: null}
myAwesomeInstance.enfoldFromObject({ anotherValueToStore: 'hi' });
foldedObject = myAwesomeInstance.foldToObject(); // will return {anotherValueToStore: 'hi'}
```
For further information read the linked docs at the top of this readme.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html)
[![repo-footer](https://pushrocks.gitlab.io/assets/repo-footer.svg)](https://maintainedby.lossless.com)

View File

@ -3,13 +3,30 @@
"npmAccessLevel": "public" "npmAccessLevel": "public"
}, },
"gitzone": { "gitzone": {
"projectType": "npm",
"module": { "module": {
"githost": "gitlab.com", "githost": "code.foss.global",
"gitscope": "pushrocks", "gitscope": "push.rocks",
"gitrepo": "smartjson", "gitrepo": "smartjson",
"shortDescription": "typed json handlers", "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.",
"npmPackagename": "@pushrocks/smartjson", "npmPackagename": "@push.rocks/smartjson",
"license": "MIT" "license": "MIT",
"keywords": [
"JSON handling",
"typed JSON",
"JSON parsing",
"JSON stringifying",
"base64 encoding",
"buffer handling",
"data serialization",
"data deserialization",
"TypeScript support",
"data encoding",
"data decoding"
]
} }
},
"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"
} }
} }

1667
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,34 +1,65 @@
{ {
"name": "@pushrocks/smartjson", "name": "@push.rocks/smartjson",
"version": "3.0.4", "version": "5.0.20",
"private": false, "private": false,
"description": "typed json handlers", "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/index.js", "main": "dist_ts/index.js",
"typings": "dist/index.d.ts", "typings": "dist_ts/index.d.ts",
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "(tstest test/ --web)",
"build": "(tsbuild)" "build": "(tsbuild --web --allowimplicitany)",
"buildDocs": "tsdoc"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+ssh://git@gitlab.com/pushrocks/smartjson.git" "url": "https://code.foss.global/push.rocks/smartjson.git"
}, },
"author": "Lossless GmbH", "author": "Lossless GmbH",
"license": "MIT", "license": "MIT",
"bugs": { "bugs": {
"url": "https://gitlab.com/pushrocks/smartjson/issues" "url": "https://gitlab.com/pushrocks/smartjson/issues"
}, },
"homepage": "https://gitlab.com/pushrocks/smartjson#README", "homepage": "https://code.foss.global/push.rocks/smartjson",
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.11", "@git.zone/tsbuild": "^2.1.66",
"@gitzone/tsrun": "^1.2.6", "@git.zone/tsrun": "^1.2.44",
"@gitzone/tstest": "^1.0.24", "@git.zone/tstest": "^1.0.88",
"@pushrocks/tapbundle": "^3.0.11", "@push.rocks/tapbundle": "^5.0.23",
"@types/node": "^12.0.12" "@types/node": "^20.12.7"
}, },
"dependencies": { "dependencies": {
"@types/fast-json-stable-stringify": "^2.0.0", "@push.rocks/smartenv": "^5.0.12",
"fast-json-stable-stringify": "^2.0.0", "@push.rocks/smartstring": "^4.0.15",
"fast-json-stable-stringify": "^2.1.0",
"lodash.clonedeep": "^4.5.0" "lodash.clonedeep": "^4.5.0"
} },
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
],
"type": "module",
"keywords": [
"JSON handling",
"typed JSON",
"JSON parsing",
"JSON stringifying",
"base64 encoding",
"buffer handling",
"data serialization",
"data deserialization",
"TypeScript support",
"data encoding",
"data decoding"
]
} }

6708
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

141
readme.md Normal file
View File

@ -0,0 +1,141 @@
# @push.rocks/smartjson
typed json handlers
## Install
To install `@push.rocks/smartjson`, you can use npm or yarn as follows:
```shell
npm install @push.rocks/smartjson --save
# or using yarn
yarn add @push.rocks/smartjson
```
## Usage
`@push.rocks/smartjson` offers typed JSON handling, including features like folding and enfolding classes from JSON, JSON parsing with support for buffers, and comparison of JSON objects for equality. This guide will walk through various use cases and scenarios to effectively utilize `@push.rocks/smartjson` in your projects.
### Basic Import
First, make sure to import the module:
```typescript
import * as smartjson from '@push.rocks/smartjson';
```
### Parsing and Stringifying JSON
- **Parsing JSON Strings:**
`smartjson` enhances JSON parsing by supporting JavaScript's typed arrays, particularly with `Buffer` handling.
```typescript
const jsonString = '{"type":"Buffer","data":[116,101,115,116]}';
const parsedObject = smartjson.parse(jsonString);
console.log(parsedObject); // Output will be based on the content of jsonString
```
- **Stringifying Objects:**
`@push.rocks/smartjson` provides a `stringify` function that can convert JavaScript objects into JSON strings, with special handling for `Buffer` objects.
```typescript
const myObject = {
exampleBuffer: new Uint8Array([116, 101, 115, 116])
};
const jsonString = smartjson.stringify(myObject);
console.log(jsonString); // Will include `exampleBuffer` encoded in a special format
```
### Working with Base64 Encoded JSON
For cases where JSON strings are encoded in base64 format, `smartjson` offers methods to encode and decode these strings transparently.
```typescript
const objectToEncode = { hello: 'world' };
const base64EncodedJson = smartjson.stringifyBase64(objectToEncode);
console.log(base64EncodedJson); // Encoded JSON string
const decodedObject = smartjson.parseBase64(base64EncodedJson);
console.log(decodedObject); // Original object
```
### Folding and Enfolding Classes
`@push.rocks/smartjson` allows you to fold (serialize) and enfold (deserialize) class instances to and from JSON. This is particularly useful when working with typed objects and you need to maintain type integrity across serialization.
- **Defining a Foldable Class:**
Decorate properties that should be included in JSON with `@smartjson.foldDec()`.
```typescript
import { Smartjson, foldDec } from '@push.rocks/smartjson';
class MyDataModel extends Smartjson {
@foldDec() public someProperty: string = 'default';
constructor(public id: number, someProperty?: string) {
super();
if (someProperty) this.someProperty = someProperty;
}
}
```
- **Folding and Enfolding Instances:**
```typescript
const instance = new MyDataModel(1, 'value');
const folded = instance.foldToJson(); // Serialize to JSON
console.log(folded);
const enfoldedInstance = MyDataModel.enfoldFromJson(folded); // Deserialize back to instance
console.log(enfoldedInstance);
```
### Deep Comparison
`@push.rocks/smartjson` enables deep comparison of objects to determine if they are equivalent.
```typescript
const obj1 = { a: 1, b: { c: 2 }};
const obj2 = { a: 1, b: { c: 2 }};
const isEqual = smartjson.deepEqualObjects(obj1, obj2);
console.log(isEqual); // true
```
### Handling Buffers and Typed Arrays
`smartjson` transparently handles JavaScript's `Buffer` and Typed Arrays during JSON serialization, making it effortless to work with binary data in JSON format.
```typescript
const buffer = new Uint8Array([1, 2, 3]);
const objWithBuffer = { key: buffer };
const serialized = smartjson.stringify(objWithBuffer);
const deserialized = smartjson.parse(serialized);
console.log(deserialized.key); // Instance of Uint8Array or Buffer
```
In addition to these features, `@push.rocks/smartjson` supports efficient base64 encoding/decoding, deep object comparison, and JSON Lines parsing, making it a versatile library for dealing with JSON in TypeScript projects.
For further information and more detailed examples, referring to the API documentation and the source code on [GitLab](https://gitlab.com/push.rocks/smartjson) can provide deeper insights into `@push.rocks/smartjson`'s capabilities.
## 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.
**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.
### Company Information
Task Venture Capital GmbH
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.
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.

75
test/test.both.ts Normal file
View File

@ -0,0 +1,75 @@
import { tap, expect } from '@push.rocks/tapbundle';
import * as smartjson from '../ts/index.js';
class SomeClass extends smartjson.Smartjson {
@smartjson.foldDec() thisis: string = 'test';
constructor() {
super();
console.log(this.saveableProperties);
}
}
let mySomeClass: SomeClass;
tap.test('should create a Foldable extended instance', async () => {
mySomeClass = new SomeClass();
expect(mySomeClass).toBeInstanceOf(SomeClass);
expect(mySomeClass).toBeInstanceOf(smartjson.Smartjson);
});
tap.test('should create a folded object', async () => {
let foldedObject = mySomeClass.foldToObject();
expect(foldedObject).property('thisis').toEqual('test');
});
tap.test('should enfold from object', async () => {
const mySomeClass2 = SomeClass.enfoldFromObject({ thisis: 'test2' });
expect(mySomeClass2).property('thisis').toEqual('test2');
});
tap.test('should products stable jsons', async () => {
const jsonString = smartjson.stringify({
a: 1,
f: 6,
b: 3,
c: 3,
e: 5,
d: 4,
});
console.log(jsonString);
});
tap.test('should work with base64', async () => {
const someObject = {
hi: 'there',
thisIs: 'awesome',
};
const base64Json = smartjson.stringifyBase64(someObject);
console.log(base64Json);
const decodedObject = smartjson.parseBase64(base64Json);
expect(decodedObject).toEqual(someObject);
});
tap.test('stringify should handle plain string', async () => {
const stringifiedString = smartjson.stringify('hello');
console.log(stringifiedString);
expect(stringifiedString).toEqual('"hello"');
expect(smartjson.parse(stringifiedString)).toEqual('hello');
});
tap.test('should work with buffers', async () => {
const someObject = {
myBuffer: new TextEncoder().encode('hello')
};
console.log(someObject.myBuffer);
const stringified = smartjson.stringify(someObject);
console.log(stringified);
const decoded = smartjson.parse(stringified);
console.log(decoded.myBuffer);
let text = new TextDecoder().decode(decoded.myBuffer);
expect(text).toEqual('hello');
});
tap.start();

View File

@ -1,35 +0,0 @@
import { tap, expect } from '@pushrocks/tapbundle';
import { Smartjson, foldDec } from '../ts/index';
class SomeClass extends Smartjson {
@foldDec() thisis: string = 'test';
constructor() {
super();
console.log(this.saveableProperties);
}
}
let mySomeClass: SomeClass;
tap.test('should create a Foldable extended instance', async () => {
mySomeClass = new SomeClass();
expect(mySomeClass).to.be.instanceof(SomeClass);
expect(mySomeClass).to.be.instanceof(Smartjson);
});
tap.test('should create a folded object', async () => {
let foldedObject = mySomeClass.foldToObject();
expect(foldedObject)
.property('thisis')
.to.equal('test');
});
tap.test('should enfold from object', async () => {
mySomeClass.enfoldFromObject({ thisis: 'test2' });
expect(mySomeClass)
.property('thisis')
.to.equal('test2');
});
tap.start();

8
ts/00_commitinfo_data.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartjson',
version: '5.0.20',
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.'
}

121
ts/bufferhandling.ts Normal file
View File

@ -0,0 +1,121 @@
import * as plugins from './smartjson.plugins.js';
// Define interfaces and types for better type checking and readability
interface IBufferLike {
type: 'Buffer';
data: string | any[]; // `any[]` for array data representation
}
interface IEncodedBuffer {
type: 'EncodedBuffer',
data: string;
}
type TParseReviver = (this: any, key: string, value: any) => any;
type TParseReplacer = (this: any, key: string, value: any) => any;
// Utility functions to handle base64 encoding/decoding in a cross-platform way
function base64Encode(data: Uint8Array): string {
return btoa(String.fromCharCode(...data));
}
function base64Decode(str: string): Uint8Array {
return new Uint8Array(Array.from(atob(str)).map((char) => char.charCodeAt(0)));
}
// Main functionality with cross-platform support
function stringify(value: any, space?: string | number): string {
return JSON.stringify(value, replacer, space);
}
function parse(text: string): any {
return JSON.parse(text, reviver);
}
const replacer: TParseReplacer = (key, value) => {
// Check if value is IBufferLike
if (isBufferLike(value)) {
let bufferData: Uint8Array;
// Handle IBufferLike objects with a .data property
if ('data' in value && isArray(value.data)) {
if (value.data.length > 0) {
bufferData = new Uint8Array(value.data);
} else {
return ''; // Return empty string for empty data arrays
}
}
// Handle Uint8Array directly
else if (value instanceof Uint8Array) {
bufferData = value;
} else {
// If not a recognized format, return value as is
return value;
}
// Encode the bufferData (Uint8Array) to base64
const base64Data = 'base64:' + base64Encode(bufferData);
return {
type: 'EncodedBuffer',
data: base64Data,
};
}
// Return value unchanged if not buffer-like
return value;
};
const reviver: TParseReviver = (key, value) => {
if (isEncodedBuffer(value)) {
if (isString(value.data) && value.data.startsWith('base64:')) {
// Correctly slice the 'base64:' prefix before decoding
const base64Data = value.data.slice(7); // Skip 'base64:' prefix
const buffer = base64Decode(base64Data);
// Assuming the rest of your application can work directly with Uint8Array,
// otherwise, you might need to convert it to another format
return buffer;
}
}
return value;
};
function isEncodedBuffer(x: any): x is IEncodedBuffer {
return isObject(x) && (x as any).type === 'EncodedBuffer' && isString((x as any).data);
}
function isBufferLike(x: any): x is IBufferLike | Uint8Array {
return (
(isObject(x) &&
((x as any).type === 'Buffer' &&
(isArray((x as any).data) || isString((x as any).data)))) ||
x instanceof Uint8Array
);
}
/**
* We use this function to check if a value is an array
* @param x
* @returns
*/
function isArray(x: any): x is any[] {
return Array.isArray(x);
}
/**
* We use this function to check if a value is a string
* @param x
* @returns
*/
function isString(x: any): x is string {
return typeof x === 'string';
}
/**
* We use this function to check if a value is an object
* @param x
*/
function isObject(x: any): x is object {
return typeof x === 'object' && x !== null;
}
export { stringify, parse, replacer, reviver };

View File

@ -1,48 +1,121 @@
import * as plugins from './smartjson.plugins'; import * as plugins from './smartjson.plugins.js';
import * as bufferhandling from './bufferhandling.js';
interface JsonObject {
[key: string]: any;
}
/**
* allows you to parse a json
*/
export const parse = bufferhandling.parse;
export const parseJsonL = (jsonlData: string): JsonObject[] => {
const lines = jsonlData.trim().split('\n');
const parsedData: JsonObject[] = lines.reduce((acc, line) => {
if (line.trim().length > 0) {
acc.push(JSON.parse(line));
}
return acc;
}, [] as JsonObject[]);
return parsedData;
}
/**
*
* @param objArg
* @param optionsArg
*/
export const stringify = (
objArg: any,
simpleOrderArray?: string[],
optionsArg: plugins.IStableJsonTypes['Options'] = {}
): string => {
const bufferedJson = bufferhandling.stringify(objArg);
objArg = JSON.parse(bufferedJson);
let returnJson = plugins.stableJson(objArg, optionsArg);
return returnJson;
};
export const stringifyPretty = (objectArg: any) => {
const stringified = stringify(objectArg);
const object = JSON.parse(stringified);
return JSON.stringify(object, null, 2);
}
export const stringifyBase64 = (...args: Parameters<typeof stringify>): string => {
const stringifiedResult = stringify(...args);
return plugins.smartstring.base64.encodeUri(stringifiedResult);
};
export const parseBase64 = (base64JsonStringArg: string) => {
const simpleStringified = plugins.smartstring.base64.decode(base64JsonStringArg);
return parse(simpleStringified);
};
parse;
export class Smartjson { export class Smartjson {
// ====== /**
// STATIC * enfolds data from an object
// ====== */
static parse = JSON.parse; public static enfoldFromObject(objectArg) {
const newInstance = new this();
for (const keyName in objectArg) {
if (newInstance.saveableProperties.indexOf(keyName) !== -1) {
newInstance[keyName] = objectArg[keyName];
}
}
return newInstance;
}
static stringify = (objArg: any, optionsArg: plugins.stableJson.Options) => { /**
return plugins.stableJson(objArg, optionsArg) * enfold from json
}; */
public static enfoldFromJson(jsonArg: string) {
const objectFromJson = parse(jsonArg);
return this.enfoldFromObject(objectFromJson);
}
// ======== // ========
// INSTANCE // INSTANCE
// ======== // ========
saveableProperties: string[]; public saveableProperties: string[];
/** /**
* folds a class into an object * folds a class into an object
*/ */
foldToObject() { public foldToObject() {
let newFoldedObject: {[key: string]: any} = {}; const newFoldedObject: { [key: string]: any } = {};
for (let keyName of this.saveableProperties) { const trackMap = [];
newFoldedObject[keyName] = plugins.lodashCloneDeep(this[keyName]); for (const keyName of this.saveableProperties) {
let value = this[keyName];
if (value instanceof Smartjson) {
if (trackMap.includes(value)) {
throw new Error('cycle detected');
}
trackMap.push(value);
value = value.foldToObject();
}
newFoldedObject[keyName] = plugins.lodashCloneDeep(value);
} }
return newFoldedObject; return newFoldedObject;
} }
/** /**
* enfolds data from an object * folds a class into an object
*/ */
enfoldFromObject(objectArg) { public foldToJson() {
for (let keyName in objectArg) { const foldedObject = this.foldToObject();
if (this.saveableProperties.indexOf(keyName) !== -1) { return stringify(foldedObject);
this[keyName] = objectArg[keyName];
}
}
} }
} }
/** /**
* Decorator that marks a property as foldable * Decorator that marks a property as foldable
*/ */
export let foldDec = () => { export const foldDec = () => {
return (target: any, key: string) => { return (target: any, key: string) => {
if (!target.saveableProperties) { if (!target.saveableProperties) {
target.saveableProperties = []; target.saveableProperties = [];
@ -50,3 +123,25 @@ export let foldDec = () => {
target.saveableProperties.push(key); target.saveableProperties.push(key);
}; };
}; };
export const deepEqualObjects = (object1: any, object2: any): boolean => {
const object1String = stringify(object1);
const object2String = stringify(object2);
return object1String === object2String;
};
export const deepEqualJsonLStrings = (jsonLString1: string, jsonLString2: string): boolean => {
const firstArray = [];
jsonLString1.split('\n').forEach((line) => {
if (line) {
firstArray.push(parse(line));
}
});
const secondArray = [];
jsonLString2.split('\n').forEach((line) => {
if (line) {
secondArray.push(parse(line));
}
});
return deepEqualObjects(firstArray, secondArray);
}

View File

@ -1,7 +1,31 @@
import lodashCloneDeep from 'lodash.clonedeep'; // @pushrocks scope
import stableJson from 'fast-json-stable-stringify'; import * as smartenv from '@push.rocks/smartenv';
import * as smartstring from '@push.rocks/smartstring';
export { export { smartenv, smartstring };
lodashCloneDeep,
stableJson // third party scope
import lodashCloneDeep from 'lodash.clonedeep';
import stableJson2 from 'fast-json-stable-stringify';
const stableJson = stableJson2 as any;
export { lodashCloneDeep, stableJson };
export interface IStableJsonTypes {
Comparator: (
a: IStableJsonTypes['CompareDescriptor'],
b: IStableJsonTypes['CompareDescriptor']
) => number;
CompareDescriptor: {
key: string;
value: any;
};
Options: {
cmp?: (
a: IStableJsonTypes['CompareDescriptor'],
b: IStableJsonTypes['CompareDescriptor']
) => number;
cycles?: boolean;
};
} }

View File

@ -1,8 +1,14 @@
{ {
"compilerOptions": { "compilerOptions": {
"experimentalDecorators": true, "experimentalDecorators": true,
"esModuleInterop": true, "useDefineForClassFields": false,
"target": "es2017", "target": "ES2022",
"module": "commonjs" "module": "NodeNext",
} "moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
} }

View File

@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}