chore: restructure repository into packages/ folder (#3197)

We're having a growing number of packages in this repository. This PR
moves them into a `packages/` directory like it's commonly done in other
projects.
This commit is contained in:
Marvin Hagemeister
2025-08-06 15:52:45 +02:00
committed by GitHub
parent 27e407a1e3
commit 815b1940e3
184 changed files with 94 additions and 82 deletions
@@ -0,0 +1,57 @@
export const snapshot = {};
snapshot[`round trip - undefined 1`] = `"-1"`;
snapshot[`round trip - null 1`] = `"-2"`;
snapshot[`round trip - 1 1`] = `"[1]"`;
snapshot[`round trip - 2 1`] = `"[2]"`;
snapshot[`round trip - -2 1`] = `"[-2]"`;
snapshot[`round trip - Infinity 1`] = `"-4"`;
snapshot[`round trip - -Infinity 1`] = `"-5"`;
snapshot[`round trip - 0 1`] = `"[0]"`;
snapshot[`round trip - -0 1`] = `"-6"`;
snapshot[`round trip - NaN 1`] = `"-3"`;
snapshot[`round trip - 0 2`] = `"[0]"`;
snapshot[`round trip - true 1`] = `"[true]"`;
snapshot[`round trip - false 1`] = `"[false]"`;
snapshot[`round trip - 'abc' 1`] = `'["abc"]'`;
snapshot[`round trip - 1n 1`] = `'[["BigInt","1"]]'`;
snapshot[`round trip - -1n 1`] = `'[["BigInt","-1"]]'`;
snapshot[`round trip - [ 1, 2, 3 ] 1`] = `"[[1,2,3],1,2,3]"`;
snapshot[`round trip - [ null, undefined, -2 ] 1`] = `"[[-2,-1,1],-2]"`;
snapshot[`round trip - { a: 1, b: null, c: -2 } 1`] = `'[{"a":1,"b":-2,"c":2},1,-2]'`;
snapshot[`round trip - Uint8Array(3) [ 1, 2, 3 ] 1`] = `'[["Uint8Array","AQID"]]'`;
snapshot[`round trip - URL {\\n href: 'https://fresh.deno.dev/',\\n origin: 'https://fresh.deno.dev',\\n protocol: 'https:',\\n username: '',\\n password: '',\\n host: 'fresh.deno.dev',\\n hostname: 'fresh.deno.dev',\\n port: '',\\n pathname: '/',\\n hash: '',\\n search: ''\\n} 1`] = `'[["URL","https://fresh.deno.dev/"]]'`;
snapshot[`round trip - 1990-05-31T00:00:00.000Z 1`] = `'[["Date","1990-05-31T00:00:00.000Z"]]'`;
snapshot[`round trip - Map(2) { 1 => null, undefined => -2 } 1`] = `'[["Map",[1,-2,-1,2]],1,-2]'`;
snapshot[`round trip - Set(5) { 1, 2, null, -2, NaN } 1`] = `'[["Set",[1,2,-2,3,-3]],1,2,-2]'`;
snapshot[`round trip - [ 1, <1 empty item>, 3 ] 1`] = `"[[1,-7,2],1,3]"`;
snapshot[`round trip - /foo["]/ 1`] = `'[["RegExp","foo[\\\\"]", ""]]'`;
snapshot[`round trip - { a: { foo: 123 }, b: [ { foo: 123 }, { foo: 123 } ] } 1`] = `'[{"a":1,"b":3},{"foo":2},123,[1,1]]'`;
snapshot[`round trip - <ref *1> { a: 1, b: [Circular *1] } 1`] = `'[{"a":1,"b":0},1]'`;
+7
View File
@@ -0,0 +1,7 @@
export const UNDEFINED = -1;
export const NULL = -2;
export const NAN = -3;
export const INFINITY_POS = -4;
export const INFINITY_NEG = -5;
export const ZERO_NEG = -6;
export const HOLE = -7;
+93
View File
@@ -0,0 +1,93 @@
import { expect } from "@std/expect";
import { parse } from "./parse.ts";
import { stringify } from "./stringify.ts";
import { Signal, signal } from "@preact/signals";
Deno.test("custom parse - Point", () => {
class Point {
constructor(public x: number, public y: number) {
this.x = x;
this.y = y;
}
}
const str = stringify(new Point(30, 40), {
Point: (value) =>
value instanceof Point ? { value: [value.x, value.y] } : undefined,
});
expect(str).toEqual('[["Point",1],[2,3],30,40]');
const point = parse(str, {
Point: ([x, y]: [number, number]) => new Point(x, y),
});
expect(point).toEqual(new Point(30, 40));
});
Deno.test("custom parse - Signals", () => {
const res = parse<Signal>('[["Signal",1],2]', {
Signal: (value) => signal(value),
});
expect(res).toBeInstanceOf(Signal);
expect(res.peek()).toEqual(2);
});
Deno.test("custom stringify - Signals", () => {
const s = signal(2);
expect(stringify(s, {
Signal: (s2: unknown) => {
return s2 instanceof Signal ? { value: s2.peek() } : undefined;
},
})).toEqual(
'[["Signal",1],2]',
);
});
Deno.test("custom parse - Signals with null value", () => {
const res = parse<Signal>('[["Signal",-2]]', {
Signal: (value) => signal(value),
});
expect(res).toBeInstanceOf(Signal);
expect(res.peek()).toEqual(null);
});
Deno.test("custom stringify - Signals with null value", () => {
const s = signal(null);
expect(stringify(s, {
Signal: (s2: unknown) => {
return s2 instanceof Signal ? { value: s2.peek() } : undefined;
},
})).toEqual(
'[["Signal",-2]]',
);
});
Deno.test("custom parse - Signals with undefined value", () => {
const res = parse<Signal>('[["Signal",-1]]', {
Signal: (value) => signal(value),
});
expect(res).toBeInstanceOf(Signal);
expect(res.peek()).toEqual(undefined);
});
Deno.test("custom stringify - Signals with undefined value", () => {
const s = signal(undefined);
expect(stringify(s, {
Signal: (s2: unknown) => {
return s2 instanceof Signal ? { value: s2.peek() } : undefined;
},
})).toEqual(
'[["Signal",-1]]',
);
});
Deno.test("custom stringify - referenced Signals", () => {
const s = signal(2);
expect(stringify([s, s], {
Signal: (s2: unknown) => {
return s2 instanceof Signal ? { value: s2.peek() } : undefined;
},
})).toEqual(
'[[1,1],["Signal",2],2]',
);
});
+132
View File
@@ -0,0 +1,132 @@
import {
HOLE,
INFINITY_NEG,
INFINITY_POS,
NAN,
NULL,
UNDEFINED,
ZERO_NEG,
} from "./constants.ts";
// deno-lint-ignore no-explicit-any
export type CustomParser = Record<string, (value: any) => unknown>;
export function parse<T = unknown>(
value: string,
custom?: CustomParser | undefined,
): T {
const data = JSON.parse(value);
if (!Array.isArray(data)) return unpack([], [], data, custom) as T;
const hydrated = new Array(data.length);
unpack(data, hydrated, 0, custom);
return hydrated[0];
}
function unpack(
arr: unknown[],
hydrated: unknown[],
idx: number,
custom: CustomParser | undefined,
): unknown {
switch (idx) {
case UNDEFINED:
return undefined;
case NULL:
return null;
case NAN:
return NaN;
case INFINITY_POS:
return Infinity;
case INFINITY_NEG:
return -Infinity;
case ZERO_NEG:
return -0;
}
if (idx in hydrated) return hydrated[idx];
const current = arr[idx];
if (typeof current === "number") {
return hydrated[idx] = current;
} else if (
typeof current === "string" || typeof current === "boolean" ||
current === null
) {
return hydrated[idx] = current;
} else if (Array.isArray(current)) {
if (current.length > 0 && typeof current[0] === "string") {
const name = current[0];
if (custom !== undefined && name in custom) {
const fn = custom[name];
const ref = current[1];
const value = unpack(arr, hydrated, ref, custom);
return hydrated[idx] = fn(value);
}
switch (name) {
case "BigInt":
return hydrated[idx] = BigInt(current[1]);
case "URL":
return hydrated[idx] = new URL(current[1]);
case "Date":
return hydrated[idx] = new Date(current[1]);
case "RegExp":
return hydrated[idx] = new RegExp(current[1], current[2]);
case "Set": {
const set = new Set();
for (let i = 0; i < current[1].length; i++) {
const ref = current[1][i];
set.add(unpack(arr, hydrated, ref, custom));
}
return hydrated[idx] = set;
}
case "Map": {
const set = new Map();
for (let i = 0; i < current[1].length; i++) {
const refKey = current[1][i++];
const key = unpack(arr, hydrated, refKey, custom);
const refValue = current[1][i];
const value = unpack(arr, hydrated, refValue, custom);
set.set(key, value);
}
return hydrated[idx] = set;
}
case "Uint8Array":
return hydrated[idx] = b64decode(current[1]);
}
} else {
const actual = new Array(current.length);
hydrated[idx] = actual;
for (let i = 0; i < current.length; i++) {
const ref = current[i];
if (ref === HOLE) {
continue;
} else {
actual[i] = unpack(arr, hydrated, ref, custom);
}
}
return actual;
}
} else if (typeof current === "object") {
const actual: Record<string, unknown> = {};
hydrated[idx] = actual;
const keys = Object.keys(current);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
// deno-lint-ignore no-explicit-any
const ref = (current as any)[key];
actual[key] = unpack(arr, hydrated, ref, custom);
}
return actual;
}
}
function b64decode(b64: string): Uint8Array {
const binString = atob(b64);
const size = binString.length;
const bytes = new Uint8Array(size);
for (let i = 0; i < size; i++) {
bytes[i] = binString.charCodeAt(i);
}
return bytes;
}
@@ -0,0 +1,52 @@
import { expect } from "@std/expect";
import { parse } from "./parse.ts";
import { assertSnapshot } from "@std/testing/snapshot";
import { inspect } from "node:util";
import { stringify } from "./stringify.ts";
const inner = { foo: 123 };
const references = { a: inner, b: [inner, inner] };
const circular = { a: 1, b: null as unknown };
circular.b = circular;
const TESTS = [
undefined,
null,
1,
2,
-2,
Infinity,
-Infinity,
0,
-0,
NaN,
1.2 -
1.2,
true,
false,
"abc",
1n,
-1n,
[1, 2, 3],
[null, undefined, -2],
{ a: 1, b: null, c: -2 },
new Uint8Array([1, 2, 3]),
new URL("https://fresh.deno.dev"),
new Date("1990-05-31"),
new Map([[1, null], [undefined, -2]]),
new Set([1, 2, null, -2, NaN]),
[1, , 3],
/foo["]/,
references,
circular,
];
for (const value of TESTS) {
Deno.test(`round trip - ${inspect(value)}`, async (t) => {
const str = stringify(value);
await assertSnapshot(t, str);
const parsed = parse(str);
expect(parsed).toEqual(value);
});
}
+192
View File
@@ -0,0 +1,192 @@
import {
INFINITY_NEG,
INFINITY_POS,
NAN,
NULL,
UNDEFINED,
ZERO_NEG,
} from "./constants.ts";
import { HOLE } from "./constants.ts";
export type Stringifiers = Record<
string,
// deno-lint-ignore no-explicit-any
(value: any) => { value: any } | undefined
>;
/**
* Serializes the following:
*
* - `null`
* - `undefined`
* - `boolean`
* - `number`
* - `bigint`
* - `string`
* - `array`
* - `object` (no prototypes)
* - `Uint8Array`
* - `URL`
* - `Date`
* - `RegExp`
* - `Set`
* - `Map`
*
* Circular references are supported and objects with the same reference are
* serialized only once.
*/
export function stringify(data: unknown, custom?: Stringifiers): string {
const out: string[] = [];
const indexes = new Map<unknown, number>();
const res = serializeInner(out, indexes, data, custom);
if (res < 0) {
return String(res);
}
return `[${out.join(",")}]`;
}
function serializeInner(
out: string[],
indexes: Map<unknown, number>,
value: unknown,
custom: Stringifiers | undefined,
): number {
const seenIdx = indexes.get(value);
if (seenIdx !== undefined) return seenIdx;
if (value === undefined) return UNDEFINED;
if (value === null) return NULL;
if (Number.isNaN(value)) return NAN;
if (value === Infinity) return INFINITY_POS;
if (value === -Infinity) return INFINITY_NEG;
if (value === 0 && 1 / value < 0) return ZERO_NEG;
const idx = out.length;
out.push("");
indexes.set(value, idx);
let str = "";
if (typeof value === "number") {
str += String(value);
} else if (typeof value === "boolean") {
str += String(value);
} else if (typeof value === "bigint") {
str += `["BigInt","${value}"]`;
} else if (typeof value === "string") {
str += JSON.stringify(value);
} else if (Array.isArray(value)) {
str += "[";
for (let i = 0; i < value.length; i++) {
if (i in value) {
str += serializeInner(out, indexes, value[i], custom);
} else {
str += HOLE;
}
if (i < value.length - 1) {
str += ",";
}
}
str += "]";
} else if (typeof value === "object") {
if (custom !== undefined) {
for (const k in custom) {
const fn = custom[k];
if (fn === undefined) continue;
const res = fn(value);
if (res === undefined) continue;
const innerIdx = serializeInner(out, indexes, res.value, custom);
str = `["${k}",${innerIdx}]`;
out[idx] = str;
return idx;
}
}
if (value instanceof URL) {
str += `["URL","${value.href}"]`;
} else if (value instanceof Date) {
str += `["Date","${value.toISOString()}"]`;
} else if (value instanceof RegExp) {
str += `["RegExp",${JSON.stringify(value.source)}, "${value.flags}"]`;
} else if (value instanceof Uint8Array) {
str += `["Uint8Array","${b64encode(value.buffer)}"]`;
} else if (value instanceof Set) {
const items = new Array(value.size);
let i = 0;
value.forEach((v) => {
items[i++] = serializeInner(out, indexes, v, custom);
});
str += `["Set",[${items.join(",")}]]`;
} else if (value instanceof Map) {
const items = new Array(value.size * 2);
let i = 0;
value.forEach((v, k) => {
items[i++] = serializeInner(out, indexes, k, custom);
items[i++] = serializeInner(out, indexes, v, custom);
});
str += `["Map",[${items.join(",")}]]`;
} else {
str += "{";
const keys = Object.keys(value);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
str += JSON.stringify(key) + ":";
// deno-lint-ignore no-explicit-any
str += serializeInner(out, indexes, (value as any)[key], custom);
if (i < keys.length - 1) {
str += ",";
}
}
str += "}";
}
} else if (typeof value === "function") {
throw new Error(`Serializing functions is not supported.`);
}
out[idx] = str;
return idx;
}
// 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: ArrayBufferLike): 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;
}
@@ -0,0 +1,14 @@
import { expect } from "@std/expect";
import { stringify } from "./stringify.ts";
Deno.test("stringify - object prototype", () => {
const obj = { __proto__: 123, foo: 1 };
expect(stringify(obj)).toEqual(
'[{"foo":1},1]',
);
});
Deno.test("stringify - throw serializing functions", () => {
const fn = () => {};
expect(() => stringify(fn)).toThrow();
});