json-storage-formatter 1.0.6 → 1.0.8

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/lib/bundle.js ADDED
@@ -0,0 +1 @@
1
+ !function(r,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["json-storage-formatter"]=t():r["json-storage-formatter"]=t()}(this,(()=>(()=>{"use strict";var r={991:(r,t,e)=>{var n=Object.create?function(r,t,e,n){void 0===n&&(n=e);var o=Object.getOwnPropertyDescriptor(t,e);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(r,n,o)}:function(r,t,e,n){void 0===n&&(n=e),r[n]=t[e]};Object.defineProperty(t,"__esModule",{value:!0}),function(r,t){for(var e in r)"default"===e||Object.prototype.hasOwnProperty.call(t,e)||n(t,r,e)}(e(729),t)},729:(r,t)=>{function e(r){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(r){return typeof r}:function(r){return r&&"function"==typeof Symbol&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},e(r)}function n(r,t,n){return(t=function(r){var t=function(r,t){if("object"!==e(r)||null===r)return r;var n=r[Symbol.toPrimitive];if(void 0!==n){var o=n.call(r,"string");if("object"!==e(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(r)}(r);return"symbol"===e(t)?t:String(t)}(t))in r?Object.defineProperty(r,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):r[t]=n,r}function o(r,t){if(r){if("string"==typeof r)return i(r,t);var e=Object.prototype.toString.call(r).slice(8,-1);return"Object"===e&&r.constructor&&(e=r.constructor.name),"Map"===e||"Set"===e?Array.from(r):"Arguments"===e||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e)?i(r,t):void 0}}function i(r,t){(null==t||t>r.length)&&(t=r.length);for(var e=0,n=new Array(t);e<t;e++)n[e]=r[e];return n}Object.defineProperty(t,"__esModule",{value:!0}),t.formatToStore=t.formatFromStore=t.isPrimitive=t.isFunction=t.isRegex=t.isDate=t.isString=t.isBoolean=t.isNumber=t.isNil=t.clone=void 0,t.clone=function(r){var e,u=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).shallow;if((0,t.isPrimitive)(r)||(0,t.isDate)(r))return r;if(Array.isArray(r))return u?function(r){if(Array.isArray(r))return i(r)}(e=r)||function(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}(e)||o(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}():r.map((function(r){return(0,t.clone)(r)}));if(r instanceof Map){var a=Array.from(r.entries());return u?new Map(a):new Map(a.map((function(r){return(0,t.clone)(r)})))}if(r instanceof Set){var f=Array.from(r.values());return u?new Set(f):new Set(f.map((function(r){return(0,t.clone)(r)})))}return r instanceof RegExp?new RegExp(r.toString()):(0,t.isFunction)(r)?u?r:Object.create(r):u?Object.assign({},r):r instanceof Error?new Error(r.message):Object.keys(r).reduce((function(e,o){var i=r[o];return Object.assign(Object.assign({},e),n({},o,(0,t.clone)(i)))}),{})},t.isNil=function(r){return null==r},t.isNumber=function(r){return"number"==typeof r},t.isBoolean=function(r){return"boolean"==typeof r},t.isString=function(r){return"string"==typeof r},t.isDate=function(r){return r instanceof Date},t.isRegex=function(r){return r instanceof RegExp},t.isFunction=function(r){return"function"==typeof r||r instanceof Function},t.isPrimitive=function(r){return(0,t.isNil)(r)||(0,t.isNumber)(r)||(0,t.isBoolean)(r)||(0,t.isString)(r)||"symbol"===e(r)},t.formatFromStore=function(r){return function(r){var e,i;if((0,t.isPrimitive)(r))return r;if("date"===(null==r?void 0:r.$t))return new Date(r.$v);if("map"===(null==r?void 0:r.$t)){var u=(null!==(e=r.$v)&&void 0!==e?e:[]).map((function(r){var e,n,i=(n=2,function(r){if(Array.isArray(r))return r}(e=r)||function(r,t){var e=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=e){var n,o,i,u,a=[],f=!0,c=!1;try{if(i=(e=e.call(r)).next,0===t){if(Object(e)!==e)return;f=!1}else for(;!(f=(n=i.call(e)).done)&&(a.push(n.value),a.length!==t);f=!0);}catch(r){c=!0,o=r}finally{try{if(!f&&null!=e.return&&(u=e.return(),Object(u)!==u))return}finally{if(c)throw o}}return a}}(e,n)||o(e,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),u=i[0],a=i[1];return[u,(0,t.formatFromStore)(a)]}));return new Map(u)}if("set"===(null==r?void 0:r.$t)){var a=null!==(i=r.$v)&&void 0!==i?i:[].map((function(r){return(0,t.formatFromStore)(r)}));return new Set(a)}return"regex"===(null==r?void 0:r.$t)?new RegExp(r.$v):"error"===(null==r?void 0:r.$t)?new Error(r.$v):Array.isArray(r)?r.map((function(r){return(0,t.formatFromStore)(r)})):"function"===(null==r?void 0:r.$t)?Function("(".concat(r.$v,")(...arguments)")):Object.keys(r).reduce((function(e,o){var i=r[o];return Object.assign(Object.assign({},e),n({},o,(0,t.formatFromStore)(i)))}),{})}((arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).jsonParse?JSON.parse(r):(0,t.clone)(r))},t.formatToStore=function(r){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{stringify:!1},i=o.stringify,u=o.validator,a=o.excludeTypes,f=o.excludeKeys,c=new Set(null!=a?a:[]),s=new Set(null!=f?f:[]),l=c.size||s.size,m=null!=u?u:function(r){var t=r.key,n=r.value;if(!l)return!0;var o=s.has(t),i=c.has(e(n));return!o&&!i},v=function r(e){if((0,t.isPrimitive)(e))return e;if(Array.isArray(e))return e.map((function(t){return r(t)}));if(e instanceof Map)return{$t:"map",$v:Array.from(e.entries()).map((function(t){return r(t)}))};if(e instanceof Set)return{$t:"set",$v:Array.from(e.values()).map((function(t){return r(t)}))};if((0,t.isDate)(e))return{$t:"date",$v:e.toISOString()};if((0,t.isRegex)(e))return{$t:"regex",$v:e.toString()};if((0,t.isFunction)(e)){var o;try{o={$t:"function",$v:e.toString()}}catch(r){o={$t:"error",$v:"Error: Could not serialize function"}}return o}return e instanceof Error?{$t:"error",$v:e.message}:Object.keys(e).reduce((function(t,o){var i=e[o],u=r(i);return m({obj:e,key:o,value:u})?Object.assign(Object.assign({},t),n({},o,r(i))):t}),{})}((0,t.clone)(r));return i?JSON.stringify(v):v}}},t={};return function e(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return r[n](i,i.exports,e),i.exports}(991)})()));
package/lib/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './json-storage-formatter';
@@ -1,14 +1,19 @@
1
- export type IValueWithMedaData = {
2
- $t?: 'map' | 'set' | 'date' | 'regex' | 'error';
1
+ export type IValueWithMetaData = {
2
+ $t?: 'map' | 'set' | 'date' | 'regex' | 'error' | 'function';
3
3
  $v?: unknown;
4
4
  };
5
5
  /**
6
6
  * Deep clone an object, it also suppors Map, Set, Arrays
7
- * @param obj
7
+ * @param value
8
8
  * @returns
9
9
  * A deep clone of the object
10
10
  * */
11
- export declare const clone: <T>(obj: T) => T;
11
+ export declare const clone: <T>(value: T, { shallow, }?: {
12
+ /**
13
+ * If true, it will only clone the first level of the object
14
+ */
15
+ shallow?: boolean;
16
+ }) => T;
12
17
  /**
13
18
  * Check if a value is null or undefined
14
19
  * @param value
@@ -54,6 +59,12 @@ export declare const isDate: (value: unknown) => boolean;
54
59
  * @returns true if the value is a RegExp, false otherwise
55
60
  * */
56
61
  export declare const isRegex: (value: unknown) => boolean;
62
+ /**
63
+ * Check if a value is a function
64
+ * @param value The value to check
65
+ * @returns true if the value is a function, false otherwise
66
+ * */
67
+ export declare const isFunction: (value: unknown) => boolean;
57
68
  /**
58
69
  * Check if a value is a primitive
59
70
  * @param value
@@ -67,18 +78,32 @@ export declare const isPrimitive: (value: unknown) => boolean;
67
78
  * Format an value with possible metadata to his original form, it also supports Map, Set, Arrays
68
79
  * @param value
69
80
  * @returns
70
- * Orinal form of the value
81
+ * Original form of the value
71
82
  */
72
- export declare const formatFromStore: <T = unknown>(value: unknown) => T;
83
+ export declare const formatFromStore: <T = unknown>(value: unknown, { jsonParse, }?: {
84
+ /** If the value should be parsed from json before formatting */
85
+ jsonParse?: boolean;
86
+ }) => T;
87
+ export type TPrimitives = 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'function' | 'object';
73
88
  /**
74
89
  * Add metadata to a value to store it as json, it also supports Map, Set, Arrays,
75
- * Returns a new object wich is a clone of the original object with metadata
90
+ * Returns a new object which is a clone of the original object with metadata
76
91
  * @template {TValue} The type of the value to format
77
92
  * @template {TStringify} If the value should be stringified
78
93
  * @param {TValue} value The value to format
79
94
  * @param {{ stringify: TStringify }} { stringify: boolean } If the value should be stringified
80
95
  */
81
- export declare const formatToStore: <TValue, TStringify extends boolean = false>(value: TValue, { stringify }?: {
82
- stringify: TStringify;
96
+ export declare const formatToStore: <TValue, TStringify extends boolean = false>(value: TValue, { stringify, validator, excludeTypes, excludeKeys, }?: {
97
+ stringify?: TStringify;
98
+ excludeTypes?: TPrimitives[] | Set<TPrimitives>;
99
+ excludeKeys?: string[] | Set<string>;
100
+ /**
101
+ * Returns true if the value should be included in the stringified version,
102
+ * if provided it will override the default validator and the excludesTypes and excludeKeys
103
+ */
104
+ validator?: ({ obj, key, value, }: {
105
+ obj: unknown;
106
+ key: string;
107
+ value: any;
108
+ }) => boolean | undefined;
83
109
  }) => TStringify extends true ? string : unknown;
84
- //# sourceMappingURL=json-storage-formatter.d.ts.map
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "json-storage-formatter",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
4
4
  "description": "Package for json stringify objects without losing data types",
5
- "main": "lib/json-storage-formatter.js",
5
+ "main": "lib/bundle.js",
6
+ "types": "lib/index.d.ts",
6
7
  "files": [
7
8
  "lib"
8
9
  ],
@@ -10,7 +11,7 @@
10
11
  "test:debug": "node --inspect-brk node_modules/.bin/jest --watch --runInBand",
11
12
  "test:quick": "jest --maxWorkers=4 -c --no-watchman -u",
12
13
  "test:coverage": "jest --maxWorkers=4 -c --colors --no-watchman --verbose --coverage",
13
- "build": "tsc",
14
+ "build": "webpack --config webpack.config.js",
14
15
  "prepare": "npm run build",
15
16
  "version": "npm run format && git add -A src",
16
17
  "postversion": "git push && git push --tags"
@@ -34,10 +35,18 @@
34
35
  },
35
36
  "homepage": "https://github.com/johnny-quesada-developer/json-storage-formatter#readme",
36
37
  "devDependencies": {
38
+ "@babel/core": "^7.21.3",
39
+ "@babel/plugin-transform-modules-commonjs": "^7.21.2",
40
+ "@babel/preset-env": "^7.20.2",
41
+ "@babel/preset-typescript": "^7.21.0",
37
42
  "@types/jest": "^26.0.17",
38
43
  "@types/lodash": "^4.14.165",
44
+ "babel-loader": "^9.1.2",
39
45
  "jest": "^29.3.1",
40
46
  "ts-jest": "^29.0.3",
41
- "typescript": "^4.1.2"
47
+ "ts-loader": "^9.4.2",
48
+ "typescript": "^4.1.2",
49
+ "webpack": "^5.76.3",
50
+ "webpack-cli": "^5.0.1"
42
51
  }
43
52
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"json-storage-formatter.d.ts","sourceRoot":"","sources":["../src/json-storage-formatter.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,kBAAkB,GAAG;IAC/B,EAAE,CAAC,EAAE,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC;IAChD,EAAE,CAAC,EAAE,OAAO,CAAC;CACd,CAAC;AAEF;;;;;KAKK;AACL,eAAO,MAAM,KAAK,kBAiDjB,CAAC;AAEF;;;;;;KAMK;AACL,eAAO,MAAM,KAAK,UAAW,OAAO,YAA0C,CAAC;AAE/E;;;;;;MAMM;AACN,eAAO,MAAM,QAAQ,UAAW,OAAO,YAA8B,CAAC;AAEtE;;;;;;KAMK;AACL,eAAO,MAAM,SAAS,UAAW,OAAO,YAA+B,CAAC;AAExE;;;;;;KAMK;AACL,eAAO,MAAM,QAAQ,UAAW,OAAO,YAA8B,CAAC;AAEtE;;;;;GAKG;AACH,eAAO,MAAM,MAAM,UAAW,OAAO,YAA0B,CAAC;AAEhE;;;;KAIK;AACL,eAAO,MAAM,OAAO,UAAW,OAAO,YAA4B,CAAC;AAEnE;;;;;;;GAOG;AACH,eAAO,MAAM,WAAW,UAAW,OAAO,YAKf,CAAC;AAE5B;;;;;GAKG;AACH,eAAO,MAAM,eAAe,uBAAwB,OAAO,MAgE1D,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa;;gDA2FzB,CAAC"}
@@ -1,224 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.formatToStore = exports.formatFromStore = exports.isPrimitive = exports.isRegex = exports.isDate = exports.isString = exports.isBoolean = exports.isNumber = exports.isNil = exports.clone = void 0;
4
- /**
5
- * Deep clone an object, it also suppors Map, Set, Arrays
6
- * @param obj
7
- * @returns
8
- * A deep clone of the object
9
- * */
10
- const clone = (obj) => {
11
- if ((0, exports.isPrimitive)(obj) || (0, exports.isDate)(obj)) {
12
- return obj;
13
- }
14
- const isArray = Array.isArray(obj);
15
- if (isArray) {
16
- return obj.map((item) => (0, exports.clone)(item));
17
- }
18
- const isMap = obj instanceof Map;
19
- if (isMap) {
20
- const pairs = Array.from(obj.entries());
21
- return new Map(pairs.map((pair) => (0, exports.clone)(pair)));
22
- }
23
- const isSet = obj instanceof Set;
24
- if (isSet) {
25
- const values = Array.from(obj.values());
26
- return new Set(values.map((value) => (0, exports.clone)(value)));
27
- }
28
- const isReg = obj instanceof RegExp;
29
- if (isReg) {
30
- return new RegExp(obj.toString());
31
- }
32
- const isError = obj instanceof Error;
33
- if (isError) {
34
- return new Error(obj.message);
35
- }
36
- const keys = Object.keys(obj);
37
- return keys.reduce((acumulator, key) => {
38
- const value = obj[key];
39
- return Object.assign(Object.assign({}, acumulator), { [key]: (0, exports.clone)(value) });
40
- }, {});
41
- };
42
- exports.clone = clone;
43
- /**
44
- * Check if a value is null or undefined
45
- * @param value
46
- * @returns
47
- * true if the value is null or undefined
48
- * false otherwise
49
- * */
50
- const isNil = (value) => value === null || value === undefined;
51
- exports.isNil = isNil;
52
- /**
53
- * Check if a value is a number
54
- * @param value
55
- * @returns
56
- * true if the value is a number
57
- * false otherwise
58
- * */
59
- const isNumber = (value) => typeof value === 'number';
60
- exports.isNumber = isNumber;
61
- /**
62
- * Check if a value is a boolean
63
- * @param value
64
- * @returns
65
- * true if the value is a boolean
66
- * false otherwise
67
- * */
68
- const isBoolean = (value) => typeof value === 'boolean';
69
- exports.isBoolean = isBoolean;
70
- /**
71
- * Check if a value is a string
72
- * @param value
73
- * @returns
74
- * true if the value is a string
75
- * false otherwise
76
- * */
77
- const isString = (value) => typeof value === 'string';
78
- exports.isString = isString;
79
- /** Check if a value is a Date
80
- * @param value
81
- * @returns
82
- * true if the value is a Date
83
- * false otherwise
84
- */
85
- const isDate = (value) => value instanceof Date;
86
- exports.isDate = isDate;
87
- /**
88
- * Check if a value is a RegExp
89
- * @param value The value to check
90
- * @returns true if the value is a RegExp, false otherwise
91
- * */
92
- const isRegex = (value) => value instanceof RegExp;
93
- exports.isRegex = isRegex;
94
- /**
95
- * Check if a value is a primitive
96
- * @param value
97
- * @returns
98
- * true if the value is a primitive
99
- * false otherwise
100
- * null, number, boolean, string, symbol
101
- */
102
- const isPrimitive = (value) => (0, exports.isNil)(value) ||
103
- (0, exports.isNumber)(value) ||
104
- (0, exports.isBoolean)(value) ||
105
- (0, exports.isString)(value) ||
106
- typeof value === 'symbol';
107
- exports.isPrimitive = isPrimitive;
108
- /**
109
- * Format an value with possible metadata to his original form, it also supports Map, Set, Arrays
110
- * @param value
111
- * @returns
112
- * Orinal form of the value
113
- */
114
- const formatFromStore = (value) => {
115
- const format = (obj) => {
116
- var _a, _b;
117
- if ((0, exports.isPrimitive)(obj)) {
118
- return obj;
119
- }
120
- const isMetaDate = (obj === null || obj === void 0 ? void 0 : obj.$t) === 'date';
121
- if (isMetaDate) {
122
- return new Date(obj.$v);
123
- }
124
- const isMetaMap = (obj === null || obj === void 0 ? void 0 : obj.$t) === 'map';
125
- if (isMetaMap) {
126
- const mapData = ((_a = obj.$v) !== null && _a !== void 0 ? _a : []).map(([key, item]) => [key, (0, exports.formatFromStore)(item)]);
127
- return new Map(mapData);
128
- }
129
- const isMetaSet = (obj === null || obj === void 0 ? void 0 : obj.$t) === 'set';
130
- if (isMetaSet) {
131
- const setData = (_b = obj.$v) !== null && _b !== void 0 ? _b : [].map((item) => (0, exports.formatFromStore)(item));
132
- return new Set(setData);
133
- }
134
- const isMetaReg = (obj === null || obj === void 0 ? void 0 : obj.$t) === 'regex';
135
- if (isMetaReg) {
136
- return new RegExp(obj.$v);
137
- }
138
- const isMetaError = (obj === null || obj === void 0 ? void 0 : obj.$t) === 'error';
139
- if (isMetaError) {
140
- return new Error(obj.$v);
141
- }
142
- const isArray = Array.isArray(obj);
143
- if (isArray) {
144
- return obj.map((item) => (0, exports.formatFromStore)(item));
145
- }
146
- const keys = Object.keys(obj);
147
- return keys.reduce((acumulator, key) => {
148
- const unformatedValue = obj[key];
149
- return Object.assign(Object.assign({}, acumulator), { [key]: (0, exports.formatFromStore)(unformatedValue) });
150
- }, {});
151
- };
152
- return format((0, exports.clone)(value));
153
- };
154
- exports.formatFromStore = formatFromStore;
155
- /**
156
- * Add metadata to a value to store it as json, it also supports Map, Set, Arrays,
157
- * Returns a new object wich is a clone of the original object with metadata
158
- * @template {TValue} The type of the value to format
159
- * @template {TStringify} If the value should be stringified
160
- * @param {TValue} value The value to format
161
- * @param {{ stringify: TStringify }} { stringify: boolean } If the value should be stringified
162
- */
163
- const formatToStore = (value, { stringify } = { stringify: false }) => {
164
- const format = (obj) => {
165
- if ((0, exports.isPrimitive)(obj)) {
166
- return obj;
167
- }
168
- const isArray = Array.isArray(obj);
169
- if (isArray) {
170
- return obj.map((item) => (0, exports.formatToStore)(item));
171
- }
172
- const isMap = obj instanceof Map;
173
- if (isMap) {
174
- const pairs = Array.from(obj.entries());
175
- const value = {
176
- $t: 'map',
177
- $v: pairs.map((pair) => (0, exports.formatToStore)(pair)),
178
- };
179
- return value;
180
- }
181
- const isSet = obj instanceof Set;
182
- if (isSet) {
183
- const values = Array.from(obj.values());
184
- const value = {
185
- $t: 'set',
186
- $v: values.map((item) => (0, exports.formatToStore)(item)),
187
- };
188
- return value;
189
- }
190
- if ((0, exports.isDate)(obj)) {
191
- const value = {
192
- $t: 'date',
193
- $v: obj.toISOString(),
194
- };
195
- return value;
196
- }
197
- if ((0, exports.isRegex)(obj)) {
198
- const value = {
199
- $t: 'regex',
200
- $v: obj.toString(),
201
- };
202
- return value;
203
- }
204
- const isError = obj instanceof Error;
205
- if (isError) {
206
- const value = {
207
- $t: 'error',
208
- $v: obj.message,
209
- };
210
- return value;
211
- }
212
- const keys = Object.keys(obj);
213
- return keys.reduce((acumulator, key) => {
214
- const prop = obj[key];
215
- return Object.assign(Object.assign({}, acumulator), { [key]: (0, exports.formatToStore)(prop) });
216
- }, {});
217
- };
218
- const objectWithMetadata = format((0, exports.clone)(value));
219
- const result = stringify
220
- ? JSON.stringify(objectWithMetadata)
221
- : objectWithMetadata;
222
- return result;
223
- };
224
- exports.formatToStore = formatToStore;