Skip to content
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
16 changes: 9 additions & 7 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -194,20 +194,22 @@ let userId: number = await authedApi.getUserId();

The following types can be passed over RPC (in arguments or return values), and will be passed "by value", meaning the content is serialized, producing a copy at the receiving end:

* Primitive values: strings, numbers, booleans, null, undefined
* Primitive values: strings, numbers (including `NaN`, `Infinity`, and `-Infinity`), booleans, null, undefined
* Plain objects (e.g., from object literals)
* Arrays
* `bigint`
* `Date`
* `Uint8Array`
* `Error` and its well-known subclasses

The following types are not supported as of this writing, but may be added in the future:
* `ArrayBuffer`
* `Map` and `Set`
* `ArrayBuffer` and typed arrays other than `Uint8Array`
* `RegExp`
* `URL` and `Headers`
* `Error` and its well-known subclasses (with full-fidelity serialization including `cause` chains and custom properties)

The following types are not supported as of this writing, but may be added in the future:
* Typed arrays other than `Uint8Array`
* `ReadableStream` and `WritableStream`, with automatic flow control.
* `Headers`, `Request`, and `Response`
* `Request` and `Response` (require asynchronous body handling)

The following are intentionally NOT supported:
* Application-defined classes that do not extend `RpcTarget`.
Expand DownExpand Up@@ -317,7 +319,7 @@ To facilitate interoperability:
So basically, it "just works".

With that said, as of this writing, the feature set is not exactly the same between the two. We aim to fix this over time, by adding missing features to both sides until they match. In particular, as of this writing:
* Workers RPC supports some types that Cap'n Web does not yet, like `Map`, streams, etc.
* Workers RPC supports some types that Cap'n Web does not yet, like streams.
* Workers RPC supports sending values that contain aliases and cycles. This can actually cause problems, so we actually plan to *remove* this feature from Workers RPC (with a compatibility flag, of course).
* Workers RPC does not yet support placing an `RpcPromise` into the parameters of a request, to be replaced by its resolution.
* Workers RPC does not yet support the magic `.map()` method.
Expand Down
71 changes: 66 additions & 5 deletions __tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,9 +26,25 @@ let SERIALIZE_TEST_CASES: Record<string, unknown> = {
'["date",1234]': new Date(1234),
'["bytes","aGVsbG8h"]': new TextEncoder().encode("hello!"),
'["undefined"]': undefined,
'["error","Error","the message"]': new Error("the message"),
'["error","TypeError","the message"]': new TypeError("the message"),
'["error","RangeError","the message"]': new RangeError("the message"),
'["error",{"name":"Error","message":"the message"}]': (() => { let e = new Error("the message"); delete e.stack; return e; })(),
'["error",{"name":"TypeError","message":"the message"}]': (() => { let e = new TypeError("the message"); delete e.stack; return e; })(),
'["error",{"name":"RangeError","message":"the message"}]': (() => { let e = new RangeError("the message"); delete e.stack; return e; })(),
'["special-number","NaN"]': NaN,
'["special-number","Infinity"]': Infinity,
'["special-number","-Infinity"]': -Infinity,
'["regexp",{"source":"test","flags":"gi"}]': /test/gi,
'["regexp",{"source":"^\\\\d+$","flags":""}]': /^\d+$/,
'["map",[[["foo","bar"]]]]': new Map([["foo", "bar"]]),
'["map",[[["a","b"]],[["c","d"]]]]': new Map([["a", "b"], ["c", "d"]]),
'["set",["foo","bar"]]': new Set(["foo", "bar"]),
'["arraybuffer","aGVsbG8h"]': new TextEncoder().encode("hello!").buffer,
'["url","https://example.com/path?q=1"]': new URL("https://example.com/path?q=1"),
'["headers",[["content-type","application/json"],["x-custom","value"]]]': (() => {
let h = new Headers();
h.set("Content-Type", "application/json");
h.set("X-Custom", "value");
return h;
})(),
};

class NotSerializable {
Expand DownExpand Up@@ -96,6 +112,49 @@ describe("simple serialization", () => {
expect(() => deserialize('["date"]')).toThrowError(); // missing timestamp
expect(() => deserialize('["error"]')).toThrowError(); // missing type and message
})

it("supports full fidelity Error serialization", () => {
// Test error with cause and custom properties
let error = new Error("outer error");
error.name = "CustomError";
let cause = new TypeError("inner error");
error.cause = cause;
(error as any).customProp = "custom value";
(error as any).code = 404;

let serialized = serialize(error);
let deserialized = deserialize(serialized) as Error;

expect(deserialized.name).toBe("CustomError");
expect(deserialized.message).toBe("outer error");
expect(deserialized.cause).toBeInstanceOf(TypeError);
expect((deserialized.cause as Error).message).toBe("inner error");
expect((deserialized as any).customProp).toBe("custom value");
expect((deserialized as any).code).toBe(404);
})

it("supports nested Map and Set structures", () => {
// Test Map with complex values
let map = new Map();
map.set("key1", "value1");
map.set(123, new Map([["nested", "map"]]));
let serialized = serialize(map);
let deserialized = deserialize(serialized) as Map<unknown, unknown>;
expect(deserialized.get("key1")).toBe("value1");
expect(deserialized.get(123)).toBeInstanceOf(Map);
expect((deserialized.get(123) as Map<unknown, unknown>).get("nested")).toBe("map");

// Test Set with complex values
let set = new Set();
set.add("item1");
set.add(new Set(["nested", "set"]));
let serializedSet = serialize(set);
let deserializedSet = deserialize(serializedSet) as Set<unknown>;
expect(deserializedSet.has("item1")).toBe(true);
let nestedSet = Array.from(deserializedSet).find(item => item instanceof Set) as Set<unknown>;
expect(nestedSet).toBeInstanceOf(Set);
expect(nestedSet.has("nested")).toBe(true);
})
});

// =======================================================================================
Expand DownExpand Up@@ -1187,8 +1246,10 @@ describe("error serialization", () => {
// By default, the stack isn't sent. A stack may be added client-side, though. So we
// verify that it doesn't contain the function name `throwErrorImpl` nor the file name
// `test-util.ts`, which should only appear on the server.
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
if ((err as Error).stack) {
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
}

return "caught";
});
Expand Down
83 changes: 79 additions & 4 deletions src/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,15 +25,21 @@ export type PropertyPath = (string | number)[];

type TypeForRpc = "unsupported" | "primitive" | "object" | "function" | "array" | "date" |
"bigint" | "bytes" | "stub" | "rpc-promise" | "rpc-target" | "rpc-thenable" | "error" |
"undefined";
"undefined" | "regexp" | "map" | "set" | "arraybuffer" | "url" | "headers" | "special-number";

