feat: support passing Uint8Array as island props (#1225)

This commit adds support for passing Uint8Array's to islands in
component props.
This commit is contained in:
Luca Casonato
2023-05-31 08:34:57 +00:00
committed by GitHub
parent e3f9a0df08
commit 38e67b0a97
5 changed files with 72 additions and 0 deletions
+46
View File
@@ -8,6 +8,7 @@
* - `string`
* - `array`
* - `object` (no prototypes)
* - `Uint8Array`
* - `Signal` from `@preact/signals`
*
* Circular references are supported and objects with the same reference are
@@ -118,6 +119,11 @@ export function serialize(data: unknown): SerializeResult {
const res = { [KEY]: "s", v: value.peek() };
parentStack.push(res);
return res;
} else if (value instanceof Uint8Array) {
requiresDeserializer = true;
const res = { [KEY]: "u8a", d: b64encode(value) };
parentStack.push(res);
return res;
} else if (typeof value === "object" && value && KEY in value) {
requiresDeserializer = true;
// deno-lint-ignore no-explicit-any
@@ -136,3 +142,43 @@ export function serialize(data: unknown): SerializeResult {
const serialized = JSON.stringify(toSerialize, replacer);
return { serialized, requiresDeserializer, hasSignals };
}
// deno-fmt-ignore
const base64abc = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d",
"e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "+", "/",
];
/**
* CREDIT: https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
* Encodes a given Uint8Array, ArrayBuffer or string into RFC4648 base64 representation
*/
export function b64encode(buffer: ArrayBuffer): string {
const uint8 = new Uint8Array(buffer);
let result = "",
i;
const l = uint8.length;
for (i = 2; i < l; i += 3) {
result += base64abc[uint8[i - 2] >> 2];
result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)];
result += base64abc[((uint8[i - 1] & 0x0f) << 2) | (uint8[i] >> 6)];
result += base64abc[uint8[i] & 0x3f];
}
if (i === l + 1) {
// 1 octet yet to write
result += base64abc[uint8[i - 2] >> 2];
result += base64abc[(uint8[i - 2] & 0x03) << 4];
result += "==";
}
if (i === l) {
// 2 octets yet to write
result += base64abc[uint8[i - 2] >> 2];
result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)];
result += base64abc[(uint8[i - 1] & 0x0f) << 2];
result += "=";
}
return result;
}