Socket
Socket
Sign inDemoInstall

typeson

Package Overview
Dependencies
Maintainers
2
Versions
58
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

typeson - npm Package Compare versions

Comparing version 6.1.0 to 7.0.0

dist/typeson.esm.js

99

package.json
{
"name": "typeson",
"version": "6.1.0",
"version": "7.0.0",
"description": "Preserves types over JSON, BSON or socket.io",
"main": "./dist/typeson-commonjs2.min.js",
"browser": "./dist/typeson.js",
"module": "./dist/typeson-esm.js",
"scripts": {
"prepublishOnly": "pnpm i",
"eslint": "eslint --ext js,md,html .",
"start": "http-server -p 8092",
"rollup": "rollup -c",
"open-test": "open-cli http://localhost:8092/test/ && npm start",
"browser-test": "npm run rollup && npm run eslint && npm run open-test",
"open-coverage": "open-cli http://localhost:8092/coverage/ && npm start",
"mocha": "mocha --require esm --require chai/register-assert --require chai/register-expect test/test.js",
"mocha-cov": "rm -Rf node_modules/.cache/esm && nyc --reporter=html --reporter=text npm run mocha",
"test": "npm run rollup && npm run eslint && npm run mocha-cov"
"main": "./dist/typeson-commonjs2.min.cjs",
"browser": "./dist/typeson.umd.js",
"module": "./dist/typeson.esm.js",
"type": "module",
"exports": {
".": {
"browser": "./dist/typeson.umd.min.js",
"import": "./dist/typeson.esm.min.js",
"require": "./dist/typeson.umd.min.js"
}
},
"nyc": {
"c8": {
"exclude": [

@@ -49,43 +45,54 @@ "test/**",

"engines": {
"node": ">=0.1.14"
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"dependencies": {},
"devDependencies": {
"@babel/core": "^7.13.15",
"@babel/preset-env": "^7.13.15",
"@brettz9/eslint-plugin": "^1.0.3",
"@babel/core": "^7.17.4",
"@babel/preset-env": "^7.16.11",
"@brettz9/eslint-plugin": "^1.0.4",
"@rollup/plugin-babel": "^5.3.0",
"@rollup/plugin-replace": "^2.4.2",
"babel-plugin-transform-async-to-promises": "^0.8.15",
"base64-arraybuffer-es6": "^0.7.0",
"chai": "^4.3.4",
"eslint": "^7.24.0",
"eslint-config-ash-nazg": "29.10.0",
"eslint-config-standard": "^16.0.2",
"babel-plugin-transform-async-to-promises": "^0.8.18",
"base64-arraybuffer-es6": "^1.0.0",
"c8": "^7.11.0",
"chai": "^4.3.6",
"eslint": "^8.9.0",
"eslint-config-ash-nazg": "32.4.0",
"eslint-config-standard": "^16.0.3",
"eslint-plugin-array-func": "^3.1.7",
"eslint-plugin-chai-expect": "^2.2.0",
"eslint-plugin-chai-friendly": "^0.6.0",
"eslint-plugin-compat": "^3.9.0",
"eslint-plugin-chai-expect": "^3.0.0",
"eslint-plugin-chai-friendly": "^0.7.2",
"eslint-plugin-compat": "^4.0.2",
"eslint-plugin-eslint-comments": "^3.2.0",
"eslint-plugin-html": "^6.1.2",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsdoc": "^32.3.0",
"eslint-plugin-markdown": "^2.0.1",
"eslint-plugin-no-unsanitized": "^3.1.4",
"eslint-plugin-html": "^6.2.0",
"eslint-plugin-import": "^2.25.4",
"eslint-plugin-jsdoc": "^37.9.2",
"eslint-plugin-markdown": "^2.2.1",
"eslint-plugin-no-unsanitized": "^4.0.1",
"eslint-plugin-no-use-extend-native": "^0.5.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^5.1.0",
"eslint-plugin-radar": "^0.2.1",
"eslint-plugin-promise": "^6.0.0",
"eslint-plugin-sonarjs": "^0.11.0",
"eslint-plugin-standard": "^4.1.0",
"eslint-plugin-unicorn": "^29.0.0",
"esm": "^3.2.25",
"http-server": "^0.12.3",
"mocha": "^8.3.2",
"nyc": "^15.1.0",
"open-cli": "^6.0.1",
"rollup": "2.45.1",
"eslint-plugin-unicorn": "^41.0.0",
"http-server": "^14.1.0",
"mocha": "^9.2.0",
"open-cli": "^7.0.1",
"rollup": "2.67.2",
"rollup-plugin-re": "^1.0.7",
"rollup-plugin-terser": "^7.0.2"
},
"tonicExample": "var Typeson = require('typeson');\nvar TSON = new Typeson().register(require('typeson-registry/presets/builtin'));\n\nTSON.stringify({foo: new Date()}, null, 2);"
}
"tonicExample": "var Typeson = require('typeson');\nvar TSON = new Typeson().register(require('typeson-registry/presets/builtin'));\n\nTSON.stringify({foo: new Date()}, null, 2);",
"scripts": {
"eslint": "eslint --ext js,md,html .",
"lint": "npm run eslint --",
"start": "http-server -p 8092",
"rollup": "rollup -c",
"open-test": "open-cli http://localhost:8092/test/ && npm start",
"browser-test": "npm run rollup && npm run eslint && npm run open-test",
"open-coverage": "open-cli http://localhost:8092/coverage/ && npm start",
"mocha": "mocha --require chai/register-assert.js --require chai/register-expect.js test/test.js",
"mocha-cov": "rm -Rf node_modules/.cache && c8 --reporter=html --reporter=text npm run mocha",
"test": "npm run rollup && npm run eslint && npm run mocha-cov"
},
"readme": "# typeson.js\n\nPreserves types over JSON, BSON or socket.io.\n\n*typeson.js is tiny. 2.6 kb minified. ~1 kb gzipped.*\n\n## Example of how a stringified object can look\n\n```js\nconst objs = [\n {foo: 'bar'},\n // {\"foo\":\"bar\"} (simple types gives plain JSON)\n {foo: new Date()},\n // {\"foo\":1464049031538, \"$types\":{\"foo\":\"Date\"}}\n {foo: new Set([new Date()])},\n // {\"foo\":[1464127925971], \"$types\":{\"foo\":\"Set\",\"foo.0\":\"Date\"}}\n {foo: {sub: /bar/iu}},\n // {\"foo\":{\"sub\":{\"source\":\"bar\",\"flags\":\"i\"}}, \"$types\":{\"foo.sub\":\"RegExp\"}}\n {foo: new Int8Array(3)},\n // {\"foo\":\"AAAA\", \"$types\":{\"foo\":\"Int8Array\"}}\n new Date()\n // {\"$\":1464128478593, \"$types\":{\"$\":{\"\":\"Date\"}}} (special format at root)\n];\n```\n\n## Why?\n\nJSON can only contain strings, numbers, booleans, `null`, arrays and objects. If you want to serialize other types over HTTP, WebSocket, `postMessage()` or other channels, this module makes it possible to serialize any type over channels that normally only accept vanilla objects. Typeson adds a metadata property `$types` to the result that maps each non-trivial property to a type name. (In the case of arrays or encoded primitives, a new object will instead be created with a `$` property that can be preserved by JSON.) The type name is a reference to a registered type specification that you need to have the same on both the stringifying and the parsing side.\n\n## Type Registry\n\n[typeson-registry](https://github.com/dfahlander/typeson-registry) contains encapsulation rules for standard JavaScript types such as `Date`, `Error`, `ArrayBuffer`, etc. Pick the types you need, use a preset or write your own.\n\n```js\nconst typeson = new Typeson().register([\n require('typeson-registry/types/date'),\n require('typeson-registry/types/set'),\n require('typeson-registry/types/regexp'),\n require('typeson-registry/types/typed-arrays')\n]);\n```\nor if you want support for all built-in JavaScript classes:\n```js\nconst typeson = new Typeson().register([\n require('typeson-registry/presets/builtin')\n]);\n```\nThe module `typeson-registry/presets/builtin` is 1.6 kb minified and gzipped and adds support 32 builtin JavaScript types: *Date, RegExp, NaN, Infinity, -Infinity, Set, Map, ArrayBuffer, DataView, Uint8Array, Int8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, Error, SyntaxError, TypeError, RangeError, ReferenceError, EvalError, URIError, InternalError, Intl.Collator, Intl.DateTimeFormat, Intl.NumberFormat, Object String, Object Number and Object Boolean*.\n\n## Compatibility\n\n- Node\n- Browser\n- Worker\n- ES5\n\n## Features\n\n- Can stringify custom and standard ES5 / ES6 classes.\n- Produces standard JSON with an additional `$types` property in case it is needed (or a new object if representing a primitive or array at root).\n- Resolves cyclic references, such as lists of objects where each object has a reference to the list\n- You can register (almost) any type to be stringifiable (serializable) with your typeson instance.\n- Output will be identical to that of `JSON.stringify()` in case your object doesnt contain special types or cyclic references.\n- Type specs may encapsulate its type in other registered types. For example, `ImageData` is encapsulated as `{array: Uint8ClampedArray, width: number, height: number}`, expecting another spec to convert the `Uint8ClampedArray`. With the [builtin](https://github.com/dfahlander/typeson-registry/blob/master/presets/builtin.js) preset this means it's gonna be converted to base64, but with the [socketio](https://github.com/dfahlander/typeson-registry/blob/master/presets/socketio.js) preset, its gonna be converted to an `ArrayBuffer` that is left as-is and streamed binary over the WebSocket channel!\n\n## Limitations\n\nSince typeson has a synchronous API, it cannot encapsulate and revive async types such as `Blob`, `File` or `Observable`. Encapsulating an async object requires to be able to emit streamed content asynchronically. Remoting libraries could however complement typeson with a streaming channel that handles the emitting of stream content. For example, a remoting library could define a typeson rule that encapsulates an [Observable](https://github.com/zenparsing/es-observable) to an id (string or number for example), then starts subscribing to it and emitting the chunks to the peer as they arrive. The peer could revive the id to an observable that when subscribed to, will listen to the channel for chunks destinated to the encapsulated ID.\n\n## Usage\n\n```\nnpm install typeson\n```\n\n```js\n// Require typeson. It's an UMD module so you could also use requirejs\n// or plain script tags.\nconst Typeson = require('typeson');\n\nconst typeson = new Typeson().register({\n Date: [\n (x) => x instanceof Date, // test function\n (d) => d.getTime(), // encapsulator function\n (number) => new Date(number) // reviver function\n ],\n Error: [\n (x) => x instanceof Error, // tester\n (e) => ({name: e.name, message: e.message}), // encapsulator\n (data) => {\n // reviver\n const e = new Error(data.message);\n e.name = data.name;\n return e;\n }\n ],\n SimpleClass // Default rules apply. See \"register (typeSpec)\"\n});\n\nfunction SimpleClass (foo) {\n this.foo = foo;\n}\n\n// Encapsulate to a JSON friendly format:\nconst jsonFriendly = typeson.encapsulate({\n date: new Date(),\n e: new Error('Oops'),\n c: new SimpleClass('bar')\n});\n// Stringify using good old JSON.stringify()\nconst json = JSON.stringify(jsonFriendly, null, 2);\n/*\n{\n \"date\": 1464049031538,\n \"e\": {\n \"name\": \"Error\",\n \"message\": \"Oops\"\n },\n \"c\": {\n \"foo\": \"bar\"\n },\n \"$types\": {\n \"date\": \"Date\",\n \"e\": \"Error\",\n \"c\": \"SimpleClass\"\n }\n}\n*/\n\n// Parse using good old JSON.parse()\nconst parsed = JSON.parse(json);\n// Revive back again:\nconst revived = typeson.revive(parsed);\n```\n\n*The above sample separates Typeson.encapsulate() from JSON.stringify(). Could also have used Typeson.stringify().*\n\n## Environment/Format support\n\n### Use with socket.io\n\nSocket.io can stream `ArrayBuffer`s as real binary data. This is more efficient than encapsulating it in base64/JSON. Typeson can leave certain types, like `ArrayBuffer`, untouched, and leave the stringification / binarization part to other libs (use `Typeson.encapsulate()` and not `Typeson.stringify()`).\n\nWhat socket.io doesn't do though, is preserve `Date`s, `Error`s or your custom types.\n\nSo to get the best of two worlds:\n\n- Register preset 'typeson-registry/presets/socketio' as well as your custom types.\n- Use `Typeson.encapsulate()` to generate an object ready for socket-io `emit()`\n- Use `Typeson.revive()` to revive the encapsulated object at the other end.\n\n```js\nconst Typeson = require('typeson'),\n presetSocketIo = require('typeson-registry/presets/socketio.js');\n\nconst TSON = new Typeson()\n .register(presetSocketIo)\n .register({\n CustomClass: [\n (x) => x instanceof CustomClass,\n (c) => ({foo: c.foo, bar: c.bar}),\n (o) => new CustomClass(o.foo, o.bar)\n ]\n });\n\nconst array = new Float64Array(65536);\narray.fill(42, 0, 65536);\n\nconst data = {\n date: new Date(),\n error: new SyntaxError('Ooops!'),\n array,\n custom: new CustomClass('foo', 'bar')\n};\n\nsocket.emit('myEvent', TSON.encapsulate(data));\n```\n\nThe `encapsulate()` method will not stringify but just traverse the object and return a simpler structure where certain properties are replaced with a substitute. The resulting object will also have a `$types` property containing the type metadata.\n\nPacking it up at the other end:\n\n```js\nsocket.on('myEvent', function (data) {\n const revived = TSON.revive(data);\n // Here we have a true `Date`, `SyntaxError`, `Float64Array`\n // and `Custom` to play with.\n});\n```\n*NOTE: Both peers must have the same types registered.*\n\n### Use with [BSON](https://www.npmjs.com/package/bson)\n\nThe BSON format can serialize object over a binary channel. It supports just the standard JSON types plus `Date`, `Error` and optionally `Function`. You can use Typeson to encapsulate and revive other types as well with BSON as bearer. Use it the same way as shown above with socket.io.\n\n### Use with Worker.postMessage()\n\nWeb Workers have the `onmessage` and `postMessage()` communication channel that has built-in support for transferring structures using the [structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). It supports `Date`, `ArrayBuffer`and many other standard types, but not `Error`s or your own custom classes. To support `Error` and custom types over web worker channels, register just the types that are needed (`Error`s and your custom types), and then use `Typeson.encapsulate()` before posting a message, and `Typeson.revive()` in the `onmessage` callback.\n\n## API\n\n### constructor ([options])\n\n```js\nconst typeson = new Typeson([options]);\n```\n\nCreates an instance of Typeson, on which you may configure additional types to support, or call `encapsulate()`, `revive()`, `stringify()` or `parse()` on.\n\n#### Arguments\n\n##### options (optional):\n\n```\n{\n cyclic?: boolean, // Default true to allow cyclic objects\n encapsulateObserver?: function, // Default no-op\n sync?: true, // Don't force a promise response regardless of type\n throwOnBadSyncType?: true // Default to throw when mismatch with `TypesonPromise` obtained for sync request or not returned for async\n}\n```\n\n###### `cyclic`: boolean\n\nWhether or not to support cyclic references. Defaults to `true` unless explicitly set to `false`. If this property is `false`, the parsing algorithm becomes a little faster and in case a single object occurs on multiple properties, it will be duplicated in the output (as `JSON.stringify()` would do). If this property is `true`, several instances of same object will only occur once in the generated JSON and other references will just contain a pointer to the single reference.\n\n###### `encapsulateObserver`: object (see description)\n\nFor encapsulations/stringifications, this callback will be executed as objects are iterated and types are detected. An observer might be used to build an interface based on the original object taking advantage of serialized values (the `replaced` property) passed to the observer along the way, even potentially without concern to the actual encapsulated result.\n\n`encapsulateObserver` is passed an object with the following properties:\n\n- `type` - If a type was detected, whether at either the `awaitingTypesonPromise` or\n `resolvingTypesonPromise` stage, this property will indicate the detected type. If\n this is a regular JSON type, its name ('null', 'boolean', 'number', 'string', 'array',\n or 'object') will be reported\n- `keypath` - The keypath at which the observer is reporting.\n- `value` - The original value found at this stage by the observer. (`replaced`, on the other hand, can be consulted to obtain any type replacement value.)\n- `cyclic` - A boolean indicating whether the current state is expecting cyclics. Will be `\"readonly\"` if this iteration is due to a recursive replacement.\n- `stateObj` - The state object at the time of observation.\n- `promisesData` - The promises array.\n- `resolvingTypesonPromise` - A boolean indicating whether or not this observation is occurring at the (Typeson) promise stage.\n- `awaitingTypesonPromise` - Will be `true` if still awaiting the full resolution; this could be ignored or used to set a placeholder.\n\nThe following properties are also present in particular cases:\n- `typeDetected` - Set to `true` when a Typeson-detected type is found but no relevant replacer is present to be performed.\n- `replacing` - Set to `true` preceding a Typeson-detected type replacement. Use this to get at the original object value before encapsulation\n- `clone` - If a plain object or array is found or if `iterateIn` is set, this property holds the clone of that object or array.\n- `replaced` - This property will be set when a type was detected. This value is useful for obtaining the serialization of types.\n- `cyclicKeypath` - Will be present if a cyclic object (including array) were detected; refers to the key path of the prior detected object.\n- `endIterateIn` - Will be `true` if finishing iteration of `in` properties.\n- `endIterateOwn` - Will be `true` if finishing iteration of \"own\" properties.\n- `endIterateUnsetNumeric` - Will be `true` if finishing iteration of unset numeric properties.\n- `end` - Convenience property that will be `true` if `endIterateIn`, `endIterateOwn`, or `endIterateUnsetNumeric` is `true`.\n\n###### `sync`: boolean (Internal property)\n\nTypes can utilize `TypesonPromise` to allow asynchronous encapsulation and stringification.\n\nWhen such a type returns a `TypesonPromise`, a regular `Promise` will be returned to the user.\n\n(This property is used internally for ensuring a regular `Promise` was not intended as the result.\nNote that its resolved value is also recursively checked for types.)\n\nTo ensure that a regular `Promise` is always returned and thereby to allow the same API to be\nused regardless of the types in effect, the `sync` option is set to `false` by the\n`*Async` methods.\n\nNote that this has no bearing on `revive`/`parse` since they can construct any object they\nwish for a return value, including a `Promise`, a stream, etc.\n\n###### `throwOnBadSyncType`: boolean\n\nThe default is to throw when an async result is received from a synchronous method or vice versa.\nThis assures you that you are receiving the intended result type.\n\nThis option can be set to `false`, however, to return the raw synchronous result or the promise, allowing you the least unambiguous results (since you can discern whether a returned `Promise` was\nthe actual result of a revival/parsing or just the inevitable return of using an async method).\n\n#### Sample\n\n```js\nconst Typeson = require('typeson');\nconst typeson = new Typeson()\n .register(require('typeson-registry/presets/builtin'));\n\nconst tson = typeson.stringify(complexObject);\nconsole.log(tson);\nconst obj = typeson.parse(tson);\n```\n\n### Properties\n\n#### `types`\n\nA map between type identifier and type-rules. Same (object-based) structure as passed to `register()`. Use this property if you want to create a new Typeson containing all types from another Typeson.\n\n##### Sample\n\n```js\nconst commonTypeson = new Typeson().register([\n require('typeson-registry/presets/builtin')\n]);\n\nconst myTypeson = new Typeson().register([\n commonTypeson.types, // Derive from commonTypeson\n myOwnSpecificTypes // Add your extra types\n]);\n```\n\n### Instance methods\n\n#### `stringify` (obj, [replacer], [space], [options])\n\n*Initial arguments identical to those of JSON.stringify()*\n\nGenerates JSON based on the given `obj`. Applies `JSON.stringify()` on the result of any relevant `replace` encapsulators.\n\nIf the supplied `obj` has special types or cyclic references, the produced JSON will contain a `$types` property on the root upon which type info relies (a map of keypath to type where the keypath is dot-separated; see `escapeKeyPathComponent` on escaping).\n\nThe `options` object argument can include a setting for `cyclic` which overrides the default or any behavior supplied for this option in the Typeson constructor.\n\nMay also return a `Promise` if a type's `replace` encapsulator returns `TypesonPromise`. See the documentation under `TypesonPromise`.\n\n##### Stringification format\n\nIf enabled, the cyclic \"type\" will be represented as `#` and cyclic references will be encoded as `#` plus the path to the referenced object.\n\nIf an array or primitive is encoded at root, an object will be created with a property `$` and a `$types` property that is an object with `$` as a key and instead of a type string as value, a keypath-type object will be its value (with the empty string indicating the root path).\n\n##### Sample\n\n```js\nconst TSON = new Typeson().register(require('typeson-registry/types/date'));\n\nTSON.stringify({date: new Date()});\n```\nOutput:\n```json\n{\"date\": 1463667643065, \"$types\": {\"date\": \"Date\"}}\n```\n\n#### `stringifySync` (obj, [replacer], [space], [options])\n\nAs with `stringify` but automatically throws upon obtaining a `TypesonPromise` return result from a `replace` encapsulator (as that is expected for asynchronous types).\n\n#### `stringifyAsync` (obj, [replacer], [space], [options])\n\nAs with `stringify` but automatically throws upon obtaining a non-`TypesonPromise` return result from a `replace` encapsulator (as only a `TypesonPromise` is expected for asynchronous types).\n\n#### `parse` (obj, [reviver])\n\n*Arguments identical to those of JSON.parse()*\n\nParses Typeson-generated JSON back into the original complex structure again.\n\nApplies `JSON.parse()` and then any relevant `revive` methods that are detected.\n\nMay also return a `Promise` if a type's reviver returns `TypesonPromise`. See\nthe documentation under `TypesonPromise`.\n\n##### Sample\n\n```js\nconst date = require('typeson-registry/types/date');\n\nconst TSON = new Typeson().register(date);\nTSON.parse('{\"date\": 1463667643065, \"$types\": {\"date\": \"Date\"}}');\n```\n\n#### `parseSync` (obj, [reviver])\n\nAs with `parse` but automatically throws upon obtaining a `TypesonPromise` return result from the reviver (as that is expected for asynchronous types).\n\n#### `parseAsync` (obj, [reviver])\n\nAs with `parse` but automatically throws upon obtaining a non-`TypesonPromise` return result from the reviver (as only a `TypesonPromise` is expected for asynchronous types).\n\n#### `encapsulate` (obj, [stateObj], [opts])\n\nEncapsulates an object but leaves the stringification part to you. Pass your encapsulated object further to socket.io, `postMessage()`, BSON or IndexedDB.\n\nApplies the `replace` method on `test`-matching spec objects. Will return the result regardless\nof whether it is an asynchronous (indicated by a `TypesonPromise`) or synchronous result.\n\nThe `options` object argument can include a setting for `cyclic` which overrides the default or any behavior supplied for this option in the Typeson constructor.\n\n#### `encapsulateSync` (obj, [opts])\n\nAs with `encapsulate` but automatically throws upon obtaining a `TypesonPromise` return result from the replacer (as that is expected for asynchronous types).\n\n#### `encapsulateAsync` (obj, [opts])\n\nAs with `encapsulate` but automatically throws upon obtaining a non-`TypesonPromise` return result from the replacer (as only a `Typeson-Promise` is expected for asynchronous types).\n\n##### Sample\n\n```js\nconst encapsulated = typeson.encapsulate(new Date());\nconst revived = typeson.revive(encapsulated);\nassert(revived instanceof Date);\n```\n\n#### `revive` / `reviveSync` / `reviveAsync` (obj)\n\nRevives an encapsulated object. See `encapsulate()`.\n\n#### `register` (typeSpec, opts = {fallback: boolean|number})\n\nIf `opts.fallback` is set, lower priority will be given (the default is that the last registered item\nhas highest priority during match testing). If a number is given, it will be used as the index of the placement.\n\n##### typeSpec\n\nAn object that maps a type-name to a specification of how to test, encapsulate and revive that type.\n\n`{TypeName => constructor-function | [tester, encapsulator, reviver] | specObject = {test: function, replace: function, replaceAsync: function, revive: function, reviveAsync: function, testPlainObjects: boolean=false}}` or an array of such structures.\n\nPlease note that if an array is supplied, the tester (and upon matching, the encapsulator)\nexecute in a last-in, first out order. (Calls to `register` can set `fallback` to `true` to\nlower the priority of a recent addition.)\n\n`this` will refer to the specification object.\n\nSubsequent calls to `register` will similarly be given higher priority so be sure to add\ncatch-all matchers *before* more precise ones.\n\nIf `testPlainObjects` is set to `true`, a tester will be checked against plain objects and\nallow replacements without recursion.\n\nNote that you can supply `null` as a spec to remove a regular previously\nregistered spec, and supply an object with only `testPlainObjects: true`\nto remove a previously registered spec which can remove a previously\nregistered spec with a plain object replacer.\n\n###### constructor-function\n\nA class (constructor function) that would use default test, encapsulation and revival rules, which is:\n\n- `test`: check if x.constructor === constructor-function.\n- `replace`: copy all enumerable own props into a vanilla object\n- `revive`: Uses `Object.create()` to revive the correct type and copies all properties into it.\n- `testPlainObjects`: `false`: Tests non-plain objects only.\n\n###### `test` (obj : any, stateObj : {ownKeys: boolean, iterateIn: ('array'|'object'), iterateUnsetNumeric: boolean}) : boolean\n\nFunction that tests whether an instance is of your type and returns a truthy value if it is.\n\nIf the context is iteration over non-\"own\" integer string properties of an array (i.e.,\nan absent (`undefined`) item in a sparse array), `ownKeys` will be set to `false`.\nOtherwise, when iterating an object or array, it will be set to `true`. The default\nfor the `stateObj` is just an empty object.\n\nIf you wish to have exceptions thrown upon encountering a certain type of\nvalue, you may leverage the tester to do so.\n\nYou may also set values on the state object.\n\nNormally, only the \"own\" keys of an object will be iterated.\nSetting `iterateIn` changes the behavior to iterate all properties\n\"in\" the object for cloning (though note that doing so will add a\nperformance cost). The value of `iterateIn` (as 'array' or 'object')\ndetermines what type of object will be created. Normally, 'object'\nwill be more useful as non-array-index properties do not\nsurvive stringification on an array.\n\nOne special case not covered by iterating all \"own\" keys or enabling \"in\"\niteration is where one may wish to iterate the keys not \"in\" the object\nbut still part of it, i.e., the unset numeric indexes of a sparse array\n(e.g., for the sake of ensuring they are ignored entirely rather than\nconverted to `null` by a `stringify` call). Thus encapsulators have the\nability to set `iterateUnsetNumeric: true` on their state object, but\nnote that doing so will add a performance cost.\n\n###### `replace` (obj: YourType, stateObj : {ownKeys: boolean, iterateIn: ('array'|'object'), iterateUnsetNumeric: boolean}) : Object\n\nFunction that maps your instance to a JSON-serializable object. Can also be called an\n`encapsulator`. For the `stateObj`, see `tester`. In a property context (for arrays\nor objects), returning `undefined` will prevent the addition of the property.\n\nSee the `tester` for a discussion of the `stateObj`.\n\nNote that replacement results will themselves be recursed for state changes\nand type detection.\n\n###### `replaceAsync` (obj: YourType, stateObj : {ownKeys: boolean, iterateIn: ('array'|'object'), iterateUnsetNumeric: boolean}) : `TypesonPromise`\n\nExpected to return a `TypesonPromise` which resolves to the replaced value.\nSee `replace`.\n\n###### `revive` (obj: Object, stateObj : {}) : YourType\n\nFunction that maps your JSON-serializable object into a real instance of your type.\nIn a property context (for arrays or objects), returning `undefined`\nwill prevent the addition of the property. To explicitly add `undefined`, see\n`Undefined`.\n\n##### Sample\n\n```js\nconst typeson = new Typeson();\n\nfunction CustomType (foo) {\n this.foo = foo;\n}\n\ntypeson.register({\n // simple style - provide just a constructor function.\n // This style works for any trivial js class without hidden closures.\n CustomType,\n\n // Date is native and hides it's internal state.\n // We must define encapsulator and reviver that always works.\n Date: [\n (x) => x instanceof Date, // tester\n (date) => date.getTime(), // encapsulator\n (obj) => new Date(obj) // reviver\n ],\n\n RegExp: [\n (x) = x instanceof RegExp,\n (re) => [re.source, re.flags],\n ([source, flags]) => new RegExp(source, flags)\n ]\n});\n\nconsole.log(typeson.stringify({\n ct: new CustomType('hello'),\n d: new Date(),\n r: /foo/giu\n}));\n// {\"ct\":{\"foo\":\"hello\"},\"d\":1464049031538,\"r\":[\"foo\",\"gi\"],\n// $types:{\"ct\":\"CustomType\",\"d\":\"Date\",\"r\":\"RegExp\"}}\n```\n\n###### `reviveAsync` (obj: Object) : YourType\n\nExpected to return a `TypesonPromise` which resolves to the revived value.\nSee `revive`.\n\n#### `specialTypeNames` (obj, [stateObj], [opts])\n\nThis method returns an array of the unique Typeson type names. To return all\ntype names including JSON type names or duplicates, use an `encapsulateObserver`.\n\n#### `rootTypeName` (obj, [stateObj], [opts])\n\nThis method returns a single type name string of the supplied\nobject at root: a Typeson type if present or a JSON type otherwise.\nThis method avoids iterating whole object/array structures.\n\n### Other exported classes\n\n#### `Undefined` class\n\nDuring encapsulation, `undefined` will not be set for property values,\nof objects or arrays (including sparse ones and replaced values)\n(`undefined` will be converted to `null` if stringified\nanyways). During revival, however, since `undefined` is also used in\nthis context to indicate a value will not be added, if you wish to\nhave an explicit `undefined` added, you can return\n`new Typeson.Undefined()` to ensure a value is set explicitly to\n`undefined`.\n\nThis distinction is used by the `undefined` type in `typeson-registry`\nto allow reconstruction of explicit `undefined` values (and its\n`sparseUndefined` type will ensure that sparse arrays can be\nreconstructed).\n\n#### `TypesonPromise` class\n\nIf you have a type which you wish to have resolved asynchronously, you\ncan can return a `Typeson.Promise` (which works otherwise like a `Promise`)\nand call its first supplied argument (`resolve`) when ready.\n\nThe reason we expect this class to be used here instead of regular `Promise`s\nas types might wish to serialize them in their own manner (or perhaps more\nlikely, to be able to throw when encountering them if they\nare not expected).\n\n##### Sample\n\n```js\nfunction MyAsync (prop) {\n this.prop = prop;\n}\n\nconst typeson = new Typeson({sync: false}).register({\n myAsyncType: [\n function (x) { return x instanceof MyAsync; },\n function (o) {\n return new Typeson.Promise(function (resolve, reject) {\n setTimeout(function () {\n // Do something more useful in real code\n if (Date.now() % 2) {\n reject(new Error('Better luck next time'));\n return;\n }\n resolve(o.prop);\n }, 800);\n });\n },\n function (data) {\n return new MyAsync(data);\n }\n ]\n});\n\nconst mya = new MyAsync(500);\n\n(async () => {\nconst result = await typeson.stringify(mya);\nconst back = typeson.parse(result, null, {sync: true});\nconsole.log(back.prop); // 500\n})();\n```\n\n### Other exported methods\n\n#### `toStringTag`\n\nA simple utility for getting the former ``[[Class]]`` internal slot of an object\n(i.e., The string between `[Object ` and `]` as returned from\n`Object.prototype.toString`) or what is known in HTML as the [\"class string\"](https://heycam.github.io/webidl/#dfn-class-string).\n\nSince [`Symbol.toStringTag`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag)\ncan set the value for other objects and is defined by JavaScript itself, we\nuse that within the method name.\n\nThe method can be used for cross-frame detection of your objects as well\nas objects associated with all\n[platform objects](https://heycam.github.io/webidl/#idl-objects)\n(i.e., non-callback interfaces or `DOMException`s) tied to WebIDL\n(such as the interfaces in HTML). The platform object's [identifier](https://heycam.github.io/webidl/#es-platform-objects) (i.e., the\ninterface name) is, per the WebIDL spec, the string to be returned.\n\nAlthough it is unfortunately not immune to forgery, it may in some\ncases be more appealing than (or usable in addition to) duck typing\nso this tiny utility is bundled for convenience.\n\n#### `hasConstructorOf` (objWithPrototypeConstructor, classToCompare: constructor or null) : boolean\n\nAnother approach for class comparisons involves checking a `constructor`\nfunction and comparing its `toString`. This is required for some classes\nwhich otherwise do not define `toStringTag`s which differ from other\nobjects. The first argument will be an object to check (whose prototoype\nwill be searched for a `constructor` property) whereas the second is a\nclass constructor to compare.\n\nIf no valid `constructor` is found, `false` will be returned unless\n`null` was supplied as the `classToCompare` in which case `true` will\nbe returned when finding a `null` prototype (and `false` otherwise).\n\n#### `isObject` (val)\n\nSimple but frequently-needed type-checking utility for\n`val && typeof val === 'object'` to avoid `null` being treated as an object.\n\n#### `isPlainObject` (val)\n\nChecks for a simple non-inherited object. Adapted from jQuery's `isPlainObject`.\n\n#### `isUserObject` (val)\n\nAllows for inherited objects but ensures the prototype chain inherits from\n`Object` (or `null`).\n\n#### `isThenable` (val, catchCheck=boolean)\n\nChecks whether an object is \"thenable\" (usable as a promise). If the second\nargument is supplied as `true`, it will also ensure it has a `catch` method.\nA regular `Promise` or `TypesonPromise` will return `true`.\n\n#### `escapeKeyPathComponent` (unescapedKeyPathComponent)\n\nEscapes a component of a key path.\n\nDots in property names are escaped as `~1`, and the tilde escape character is\nitself escaped as `~0`.\n\n#### `unescapeKeyPathComponent` (escapedKeyPathComponent)\n\nUnescapes a key path component. See `escapeKeyPathComponent`.\n\n#### `getByKeyPath` (obj, keyPath)\n\nRetrieves a value pointed to by a key path on an object.\n\n#### `getJSONType` (obj)\n\nUtility that returns 'null', 'boolean', 'number', 'string', 'array',\nor 'object' depending on JSON type.\n\n### Exported properties\n\n#### `JSON_TYPES`\n\nSet to the following array of JSON type names.\n\n`['null', 'boolean', 'number', 'string', 'array', 'object']`\n\n## Finding types and groups of types\n\n[typeson-registry](https://github.com/dfahlander/typeson-registry) contains ready-to-use types and presets to register with your Typeson instances.\n"
}

@@ -134,4 +134,4 @@ # typeson.js

const revived = typeson.revive(parsed);
```
```
*The above sample separates Typeson.encapsulate() from JSON.stringify(). Could also have used Typeson.stringify().*

@@ -220,3 +220,3 @@

sync?: true, // Don't force a promise response regardless of type
throwOnBadSyncType?: true // Default to throw when mismatch with `Typeson.Promise` obtained for sync request or not returned for async
throwOnBadSyncType?: true // Default to throw when mismatch with `TypesonPromise` obtained for sync request or not returned for async
}

@@ -260,5 +260,5 @@ ```

Types can utilize `Typeson.Promise` to allow asynchronous encapsulation and stringification.
Types can utilize `TypesonPromise` to allow asynchronous encapsulation and stringification.
When such a type returns a `Typeson.Promise`, a regular `Promise` will be returned to the user.
When such a type returns a `TypesonPromise`, a regular `Promise` will be returned to the user.

@@ -322,7 +322,7 @@ (This property is used internally for ensuring a regular `Promise` was not intended as the result.

If the supplied `obj` has special types or cyclic references, the produced JSON will contain a `$types` property on the root upon which type info relies (a map of keypath to type where the keypath is dot-separated; see `Typeson.escapeKeyPathComponent` on escaping).
If the supplied `obj` has special types or cyclic references, the produced JSON will contain a `$types` property on the root upon which type info relies (a map of keypath to type where the keypath is dot-separated; see `escapeKeyPathComponent` on escaping).
The `options` object argument can include a setting for `cyclic` which overrides the default or any behavior supplied for this option in the Typeson constructor.
May also return a `Promise` if a type's `replace` encapsulator returns `Typeson.Promise`. See the documentation under `Typeson.Promise`.
May also return a `Promise` if a type's `replace` encapsulator returns `TypesonPromise`. See the documentation under `TypesonPromise`.

@@ -349,7 +349,7 @@ ##### Stringification format

As with `stringify` but automatically throws upon obtaining a `Typeson.Promise` return result from a `replace` encapsulator (as that is expected for asynchronous types).
As with `stringify` but automatically throws upon obtaining a `TypesonPromise` return result from a `replace` encapsulator (as that is expected for asynchronous types).
#### `stringifyAsync` (obj, [replacer], [space], [options])
As with `stringify` but automatically throws upon obtaining a non-`Typeson.Promise` return result from a `replace` encapsulator (as only a `Typeson.Promise` is expected for asynchronous types).
As with `stringify` but automatically throws upon obtaining a non-`TypesonPromise` return result from a `replace` encapsulator (as only a `TypesonPromise` is expected for asynchronous types).

@@ -364,4 +364,4 @@ #### `parse` (obj, [reviver])

May also return a `Promise` if a type's reviver returns `Typeson.Promise`. See
the documentation under `Typeson.Promise`.
May also return a `Promise` if a type's reviver returns `TypesonPromise`. See
the documentation under `TypesonPromise`.

@@ -379,7 +379,7 @@ ##### Sample

As with `parse` but automatically throws upon obtaining a `Typeson.Promise` return result from the reviver (as that is expected for asynchronous types).
As with `parse` but automatically throws upon obtaining a `TypesonPromise` return result from the reviver (as that is expected for asynchronous types).
#### `parseAsync` (obj, [reviver])
As with `parse` but automatically throws upon obtaining a non-`Typeson.Promise` return result from the reviver (as only a `Typeson.Promise` is expected for asynchronous types).
As with `parse` but automatically throws upon obtaining a non-`TypesonPromise` return result from the reviver (as only a `TypesonPromise` is expected for asynchronous types).

@@ -391,3 +391,3 @@ #### `encapsulate` (obj, [stateObj], [opts])

Applies the `replace` method on `test`-matching spec objects. Will return the result regardless
of whether it is an asynchronous (indicated by a `Typeson.Promise`) or synchronous result.
of whether it is an asynchronous (indicated by a `TypesonPromise`) or synchronous result.

@@ -398,7 +398,7 @@ The `options` object argument can include a setting for `cyclic` which overrides the default or any behavior supplied for this option in the Typeson constructor.

As with `encapsulate` but automatically throws upon obtaining a `Typeson.Promise` return result from the replacer (as that is expected for asynchronous types).
As with `encapsulate` but automatically throws upon obtaining a `TypesonPromise` return result from the replacer (as that is expected for asynchronous types).
#### `encapsulateAsync` (obj, [opts])
As with `encapsulate` but automatically throws upon obtaining a non-`Typeson.Promise` return result from the replacer (as only a `Typeson-Promise` is expected for asynchronous types).
As with `encapsulate` but automatically throws upon obtaining a non-`TypesonPromise` return result from the replacer (as only a `Typeson-Promise` is expected for asynchronous types).

@@ -495,5 +495,5 @@ ##### Sample

###### `replaceAsync` (obj: YourType, stateObj : {ownKeys: boolean, iterateIn: ('array'|'object'), iterateUnsetNumeric: boolean}) : `Typeson.Promise`
###### `replaceAsync` (obj: YourType, stateObj : {ownKeys: boolean, iterateIn: ('array'|'object'), iterateUnsetNumeric: boolean}) : `TypesonPromise`
Expected to return a `Typeson.Promise` which resolves to the replaced value.
Expected to return a `TypesonPromise` which resolves to the replaced value.
See `replace`.

@@ -506,3 +506,3 @@

will prevent the addition of the property. To explicitly add `undefined`, see
`Typeson.Undefined`.
`Undefined`.

@@ -549,3 +549,3 @@ ##### Sample

Expected to return a `Typeson.Promise` which resolves to the revived value.
Expected to return a `TypesonPromise` which resolves to the revived value.
See `revive`.

@@ -564,5 +564,5 @@

### Class methods
### Other exported classes
#### `Typeson.Undefined` class
#### `Undefined` class

@@ -583,3 +583,3 @@ During encapsulation, `undefined` will not be set for property values,

#### `Typeson.Promise` class
#### `TypesonPromise` class

@@ -632,4 +632,6 @@ If you have a type which you wish to have resolved asynchronously, you

#### `Typeson.toStringTag`
### Other exported methods
#### `toStringTag`
A simple utility for getting the former ``[[Class]]`` internal slot of an object

@@ -654,3 +656,3 @@ (i.e., The string between `[Object ` and `]` as returned from

#### `Typeson.hasConstructorOf` (objWithPrototypeConstructor, classToCompare: constructor or null) : boolean
#### `hasConstructorOf` (objWithPrototypeConstructor, classToCompare: constructor or null) : boolean

@@ -668,3 +670,3 @@ Another approach for class comparisons involves checking a `constructor`

#### `Typeson.isObject` (val)
#### `isObject` (val)

@@ -674,7 +676,7 @@ Simple but frequently-needed type-checking utility for

#### `Typeson.isPlainObject` (val)
#### `isPlainObject` (val)
Checks for a simple non-inherited object. Adapted from jQuery's `isPlainObject`.
#### `Typeson.isUserObject` (val)
#### `isUserObject` (val)

@@ -684,9 +686,9 @@ Allows for inherited objects but ensures the prototype chain inherits from

#### `Typeson.isThenable` (val, catchCheck=boolean)
#### `isThenable` (val, catchCheck=boolean)
Checks whether an object is "thenable" (usable as a promise). If the second
argument is supplied as `true`, it will also ensure it has a `catch` method.
A regular `Promise` or `Typeson.Promise` will return `true`.
A regular `Promise` or `TypesonPromise` will return `true`.
#### `Typeson.escapeKeyPathComponent` (unescapedKeyPathComponent)
#### `escapeKeyPathComponent` (unescapedKeyPathComponent)

@@ -698,11 +700,11 @@ Escapes a component of a key path.

#### `Typeson.unescapeKeyPathComponent` (escapedKeyPathComponent)
#### `unescapeKeyPathComponent` (escapedKeyPathComponent)
Unescapes a key path component. See `Typeson.escapeKeyPathComponent`.
Unescapes a key path component. See `escapeKeyPathComponent`.
#### `Typeson.getByKeyPath` (obj, keyPath)
#### `getByKeyPath` (obj, keyPath)
Retrieves a value pointed to by a key path on an object.
#### `Typeson.getJSONType` (obj)
#### `getJSONType` (obj)

@@ -712,5 +714,5 @@ Utility that returns 'null', 'boolean', 'number', 'string', 'array',

### Class properties
### Exported properties
#### `Typeson.JSON_TYPES`
#### `JSON_TYPES`

@@ -717,0 +719,0 @@ Set to the following array of JSON type names.

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc