{"_id":"algorand-msgpack","_rev":"3-da4874b471110687754edb05ea51b5f8","name":"algorand-msgpack","dist-tags":{"latest":"1.1.0"},"versions":{"1.0.1":{"name":"algorand-msgpack","version":"1.0.1","keywords":["msgpack","MessagePack","serialization","universal"],"author":{"name":"Algorand Technologies & the MessagePack community"},"license":"ISC","_id":"algorand-msgpack@1.0.1","maintainers":[{"name":"jasonpaulos","email":"jasonpaulospublic@gmail.com"}],"homepage":"https://msgpack.org/","bugs":{"url":"https://github.com/algorand/msgpack-javascript/issues"},"cdn":"./dist.es5+umd/msgpack.min.js","dist":{"shasum":"ca8d519a01ae011823ccfaec80b17468255229d1","tarball":"https://registry.npmjs.org/algorand-msgpack/-/algorand-msgpack-1.0.1.tgz","fileCount":110,"integrity":"sha512-8vVEar8APmTT7cp6Ye2pJg7tHFSgXfJlXmq85v3MTlqPQp14KnxndbyKIq5xjCBT/oarx9p5ncDfRq3hzYg/NA==","signatures":[{"sig":"MEQCIDd8N0TABZXatttqOEYElc0vz+zQ0filc4C/m67axUtTAiA5lm8rEGpH/XNkS3Q5WgMeTGiiZeRAk9oVcLJshkt3WQ==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":779046},"main":"./dist/index.js","types":"./dist/index.d.ts","unpkg":"./dist.es5+umd/msgpack.min.js","module":"./dist.es5+esm/index.mjs","engines":{"node":">= 14"},"gitHead":"0634ae64a12cf7f58d9847714152d48191052c6c","scripts":{"lint":"eslint --ext .ts src test","test":"mocha 'test/**/*.test.ts'","build":"npm publish --dry-run","clean":"rimraf build dist dist.es5+esm dist.umd","prepare":"npm run clean && webpack --bail && tsc --build tsconfig.dist.json tsconfig.dist.es5+esm.json && ts-node tools/esmify.ts dist.es5+esm/*.js dist.es5+esm/*/*.js","lint:fix":"prettier --loglevel=warn --write 'src/**/*.ts' 'test/**/*.ts' && eslint --fix --ext .ts src test","test:deno":"deno test test/deno_test.ts","test:dist":"npm run lint && npm run test && npm run test:browser && npm run test:deno","test:fuzz":"npm exec --yes -- jsfuzz@git+https://gitlab.com/gitlab-org/security-products/analyzers/fuzzers/jsfuzz.git#39e6cf16613a0e30c7a7953f62e64292dbd5d3f3 --fuzzTime 60 --no-versifier test/decode.jsfuzz.js corpus","test:cover":"npm run cover:clean && npx nyc --no-clean npm run 'test' && npm run cover:report","cover:clean":"rimraf .nyc_output coverage/","cover:report":"npx nyc report --reporter=text-summary --reporter=html --reporter=json","test:browser":"karma start --single-run","prepublishOnly":"npm run test:dist","lint:print-config":"eslint --print-config .eslintrc.js","test:watch:nodejs":"mocha -w 'test/**/*.test.ts'","test:watch:browser":"karma start --browsers ChromeHeadless,FirefoxHeadless","test:browser:chrome":"karma start --single-run --browsers ChromeHeadless","update-dependencies":"npx rimraf node_modules/ package-lock.json ; npm install ; npm audit fix --force ; git restore package.json ; npm install","test:browser:firefox":"karma start --single-run --browsers FirefoxHeadless"},"_npmUser":{"name":"jasonpaulos","email":"jasonpaulospublic@gmail.com"},"repository":{"url":"git+https://github.com/algorand/msgpack-javascript.git","type":"git"},"_npmVersion":"10.2.3","description":"MessagePack for ECMA-262/JavaScript/TypeScript","directories":{},"sideEffects":false,"_nodeVersion":"20.10.0","_hasShrinkwrap":false,"devDependencies":{"glob":"^10.3.10","karma":"latest","mocha":"latest","assert":"latest","buffer":"latest","eslint":"latest","lodash":"latest","rimraf":"latest","core-js":"latest","ieee754":"latest","msg-ext":"^1.0.1","ts-node":"latest","webpack":"latest","prettier":"latest","karma-cli":"latest","msg-int64":"^0.1.1","ts-loader":"latest","typescript":"latest","@types/node":"latest","karma-mocha":"latest","webpack-cli":"latest","@types/mocha":"latest","@types/lodash":"latest","karma-webpack":"latest","msg-timestamp":"^1.0.1","tsconfig-paths":"latest","eslint-plugin-tsdoc":"latest","eslint-plugin-import":"latest","karma-chrome-launcher":"latest","eslint-config-prettier":"latest","karma-firefox-launcher":"latest","karma-sourcemap-loader":"latest","@typescript-eslint/parser":"latest","@typescript-eslint/eslint-plugin":"latest","@bitjourney/check-es-version-webpack-plugin":"latest"},"_npmOperationalInternal":{"tmp":"tmp/algorand-msgpack_1.0.1_1710272193156_0.39579122628506846","host":"s3://npm-registry-packages"}},"1.1.0":{"name":"algorand-msgpack","version":"1.1.0","keywords":["msgpack","MessagePack","serialization","universal"],"author":{"name":"Algorand Technologies & the MessagePack community"},"license":"ISC","_id":"algorand-msgpack@1.1.0","maintainers":[{"name":"jasonpaulos","email":"jasonpaulospublic@gmail.com"},{"name":"algojohnlee","email":"john.lee@algorand.com"}],"homepage":"https://msgpack.org/","bugs":{"url":"https://github.com/algorand/msgpack-javascript/issues"},"cdn":"./dist.es5+umd/msgpack.min.js","dist":{"shasum":"46c67c7232a3ee1bafc3c64b67fefbdb504e6560","tarball":"https://registry.npmjs.org/algorand-msgpack/-/algorand-msgpack-1.1.0.tgz","fileCount":110,"integrity":"sha512-08k7pBQnkaUB5p+jL7f1TRaUIlTSDE0cesFu1mD7llLao+1cAhtvvZmGE3OnisTd0xOn118QMw74SRqddqaYvw==","signatures":[{"sig":"MEUCIAh8P7d8ns3fKUag/lgjmXeR3wjtiRKlSTLh1FHWMZFnAiEAxbVmVw2WP7HHG+nL/uaMftHtXN4ysmDz6H/pYZtRVuE=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":799845},"main":"./dist/index.js","types":"./dist/index.d.ts","unpkg":"./dist.es5+umd/msgpack.min.js","module":"./dist.es5+esm/index.mjs","engines":{"node":">= 14"},"gitHead":"d622c4af449a4aef377eed8e9d54b77e88a2c917","scripts":{"lint":"eslint --ext .ts src test","test":"mocha 'test/**/*.test.ts'","build":"npm publish --dry-run","clean":"rimraf build dist dist.es5+esm dist.umd","prepare":"npm run clean && webpack --bail && tsc --build tsconfig.dist.json tsconfig.dist.es5+esm.json && ts-node tools/esmify.ts dist.es5+esm/*.js dist.es5+esm/*/*.js","lint:fix":"prettier --loglevel=warn --write 'src/**/*.ts' 'test/**/*.ts' && eslint --fix --ext .ts src test","test:deno":"deno test test/deno_test.ts","test:dist":"npm run lint && npm run test","test:fuzz":"npm exec --yes -- jsfuzz@git+https://gitlab.com/gitlab-org/security-products/analyzers/fuzzers/jsfuzz.git#39e6cf16613a0e30c7a7953f62e64292dbd5d3f3 --fuzzTime 60 --no-versifier test/decode.jsfuzz.js corpus","test:cover":"npm run cover:clean && npx nyc --no-clean npm run 'test' && npm run cover:report","cover:clean":"rimraf .nyc_output coverage/","cover:report":"npx nyc report --reporter=text-summary --reporter=html --reporter=json","test:browser":"karma start --single-run","prepublishOnly":"npm run test:dist","lint:print-config":"eslint --print-config .eslintrc.js","test:watch:nodejs":"mocha -w 'test/**/*.test.ts'","test:watch:browser":"karma start --browsers ChromeHeadless,FirefoxHeadless","test:browser:chrome":"karma start --single-run --browsers ChromeHeadless","update-dependencies":"npx rimraf node_modules/ package-lock.json ; npm install ; npm audit fix --force ; git restore package.json ; npm install","test:browser:firefox":"karma start --single-run --browsers FirefoxHeadless"},"_npmUser":{"name":"jasonpaulos","email":"jasonpaulospublic@gmail.com"},"repository":{"url":"git+https://github.com/algorand/msgpack-javascript.git","type":"git"},"_npmVersion":"10.2.3","description":"MessagePack for ECMA-262/JavaScript/TypeScript","directories":{},"sideEffects":false,"_nodeVersion":"20.10.0","_hasShrinkwrap":false,"devDependencies":{"glob":"^10.3.10","karma":"latest","mocha":"latest","assert":"latest","buffer":"latest","eslint":"latest","lodash":"latest","rimraf":"latest","core-js":"latest","ieee754":"latest","msg-ext":"^1.0.1","ts-node":"latest","webpack":"latest","prettier":"latest","karma-cli":"latest","msg-int64":"^0.1.1","ts-loader":"latest","typescript":"latest","@types/node":"latest","karma-mocha":"latest","webpack-cli":"latest","@types/mocha":"latest","@types/lodash":"latest","karma-webpack":"latest","msg-timestamp":"^1.0.1","tsconfig-paths":"latest","eslint-plugin-tsdoc":"latest","eslint-plugin-import":"latest","karma-chrome-launcher":"latest","eslint-config-prettier":"latest","karma-firefox-launcher":"latest","karma-sourcemap-loader":"latest","@typescript-eslint/parser":"latest","@typescript-eslint/eslint-plugin":"latest","@bitjourney/check-es-version-webpack-plugin":"latest"},"_npmOperationalInternal":{"tmp":"tmp/algorand-msgpack_1.1.0_1722454098635_0.7667922794921149","host":"s3://npm-registry-packages"}}},"time":{"created":"2024-03-12T19:36:33.155Z","modified":"2024-09-03T15:09:10.799Z","1.0.1":"2024-03-12T19:36:33.374Z","1.1.0":"2024-07-31T19:28:18.788Z"},"bugs":{"url":"https://github.com/algorand/msgpack-javascript/issues"},"author":{"name":"Algorand Technologies & the MessagePack community"},"license":"ISC","homepage":"https://msgpack.org/","keywords":["msgpack","MessagePack","serialization","universal"],"repository":{"url":"git+https://github.com/algorand/msgpack-javascript.git","type":"git"},"description":"MessagePack for ECMA-262/JavaScript/TypeScript","maintainers":[{"email":"john.lee@algorand.com","name":"algojohnlee"},{"email":"devops-service@algorand.com","name":"algo-devops-service"}],"readme":"# MessagePack for JavaScript/ECMA-262 <!-- omit in toc -->\n\n[![npm version](https://img.shields.io/npm/v/algorand-msgpack.svg)](https://www.npmjs.com/package/algorand-msgpack) ![CI](https://github.com/algorand/msgpack-javascript/workflows/CI/badge.svg) [![codecov](https://codecov.io/gh/algorand/msgpack-javascript/branch/master/graphs/badge.svg)](https://codecov.io/gh/algorand/msgpack-javascript) [![minzip](https://badgen.net/bundlephobia/minzip/algorand-msgpack)](https://bundlephobia.com/result?p=algorand-msgpack) [![tree-shaking](https://badgen.net/bundlephobia/tree-shaking/algorand-msgpack)](https://bundlephobia.com/result?p=algorand-msgpack)\n\n> NOTE: This library is a fork of [msgpack/msgpack-javascript](https://github.com/msgpack/msgpack-javascript), with the following changes:\n>\n> - Improved bigint support. Bigints are no longer solely encoded as int64/uint64, which allows for greater compatibility with other MessagePack libraries. Additional decoding options are available as well.\n> - Raw string decoding support. When decoding, strings can be decoded as Uint8Arrays. This supports reading non-UTF-8 encoded strings.\n> - Number and binary map key support with Maps.\n>\n> The exact changes can be viewed [in this comparison](https://github.com/msgpack/msgpack-javascript/compare/1fc7622...algorand:msgpack-javascript:main).\n>\n> You may install this forked library with `npm i algorand-msgpack`.\n\nThis library is an implementation of **MessagePack** for TypeScript and JavaScript, providing a compact and efficient binary serialization format. Learn more about MessagePack at:\n\nhttps://msgpack.org/\n\nThis library serves as a comprehensive reference implementation of MessagePack for JavaScript with a focus on accuracy, compatibility, interoperability, and performance.\n\nAdditionally, this is also a universal JavaScript library. It is compatible not only with browsers, but with Node.js or other JavaScript engines that implement ES2015+ standards. As it is written in [TypeScript](https://www.typescriptlang.org/), this library bundles up-to-date type definition files (`d.ts`).\n\n\\*Note that this is the second edition of \"MessagePack for JavaScript\". The first edition, which was implemented in ES5 and never released to npmjs.com, is tagged as [`classic`](https://github.com/msgpack/msgpack-javascript/tree/classic).\n\n## Synopsis\n\n```typescript\nimport { deepStrictEqual } from \"assert\";\nimport { encode, decode } from \"@msgpack/msgpack\";\n\nconst object = {\n  nil: null,\n  integer: 1,\n  float: Math.PI,\n  string: \"Hello, world!\",\n  binary: Uint8Array.from([1, 2, 3]),\n  array: [10, 20, 30],\n  map: { foo: \"bar\" },\n  timestampExt: new Date(),\n};\n\nconst encoded: Uint8Array = encode(object);\n\ndeepStrictEqual(decode(encoded), object);\n```\n\n## Table of Contents\n\n- [Synopsis](#synopsis)\n- [Table of Contents](#table-of-contents)\n- [Install](#install)\n- [API](#api)\n  - [`encode(data: unknown, options?: EncoderOptions): Uint8Array`](#encodedata-unknown-options-encoderoptions-uint8array)\n    - [`EncoderOptions`](#encoderoptions)\n  - [`decode(buffer: ArrayLike<number> | BufferSource, options?: DecoderOptions): unknown`](#decodebuffer-arraylikenumber--buffersource-options-decoderoptions-unknown)\n    - [`DecoderOptions`](#decoderoptions)\n      - [`IntMode`](#intmode)\n  - [`decodeMulti(buffer: ArrayLike<number> | BufferSource, options?: DecoderOptions): Generator<unknown, void, unknown>`](#decodemultibuffer-arraylikenumber--buffersource-options-decoderoptions-generatorunknown-void-unknown)\n  - [`decodeAsync(stream: ReadableStreamLike<ArrayLike<number> | BufferSource>, options?: DecoderOptions): Promise<unknown>`](#decodeasyncstream-readablestreamlikearraylikenumber--buffersource-options-decoderoptions-promiseunknown)\n  - [`decodeArrayStream(stream: ReadableStreamLike<ArrayLike<number> | BufferSource>, options?: DecoderOptions): AsyncIterable<unknown>`](#decodearraystreamstream-readablestreamlikearraylikenumber--buffersource-options-decoderoptions-asynciterableunknown)\n  - [`decodeMultiStream(stream: ReadableStreamLike<ArrayLike<number> | BufferSource>, options?: DecoderOptions): AsyncIterable<unknown>`](#decodemultistreamstream-readablestreamlikearraylikenumber--buffersource-options-decoderoptions-asynciterableunknown)\n  - [Reusing Encoder and Decoder instances](#reusing-encoder-and-decoder-instances)\n- [Extension Types](#extension-types)\n  - [ExtensionCodec context](#extensioncodec-context)\n  - [Handling BigInt](#handling-bigint)\n  - [The temporal module as timestamp extensions](#the-temporal-module-as-timestamp-extensions)\n- [Decoding a Blob](#decoding-a-blob)\n- [MessagePack Specification](#messagepack-specification)\n  - [MessagePack Mapping Table](#messagepack-mapping-table)\n- [Prerequisites](#prerequisites)\n  - [ECMA-262](#ecma-262)\n  - [NodeJS](#nodejs)\n  - [TypeScript Compiler / Type Definitions](#typescript-compiler--type-definitions)\n- [Benchmark](#benchmark)\n- [Distribution](#distribution)\n  - [NPM / npmjs.com](#npm--npmjscom)\n  - [CDN / unpkg.com](#cdn--unpkgcom)\n- [Deno Support](#deno-support)\n- [Maintenance](#maintenance)\n  - [Testing](#testing)\n  - [Continuous Integration](#continuous-integration)\n  - [Release Engineering](#release-engineering)\n  - [Updating Dependencies](#updating-dependencies)\n- [License](#license)\n\n## Install\n\nThis library is published to `npmjs.com` as [@msgpack/msgpack](https://www.npmjs.com/package/@msgpack/msgpack).\n\n```shell\nnpm install @msgpack/msgpack\n```\n\n## API\n\n### `encode(data: unknown, options?: EncoderOptions): Uint8Array`\n\nIt encodes `data` into a single MessagePack-encoded object, and returns a byte array as `Uint8Array`. It throws errors if `data` is, or includes, a non-serializable object such as a `function` or a `symbol`.\n\nfor example:\n\n```typescript\nimport { encode } from \"@msgpack/msgpack\";\n\nconst encoded: Uint8Array = encode({ foo: \"bar\" });\nconsole.log(encoded);\n```\n\nIf you'd like to convert an `uint8array` to a NodeJS `Buffer`, use `Buffer.from(arrayBuffer, offset, length)` in order not to copy the underlying `ArrayBuffer`, while `Buffer.from(uint8array)` copies it:\n\n```typescript\nimport { encode } from \"@msgpack/msgpack\";\n\nconst encoded: Uint8Array = encode({ foo: \"bar\" });\n\n// `buffer` refers the same ArrayBuffer as `encoded`.\nconst buffer: Buffer = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength);\nconsole.log(buffer);\n```\n\n#### `EncoderOptions`\n\n| Name                | Type           | Default                       |\n| ------------------- | -------------- | ----------------------------- |\n| extensionCodec      | ExtensionCodec | `ExtensionCodec.defaultCodec` |\n| context             | user-defined   | -                             |\n| forceBigIntToInt64  | boolean        | false                         |\n| maxDepth            | number         | `100`                         |\n| initialBufferSize   | number         | `2048`                        |\n| sortKeys            | boolean        | false                         |\n| forceFloat32        | boolean        | false                         |\n| forceIntegerToFloat | boolean        | false                         |\n| ignoreUndefined     | boolean        | false                         |\n\n### `decode(buffer: ArrayLike<number> | BufferSource, options?: DecoderOptions): unknown`\n\nIt decodes `buffer` that includes a MessagePack-encoded object, and returns the decoded object typed `unknown`.\n\n`buffer` must be an array of bytes, which is typically `Uint8Array` or `ArrayBuffer`. `BufferSource` is defined as `ArrayBuffer | ArrayBufferView`.\n\nThe `buffer` must include a single encoded object. If the `buffer` includes extra bytes after an object or the `buffer` is empty, it throws `RangeError`. To decode `buffer` that includes multiple encoded objects, use `decodeMulti()` or `decodeMultiStream()` (recommended) instead.\n\nfor example:\n\n```typescript\nimport { decode } from \"@msgpack/msgpack\";\n\nconst encoded: Uint8Array;\nconst object = decode(encoded);\nconsole.log(object);\n```\n\nNodeJS `Buffer` is also acceptable because it is a subclass of `Uint8Array`.\n\n#### `DecoderOptions`\n\n| Name                    | Type           | Default                                                                              |\n| ----------------------- | -------------- | ------------------------------------------------------------------------------------ |\n| extensionCodec          | ExtensionCodec | `ExtensionCodec.defaultCodec`                                                        |\n| context                 | user-defined   | -                                                                                    |\n| useBigInt64             | boolean        | false                                                                                |\n| intMode                 | IntMode        | `IntMode.AS_ENCODED` if `useBigInt64` is `true` or `IntMode.UNSAFE_NUMBER` otherwise |\n| rawBinaryStringKeys     | boolean        | false                                                                                |\n| rawBinaryStringValues   | boolean        | false                                                                                |\n| useRawBinaryStringClass | boolean        | false                                                                                |\n| useMap                  | boolean        | false                                                                                |\n| supportObjectNumberKeys | boolean        | false                                                                                |\n| maxStrLength            | number         | `4_294_967_295` (UINT32_MAX)                                                         |\n| maxBinLength            | number         | `4_294_967_295` (UINT32_MAX)                                                         |\n| maxArrayLength          | number         | `4_294_967_295` (UINT32_MAX)                                                         |\n| maxMapLength            | number         | `4_294_967_295` (UINT32_MAX)                                                         |\n| maxExtLength            | number         | `4_294_967_295` (UINT32_MAX)                                                         |\n\nYou can use `max${Type}Length` to limit the length of each type decoded.\n\n`intMode` determines whether decoded integers should be returned as numbers or bigints in different circumstances. The possible values are [described below](#intmode).\n\nTo skip UTF-8 decoding of strings, one or both of `rawBinaryStringKeys` and `rawBinaryStringValues` can be set to `true`. If enabled, strings are decoded into `Uint8Array`, or a `RawBinaryString` which wraps a `Uint8Array` if `useRawBinaryStringClass` is true. `rawBinaryStringKeys` affects only map keys, while `rawBinaryStringValues` affect all other string values. You may want to enable `useRawBinaryStringClass` if you want to distinguish between regular strings and binary strings, or if you wish to re-encode the object, since `RawBinaryString` instances will be encoded as regular strings.\n\nIf `useMap` is enabled, maps are decoded into the `Map` container instead of plain objects. `Map` objects support a wider range of key types. Plain objects only support string keys (though you can enable `supportObjectNumberKeys` to coerce number keys to strings), while `Map` objects support strings, numbers, bigints, and Uint8Arrays.\n\n##### `IntMode`\n\nThe `IntMode` enum defines different options for decoding integers. They are described below:\n\n- `IntMode.UNSAFE_NUMBER`: Always returns the value as a number. Be aware that there will be a loss of precision if the value is outside the range of `Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`.\n- `IntMode.SAFE_NUMBER`: Always returns the value as a number, but throws an error if the value is outside of the range of `Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`.\n- `IntMode.MIXED`: Returns all values inside the range of `Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER` as numbers and all values outside that range as bigints.\n- `IntMode.AS_ENCODED`: Returns all values encoded as int64/uint64 as bigints and all other integers as numbers.\n- `IntMode.BIGINT`: Always returns the value as a bigint, even if it is small enough to safely fit in a number.\n\n### `decodeMulti(buffer: ArrayLike<number> | BufferSource, options?: DecoderOptions): Generator<unknown, void, unknown>`\n\nIt decodes `buffer` that includes multiple MessagePack-encoded objects, and returns decoded objects as a generator. See also `decodeMultiStream()`, which is an asynchronous variant of this function.\n\nThis function is not recommended to decode a MessagePack binary via I/O stream including sockets because it's synchronous. Instead, `decodeMultiStream()` decodes a binary stream asynchronously, typically spending less CPU and memory.\n\nfor example:\n\n```typescript\nimport { decode } from \"@msgpack/msgpack\";\n\nconst encoded: Uint8Array;\n\nfor (const object of decodeMulti(encoded)) {\n  console.log(object);\n}\n```\n\n### `decodeAsync(stream: ReadableStreamLike<ArrayLike<number> | BufferSource>, options?: DecoderOptions): Promise<unknown>`\n\nIt decodes `stream`, where `ReadableStreamLike<T>` is defined as `ReadableStream<T> | AsyncIterable<T>`, in an async iterable of byte arrays, and returns decoded object as `unknown` type, wrapped in `Promise`.\n\nThis function works asynchronously, and might CPU resources more efficiently compared with synchronous `decode()`, because it doesn't wait for the completion of downloading.\n\nThis function is designed to work with whatwg `fetch()` like this:\n\n```typescript\nimport { decodeAsync } from \"@msgpack/msgpack\";\n\nconst MSGPACK_TYPE = \"application/x-msgpack\";\n\nconst response = await fetch(url);\nconst contentType = response.headers.get(\"Content-Type\");\nif (contentType && contentType.startsWith(MSGPACK_TYPE) && response.body != null) {\n  const object = await decodeAsync(response.body);\n  // do something with object\n} else {\n  /* handle errors */\n}\n```\n\n### `decodeArrayStream(stream: ReadableStreamLike<ArrayLike<number> | BufferSource>, options?: DecoderOptions): AsyncIterable<unknown>`\n\nIt is alike to `decodeAsync()`, but only accepts a `stream` that includes an array of items, and emits a decoded item one by one.\n\nfor example:\n\n```typescript\nimport { decodeArrayStream } from \"@msgpack/msgpack\";\n\nconst stream: AsyncIterator<Uint8Array>;\n\n// in an async function:\nfor await (const item of decodeArrayStream(stream)) {\n  console.log(item);\n}\n```\n\n### `decodeMultiStream(stream: ReadableStreamLike<ArrayLike<number> | BufferSource>, options?: DecoderOptions): AsyncIterable<unknown>`\n\nIt is alike to `decodeAsync()` and `decodeArrayStream()`, but the input `stream` must consist of multiple MessagePack-encoded items. This is an asynchronous variant for `decodeMulti()`.\n\nIn other words, it could decode an unlimited stream and emits a decoded item one by one.\n\nfor example:\n\n```typescript\nimport { decodeMultiStream } from \"@msgpack/msgpack\";\n\nconst stream: AsyncIterator<Uint8Array>;\n\n// in an async function:\nfor await (const item of decodeMultiStream(stream)) {\n  console.log(item);\n}\n```\n\nThis function is available since v2.4.0; previously it was called as `decodeStream()`.\n\n### Reusing Encoder and Decoder instances\n\n`Encoder` and `Decoder` classes are provided to have better performance by reusing instances:\n\n```typescript\nimport { deepStrictEqual } from \"assert\";\nimport { Encoder, Decoder } from \"@msgpack/msgpack\";\n\nconst encoder = new Encoder();\nconst decoder = new Decoder();\n\nconst encoded: Uint8Array = encoder.encode(object);\ndeepStrictEqual(decoder.decode(encoded), object);\n```\n\nAccording to our benchmark, reusing `Encoder` instance is about 20% faster\nthan `encode()` function, and reusing `Decoder` instance is about 2% faster\nthan `decode()` function. Note that the result should vary in environments\nand data structure.\n\n`Encoder` and `Decoder` take the same options as `encode()` and `decode()` respectively.\n\n## Extension Types\n\nTo handle [MessagePack Extension Types](https://github.com/msgpack/msgpack/blob/master/spec.md#extension-types), this library provides `ExtensionCodec` class.\n\nThis is an example to setup custom extension types that handles `Map` and `Set` classes in TypeScript:\n\n```typescript\nimport { encode, decode, ExtensionCodec } from \"@msgpack/msgpack\";\n\nconst extensionCodec = new ExtensionCodec();\n\n// Set<T>\nconst SET_EXT_TYPE = 0; // Any in 0-127\nextensionCodec.register({\n  type: SET_EXT_TYPE,\n  encode: (object: unknown): Uint8Array | null => {\n    if (object instanceof Set) {\n      return encode([...object], { extensionCodec });\n    } else {\n      return null;\n    }\n  },\n  decode: (data: Uint8Array) => {\n    const array = decode(data, { extensionCodec }) as Array<unknown>;\n    return new Set(array);\n  },\n});\n\n// Map<T>\nconst MAP_EXT_TYPE = 1; // Any in 0-127\nextensionCodec.register({\n  type: MAP_EXT_TYPE,\n  encode: (object: unknown): Uint8Array => {\n    if (object instanceof Map) {\n      return encode([...object], { extensionCodec });\n    } else {\n      return null;\n    }\n  },\n  decode: (data: Uint8Array) => {\n    const array = decode(data, { extensionCodec }) as Array<[unknown, unknown]>;\n    return new Map(array);\n  },\n});\n\nconst encoded = encode([new Set<any>(), new Map<any, any>()], { extensionCodec });\nconst decoded = decode(encoded, { extensionCodec });\n```\n\nEnsure you include your extensionCodec in any recursive encode and decode statements!\n\nNote that extension types for custom objects must be `[0, 127]`, while `[-1, -128]` is reserved for MessagePack itself.\n\n#### ExtensionCodec context\n\nWhen you use an extension codec, it might be necessary to have encoding/decoding state to keep track of which objects got encoded/re-created. To do this, pass a `context` to the `EncoderOptions` and `DecoderOptions`:\n\n```typescript\nimport { encode, decode, ExtensionCodec } from \"@msgpack/msgpack\";\n\nclass MyContext {\n  track(object: any) { /*...*/ }\n}\n\nclass MyType { /* ... */ }\n\nconst extensionCodec = new ExtensionCodec<MyContext>();\n\n// MyType\nconst MYTYPE_EXT_TYPE = 0 // Any in 0-127\nextensionCodec.register({\n  type: MYTYPE_EXT_TYPE,\n  encode: (object, context) => {\n    if (object instanceof MyType) {\n      context.track(object); // <-- like this\n      return encode(object.toJSON(), { extensionCodec, context });\n    } else {\n      return null;\n    }\n  },\n  decode: (data, extType, context) => {\n    const decoded = decode(data, { extensionCodec, context });\n    const my = new MyType(decoded);\n    context.track(my); // <-- and like this\n    return my;\n  },\n});\n\n// and later\nimport { encode, decode } from \"@msgpack/msgpack\";\n\nconst context = new MyContext();\n\nconst encoded = = encode({myType: new MyType<any>()}, { extensionCodec, context });\nconst decoded = decode(encoded, { extensionCodec, context });\n```\n\n#### Handling BigInt\n\n**Decoding**\n\nThis library does not handle decoding BigInt by default, but you have three options to decode using BigInt's:\n\n- Set `useBigInt64: true` to decode MessagePack's `int64`/`uint64` into a BigInt\n- Set `intMode` to exert [greater control](#intmode) over BigInt handling\n- Define a custom `ExtensionCodec` to map bigint to a MessagePack extension type\n\n**Encoding**\n\nThis library will encode a BigInt into a MessagePack int64/uint64 if it is > 32-bit OR you set `forceBigIntToInt64` to `true`. This library will encode a `number` that is > 32-bit into a MessagePack int64/uint64 if it is > 32-bit.\n\nIf you set `forceBigIntToInt64` to `true` note:\n\n- A bigint is encoded in 8 byte binaries even if it's a small integer\n- A bigint must be smaller than the max value of the uint64 and larger than the min value of the int64. Otherwise the behavior is undefined.\n\n**Custom codec**\n\nAlternatively, you can define a custom codec to handle bigint like this:\n\n```typescript\nimport { deepStrictEqual } from \"assert\";\nimport { encode, decode, ExtensionCodec } from \"@msgpack/msgpack\";\n\n// to define a custom codec:\nconst BIGINT_EXT_TYPE = 0; // Any in 0-127\nconst extensionCodec = new ExtensionCodec();\nextensionCodec.register({\n  type: BIGINT_EXT_TYPE,\n  encode(input: unknown): Uint8Array | null {\n    if (typeof input === \"bigint\") {\n      if (input <= Number.MAX_SAFE_INTEGER && input >= Number.MIN_SAFE_INTEGER) {\n        return encode(Number(input));\n      } else {\n        return encode(String(input));\n      }\n    } else {\n      return null;\n    }\n  },\n  decode(data: Uint8Array): bigint {\n    const val = decode(data);\n    if (!(typeof val === \"string\" || typeof val === \"number\")) {\n      throw new DecodeError(`unexpected BigInt source: ${val} (${typeof val})`);\n    }\n    return BigInt(val);\n  },\n});\n\n// to use it:\nconst value = BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1);\nconst encoded: = encode(value, { extensionCodec });\ndeepStrictEqual(decode(encoded, { extensionCodec }), value);\n```\n\n#### The temporal module as timestamp extensions\n\nThere is a proposal for a new date/time representations in JavaScript:\n\n- https://github.com/tc39/proposal-temporal\n\nThis library maps `Date` to the MessagePack timestamp extension by default, but you can re-map the temporal module (or [Temporal Polyfill](https://github.com/tc39/proposal-temporal/tree/main/polyfill)) to the timestamp extension like this:\n\n```typescript\nimport { Instant } from \"@std-proposal/temporal\";\nimport { deepStrictEqual } from \"assert\";\nimport {\n  encode,\n  decode,\n  ExtensionCodec,\n  EXT_TIMESTAMP,\n  encodeTimeSpecToTimestamp,\n  decodeTimestampToTimeSpec,\n} from \"@msgpack/msgpack\";\n\n// to define a custom codec\nconst extensionCodec = new ExtensionCodec();\nextensionCodec.register({\n  type: EXT_TIMESTAMP, // override the default behavior!\n  encode(input: unknown): Uint8Array | null {\n    if (input instanceof Instant) {\n      const sec = input.seconds;\n      const nsec = Number(input.nanoseconds - BigInt(sec) * BigInt(1e9));\n      return encodeTimeSpecToTimestamp({ sec, nsec });\n    } else {\n      return null;\n    }\n  },\n  decode(data: Uint8Array): Instant {\n    const timeSpec = decodeTimestampToTimeSpec(data);\n    const sec = BigInt(timeSpec.sec);\n    const nsec = BigInt(timeSpec.nsec);\n    return Instant.fromEpochNanoseconds(sec * BigInt(1e9) + nsec);\n  },\n});\n\n// to use it\nconst instant = Instant.fromEpochMilliseconds(Date.now());\nconst encoded = encode(instant, { extensionCodec });\nconst decoded = decode(encoded, { extensionCodec });\ndeepStrictEqual(decoded, instant);\n```\n\nThis will become default in this library with major-version increment, if the temporal module is standardized.\n\n## Decoding a Blob\n\n[`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) is a binary data container provided by browsers. To read its contents, you can use `Blob#arrayBuffer()` or `Blob#stream()`. `Blob#stream()`\nis recommended if your target platform support it. This is because streaming\ndecode should be faster for large objects. In both ways, you need to use\nasynchronous API.\n\n```typescript\nasync function decodeFromBlob(blob: Blob): unknown {\n  if (blob.stream) {\n    // Blob#stream(): ReadableStream<Uint8Array> (recommended)\n    return await decodeAsync(blob.stream());\n  } else {\n    // Blob#arrayBuffer(): Promise<ArrayBuffer> (if stream() is not available)\n    return decode(await blob.arrayBuffer());\n  }\n}\n```\n\n## MessagePack Specification\n\nThis library is compatible with the \"August 2017\" revision of MessagePack specification at the point where timestamp ext was added:\n\n- [x] str/bin separation, added at August 2013\n- [x] extension types, added at August 2013\n- [x] timestamp ext type, added at August 2017\n\nThe living specification is here:\n\nhttps://github.com/msgpack/msgpack\n\nNote that as of June 2019 there're no official \"version\" on the MessagePack specification. See https://github.com/msgpack/msgpack/issues/195 for the discussions.\n\n### MessagePack Mapping Table\n\nThe following table shows how JavaScript values are mapped to [MessagePack formats](https://github.com/msgpack/msgpack/blob/master/spec.md) and vice versa.\n\nThe mapping of integers varies on the setting of `intMode`.\n\n| Source Value          | MessagePack Format   | Value Decoded          |\n| --------------------- | -------------------- | ---------------------- |\n| null, undefined       | nil                  | null (\\*1)             |\n| boolean (true, false) | bool family          | boolean (true, false)  |\n| number (53-bit int)   | int family           | number or bigint (\\*2) |\n| number (64-bit float) | float family         | number (64-bit float)  |\n| bigint                | int family           | number or bigint (\\*2) |\n| string                | str family           | string (\\*3)           |\n| ArrayBufferView       | bin family           | Uint8Array (\\*4)       |\n| Array                 | array family         | Array                  |\n| Object                | map family           | Object (\\*5)           |\n| Date                  | timestamp ext family | Date (\\*6)             |\n| bigint                | int family           | bigint                 |\n\n- \\*1 Both `null` and `undefined` are mapped to `nil` (`0xC0`) type, and are decoded into `null`\n- \\*2 MessagePack ints are decoded as either numbers or bigints depending on the [IntMode](#intmode) used during decoding.\n- \\*3 If you'd like to skip UTF-8 decoding of strings, enable one of `rawBinaryStringKeys` or `rawBinaryStringValues`. In that case, strings are decoded into a `Uint8Array` or a `RawBinaryString`, depending on the value of `useRawBinaryStringClass`.\n- \\*4 Any `ArrayBufferView`s including NodeJS's `Buffer` are mapped to `bin` family, and are decoded into `Uint8Array`\n- \\*5 In handling `Object`, it is regarded as `Record<string, unknown>` in terms of TypeScript\n- \\*6 MessagePack timestamps may have nanoseconds, which will lost when it is decoded into JavaScript `Date`. This behavior can be overridden by registering `-1` for the extension codec.\n\nIf you set `useBigInt64: true`, the following mapping is used:\n\n| Source Value                      | MessagePack Format   | Value Decoded         |\n| --------------------------------- | -------------------- | --------------------- |\n| null, undefined                   | nil                  | null                  |\n| boolean (true, false)             | bool family          | boolean (true, false) |\n| **number (32-bit int)**           | int family           | number                |\n| **number (except for the above)** | float family         | number                |\n| **bigint**                        | int64 / uint64       | bigint (\\*5)          |\n| string                            | str family           | string                |\n| ArrayBufferView                   | bin family           | Uint8Array            |\n| Array                             | array family         | Array                 |\n| Object                            | map family           | Object                |\n| Date                              | timestamp ext family | Date                  |\n\n- \\*6 If the bigint is larger than the max value of uint64 or smaller than the min value of int64, then the behavior is undefined.\n\n- \\*7 If the bigint is larger than the max value of uint64 or smaller than the min value of int64, then the behavior is undefined.\n\n## Prerequisites\n\nThis is a universal JavaScript library that supports major browsers and NodeJS.\n\n### ECMA-262\n\n- ES2015 language features\n- ES2018 standard library, including:\n  - Typed arrays (ES2015)\n  - Async iterations (ES2018)\n  - Features added in ES2015-ES2022\n- whatwg encodings (`TextEncoder` and `TextDecoder`)\n\nES2022 standard library used in this library can be polyfilled with [core-js](https://github.com/zloirock/core-js).\n\nIE11 is no longer supported. If you'd like to use this library in IE11, use v2.x versions.\n\n### NodeJS\n\nNodeJS v14 is required.\n\n### TypeScript Compiler / Type Definitions\n\nThis module requires type definitions of `AsyncIterator`, `SourceBuffer`, whatwg streams, and so on. They are provided by `\"lib\": [\"ES2021\", \"DOM\"]` in `tsconfig.json`.\n\nRegarding the TypeScript compiler version, only the latest TypeScript is tested in development.\n\n## Benchmark\n\nRun-time performance is not the only reason to use MessagePack, but it's important to choose MessagePack libraries, so a benchmark suite is provided to monitor the performance of this library.\n\nV8's built-in JSON has been improved for years, esp. `JSON.parse()` is [significantly improved in V8/7.6](https://v8.dev/blog/v8-release-76), it is the fastest deserializer as of 2019, as the benchmark result bellow suggests.\n\nHowever, MessagePack can handles binary data effectively, actual performance depends on situations. You'd better take benchmark on your own use-case if performance matters.\n\nBenchmark on NodeJS/v18.1.0 (V8/10.1)\n\n| operation                                         |      op |   ms |   op/s |\n| ------------------------------------------------- | ------: | ---: | -----: |\n| buf = Buffer.from(JSON.stringify(obj));           |  902100 | 5000 | 180420 |\n| obj = JSON.parse(buf.toString(\"utf-8\"));          |  898700 | 5000 | 179740 |\n| buf = require(\"msgpack-lite\").encode(obj);        |  411000 | 5000 |  82200 |\n| obj = require(\"msgpack-lite\").decode(buf);        |  246200 | 5001 |  49230 |\n| buf = require(\"@msgpack/msgpack\").encode(obj);    |  843300 | 5000 | 168660 |\n| obj = require(\"@msgpack/msgpack\").decode(buf);    |  489300 | 5000 |  97860 |\n| buf = /_ @msgpack/msgpack _/ encoder.encode(obj); | 1154200 | 5000 | 230840 |\n| obj = /_ @msgpack/msgpack _/ decoder.decode(buf); |  448900 | 5000 |  89780 |\n\nNote that `JSON` cases use `Buffer` to emulate I/O where a JavaScript string must be converted into a byte array encoded in UTF-8, whereas MessagePack modules deal with byte arrays.\n\n## Distribution\n\n### NPM / npmjs.com\n\nThe NPM package distributed in npmjs.com includes both ES2015+ and ES5 files:\n\n- `dist/` is compiled into ES2019 with CommomJS, provided for NodeJS v10\n- `dist.es5+umd/` is compiled into ES5 with UMD\n  - `dist.es5+umd/msgpack.min.js` - the minified file\n  - `dist.es5+umd/msgpack.js` - the non-minified file\n- `dist.es5+esm/` is compiled into ES5 with ES modules, provided for webpack-like bundlers and NodeJS's ESM-mode\n\nIf you use NodeJS and/or webpack, their module resolvers use the suitable one automatically.\n\n### CDN / unpkg.com\n\nThis library is available via CDN:\n\n```html\n<script crossorigin src=\"https://unpkg.com/@msgpack/msgpack\"></script>\n```\n\nIt loads `MessagePack` module to the global object.\n\n## Deno Support\n\nYou can use this module on Deno.\n\nSee `example/deno-*.ts` for examples.\n\n`deno.land/x` is not supported yet.\n\n## Maintenance\n\n### Testing\n\nFor simple testing:\n\n```\nnpm run test\n```\n\n### Continuous Integration\n\nThis library uses Travis CI.\n\ntest matrix:\n\n- TypeScript targets\n  - `target=es2019` / `target=es5`\n- JavaScript engines\n  - NodeJS, browsers (Chrome, Firefox, Safari, IE11, and so on)\n\nSee [test:\\* in package.json](./package.json) and [.travis.yml](./.travis.yml) for details.\n\n### Release Engineering\n\n```console\n# run tests on NodeJS, Chrome, and Firefox\nmake test-all\n\n# edit the changelog\ncode CHANGELOG.md\n\n# bump version\nnpm version patch|minor|major\n\n# run the publishing task\nmake publish\n```\n\n### Updating Dependencies\n\n```console\nnpm run update-dependencies\n```\n\n## License\n\nCopyright 2019 The MessagePack community.\n\nThis software uses the ISC license:\n\nhttps://opensource.org/licenses/ISC\n\nSee [LICENSE](./LICENSE) for details.\n","readmeFilename":"README.md"}