export function typeForRpc(value: unknown): TypeForRpc {
switch (typeof value) {
case "boolean":
case "number":
case "string":
return "primitive";

case "number":
// Check for special numbers (NaN, Infinity, -Infinity)
if (!isFinite(value)) {
return "special-number";
}
return "primitive";

case "undefined":
return "undefined";

Expand DownExpand Up@@ -74,7 +80,17 @@ export function typeForRpc(value: unknown): TypeForRpc {
case Uint8Array.prototype:
return "bytes";

// TODO: All other structured clone types.
case RegExp.prototype:
return "regexp";

case Map.prototype:
return "map";

case Set.prototype:
return "set";

case ArrayBuffer.prototype:
return "arraybuffer";

case RpcStub.prototype:
return "stub";
Expand DownExpand Up@@ -107,6 +123,14 @@ export function typeForRpc(value: unknown): TypeForRpc {
return "error";
}

// Check for URL and Headers (these don't have standard prototypes we can switch on)
if (typeof URL !== "undefined" && value instanceof URL) {
return "url";
}
if (typeof Headers !== "undefined" && value instanceof Headers) {
return "headers";
}

return "unsupported";
}
}
Expand DownExpand Up@@ -766,10 +790,36 @@ export class RpcPayload {
case "bytes":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// immutable, no need to copy
// TODO: Should errors be copied if they have own properties?
return value;

case "map": {
let map = value as Map<unknown, unknown>;
let result = new Map();
for (let [key, val] of map) {
result.set(
this.deepCopy(key, map, 0, result, dupStubs, owner),
this.deepCopy(val, map, 1, result, dupStubs, owner)
);
}
return result;
}

case "set": {
let set = value as Set<unknown>;
let result = new Set();
for (let val of set) {
result.add(this.deepCopy(val, set, 0, result, dupStubs, owner));
}
return result;
}

case "array": {
// We have to construct the new array first, then fill it in, so we can pass it as the
// parent.
Expand DownExpand Up@@ -1034,6 +1084,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
return;

case "array": {
Expand DownExpand Up@@ -1120,6 +1177,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
case "function":
case "rpc-target":
return;
Expand DownExpand Up@@ -1247,7 +1311,18 @@ function followPath(value: unknown, parent: object | undefined,
case "bytes":
case "date":
case "error":
// These have no properties that can be accessed remotely.
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// These have no properties that can be accessed remotely (or are immutable).
value = undefined;
break;

case "map":
case "set":
// Map and Set don't support property access via this mechanism
value = undefined;
break;

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Add support for additional serialization types by lmaccherone · Pull Request #99 · cloudflare/capnweb · GitHub
Skip to content
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
16 changes: 9 additions & 7 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -194,20 +194,22 @@ let userId: number = await authedApi.getUserId();

The following types can be passed over RPC (in arguments or return values), and will be passed "by value", meaning the content is serialized, producing a copy at the receiving end:

* Primitive values: strings, numbers, booleans, null, undefined
* Primitive values: strings, numbers (including `NaN`, `Infinity`, and `-Infinity`), booleans, null, undefined
* Plain objects (e.g., from object literals)
* Arrays
* `bigint`
* `Date`
* `Uint8Array`
* `Error` and its well-known subclasses

The following types are not supported as of this writing, but may be added in the future:
* `ArrayBuffer`
* `Map` and `Set`
* `ArrayBuffer` and typed arrays other than `Uint8Array`
* `RegExp`
* `URL` and `Headers`
* `Error` and its well-known subclasses (with full-fidelity serialization including `cause` chains and custom properties)

The following types are not supported as of this writing, but may be added in the future:
* Typed arrays other than `Uint8Array`
* `ReadableStream` and `WritableStream`, with automatic flow control.
* `Headers`, `Request`, and `Response`
* `Request` and `Response` (require asynchronous body handling)

The following are intentionally NOT supported:
* Application-defined classes that do not extend `RpcTarget`.
Expand DownExpand Up@@ -317,7 +319,7 @@ To facilitate interoperability:
So basically, it "just works".

With that said, as of this writing, the feature set is not exactly the same between the two. We aim to fix this over time, by adding missing features to both sides until they match. In particular, as of this writing:
* Workers RPC supports some types that Cap'n Web does not yet, like `Map`, streams, etc.
* Workers RPC supports some types that Cap'n Web does not yet, like streams.
* Workers RPC supports sending values that contain aliases and cycles. This can actually cause problems, so we actually plan to *remove* this feature from Workers RPC (with a compatibility flag, of course).
* Workers RPC does not yet support placing an `RpcPromise` into the parameters of a request, to be replaced by its resolution.
* Workers RPC does not yet support the magic `.map()` method.
Expand Down
71 changes: 66 additions & 5 deletions __tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,9 +26,25 @@ let SERIALIZE_TEST_CASES: Record<string, unknown> = {
'["date",1234]': new Date(1234),
'["bytes","aGVsbG8h"]': new TextEncoder().encode("hello!"),
'["undefined"]': undefined,
'["error","Error","the message"]': new Error("the message"),
'["error","TypeError","the message"]': new TypeError("the message"),
'["error","RangeError","the message"]': new RangeError("the message"),
'["error",{"name":"Error","message":"the message"}]': (() => { let e = new Error("the message"); delete e.stack; return e; })(),
'["error",{"name":"TypeError","message":"the message"}]': (() => { let e = new TypeError("the message"); delete e.stack; return e; })(),
'["error",{"name":"RangeError","message":"the message"}]': (() => { let e = new RangeError("the message"); delete e.stack; return e; })(),
'["special-number","NaN"]': NaN,
'["special-number","Infinity"]': Infinity,
'["special-number","-Infinity"]': -Infinity,
'["regexp",{"source":"test","flags":"gi"}]': /test/gi,
'["regexp",{"source":"^\\\\d+$","flags":""}]': /^\d+$/,
'["map",[[["foo","bar"]]]]': new Map([["foo", "bar"]]),
'["map",[[["a","b"]],[["c","d"]]]]': new Map([["a", "b"], ["c", "d"]]),
'["set",["foo","bar"]]': new Set(["foo", "bar"]),
'["arraybuffer","aGVsbG8h"]': new TextEncoder().encode("hello!").buffer,
'["url","https://example.com/path?q=1"]': new URL("https://example.com/path?q=1"),
'["headers",[["content-type","application/json"],["x-custom","value"]]]': (() => {
let h = new Headers();
h.set("Content-Type", "application/json");
h.set("X-Custom", "value");
return h;
})(),
};

class NotSerializable {
Expand DownExpand Up@@ -96,6 +112,49 @@ describe("simple serialization", () => {
expect(() => deserialize('["date"]')).toThrowError(); // missing timestamp
expect(() => deserialize('["error"]')).toThrowError(); // missing type and message
})

it("supports full fidelity Error serialization", () => {
// Test error with cause and custom properties
let error = new Error("outer error");
error.name = "CustomError";
let cause = new TypeError("inner error");
error.cause = cause;
(error as any).customProp = "custom value";
(error as any).code = 404;

let serialized = serialize(error);
let deserialized = deserialize(serialized) as Error;

expect(deserialized.name).toBe("CustomError");
expect(deserialized.message).toBe("outer error");
expect(deserialized.cause).toBeInstanceOf(TypeError);
expect((deserialized.cause as Error).message).toBe("inner error");
expect((deserialized as any).customProp).toBe("custom value");
expect((deserialized as any).code).toBe(404);
})

it("supports nested Map and Set structures", () => {
// Test Map with complex values
let map = new Map();
map.set("key1", "value1");
map.set(123, new Map([["nested", "map"]]));
let serialized = serialize(map);
let deserialized = deserialize(serialized) as Map<unknown, unknown>;
expect(deserialized.get("key1")).toBe("value1");
expect(deserialized.get(123)).toBeInstanceOf(Map);
expect((deserialized.get(123) as Map<unknown, unknown>).get("nested")).toBe("map");

// Test Set with complex values
let set = new Set();
set.add("item1");
set.add(new Set(["nested", "set"]));
let serializedSet = serialize(set);
let deserializedSet = deserialize(serializedSet) as Set<unknown>;
expect(deserializedSet.has("item1")).toBe(true);
let nestedSet = Array.from(deserializedSet).find(item => item instanceof Set) as Set<unknown>;
expect(nestedSet).toBeInstanceOf(Set);
expect(nestedSet.has("nested")).toBe(true);
})
});

// =======================================================================================
Expand DownExpand Up@@ -1187,8 +1246,10 @@ describe("error serialization", () => {
// By default, the stack isn't sent. A stack may be added client-side, though. So we
// verify that it doesn't contain the function name `throwErrorImpl` nor the file name
// `test-util.ts`, which should only appear on the server.
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
if ((err as Error).stack) {
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
}

return "caught";
});
Expand Down
83 changes: 79 additions & 4 deletions src/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,15 +25,21 @@ export type PropertyPath = (string | number)[];

type TypeForRpc = "unsupported" | "primitive" | "object" | "function" | "array" | "date" |
"bigint" | "bytes" | "stub" | "rpc-promise" | "rpc-target" | "rpc-thenable" | "error" |
"undefined";
"undefined" | "regexp" | "map" | "set" | "arraybuffer" | "url" | "headers" | "special-number";

export function typeForRpc(value: unknown): TypeForRpc {
switch (typeof value) {
case "boolean":
case "number":
case "string":
return "primitive";

case "number":
// Check for special numbers (NaN, Infinity, -Infinity)
if (!isFinite(value)) {
return "special-number";
}
return "primitive";

case "undefined":
return "undefined";

Expand DownExpand Up@@ -74,7 +80,17 @@ export function typeForRpc(value: unknown): TypeForRpc {
case Uint8Array.prototype:
return "bytes";

// TODO: All other structured clone types.
case RegExp.prototype:
return "regexp";

case Map.prototype:
return "map";

case Set.prototype:
return "set";

case ArrayBuffer.prototype:
return "arraybuffer";

case RpcStub.prototype:
return "stub";
Expand DownExpand Up@@ -107,6 +123,14 @@ export function typeForRpc(value: unknown): TypeForRpc {
return "error";
}

// Check for URL and Headers (these don't have standard prototypes we can switch on)
if (typeof URL !== "undefined" && value instanceof URL) {
return "url";
}
if (typeof Headers !== "undefined" && value instanceof Headers) {
return "headers";
}

return "unsupported";
}
}
Expand DownExpand Up@@ -766,10 +790,36 @@ export class RpcPayload {
case "bytes":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// immutable, no need to copy
// TODO: Should errors be copied if they have own properties?
return value;

case "map": {
let map = value as Map<unknown, unknown>;
let result = new Map();
for (let [key, val] of map) {
result.set(
this.deepCopy(key, map, 0, result, dupStubs, owner),
this.deepCopy(val, map, 1, result, dupStubs, owner)
);
}
return result;
}

case "set": {
let set = value as Set<unknown>;
let result = new Set();
for (let val of set) {
result.add(this.deepCopy(val, set, 0, result, dupStubs, owner));
}
return result;
}

case "array": {
// We have to construct the new array first, then fill it in, so we can pass it as the
// parent.
Expand DownExpand Up@@ -1034,6 +1084,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
return;

case "array": {
Expand DownExpand Up@@ -1120,6 +1177,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
case "function":
case "rpc-target":
return;
Expand DownExpand Up@@ -1247,7 +1311,18 @@ function followPath(value: unknown, parent: object | undefined,
case "bytes":
case "date":
case "error":
// These have no properties that can be accessed remotely.
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// These have no properties that can be accessed remotely (or are immutable).
value = undefined;
break;

case "map":
case "set":
// Map and Set don't support property access via this mechanism
value = undefined;
break;

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Add support for additional serialization types by lmaccherone · Pull Request #99 · cloudflare/capnweb · GitHub
Skip to content
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
16 changes: 9 additions & 7 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -194,20 +194,22 @@ let userId: number = await authedApi.getUserId();

The following types can be passed over RPC (in arguments or return values), and will be passed "by value", meaning the content is serialized, producing a copy at the receiving end:

* Primitive values: strings, numbers, booleans, null, undefined
* Primitive values: strings, numbers (including `NaN`, `Infinity`, and `-Infinity`), booleans, null, undefined
* Plain objects (e.g., from object literals)
* Arrays
* `bigint`
* `Date`
* `Uint8Array`
* `Error` and its well-known subclasses

The following types are not supported as of this writing, but may be added in the future:
* `ArrayBuffer`
* `Map` and `Set`
* `ArrayBuffer` and typed arrays other than `Uint8Array`
* `RegExp`
* `URL` and `Headers`
* `Error` and its well-known subclasses (with full-fidelity serialization including `cause` chains and custom properties)

The following types are not supported as of this writing, but may be added in the future:
* Typed arrays other than `Uint8Array`
* `ReadableStream` and `WritableStream`, with automatic flow control.
* `Headers`, `Request`, and `Response`
* `Request` and `Response` (require asynchronous body handling)

The following are intentionally NOT supported:
* Application-defined classes that do not extend `RpcTarget`.
Expand DownExpand Up@@ -317,7 +319,7 @@ To facilitate interoperability:
So basically, it "just works".

With that said, as of this writing, the feature set is not exactly the same between the two. We aim to fix this over time, by adding missing features to both sides until they match. In particular, as of this writing:
* Workers RPC supports some types that Cap'n Web does not yet, like `Map`, streams, etc.
* Workers RPC supports some types that Cap'n Web does not yet, like streams.
* Workers RPC supports sending values that contain aliases and cycles. This can actually cause problems, so we actually plan to *remove* this feature from Workers RPC (with a compatibility flag, of course).
* Workers RPC does not yet support placing an `RpcPromise` into the parameters of a request, to be replaced by its resolution.
* Workers RPC does not yet support the magic `.map()` method.
Expand Down
71 changes: 66 additions & 5 deletions __tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,9 +26,25 @@ let SERIALIZE_TEST_CASES: Record<string, unknown> = {
'["date",1234]': new Date(1234),
'["bytes","aGVsbG8h"]': new TextEncoder().encode("hello!"),
'["undefined"]': undefined,
'["error","Error","the message"]': new Error("the message"),
'["error","TypeError","the message"]': new TypeError("the message"),
'["error","RangeError","the message"]': new RangeError("the message"),
'["error",{"name":"Error","message":"the message"}]': (() => { let e = new Error("the message"); delete e.stack; return e; })(),
'["error",{"name":"TypeError","message":"the message"}]': (() => { let e = new TypeError("the message"); delete e.stack; return e; })(),
'["error",{"name":"RangeError","message":"the message"}]': (() => { let e = new RangeError("the message"); delete e.stack; return e; })(),
'["special-number","NaN"]': NaN,
'["special-number","Infinity"]': Infinity,
'["special-number","-Infinity"]': -Infinity,
'["regexp",{"source":"test","flags":"gi"}]': /test/gi,
'["regexp",{"source":"^\\\\d+$","flags":""}]': /^\d+$/,
'["map",[[["foo","bar"]]]]': new Map([["foo", "bar"]]),
'["map",[[["a","b"]],[["c","d"]]]]': new Map([["a", "b"], ["c", "d"]]),
'["set",["foo","bar"]]': new Set(["foo", "bar"]),
'["arraybuffer","aGVsbG8h"]': new TextEncoder().encode("hello!").buffer,
'["url","https://example.com/path?q=1"]': new URL("https://example.com/path?q=1"),
'["headers",[["content-type","application/json"],["x-custom","value"]]]': (() => {
let h = new Headers();
h.set("Content-Type", "application/json");
h.set("X-Custom", "value");
return h;
})(),
};

class NotSerializable {
Expand DownExpand Up@@ -96,6 +112,49 @@ describe("simple serialization", () => {
expect(() => deserialize('["date"]')).toThrowError(); // missing timestamp
expect(() => deserialize('["error"]')).toThrowError(); // missing type and message
})

it("supports full fidelity Error serialization", () => {
// Test error with cause and custom properties
let error = new Error("outer error");
error.name = "CustomError";
let cause = new TypeError("inner error");
error.cause = cause;
(error as any).customProp = "custom value";
(error as any).code = 404;

let serialized = serialize(error);
let deserialized = deserialize(serialized) as Error;

expect(deserialized.name).toBe("CustomError");
expect(deserialized.message).toBe("outer error");
expect(deserialized.cause).toBeInstanceOf(TypeError);
expect((deserialized.cause as Error).message).toBe("inner error");
expect((deserialized as any).customProp).toBe("custom value");
expect((deserialized as any).code).toBe(404);
})

it("supports nested Map and Set structures", () => {
// Test Map with complex values
let map = new Map();
map.set("key1", "value1");
map.set(123, new Map([["nested", "map"]]));
let serialized = serialize(map);
let deserialized = deserialize(serialized) as Map<unknown, unknown>;
expect(deserialized.get("key1")).toBe("value1");
expect(deserialized.get(123)).toBeInstanceOf(Map);
expect((deserialized.get(123) as Map<unknown, unknown>).get("nested")).toBe("map");

// Test Set with complex values
let set = new Set();
set.add("item1");
set.add(new Set(["nested", "set"]));
let serializedSet = serialize(set);
let deserializedSet = deserialize(serializedSet) as Set<unknown>;
expect(deserializedSet.has("item1")).toBe(true);
let nestedSet = Array.from(deserializedSet).find(item => item instanceof Set) as Set<unknown>;
expect(nestedSet).toBeInstanceOf(Set);
expect(nestedSet.has("nested")).toBe(true);
})
});

// =======================================================================================
Expand DownExpand Up@@ -1187,8 +1246,10 @@ describe("error serialization", () => {
// By default, the stack isn't sent. A stack may be added client-side, though. So we
// verify that it doesn't contain the function name `throwErrorImpl` nor the file name
// `test-util.ts`, which should only appear on the server.
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
if ((err as Error).stack) {
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
}

return "caught";
});
Expand Down
83 changes: 79 additions & 4 deletions src/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,15 +25,21 @@ export type PropertyPath = (string | number)[];

type TypeForRpc = "unsupported" | "primitive" | "object" | "function" | "array" | "date" |
"bigint" | "bytes" | "stub" | "rpc-promise" | "rpc-target" | "rpc-thenable" | "error" |
"undefined";
"undefined" | "regexp" | "map" | "set" | "arraybuffer" | "url" | "headers" | "special-number";

export function typeForRpc(value: unknown): TypeForRpc {
switch (typeof value) {
case "boolean":
case "number":
case "string":
return "primitive";

case "number":
// Check for special numbers (NaN, Infinity, -Infinity)
if (!isFinite(value)) {
return "special-number";
}
return "primitive";

case "undefined":
return "undefined";

Expand DownExpand Up@@ -74,7 +80,17 @@ export function typeForRpc(value: unknown): TypeForRpc {
case Uint8Array.prototype:
return "bytes";

// TODO: All other structured clone types.
case RegExp.prototype:
return "regexp";

case Map.prototype:
return "map";

case Set.prototype:
return "set";

case ArrayBuffer.prototype:
return "arraybuffer";

case RpcStub.prototype:
return "stub";
Expand DownExpand Up@@ -107,6 +123,14 @@ export function typeForRpc(value: unknown): TypeForRpc {
return "error";
}

// Check for URL and Headers (these don't have standard prototypes we can switch on)
if (typeof URL !== "undefined" && value instanceof URL) {
return "url";
}
if (typeof Headers !== "undefined" && value instanceof Headers) {
return "headers";
}

return "unsupported";
}
}
Expand DownExpand Up@@ -766,10 +790,36 @@ export class RpcPayload {
case "bytes":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// immutable, no need to copy
// TODO: Should errors be copied if they have own properties?
return value;

case "map": {
let map = value as Map<unknown, unknown>;
let result = new Map();
for (let [key, val] of map) {
result.set(
this.deepCopy(key, map, 0, result, dupStubs, owner),
this.deepCopy(val, map, 1, result, dupStubs, owner)
);
}
return result;
}

case "set": {
let set = value as Set<unknown>;
let result = new Set();
for (let val of set) {
result.add(this.deepCopy(val, set, 0, result, dupStubs, owner));
}
return result;
}

case "array": {
// We have to construct the new array first, then fill it in, so we can pass it as the
// parent.
Expand DownExpand Up@@ -1034,6 +1084,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
return;

case "array": {
Expand DownExpand Up@@ -1120,6 +1177,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
case "function":
case "rpc-target":
return;
Expand DownExpand Up@@ -1247,7 +1311,18 @@ function followPath(value: unknown, parent: object | undefined,
case "bytes":
case "date":
case "error":
// These have no properties that can be accessed remotely.
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// These have no properties that can be accessed remotely (or are immutable).
value = undefined;
break;

case "map":
case "set":
// Map and Set don't support property access via this mechanism
value = undefined;
break;

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Add support for additional serialization types by lmaccherone · Pull Request #99 · cloudflare/capnweb · GitHub
Skip to content
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
16 changes: 9 additions & 7 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -194,20 +194,22 @@ let userId: number = await authedApi.getUserId();

The following types can be passed over RPC (in arguments or return values), and will be passed "by value", meaning the content is serialized, producing a copy at the receiving end:

* Primitive values: strings, numbers, booleans, null, undefined
* Primitive values: strings, numbers (including `NaN`, `Infinity`, and `-Infinity`), booleans, null, undefined
* Plain objects (e.g., from object literals)
* Arrays
* `bigint`
* `Date`
* `Uint8Array`
* `Error` and its well-known subclasses

The following types are not supported as of this writing, but may be added in the future:
* `ArrayBuffer`
* `Map` and `Set`
* `ArrayBuffer` and typed arrays other than `Uint8Array`
* `RegExp`
* `URL` and `Headers`
* `Error` and its well-known subclasses (with full-fidelity serialization including `cause` chains and custom properties)

The following types are not supported as of this writing, but may be added in the future:
* Typed arrays other than `Uint8Array`
* `ReadableStream` and `WritableStream`, with automatic flow control.
* `Headers`, `Request`, and `Response`
* `Request` and `Response` (require asynchronous body handling)

The following are intentionally NOT supported:
* Application-defined classes that do not extend `RpcTarget`.
Expand DownExpand Up@@ -317,7 +319,7 @@ To facilitate interoperability:
So basically, it "just works".

With that said, as of this writing, the feature set is not exactly the same between the two. We aim to fix this over time, by adding missing features to both sides until they match. In particular, as of this writing:
* Workers RPC supports some types that Cap'n Web does not yet, like `Map`, streams, etc.
* Workers RPC supports some types that Cap'n Web does not yet, like streams.
* Workers RPC supports sending values that contain aliases and cycles. This can actually cause problems, so we actually plan to *remove* this feature from Workers RPC (with a compatibility flag, of course).
* Workers RPC does not yet support placing an `RpcPromise` into the parameters of a request, to be replaced by its resolution.
* Workers RPC does not yet support the magic `.map()` method.
Expand Down
71 changes: 66 additions & 5 deletions __tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,9 +26,25 @@ let SERIALIZE_TEST_CASES: Record<string, unknown> = {
'["date",1234]': new Date(1234),
'["bytes","aGVsbG8h"]': new TextEncoder().encode("hello!"),
'["undefined"]': undefined,
'["error","Error","the message"]': new Error("the message"),
'["error","TypeError","the message"]': new TypeError("the message"),
'["error","RangeError","the message"]': new RangeError("the message"),
'["error",{"name":"Error","message":"the message"}]': (() => { let e = new Error("the message"); delete e.stack; return e; })(),
'["error",{"name":"TypeError","message":"the message"}]': (() => { let e = new TypeError("the message"); delete e.stack; return e; })(),
'["error",{"name":"RangeError","message":"the message"}]': (() => { let e = new RangeError("the message"); delete e.stack; return e; })(),
'["special-number","NaN"]': NaN,
'["special-number","Infinity"]': Infinity,
'["special-number","-Infinity"]': -Infinity,
'["regexp",{"source":"test","flags":"gi"}]': /test/gi,
'["regexp",{"source":"^\\\\d+$","flags":""}]': /^\d+$/,
'["map",[[["foo","bar"]]]]': new Map([["foo", "bar"]]),
'["map",[[["a","b"]],[["c","d"]]]]': new Map([["a", "b"], ["c", "d"]]),
'["set",["foo","bar"]]': new Set(["foo", "bar"]),
'["arraybuffer","aGVsbG8h"]': new TextEncoder().encode("hello!").buffer,
'["url","https://example.com/path?q=1"]': new URL("https://example.com/path?q=1"),
'["headers",[["content-type","application/json"],["x-custom","value"]]]': (() => {
let h = new Headers();
h.set("Content-Type", "application/json");
h.set("X-Custom", "value");
return h;
})(),
};

class NotSerializable {
Expand DownExpand Up@@ -96,6 +112,49 @@ describe("simple serialization", () => {
expect(() => deserialize('["date"]')).toThrowError(); // missing timestamp
expect(() => deserialize('["error"]')).toThrowError(); // missing type and message
})

it("supports full fidelity Error serialization", () => {
// Test error with cause and custom properties
let error = new Error("outer error");
error.name = "CustomError";
let cause = new TypeError("inner error");
error.cause = cause;
(error as any).customProp = "custom value";
(error as any).code = 404;

let serialized = serialize(error);
let deserialized = deserialize(serialized) as Error;

expect(deserialized.name).toBe("CustomError");
expect(deserialized.message).toBe("outer error");
expect(deserialized.cause).toBeInstanceOf(TypeError);
expect((deserialized.cause as Error).message).toBe("inner error");
expect((deserialized as any).customProp).toBe("custom value");
expect((deserialized as any).code).toBe(404);
})

it("supports nested Map and Set structures", () => {
// Test Map with complex values
let map = new Map();
map.set("key1", "value1");
map.set(123, new Map([["nested", "map"]]));
let serialized = serialize(map);
let deserialized = deserialize(serialized) as Map<unknown, unknown>;
expect(deserialized.get("key1")).toBe("value1");
expect(deserialized.get(123)).toBeInstanceOf(Map);
expect((deserialized.get(123) as Map<unknown, unknown>).get("nested")).toBe("map");

// Test Set with complex values
let set = new Set();
set.add("item1");
set.add(new Set(["nested", "set"]));
let serializedSet = serialize(set);
let deserializedSet = deserialize(serializedSet) as Set<unknown>;
expect(deserializedSet.has("item1")).toBe(true);
let nestedSet = Array.from(deserializedSet).find(item => item instanceof Set) as Set<unknown>;
expect(nestedSet).toBeInstanceOf(Set);
expect(nestedSet.has("nested")).toBe(true);
})
});

// =======================================================================================
Expand DownExpand Up@@ -1187,8 +1246,10 @@ describe("error serialization", () => {
// By default, the stack isn't sent. A stack may be added client-side, though. So we
// verify that it doesn't contain the function name `throwErrorImpl` nor the file name
// `test-util.ts`, which should only appear on the server.
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
if ((err as Error).stack) {
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
}

return "caught";
});
Expand Down
83 changes: 79 additions & 4 deletions src/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,15 +25,21 @@ export type PropertyPath = (string | number)[];

type TypeForRpc = "unsupported" | "primitive" | "object" | "function" | "array" | "date" |
"bigint" | "bytes" | "stub" | "rpc-promise" | "rpc-target" | "rpc-thenable" | "error" |
"undefined";
"undefined" | "regexp" | "map" | "set" | "arraybuffer" | "url" | "headers" | "special-number";

export function typeForRpc(value: unknown): TypeForRpc {
switch (typeof value) {
case "boolean":
case "number":
case "string":
return "primitive";

case "number":
// Check for special numbers (NaN, Infinity, -Infinity)
if (!isFinite(value)) {
return "special-number";
}
return "primitive";

case "undefined":
return "undefined";

Expand DownExpand Up@@ -74,7 +80,17 @@ export function typeForRpc(value: unknown): TypeForRpc {
case Uint8Array.prototype:
return "bytes";

// TODO: All other structured clone types.
case RegExp.prototype:
return "regexp";

case Map.prototype:
return "map";

case Set.prototype:
return "set";

case ArrayBuffer.prototype:
return "arraybuffer";

case RpcStub.prototype:
return "stub";
Expand DownExpand Up@@ -107,6 +123,14 @@ export function typeForRpc(value: unknown): TypeForRpc {
return "error";
}

// Check for URL and Headers (these don't have standard prototypes we can switch on)
if (typeof URL !== "undefined" && value instanceof URL) {
return "url";
}
if (typeof Headers !== "undefined" && value instanceof Headers) {
return "headers";
}

return "unsupported";
}
}
Expand DownExpand Up@@ -766,10 +790,36 @@ export class RpcPayload {
case "bytes":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// immutable, no need to copy
// TODO: Should errors be copied if they have own properties?
return value;

case "map": {
let map = value as Map<unknown, unknown>;
let result = new Map();
for (let [key, val] of map) {
result.set(
this.deepCopy(key, map, 0, result, dupStubs, owner),
this.deepCopy(val, map, 1, result, dupStubs, owner)
);
}
return result;
}

case "set": {
let set = value as Set<unknown>;
let result = new Set();
for (let val of set) {
result.add(this.deepCopy(val, set, 0, result, dupStubs, owner));
}
return result;
}

case "array": {
// We have to construct the new array first, then fill it in, so we can pass it as the
// parent.
Expand DownExpand Up@@ -1034,6 +1084,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
return;

case "array": {
Expand DownExpand Up@@ -1120,6 +1177,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
case "function":
case "rpc-target":
return;
Expand DownExpand Up@@ -1247,7 +1311,18 @@ function followPath(value: unknown, parent: object | undefined,
case "bytes":
case "date":
case "error":
// These have no properties that can be accessed remotely.
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// These have no properties that can be accessed remotely (or are immutable).
value = undefined;
break;

case "map":
case "set":
// Map and Set don't support property access via this mechanism
value = undefined;
break;

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Add support for additional serialization types by lmaccherone · Pull Request #99 · cloudflare/capnweb · GitHub
Skip to content
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
16 changes: 9 additions & 7 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -194,20 +194,22 @@ let userId: number = await authedApi.getUserId();

The following types can be passed over RPC (in arguments or return values), and will be passed "by value", meaning the content is serialized, producing a copy at the receiving end:

* Primitive values: strings, numbers, booleans, null, undefined
* Primitive values: strings, numbers (including `NaN`, `Infinity`, and `-Infinity`), booleans, null, undefined
* Plain objects (e.g., from object literals)
* Arrays
* `bigint`
* `Date`
* `Uint8Array`
* `Error` and its well-known subclasses

The following types are not supported as of this writing, but may be added in the future:
* `ArrayBuffer`
* `Map` and `Set`
* `ArrayBuffer` and typed arrays other than `Uint8Array`
* `RegExp`
* `URL` and `Headers`
* `Error` and its well-known subclasses (with full-fidelity serialization including `cause` chains and custom properties)

The following types are not supported as of this writing, but may be added in the future:
* Typed arrays other than `Uint8Array`
* `ReadableStream` and `WritableStream`, with automatic flow control.
* `Headers`, `Request`, and `Response`
* `Request` and `Response` (require asynchronous body handling)

The following are intentionally NOT supported:
* Application-defined classes that do not extend `RpcTarget`.
Expand DownExpand Up@@ -317,7 +319,7 @@ To facilitate interoperability:
So basically, it "just works".

With that said, as of this writing, the feature set is not exactly the same between the two. We aim to fix this over time, by adding missing features to both sides until they match. In particular, as of this writing:
* Workers RPC supports some types that Cap'n Web does not yet, like `Map`, streams, etc.
* Workers RPC supports some types that Cap'n Web does not yet, like streams.
* Workers RPC supports sending values that contain aliases and cycles. This can actually cause problems, so we actually plan to *remove* this feature from Workers RPC (with a compatibility flag, of course).
* Workers RPC does not yet support placing an `RpcPromise` into the parameters of a request, to be replaced by its resolution.
* Workers RPC does not yet support the magic `.map()` method.
Expand Down
71 changes: 66 additions & 5 deletions __tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,9 +26,25 @@ let SERIALIZE_TEST_CASES: Record<string, unknown> = {
'["date",1234]': new Date(1234),
'["bytes","aGVsbG8h"]': new TextEncoder().encode("hello!"),
'["undefined"]': undefined,
'["error","Error","the message"]': new Error("the message"),
'["error","TypeError","the message"]': new TypeError("the message"),
'["error","RangeError","the message"]': new RangeError("the message"),
'["error",{"name":"Error","message":"the message"}]': (() => { let e = new Error("the message"); delete e.stack; return e; })(),
'["error",{"name":"TypeError","message":"the message"}]': (() => { let e = new TypeError("the message"); delete e.stack; return e; })(),
'["error",{"name":"RangeError","message":"the message"}]': (() => { let e = new RangeError("the message"); delete e.stack; return e; })(),
'["special-number","NaN"]': NaN,
'["special-number","Infinity"]': Infinity,
'["special-number","-Infinity"]': -Infinity,
'["regexp",{"source":"test","flags":"gi"}]': /test/gi,
'["regexp",{"source":"^\\\\d+$","flags":""}]': /^\d+$/,
'["map",[[["foo","bar"]]]]': new Map([["foo", "bar"]]),
'["map",[[["a","b"]],[["c","d"]]]]': new Map([["a", "b"], ["c", "d"]]),
'["set",["foo","bar"]]': new Set(["foo", "bar"]),
'["arraybuffer","aGVsbG8h"]': new TextEncoder().encode("hello!").buffer,
'["url","https://example.com/path?q=1"]': new URL("https://example.com/path?q=1"),
'["headers",[["content-type","application/json"],["x-custom","value"]]]': (() => {
let h = new Headers();
h.set("Content-Type", "application/json");
h.set("X-Custom", "value");
return h;
})(),
};

class NotSerializable {
Expand DownExpand Up@@ -96,6 +112,49 @@ describe("simple serialization", () => {
expect(() => deserialize('["date"]')).toThrowError(); // missing timestamp
expect(() => deserialize('["error"]')).toThrowError(); // missing type and message
})

it("supports full fidelity Error serialization", () => {
// Test error with cause and custom properties
let error = new Error("outer error");
error.name = "CustomError";
let cause = new TypeError("inner error");
error.cause = cause;
(error as any).customProp = "custom value";
(error as any).code = 404;

let serialized = serialize(error);
let deserialized = deserialize(serialized) as Error;

expect(deserialized.name).toBe("CustomError");
expect(deserialized.message).toBe("outer error");
expect(deserialized.cause).toBeInstanceOf(TypeError);
expect((deserialized.cause as Error).message).toBe("inner error");
expect((deserialized as any).customProp).toBe("custom value");
expect((deserialized as any).code).toBe(404);
})

it("supports nested Map and Set structures", () => {
// Test Map with complex values
let map = new Map();
map.set("key1", "value1");
map.set(123, new Map([["nested", "map"]]));
let serialized = serialize(map);
let deserialized = deserialize(serialized) as Map<unknown, unknown>;
expect(deserialized.get("key1")).toBe("value1");
expect(deserialized.get(123)).toBeInstanceOf(Map);
expect((deserialized.get(123) as Map<unknown, unknown>).get("nested")).toBe("map");

// Test Set with complex values
let set = new Set();
set.add("item1");
set.add(new Set(["nested", "set"]));
let serializedSet = serialize(set);
let deserializedSet = deserialize(serializedSet) as Set<unknown>;
expect(deserializedSet.has("item1")).toBe(true);
let nestedSet = Array.from(deserializedSet).find(item => item instanceof Set) as Set<unknown>;
expect(nestedSet).toBeInstanceOf(Set);
expect(nestedSet.has("nested")).toBe(true);
})
});

// =======================================================================================
Expand DownExpand Up@@ -1187,8 +1246,10 @@ describe("error serialization", () => {
// By default, the stack isn't sent. A stack may be added client-side, though. So we
// verify that it doesn't contain the function name `throwErrorImpl` nor the file name
// `test-util.ts`, which should only appear on the server.
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
if ((err as Error).stack) {
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
}

return "caught";
});
Expand Down
83 changes: 79 additions & 4 deletions src/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,15 +25,21 @@ export type PropertyPath = (string | number)[];

type TypeForRpc = "unsupported" | "primitive" | "object" | "function" | "array" | "date" |
"bigint" | "bytes" | "stub" | "rpc-promise" | "rpc-target" | "rpc-thenable" | "error" |
"undefined";
"undefined" | "regexp" | "map" | "set" | "arraybuffer" | "url" | "headers" | "special-number";

export function typeForRpc(value: unknown): TypeForRpc {
switch (typeof value) {
case "boolean":
case "number":
case "string":
return "primitive";

case "number":
// Check for special numbers (NaN, Infinity, -Infinity)
if (!isFinite(value)) {
return "special-number";
}
return "primitive";

case "undefined":
return "undefined";

Expand DownExpand Up@@ -74,7 +80,17 @@ export function typeForRpc(value: unknown): TypeForRpc {
case Uint8Array.prototype:
return "bytes";

// TODO: All other structured clone types.
case RegExp.prototype:
return "regexp";

case Map.prototype:
return "map";

case Set.prototype:
return "set";

case ArrayBuffer.prototype:
return "arraybuffer";

case RpcStub.prototype:
return "stub";
Expand DownExpand Up@@ -107,6 +123,14 @@ export function typeForRpc(value: unknown): TypeForRpc {
return "error";
}

// Check for URL and Headers (these don't have standard prototypes we can switch on)
if (typeof URL !== "undefined" && value instanceof URL) {
return "url";
}
if (typeof Headers !== "undefined" && value instanceof Headers) {
return "headers";
}

return "unsupported";
}
}
Expand DownExpand Up@@ -766,10 +790,36 @@ export class RpcPayload {
case "bytes":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// immutable, no need to copy
// TODO: Should errors be copied if they have own properties?
return value;

case "map": {
let map = value as Map<unknown, unknown>;
let result = new Map();
for (let [key, val] of map) {
result.set(
this.deepCopy(key, map, 0, result, dupStubs, owner),
this.deepCopy(val, map, 1, result, dupStubs, owner)
);
}
return result;
}

case "set": {
let set = value as Set<unknown>;
let result = new Set();
for (let val of set) {
result.add(this.deepCopy(val, set, 0, result, dupStubs, owner));
}
return result;
}

case "array": {
// We have to construct the new array first, then fill it in, so we can pass it as the
// parent.
Expand DownExpand Up@@ -1034,6 +1084,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
return;

case "array": {
Expand DownExpand Up@@ -1120,6 +1177,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
case "function":
case "rpc-target":
return;
Expand DownExpand Up@@ -1247,7 +1311,18 @@ function followPath(value: unknown, parent: object | undefined,
case "bytes":
case "date":
case "error":
// These have no properties that can be accessed remotely.
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// These have no properties that can be accessed remotely (or are immutable).
value = undefined;
break;

case "map":
case "set":
// Map and Set don't support property access via this mechanism
value = undefined;
break;

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Add support for additional serialization types by lmaccherone · Pull Request #99 · cloudflare/capnweb · GitHub
Skip to content
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
16 changes: 9 additions & 7 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -194,20 +194,22 @@ let userId: number = await authedApi.getUserId();

The following types can be passed over RPC (in arguments or return values), and will be passed "by value", meaning the content is serialized, producing a copy at the receiving end:

* Primitive values: strings, numbers, booleans, null, undefined
* Primitive values: strings, numbers (including `NaN`, `Infinity`, and `-Infinity`), booleans, null, undefined
* Plain objects (e.g., from object literals)
* Arrays
* `bigint`
* `Date`
* `Uint8Array`
* `Error` and its well-known subclasses

The following types are not supported as of this writing, but may be added in the future:
* `ArrayBuffer`
* `Map` and `Set`
* `ArrayBuffer` and typed arrays other than `Uint8Array`
* `RegExp`
* `URL` and `Headers`
* `Error` and its well-known subclasses (with full-fidelity serialization including `cause` chains and custom properties)

The following types are not supported as of this writing, but may be added in the future:
* Typed arrays other than `Uint8Array`
* `ReadableStream` and `WritableStream`, with automatic flow control.
* `Headers`, `Request`, and `Response`
* `Request` and `Response` (require asynchronous body handling)

The following are intentionally NOT supported:
* Application-defined classes that do not extend `RpcTarget`.
Expand DownExpand Up@@ -317,7 +319,7 @@ To facilitate interoperability:
So basically, it "just works".

With that said, as of this writing, the feature set is not exactly the same between the two. We aim to fix this over time, by adding missing features to both sides until they match. In particular, as of this writing:
* Workers RPC supports some types that Cap'n Web does not yet, like `Map`, streams, etc.
* Workers RPC supports some types that Cap'n Web does not yet, like streams.
* Workers RPC supports sending values that contain aliases and cycles. This can actually cause problems, so we actually plan to *remove* this feature from Workers RPC (with a compatibility flag, of course).
* Workers RPC does not yet support placing an `RpcPromise` into the parameters of a request, to be replaced by its resolution.
* Workers RPC does not yet support the magic `.map()` method.
Expand Down
71 changes: 66 additions & 5 deletions __tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,9 +26,25 @@ let SERIALIZE_TEST_CASES: Record<string, unknown> = {
'["date",1234]': new Date(1234),
'["bytes","aGVsbG8h"]': new TextEncoder().encode("hello!"),
'["undefined"]': undefined,
'["error","Error","the message"]': new Error("the message"),
'["error","TypeError","the message"]': new TypeError("the message"),
'["error","RangeError","the message"]': new RangeError("the message"),
'["error",{"name":"Error","message":"the message"}]': (() => { let e = new Error("the message"); delete e.stack; return e; })(),
'["error",{"name":"TypeError","message":"the message"}]': (() => { let e = new TypeError("the message"); delete e.stack; return e; })(),
'["error",{"name":"RangeError","message":"the message"}]': (() => { let e = new RangeError("the message"); delete e.stack; return e; })(),
'["special-number","NaN"]': NaN,
'["special-number","Infinity"]': Infinity,
'["special-number","-Infinity"]': -Infinity,
'["regexp",{"source":"test","flags":"gi"}]': /test/gi,
'["regexp",{"source":"^\\\\d+$","flags":""}]': /^\d+$/,
'["map",[[["foo","bar"]]]]': new Map([["foo", "bar"]]),
'["map",[[["a","b"]],[["c","d"]]]]': new Map([["a", "b"], ["c", "d"]]),
'["set",["foo","bar"]]': new Set(["foo", "bar"]),
'["arraybuffer","aGVsbG8h"]': new TextEncoder().encode("hello!").buffer,
'["url","https://example.com/path?q=1"]': new URL("https://example.com/path?q=1"),
'["headers",[["content-type","application/json"],["x-custom","value"]]]': (() => {
let h = new Headers();
h.set("Content-Type", "application/json");
h.set("X-Custom", "value");
return h;
})(),
};

class NotSerializable {
Expand DownExpand Up@@ -96,6 +112,49 @@ describe("simple serialization", () => {
expect(() => deserialize('["date"]')).toThrowError(); // missing timestamp
expect(() => deserialize('["error"]')).toThrowError(); // missing type and message
})

it("supports full fidelity Error serialization", () => {
// Test error with cause and custom properties
let error = new Error("outer error");
error.name = "CustomError";
let cause = new TypeError("inner error");
error.cause = cause;
(error as any).customProp = "custom value";
(error as any).code = 404;

let serialized = serialize(error);
let deserialized = deserialize(serialized) as Error;

expect(deserialized.name).toBe("CustomError");
expect(deserialized.message).toBe("outer error");
expect(deserialized.cause).toBeInstanceOf(TypeError);
expect((deserialized.cause as Error).message).toBe("inner error");
expect((deserialized as any).customProp).toBe("custom value");
expect((deserialized as any).code).toBe(404);
})

it("supports nested Map and Set structures", () => {
// Test Map with complex values
let map = new Map();
map.set("key1", "value1");
map.set(123, new Map([["nested", "map"]]));
let serialized = serialize(map);
let deserialized = deserialize(serialized) as Map<unknown, unknown>;
expect(deserialized.get("key1")).toBe("value1");
expect(deserialized.get(123)).toBeInstanceOf(Map);
expect((deserialized.get(123) as Map<unknown, unknown>).get("nested")).toBe("map");

// Test Set with complex values
let set = new Set();
set.add("item1");
set.add(new Set(["nested", "set"]));
let serializedSet = serialize(set);
let deserializedSet = deserialize(serializedSet) as Set<unknown>;
expect(deserializedSet.has("item1")).toBe(true);
let nestedSet = Array.from(deserializedSet).find(item => item instanceof Set) as Set<unknown>;
expect(nestedSet).toBeInstanceOf(Set);
expect(nestedSet.has("nested")).toBe(true);
})
});

// =======================================================================================
Expand DownExpand Up@@ -1187,8 +1246,10 @@ describe("error serialization", () => {
// By default, the stack isn't sent. A stack may be added client-side, though. So we
// verify that it doesn't contain the function name `throwErrorImpl` nor the file name
// `test-util.ts`, which should only appear on the server.
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
if ((err as Error).stack) {
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
}

return "caught";
});
Expand Down
83 changes: 79 additions & 4 deletions src/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,15 +25,21 @@ export type PropertyPath = (string | number)[];

type TypeForRpc = "unsupported" | "primitive" | "object" | "function" | "array" | "date" |
"bigint" | "bytes" | "stub" | "rpc-promise" | "rpc-target" | "rpc-thenable" | "error" |
"undefined";
"undefined" | "regexp" | "map" | "set" | "arraybuffer" | "url" | "headers" | "special-number";

export function typeForRpc(value: unknown): TypeForRpc {
switch (typeof value) {
case "boolean":
case "number":
case "string":
return "primitive";

case "number":
// Check for special numbers (NaN, Infinity, -Infinity)
if (!isFinite(value)) {
return "special-number";
}
return "primitive";

case "undefined":
return "undefined";

Expand DownExpand Up@@ -74,7 +80,17 @@ export function typeForRpc(value: unknown): TypeForRpc {
case Uint8Array.prototype:
return "bytes";

// TODO: All other structured clone types.
case RegExp.prototype:
return "regexp";

case Map.prototype:
return "map";

case Set.prototype:
return "set";

case ArrayBuffer.prototype:
return "arraybuffer";

case RpcStub.prototype:
return "stub";
Expand DownExpand Up@@ -107,6 +123,14 @@ export function typeForRpc(value: unknown): TypeForRpc {
return "error";
}

// Check for URL and Headers (these don't have standard prototypes we can switch on)
if (typeof URL !== "undefined" && value instanceof URL) {
return "url";
}
if (typeof Headers !== "undefined" && value instanceof Headers) {
return "headers";
}

return "unsupported";
}
}
Expand DownExpand Up@@ -766,10 +790,36 @@ export class RpcPayload {
case "bytes":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// immutable, no need to copy
// TODO: Should errors be copied if they have own properties?
return value;

case "map": {
let map = value as Map<unknown, unknown>;
let result = new Map();
for (let [key, val] of map) {
result.set(
this.deepCopy(key, map, 0, result, dupStubs, owner),
this.deepCopy(val, map, 1, result, dupStubs, owner)
);
}
return result;
}

case "set": {
let set = value as Set<unknown>;
let result = new Set();
for (let val of set) {
result.add(this.deepCopy(val, set, 0, result, dupStubs, owner));
}
return result;
}

case "array": {
// We have to construct the new array first, then fill it in, so we can pass it as the
// parent.
Expand DownExpand Up@@ -1034,6 +1084,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
return;

case "array": {
Expand DownExpand Up@@ -1120,6 +1177,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
case "function":
case "rpc-target":
return;
Expand DownExpand Up@@ -1247,7 +1311,18 @@ function followPath(value: unknown, parent: object | undefined,
case "bytes":
case "date":
case "error":
// These have no properties that can be accessed remotely.
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// These have no properties that can be accessed remotely (or are immutable).
value = undefined;
break;

case "map":
case "set":
// Map and Set don't support property access via this mechanism
value = undefined;
break;

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Add support for additional serialization types by lmaccherone · Pull Request #99 · cloudflare/capnweb · GitHub
Skip to content
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
16 changes: 9 additions & 7 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -194,20 +194,22 @@ let userId: number = await authedApi.getUserId();

The following types can be passed over RPC (in arguments or return values), and will be passed "by value", meaning the content is serialized, producing a copy at the receiving end:

* Primitive values: strings, numbers, booleans, null, undefined
* Primitive values: strings, numbers (including `NaN`, `Infinity`, and `-Infinity`), booleans, null, undefined
* Plain objects (e.g., from object literals)
* Arrays
* `bigint`
* `Date`
* `Uint8Array`
* `Error` and its well-known subclasses

The following types are not supported as of this writing, but may be added in the future:
* `ArrayBuffer`
* `Map` and `Set`
* `ArrayBuffer` and typed arrays other than `Uint8Array`
* `RegExp`
* `URL` and `Headers`
* `Error` and its well-known subclasses (with full-fidelity serialization including `cause` chains and custom properties)

The following types are not supported as of this writing, but may be added in the future:
* Typed arrays other than `Uint8Array`
* `ReadableStream` and `WritableStream`, with automatic flow control.
* `Headers`, `Request`, and `Response`
* `Request` and `Response` (require asynchronous body handling)

The following are intentionally NOT supported:
* Application-defined classes that do not extend `RpcTarget`.
Expand DownExpand Up@@ -317,7 +319,7 @@ To facilitate interoperability:
So basically, it "just works".

With that said, as of this writing, the feature set is not exactly the same between the two. We aim to fix this over time, by adding missing features to both sides until they match. In particular, as of this writing:
* Workers RPC supports some types that Cap'n Web does not yet, like `Map`, streams, etc.
* Workers RPC supports some types that Cap'n Web does not yet, like streams.
* Workers RPC supports sending values that contain aliases and cycles. This can actually cause problems, so we actually plan to *remove* this feature from Workers RPC (with a compatibility flag, of course).
* Workers RPC does not yet support placing an `RpcPromise` into the parameters of a request, to be replaced by its resolution.
* Workers RPC does not yet support the magic `.map()` method.
Expand Down
71 changes: 66 additions & 5 deletions __tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,9 +26,25 @@ let SERIALIZE_TEST_CASES: Record<string, unknown> = {
'["date",1234]': new Date(1234),
'["bytes","aGVsbG8h"]': new TextEncoder().encode("hello!"),
'["undefined"]': undefined,
'["error","Error","the message"]': new Error("the message"),
'["error","TypeError","the message"]': new TypeError("the message"),
'["error","RangeError","the message"]': new RangeError("the message"),
'["error",{"name":"Error","message":"the message"}]': (() => { let e = new Error("the message"); delete e.stack; return e; })(),
'["error",{"name":"TypeError","message":"the message"}]': (() => { let e = new TypeError("the message"); delete e.stack; return e; })(),
'["error",{"name":"RangeError","message":"the message"}]': (() => { let e = new RangeError("the message"); delete e.stack; return e; })(),
'["special-number","NaN"]': NaN,
'["special-number","Infinity"]': Infinity,
'["special-number","-Infinity"]': -Infinity,
'["regexp",{"source":"test","flags":"gi"}]': /test/gi,
'["regexp",{"source":"^\\\\d+$","flags":""}]': /^\d+$/,
'["map",[[["foo","bar"]]]]': new Map([["foo", "bar"]]),
'["map",[[["a","b"]],[["c","d"]]]]': new Map([["a", "b"], ["c", "d"]]),
'["set",["foo","bar"]]': new Set(["foo", "bar"]),
'["arraybuffer","aGVsbG8h"]': new TextEncoder().encode("hello!").buffer,
'["url","https://example.com/path?q=1"]': new URL("https://example.com/path?q=1"),
'["headers",[["content-type","application/json"],["x-custom","value"]]]': (() => {
let h = new Headers();
h.set("Content-Type", "application/json");
h.set("X-Custom", "value");
return h;
})(),
};

class NotSerializable {
Expand DownExpand Up@@ -96,6 +112,49 @@ describe("simple serialization", () => {
expect(() => deserialize('["date"]')).toThrowError(); // missing timestamp
expect(() => deserialize('["error"]')).toThrowError(); // missing type and message
})

it("supports full fidelity Error serialization", () => {
// Test error with cause and custom properties
let error = new Error("outer error");
error.name = "CustomError";
let cause = new TypeError("inner error");
error.cause = cause;
(error as any).customProp = "custom value";
(error as any).code = 404;

let serialized = serialize(error);
let deserialized = deserialize(serialized) as Error;

expect(deserialized.name).toBe("CustomError");
expect(deserialized.message).toBe("outer error");
expect(deserialized.cause).toBeInstanceOf(TypeError);
expect((deserialized.cause as Error).message).toBe("inner error");
expect((deserialized as any).customProp).toBe("custom value");
expect((deserialized as any).code).toBe(404);
})

it("supports nested Map and Set structures", () => {
// Test Map with complex values
let map = new Map();
map.set("key1", "value1");
map.set(123, new Map([["nested", "map"]]));
let serialized = serialize(map);
let deserialized = deserialize(serialized) as Map<unknown, unknown>;
expect(deserialized.get("key1")).toBe("value1");
expect(deserialized.get(123)).toBeInstanceOf(Map);
expect((deserialized.get(123) as Map<unknown, unknown>).get("nested")).toBe("map");

// Test Set with complex values
let set = new Set();
set.add("item1");
set.add(new Set(["nested", "set"]));
let serializedSet = serialize(set);
let deserializedSet = deserialize(serializedSet) as Set<unknown>;
expect(deserializedSet.has("item1")).toBe(true);
let nestedSet = Array.from(deserializedSet).find(item => item instanceof Set) as Set<unknown>;
expect(nestedSet).toBeInstanceOf(Set);
expect(nestedSet.has("nested")).toBe(true);
})
});

// =======================================================================================
Expand DownExpand Up@@ -1187,8 +1246,10 @@ describe("error serialization", () => {
// By default, the stack isn't sent. A stack may be added client-side, though. So we
// verify that it doesn't contain the function name `throwErrorImpl` nor the file name
// `test-util.ts`, which should only appear on the server.
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
if ((err as Error).stack) {
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
}

return "caught";
});
Expand Down
83 changes: 79 additions & 4 deletions src/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,15 +25,21 @@ export type PropertyPath = (string | number)[];

type TypeForRpc = "unsupported" | "primitive" | "object" | "function" | "array" | "date" |
"bigint" | "bytes" | "stub" | "rpc-promise" | "rpc-target" | "rpc-thenable" | "error" |
"undefined";
"undefined" | "regexp" | "map" | "set" | "arraybuffer" | "url" | "headers" | "special-number";

export function typeForRpc(value: unknown): TypeForRpc {
switch (typeof value) {
case "boolean":
case "number":
case "string":
return "primitive";

case "number":
// Check for special numbers (NaN, Infinity, -Infinity)
if (!isFinite(value)) {
return "special-number";
}
return "primitive";

case "undefined":
return "undefined";

Expand DownExpand Up@@ -74,7 +80,17 @@ export function typeForRpc(value: unknown): TypeForRpc {
case Uint8Array.prototype:
return "bytes";

// TODO: All other structured clone types.
case RegExp.prototype:
return "regexp";

case Map.prototype:
return "map";

case Set.prototype:
return "set";

case ArrayBuffer.prototype:
return "arraybuffer";

case RpcStub.prototype:
return "stub";
Expand DownExpand Up@@ -107,6 +123,14 @@ export function typeForRpc(value: unknown): TypeForRpc {
return "error";
}

// Check for URL and Headers (these don't have standard prototypes we can switch on)
if (typeof URL !== "undefined" && value instanceof URL) {
return "url";
}
if (typeof Headers !== "undefined" && value instanceof Headers) {
return "headers";
}

return "unsupported";
}
}
Expand DownExpand Up@@ -766,10 +790,36 @@ export class RpcPayload {
case "bytes":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// immutable, no need to copy
// TODO: Should errors be copied if they have own properties?
return value;

case "map": {
let map = value as Map<unknown, unknown>;
let result = new Map();
for (let [key, val] of map) {
result.set(
this.deepCopy(key, map, 0, result, dupStubs, owner),
this.deepCopy(val, map, 1, result, dupStubs, owner)
);
}
return result;
}

case "set": {
let set = value as Set<unknown>;
let result = new Set();
for (let val of set) {
result.add(this.deepCopy(val, set, 0, result, dupStubs, owner));
}
return result;
}

case "array": {
// We have to construct the new array first, then fill it in, so we can pass it as the
// parent.
Expand DownExpand Up@@ -1034,6 +1084,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
return;

case "array": {
Expand DownExpand Up@@ -1120,6 +1177,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
case "function":
case "rpc-target":
return;
Expand DownExpand Up@@ -1247,7 +1311,18 @@ function followPath(value: unknown, parent: object | undefined,
case "bytes":
case "date":
case "error":
// These have no properties that can be accessed remotely.
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// These have no properties that can be accessed remotely (or are immutable).
value = undefined;
break;

case "map":
case "set":
// Map and Set don't support property access via this mechanism
value = undefined;
break;

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Add support for additional serialization types by lmaccherone · Pull Request #99 · cloudflare/capnweb · GitHub
Skip to content
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
16 changes: 9 additions & 7 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -194,20 +194,22 @@ let userId: number = await authedApi.getUserId();

The following types can be passed over RPC (in arguments or return values), and will be passed "by value", meaning the content is serialized, producing a copy at the receiving end:

* Primitive values: strings, numbers, booleans, null, undefined
* Primitive values: strings, numbers (including `NaN`, `Infinity`, and `-Infinity`), booleans, null, undefined
* Plain objects (e.g., from object literals)
* Arrays
* `bigint`
* `Date`
* `Uint8Array`
* `Error` and its well-known subclasses

The following types are not supported as of this writing, but may be added in the future:
* `ArrayBuffer`
* `Map` and `Set`
* `ArrayBuffer` and typed arrays other than `Uint8Array`
* `RegExp`
* `URL` and `Headers`
* `Error` and its well-known subclasses (with full-fidelity serialization including `cause` chains and custom properties)

The following types are not supported as of this writing, but may be added in the future:
* Typed arrays other than `Uint8Array`
* `ReadableStream` and `WritableStream`, with automatic flow control.
* `Headers`, `Request`, and `Response`
* `Request` and `Response` (require asynchronous body handling)

The following are intentionally NOT supported:
* Application-defined classes that do not extend `RpcTarget`.
Expand DownExpand Up@@ -317,7 +319,7 @@ To facilitate interoperability:
So basically, it "just works".

With that said, as of this writing, the feature set is not exactly the same between the two. We aim to fix this over time, by adding missing features to both sides until they match. In particular, as of this writing:
* Workers RPC supports some types that Cap'n Web does not yet, like `Map`, streams, etc.
* Workers RPC supports some types that Cap'n Web does not yet, like streams.
* Workers RPC supports sending values that contain aliases and cycles. This can actually cause problems, so we actually plan to *remove* this feature from Workers RPC (with a compatibility flag, of course).
* Workers RPC does not yet support placing an `RpcPromise` into the parameters of a request, to be replaced by its resolution.
* Workers RPC does not yet support the magic `.map()` method.
Expand Down
71 changes: 66 additions & 5 deletions __tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,9 +26,25 @@ let SERIALIZE_TEST_CASES: Record<string, unknown> = {
'["date",1234]': new Date(1234),
'["bytes","aGVsbG8h"]': new TextEncoder().encode("hello!"),
'["undefined"]': undefined,
'["error","Error","the message"]': new Error("the message"),
'["error","TypeError","the message"]': new TypeError("the message"),
'["error","RangeError","the message"]': new RangeError("the message"),
'["error",{"name":"Error","message":"the message"}]': (() => { let e = new Error("the message"); delete e.stack; return e; })(),
'["error",{"name":"TypeError","message":"the message"}]': (() => { let e = new TypeError("the message"); delete e.stack; return e; })(),
'["error",{"name":"RangeError","message":"the message"}]': (() => { let e = new RangeError("the message"); delete e.stack; return e; })(),
'["special-number","NaN"]': NaN,
'["special-number","Infinity"]': Infinity,
'["special-number","-Infinity"]': -Infinity,
'["regexp",{"source":"test","flags":"gi"}]': /test/gi,
'["regexp",{"source":"^\\\\d+$","flags":""}]': /^\d+$/,
'["map",[[["foo","bar"]]]]': new Map([["foo", "bar"]]),
'["map",[[["a","b"]],[["c","d"]]]]': new Map([["a", "b"], ["c", "d"]]),
'["set",["foo","bar"]]': new Set(["foo", "bar"]),
'["arraybuffer","aGVsbG8h"]': new TextEncoder().encode("hello!").buffer,
'["url","https://example.com/path?q=1"]': new URL("https://example.com/path?q=1"),
'["headers",[["content-type","application/json"],["x-custom","value"]]]': (() => {
let h = new Headers();
h.set("Content-Type", "application/json");
h.set("X-Custom", "value");
return h;
})(),
};

class NotSerializable {
Expand DownExpand Up@@ -96,6 +112,49 @@ describe("simple serialization", () => {
expect(() => deserialize('["date"]')).toThrowError(); // missing timestamp
expect(() => deserialize('["error"]')).toThrowError(); // missing type and message
})

it("supports full fidelity Error serialization", () => {
// Test error with cause and custom properties
let error = new Error("outer error");
error.name = "CustomError";
let cause = new TypeError("inner error");
error.cause = cause;
(error as any).customProp = "custom value";
(error as any).code = 404;

let serialized = serialize(error);
let deserialized = deserialize(serialized) as Error;

expect(deserialized.name).toBe("CustomError");
expect(deserialized.message).toBe("outer error");
expect(deserialized.cause).toBeInstanceOf(TypeError);
expect((deserialized.cause as Error).message).toBe("inner error");
expect((deserialized as any).customProp).toBe("custom value");
expect((deserialized as any).code).toBe(404);
})

it("supports nested Map and Set structures", () => {
// Test Map with complex values
let map = new Map();
map.set("key1", "value1");
map.set(123, new Map([["nested", "map"]]));
let serialized = serialize(map);
let deserialized = deserialize(serialized) as Map<unknown, unknown>;
expect(deserialized.get("key1")).toBe("value1");
expect(deserialized.get(123)).toBeInstanceOf(Map);
expect((deserialized.get(123) as Map<unknown, unknown>).get("nested")).toBe("map");

// Test Set with complex values
let set = new Set();
set.add("item1");
set.add(new Set(["nested", "set"]));
let serializedSet = serialize(set);
let deserializedSet = deserialize(serializedSet) as Set<unknown>;
expect(deserializedSet.has("item1")).toBe(true);
let nestedSet = Array.from(deserializedSet).find(item => item instanceof Set) as Set<unknown>;
expect(nestedSet).toBeInstanceOf(Set);
expect(nestedSet.has("nested")).toBe(true);
})
});

// =======================================================================================
Expand DownExpand Up@@ -1187,8 +1246,10 @@ describe("error serialization", () => {
// By default, the stack isn't sent. A stack may be added client-side, though. So we
// verify that it doesn't contain the function name `throwErrorImpl` nor the file name
// `test-util.ts`, which should only appear on the server.
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
if ((err as Error).stack) {
expect((err as Error).stack).not.toContain("throwErrorImpl");
expect((err as Error).stack).not.toContain("test-util.ts");
}

return "caught";
});
Expand Down
83 changes: 79 additions & 4 deletions src/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,15 +25,21 @@ export type PropertyPath = (string | number)[];

type TypeForRpc = "unsupported" | "primitive" | "object" | "function" | "array" | "date" |
"bigint" | "bytes" | "stub" | "rpc-promise" | "rpc-target" | "rpc-thenable" | "error" |
"undefined";
"undefined" | "regexp" | "map" | "set" | "arraybuffer" | "url" | "headers" | "special-number";

export function typeForRpc(value: unknown): TypeForRpc {
switch (typeof value) {
case "boolean":
case "number":
case "string":
return "primitive";

case "number":
// Check for special numbers (NaN, Infinity, -Infinity)
if (!isFinite(value)) {
return "special-number";
}
return "primitive";

case "undefined":
return "undefined";

Expand DownExpand Up@@ -74,7 +80,17 @@ export function typeForRpc(value: unknown): TypeForRpc {
case Uint8Array.prototype:
return "bytes";

// TODO: All other structured clone types.
case RegExp.prototype:
return "regexp";

case Map.prototype:
return "map";

case Set.prototype:
return "set";

case ArrayBuffer.prototype:
return "arraybuffer";

case RpcStub.prototype:
return "stub";
Expand DownExpand Up@@ -107,6 +123,14 @@ export function typeForRpc(value: unknown): TypeForRpc {
return "error";
}

// Check for URL and Headers (these don't have standard prototypes we can switch on)
if (typeof URL !== "undefined" && value instanceof URL) {
return "url";
}
if (typeof Headers !== "undefined" && value instanceof Headers) {
return "headers";
}

return "unsupported";
}
}
Expand DownExpand Up@@ -766,10 +790,36 @@ export class RpcPayload {
case "bytes":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// immutable, no need to copy
// TODO: Should errors be copied if they have own properties?
return value;

case "map": {
let map = value as Map<unknown, unknown>;
let result = new Map();
for (let [key, val] of map) {
result.set(
this.deepCopy(key, map, 0, result, dupStubs, owner),
this.deepCopy(val, map, 1, result, dupStubs, owner)
);
}
return result;
}

case "set": {
let set = value as Set<unknown>;
let result = new Set();
for (let val of set) {
result.add(this.deepCopy(val, set, 0, result, dupStubs, owner));
}
return result;
}

case "array": {
// We have to construct the new array first, then fill it in, so we can pass it as the
// parent.
Expand DownExpand Up@@ -1034,6 +1084,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
return;

case "array": {
Expand DownExpand Up@@ -1120,6 +1177,13 @@ export class RpcPayload {
case "date":
case "error":
case "undefined":
case "special-number":
case "regexp":
case "map":
case "set":
case "arraybuffer":
case "url":
case "headers":
case "function":
case "rpc-target":
return;
Expand DownExpand Up@@ -1247,7 +1311,18 @@ function followPath(value: unknown, parent: object | undefined,
case "bytes":
case "date":
case "error":
// These have no properties that can be accessed remotely.
case "special-number":
case "regexp":
case "arraybuffer":
case "url":
case "headers":
// These have no properties that can be accessed remotely (or are immutable).
value = undefined;
break;

case "map":
case "set":
// Map and Set don't support property access via this mechanism
value = undefined;
break;

Expand Down
Loading