Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add JavaScriptCodec to serialize JavaScript data structure #61

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"test:cover:wasm": "npx nyc --no-clean npm run test:wasm",
"test:cover:td": "npx nyc --no-clean npm run test:td",
"cover:clean": "rimraf .nyc_output coverage/",
"cover:report": "nyc report --reporter=text-summary --reporter=html --reporter=json",
"cover:report": "npx nyc report --reporter=text-summary --reporter=html --reporter=json",
"test:browser": "karma start --single-run",
"test:browser:firefox": "karma start --single-run --browsers FirefoxHeadless",
"test:browser:chrome": "karma start --single-run --browsers ChromeHeadless",
Expand Down
16 changes: 8 additions & 8 deletions src/ExtensionCodec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,25 +50,25 @@ export class ExtensionCodec implements ExtensionCodecType {
}

public tryToEncode(object: unknown): ExtData | null {
// built-in extensions
for (let i = 0; i < this.builtInEncoders.length; i++) {
const encoder = this.builtInEncoders[i];
// custom extensions
for (let i = 0; i < this.encoders.length; i++) {
const encoder = this.encoders[i];
if (encoder != null) {
const data = encoder(object);
if (data != null) {
const type = -1 - i;
const type = i;
return new ExtData(type, data);
}
}
}

// custom extensions
for (let i = 0; i < this.encoders.length; i++) {
const encoder = this.encoders[i];
// built-in extensions
for (let i = 0; i < this.builtInEncoders.length; i++) {
const encoder = this.builtInEncoders[i];
if (encoder != null) {
const data = encoder(object);
if (data != null) {
const type = i;
const type = -1 - i;
return new ExtData(type, data);
}
}
Expand Down
69 changes: 69 additions & 0 deletions src/JavaScriptCodec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { ExtensionCodec, ExtensionCodecType } from "./ExtensionCodec";
import { encode } from "./encode";
import { decode } from "./decode";

export const EXT_JAVASCRIPT = 0;

const enum JSData {
Map,
Set,
Date,
RegExp,
BigInt,
}

export function encodeJavaScriptData(input: unknown): Uint8Array | null {
if (input instanceof Map) {
return encode([JSData.Map, [...input]]);
} else if (input instanceof Set) {
return encode([JSData.Set, [...input]]);
} else if (input instanceof Date) {
// Not a MessagePack timestamp because
// it may be overrided by users
return encode([JSData.Date, input.getTime()]);
} else if (input instanceof RegExp) {
return encode([JSData.RegExp, [input.source, input.flags]]);
} else if (typeof input === "bigint") {
return encode([JSData.BigInt, input.toString()]);
} else {
return null;
}
}

export function decodeJavaScriptData(data: Uint8Array) {
const [jsDataType, source] = decode(data) as [JSData, any];

switch (jsDataType) {
case JSData.Map: {
return new Map<unknown, unknown>(source);
}
case JSData.Set: {
return new Set<unknown>(source);
}
case JSData.Date: {
return new Date(source);
}
case JSData.RegExp: {
const [pattern, flags] = source;
return new RegExp(pattern, flags);
}
case JSData.BigInt: {
return BigInt(source);
}
default: {
throw new Error(`Unknown data type: ${jsDataType}`);
}
}
}

export const JavaScriptCodec: ExtensionCodecType = (() => {
const ext = new ExtensionCodec();

ext.register({
type: EXT_JAVASCRIPT,
encode: encodeJavaScriptData,
decode: decodeJavaScriptData,
});

return ext;
})();
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,6 @@ export {
decodeTimestampExtension,
} from "./timestamp";

export { JavaScriptCodec, EXT_JAVASCRIPT, encodeJavaScriptData, decodeJavaScriptData } from "./JavaScriptCodec";

export { WASM_AVAILABLE as __WASM_AVAILABLE } from "./wasmFunctions";
28 changes: 28 additions & 0 deletions test/javascript-codec.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import assert from "assert";
import { encode, decode, JavaScriptCodec } from "@msgpack/msgpack";

describe("JavaScriptCodec", () => {
context("mixed", () => {
// this data comes from https://github.com/yahoo/serialize-javascript

it("encodes and decodes the object", () => {
const object = {
str: "string",
num: 0,
obj: { foo: "foo", bar: "bar" },
arr: [1, 2, 3],
bool: true,
nil: null,
// undef: undefined, // not supported
date: new Date("Thu, 28 Apr 2016 22:02:17 GMT"),
map: new Map([["foo", 10], ["bar", 20]]),
set: new Set([123, 456]),
regexp: /foo\n/i,
bigint: typeof(BigInt) !== "undefined" ? BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1) : null,
};
const encoded = encode(object, { extensionCodec: JavaScriptCodec });

assert.deepStrictEqual(decode(encoded, { extensionCodec: JavaScriptCodec }), object);
});
});
});