The type registry for typeson
npm install typeson-registryThe type registry for typeson.
- Types listed under
types
- Presets listed under
presets
See below for notes on these types and presets.
Note that some types will require polyfills in Node such as viajsdom.
See the testing environment of test/test.js for some examples.
Note that for Node.js, to use the file or blob types (or the filelist
type or structuredCloning and structuredCloningThrowing presets which
include them), you will need a polyfill for Blob or File, respectively,
as well as FileReader and URL.createObjectURL (and a
polyfill for URL if you are using Node < 10.0.0 or an older browser).
Note that our URL.createObjectURL polyfill expects a globalXMLHttpRequest and location.href predefined before it as well (and one
which can handle data: URLs). For Node, you can add it like this:
``js
const url = require('url'); // This line only needed to support Node < 10.0.0
const {createObjectURL} = require('typeson-registry/polyfills/createObjectURL.umd.cjs');
const URL = url.Url; // This line only needed to support Node < 10.0.0
URL.createObjectURL = createObjectURL;
`
We have not added jsdom as a dependency, but it is required if this
polyfill is used.
Besides the polyfills for file or blob, the structuredCloningThrowingDOMException
preset also needs a global polyfill.
The filelist type, in addition to the polyfills for file, will needFileList
a polyfill (including a FileList string tag).
The imagebitmap type requires a global createImageBitmap polyfill (andImageBitmap
an polyfill (including an ImageBitmap string tag).
The imagedata type requires a global ImageData polyfill (including anImageData string tag).
You may wish to see our test-environment.js file for how somejsdom
polyfilling may be done (largely using ).
If you have cloned the repo (and not the npm package), you must run
npm install to get the devDependencies and then runnpm run rollup to get the individual browser scripts built locallydist
(into ) or to get index.js to be rebuilt based on existing
presets and types).
`js
import {Typeson, date, error, regexp, typedArrays} from 'typeson-registry';
const TSON = new Typeson().register([
date,
error,
regexp,
typedArrays
// ...
]);
const tson = TSON.stringify({
Hello: 'world',
date: new Date(),
error: new Error('test'),
inner: {
x: /foo/gui,
bin: new Uint8Array(64)
}
}, null, 2);
console.log(tson);
/* Output:
{
"Hello": "world",
"date": 1464049031538,
"error": {
"name": "Error",
"message": "test"
},
"inner": {
"x": {
"source": "foo",
"flags": "gi"
},
"bin": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
},
"$types": {
"date": "Date",
"error": "Error",
"inner.x": "RegExp",
"inner.bin": "Uint8Array"
}
}
*/
const parsedBack = TSON.parse(tson);
console.log(parsedBack.date instanceof Date);
console.log(parsedBack.inner.bin instanceof Uint8Array);
`
`js
const {Typeson, builtin} = require('typeson-registry');
const tson = new Typeson().register([
builtin
]);
`
in supporting browsers without own Rollup)`html
import {Typeson, builtin} from './node_modules/typeson-registry/dist/index.js';
const TSON = new Typeson().register([
builtin
]);
`
All types and presets under dist/ are UMD modules so you could also
require them as AMD modules with requirejs if you prefer.
`html
const TSON = new Typeson().register(builtin);
const tson = TSON.stringify({
Hello: 'world',
date: new Date(),
error: new Error('err'),
inner: {
x: /foo/giu,
bin: new Uint8Array(64)
}
}, null, 2);
alert(tson);
/* Alerts:
{
"Hello": "world",
"date": 1464049031538,
"error": {
"name": "Error",
"message": "err"
},
"inner": {
"x": {
"source": "foo",
"flags": "gi"
},
"bin": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
},
"$types": {
"date": "Date",
"error": "Error",
"inner.x": "RegExp",
"inner.bin": "Uint8Array"
}
}
*/
`
Note that the type name corresponds to the file name in the following manner:
1. Genuine separate words are camel-cased in the type name but hyphenated in
the file name (e.g., negativeInfinity and negativity-infinity.js);arraybuffer
names whose original API is camel-cased are not hyphenated, however
(e.g., and arraybuffer.js given ArrayBuffer).date
1. All other portions of names are lower-cased (e.g., and date.js).undef
1. Type names that would clash with existing objects when exported (even after
lower-casing) must have a separate, preferably abbreviated form (e.g.,
the type and preset and undef.js was necessary for undefined)Intl
1. Type names which are not allowed as ES6 exports (e.g., periods in Intl.Collator
types are now removed: -> IntlCollator)userObject
1. Type names should indicate the singular (e.g., ) except forerrors
files containing multiple related exports (e.g., , typed-arrays,typed-arrays-socketio.js
and ); files with multiple exports whose extrafilelist
exports are incidental (e.g., ) do not need a plural.
- arraybufferbigintObject
- bigint
- blob
- - Has sync and async encapsulation/replacements (though sync onlycloneable
via deprecated means)
- - Looks for Symbol.for('cloneEncapsulate') andSymbol.for('cloneRevive')
methods to allowcryptokey
for a means of extending our built-in structured cloning presets (though if
you are polyfilling a standard object, we welcome you to submit back as a
PR!). The clones cannot be revived past the current window session,
however.
- dataview
- date
- domexception
- dommatrix
- dommatrixreadonly
- dompoint
- dompointreadonly
- domquad
- domrect
- domrectreadonly
- error.js
- (Error) and errors.js (TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError, InternalError) - Thesefile
provide a means of resurrecting error object across cloning boundaries
(since they are not otherwise treated as cloneable by the Structured
Cloning Algorithm).
- - Has sync and async encapsulation/replacements (though sync onlyfilelist
via deprecated means)
- - HTML does not provide a means of creating a FileList objectFile
dynamically, so we polyfill one for revival. This method also sets imagebitmap
- - Has sync and async revivers. If OffscreenCanvas is notImageBitmap
supported, the sync method does not produce a genuine ImageBitmap
but instead produces a canvas element which can frequently be used in
a similar context to .imagedata
- infinity
- - Preserves positive infinityintl-types.js
- (Intl.Collator, Intl.DateTimeFormat, Intl.NumberFormat) -map
Not all properties can be preserved
- nan
- - Preserves NaN (not a number)negativeInfinity
- - Preserves negative infinitynegativeZero
- - Preserves -0 (produces + or - Infinity when used as divisor)nonBuiltInIgnore
- - For roughly detecting non-builtin objects and to avoidprimitive-objects.js
adding them as properties
- (StringObject, BooleanObject, NumberObject)promise
- regexp
- resurrectable
- - Resurrects any non-array object, function, or symbol; canset
only be revived for the current window session.
- symbol
- typed-arrays-socketio.js
- (Int8Array, Uint8Array, Uint8ClampedArray,Int16Array
, Uint16Array, Int32Array, Uint32Array, Float32Array,Float64Array
) - Seepresets/socketio.js
typeson#environmentformat-support
and typed-arrays.js
- (Int8Array, Uint8Array, Uint8ClampedArray,Int16Array
, Uint16Array, Int32Array, Uint32Array,Float32Array
, Float64Array) - Base64-encodesundef
- (for undefined) (See also presets/undefined.js andpresets/sparse-undefined.js
)userObjects
- - Allows for inherited objects but ensures the prototype chainObject
inherits from (or null). Should be low priority if one is
matching other objects as it will readily match many objects.
- array-nonindex-keys.jsbuiltin.js
- - Types that are built into the JavaScript language itself.postmessage.js
Types that were added in ES6 or beyond will be checked before inclusion
so that this module can be consumed by both ES5 and ES6 environments.
Some imperfectly serializable objects (such as functions and Symbols)
are not included in this preset.
- - This preset is intended as a utility to expand on what isstrcutured-cloning.js
cloneable via and supports Error objects.socketio.js
- sparse-undefined.js
- (sparseArrays and sparseUndefined) - Supportsundefined
reconstructing sparse arrays (with missing properties not even assigned
an explicit ). See types/undefined.js for the explicit casepresets/undefined.js
or for a utility combining both.special-numbers.js
- (preserves NaN, Infinity, -Infinity)structured-cloning.js
- - For the Structured Cloning Algorithm used by thepostMessage
likes of and indexedDB. See also the cloneable type.structured-cloning-throwing.js
- - Same as structured-cloning.js butcloneable
throws with non-recognized types. See also the type.undef.js
- - Supports reconstructing explicit and implicit (sparse)undefined
uses of .universal.js
- - Meant for de-facto universal types. Currently includes
built-ins only.
If you are looking for a way to resurrect functions, you can use the following,
but please bear in mind that it uses eval which is prohibited by some
Content Security Policies (CSP) (so we are not packaging it with our builds),
that it is unsafe, and also that the function might not behave
deterministically when revived (e.g., if the function were provided from
another context).
`js
const functionType = {functionType: [
function (x) { return typeof x === 'function'; },
function (funcType) { return '(' + funcType.toString() + ')'; },
// eslint-disable-next-line no-eval -- Demonstrating
function (o) { return eval(o); }
]};
const typeson = new Typeson().register(functionType);
const tson = typeson.stringify(function () { return 'abc'; });
const back = typeson.parse(tson);
back(); // 'abc'
`
node-canvas is used to test
ImageData.
Be sure to follow the installation steps.
On Windows, besides following the
Windows installation steps,
this
helped complete the installation. If you need to have it rebuilt, you can
run npm i inside of the node_modules/canvas directory.
These steps
were also necessary but you can run npm run windows after install to getnode-canvas` copy.
these steps applied. These are the only steps which should need to be re-run
if you have deleted your local
- typeson