WIP: bootstrap and partial real Solana watcher implementation

This commit is contained in:
2026-08-16 09:17:45 +00:00
commit dc23412c3f
7232 changed files with 1687637 additions and 0 deletions

View File

@@ -0,0 +1,717 @@
import { describe, expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
import * as core from "zod/v4/core";
const Test = z.object({
f1: z.number(),
f2: z.string().optional(),
f3: z.string().nullable(),
f4: z.array(z.object({ t: z.union([z.string(), z.boolean()]) })),
});
test("object type inference", () => {
type TestType = {
f1: number;
f2?: string | undefined;
f3: string | null;
f4: { t: string | boolean }[];
};
expectTypeOf<z.TypeOf<typeof Test>>().toEqualTypeOf<TestType>();
});
test("unknown throw", () => {
const asdf: unknown = 35;
expect(() => Test.parse(asdf)).toThrow();
});
test("shape() should return schema of particular key", () => {
const f1Schema = Test.shape.f1;
const f2Schema = Test.shape.f2;
const f3Schema = Test.shape.f3;
const f4Schema = Test.shape.f4;
expect(f1Schema).toBeInstanceOf(z.ZodNumber);
expect(f2Schema).toBeInstanceOf(z.ZodOptional);
expect(f3Schema).toBeInstanceOf(z.ZodNullable);
expect(f4Schema).toBeInstanceOf(z.ZodArray);
});
test("correct parsing", () => {
Test.parse({
f1: 12,
f2: "string",
f3: "string",
f4: [
{
t: "string",
},
],
});
Test.parse({
f1: 12,
f3: null,
f4: [
{
t: false,
},
],
});
});
test("nonstrict by default", () => {
z.object({ points: z.number() }).parse({
points: 2314,
unknown: "asdf",
});
});
test("parse optional keys ", () => {
const schema = z.object({
a: z.string().optional(),
});
expect(schema.parse({ a: "asdf" })).toEqual({ a: "asdf" });
});
test("empty object", () => {
const schema = z.object({});
expect(schema.parse({})).toEqual({});
expect(schema.parse({ name: "asdf" })).toEqual({});
expect(schema.safeParse(null).success).toEqual(false);
expect(schema.safeParse("asdf").success).toEqual(false);
expectTypeOf<z.output<typeof schema>>().toEqualTypeOf<Record<string, never>>();
});
const data = {
points: 2314,
unknown: "asdf",
};
test("strip by default", () => {
const val = z.object({ points: z.number() }).parse(data);
expect(val).toEqual({ points: 2314 });
});
test("unknownkeys override", () => {
const val = z.object({ points: z.number() }).strict().passthrough().strip().passthrough().parse(data);
expect(val).toEqual(data);
});
test("passthrough unknown", () => {
const val = z.object({ points: z.number() }).passthrough().parse(data);
expect(val).toEqual(data);
});
test("strip unknown", () => {
const val = z.object({ points: z.number() }).strip().parse(data);
expect(val).toEqual({ points: 2314 });
});
test("strict", () => {
const val = z.object({ points: z.number() }).strict().safeParse(data);
expect(val.success).toEqual(false);
});
test("catchall inference", () => {
const o1 = z
.object({
first: z.string(),
})
.catchall(z.number());
const d1 = o1.parse({ first: "asdf", num: 1243 });
// expectTypeOf<(typeof d1)["asdf"]>().toEqualTypeOf<number>();
expectTypeOf<(typeof d1)["first"]>().toEqualTypeOf<string>();
});
test("catchall overrides strict", () => {
const o1 = z.object({ first: z.string().optional() }).strict().catchall(z.number());
// should run fine
// setting a catchall overrides the unknownKeys behavior
o1.parse({
asdf: 1234,
});
// should only run catchall validation
// against unknown keys
o1.parse({
first: "asdf",
asdf: 1234,
});
});
test("catchall overrides strict", () => {
const o1 = z
.object({
first: z.string(),
})
.strict()
.catchall(z.number());
// should run fine
// setting a catchall overrides the unknownKeys behavior
o1.parse({
first: "asdf",
asdf: 1234,
});
});
test("optional keys are unset", () => {
const SNamedEntity = z.object({
id: z.string(),
set: z.string().optional(),
unset: z.string().optional(),
});
const result = SNamedEntity.parse({
id: "asdf",
set: undefined,
});
expect(Object.keys(result)).toEqual(["id", "set"]);
});
test("catchall parsing", async () => {
const result = z.object({ name: z.string() }).catchall(z.number()).parse({ name: "Foo", validExtraKey: 61 });
expect(result).toEqual({ name: "Foo", validExtraKey: 61 });
const result2 = z
.object({ name: z.string() })
.catchall(z.number())
.safeParse({ name: "Foo", validExtraKey: 61, invalid: "asdf" });
expect(result2.success).toEqual(false);
});
test("nonexistent keys", async () => {
const Schema = z.union([z.object({ a: z.string() }), z.object({ b: z.number() })]);
const obj = { a: "A" };
const result = await Schema.spa(obj); // Works with 1.11.10, breaks with 2.0.0-beta.21
expect(result.success).toBe(true);
});
test("test async union", async () => {
const Schema2 = z.union([
z.object({
ty: z.string(),
}),
z.object({
ty: z.number(),
}),
]);
const obj = { ty: "A" };
const result = await Schema2.spa(obj); // Works with 1.11.10, breaks with 2.0.0-beta.21
expect(result.success).toEqual(true);
});
test("test inferred merged type", async () => {
const asdf = z.object({ a: z.string() }).merge(z.object({ a: z.number() }));
type asdf = z.infer<typeof asdf>;
expectTypeOf<asdf>().toEqualTypeOf<{ a: number }>();
});
test("inferred type with Record shape", () => {
type A = z.ZodObject<Record<string, z.ZodType<string, number>>>;
expectTypeOf<z.infer<A>>().toEqualTypeOf<Record<string, string>>();
expectTypeOf<z.input<A>>().toEqualTypeOf<Record<string, number>>();
type B = z.ZodObject;
expectTypeOf<z.infer<B>>().toEqualTypeOf<Record<string, unknown>>();
expectTypeOf<z.input<B>>().toEqualTypeOf<Record<string, unknown>>();
});
test("inferred merged object type with optional properties", async () => {
const Merged = z
.object({ a: z.string(), b: z.string().optional() })
.merge(z.object({ a: z.string().optional(), b: z.string() }));
type Merged = z.infer<typeof Merged>;
expectTypeOf<Merged>().toEqualTypeOf<{ a?: string | undefined; b: string }>();
});
test("inferred unioned object type with optional properties", async () => {
const Unioned = z.union([
z.object({ a: z.string(), b: z.string().optional() }),
z.object({ a: z.string().optional(), b: z.string() }),
]);
type Unioned = z.infer<typeof Unioned>;
expectTypeOf<Unioned>().toEqualTypeOf<
{ a: string; b?: string | undefined } | { a?: string | undefined; b: string }
>();
});
test("inferred enum type", async () => {
const Enum = z.object({ a: z.string(), b: z.string().optional() }).keyof();
expect(Enum.enum).toEqual({
a: "a",
b: "b",
});
expect(Enum._zod.def.entries).toEqual({
a: "a",
b: "b",
});
type Enum = z.infer<typeof Enum>;
expectTypeOf<Enum>().toEqualTypeOf<"a" | "b">();
});
test("z.keyof returns enum", () => {
const User = z.object({ name: z.string(), age: z.number() });
const keysSchema = z.keyof(User);
expect(keysSchema.enum).toEqual({
name: "name",
age: "age",
});
expect(keysSchema._zod.def.entries).toEqual({
name: "name",
age: "age",
});
type Keys = z.infer<typeof keysSchema>;
expectTypeOf<Keys>().toEqualTypeOf<"name" | "age">();
});
test("inferred partial object type with optional properties", async () => {
const Partial = z.object({ a: z.string(), b: z.string().optional() }).partial();
type Partial = z.infer<typeof Partial>;
expectTypeOf<Partial>().toEqualTypeOf<{ a?: string | undefined; b?: string | undefined }>();
});
test("inferred picked object type with optional properties", async () => {
const Picked = z.object({ a: z.string(), b: z.string().optional() }).pick({ b: true });
type Picked = z.infer<typeof Picked>;
expectTypeOf<Picked>().toEqualTypeOf<{ b?: string | undefined }>();
});
test("inferred type for unknown/any keys", () => {
const myType = z.object({
anyOptional: z.any().optional(),
anyRequired: z.any(),
unknownOptional: z.unknown().optional(),
unknownRequired: z.unknown(),
});
type myType = z.infer<typeof myType>;
expectTypeOf<myType>().toEqualTypeOf<{
anyOptional?: any;
anyRequired: any;
unknownOptional?: unknown;
unknownRequired: unknown;
}>();
});
test("strictObject", async () => {
const strictObj = z.strictObject({
name: z.string(),
});
const syncResult = strictObj.safeParse({ name: "asdf", unexpected: 13 });
expect(syncResult.success).toEqual(false);
const asyncResult = await strictObj.spa({ name: "asdf", unexpected: 13 });
expect(asyncResult.success).toEqual(false);
});
test("object with refine", async () => {
const schema = z
.object({
a: z.string().default("foo"),
b: z.number(),
})
.refine(() => true);
expect(schema.parse({ b: 5 })).toEqual({ b: 5, a: "foo" });
const result = await schema.parseAsync({ b: 5 });
expect(result).toEqual({ b: 5, a: "foo" });
});
test("intersection of object with date", async () => {
const schema = z.object({
a: z.date(),
});
expect(z.intersection(schema, schema).parse({ a: new Date(1637353595983) })).toEqual({
a: new Date(1637353595983),
});
const result = await schema.parseAsync({ a: new Date(1637353595983) });
expect(result).toEqual({ a: new Date(1637353595983) });
});
test("intersection of object with refine with date", async () => {
const schema = z
.object({
a: z.date(),
})
.refine(() => true);
expect(z.intersection(schema, schema).parse({ a: new Date(1637353595983) })).toEqual({
a: new Date(1637353595983),
});
const result = await schema.parseAsync({ a: new Date(1637353595983) });
expect(result).toEqual({ a: new Date(1637353595983) });
});
test("constructor key", () => {
const person = z
.object({
name: z.string(),
})
.strict();
expect(() =>
person.parse({
name: "bob dylan",
constructor: 61,
})
).toThrow();
});
test("constructor key", () => {
const Example = z.object({
prop: z.string(),
opt: z.number().optional(),
arr: z.string().array(),
});
type Example = z.infer<typeof Example>;
expectTypeOf<keyof Example>().toEqualTypeOf<"prop" | "opt" | "arr">();
});
test("catchall", () => {
const a = z.object({});
expect(a._zod.def.catchall).toBeUndefined();
const b = z.strictObject({});
expect(b._zod.def.catchall).toBeInstanceOf(core.$ZodNever);
const c = z.looseObject({});
expect(c._zod.def.catchall).toBeInstanceOf(core.$ZodUnknown);
const d = z.object({}).catchall(z.number());
expect(d._zod.def.catchall).toBeInstanceOf(core.$ZodNumber);
});
test("unknownkeys merging", () => {
// This one is "strict"
const a = z.looseObject({
a: z.string(),
});
const b = z.strictObject({ b: z.string() });
// incoming object overrides
const c = a.merge(b);
expect(c._zod.def.catchall).toBeInstanceOf(core.$ZodNever);
});
test("merge() throws when receiver has refinements", () => {
const a = z
.object({
password: z.string(),
confirmPassword: z.string(),
})
.refine((data) => data.password === data.confirmPassword);
const b = z.object({ email: z.string() });
expect(() => a.merge(b)).toThrow(".merge() cannot be used on object schemas containing refinements");
});
test("merge() throws when receiver has superRefine", () => {
const a = z.object({ x: z.string() }).superRefine(() => {});
const b = z.object({ y: z.number() });
expect(() => a.merge(b)).toThrow(".merge() cannot be used on object schemas containing refinements");
});
test("merge() preserves refinements on the second schema", () => {
const a = z.object({ name: z.string() });
const b = z.object({ age: z.number() }).refine((data) => data.age >= 18, { message: "Must be 18+" });
const merged = a.merge(b);
expect(merged.parse({ name: "n", age: 21 })).toEqual({ name: "n", age: 21 });
expect(() => merged.parse({ name: "n", age: 12 })).toThrow("Must be 18+");
});
const personToExtend = z.object({
firstName: z.string(),
lastName: z.string(),
});
test("extend() should return schema with new key", () => {
const PersonWithNickname = personToExtend.extend({ nickName: z.string() });
type PersonWithNickname = z.infer<typeof PersonWithNickname>;
const expected = { firstName: "f", nickName: "n", lastName: "l" };
const actual = PersonWithNickname.parse(expected);
expect(actual).toEqual(expected);
expectTypeOf<keyof PersonWithNickname>().toEqualTypeOf<"firstName" | "lastName" | "nickName">();
expectTypeOf<PersonWithNickname>().toEqualTypeOf<{ firstName: string; lastName: string; nickName: string }>();
});
test("extend() should have power to override existing key", () => {
const PersonWithNumberAsLastName = personToExtend.extend({
lastName: z.number(),
});
type PersonWithNumberAsLastName = z.infer<typeof PersonWithNumberAsLastName>;
const expected = { firstName: "f", lastName: 42 };
const actual = PersonWithNumberAsLastName.parse(expected);
expect(actual).toEqual(expected);
expectTypeOf<PersonWithNumberAsLastName>().toEqualTypeOf<{ firstName: string; lastName: number }>();
});
test("safeExtend() should have power to override existing key", () => {
const PersonWithMinLastName = personToExtend.safeExtend({
lastName: z.string().min(3),
});
type PersonWithMinLastName = z.infer<typeof PersonWithMinLastName>;
const expected = { firstName: "f", lastName: "abc" };
const actual = PersonWithMinLastName.parse(expected);
expect(actual).toEqual(expected);
expect(() => PersonWithMinLastName.parse({ firstName: "f", lastName: "ab" })).toThrow();
expectTypeOf<PersonWithMinLastName>().toEqualTypeOf<{ firstName: string; lastName: string }>();
});
test("safeExtend() maintains refinements", () => {
const schema = z.object({ name: z.string().min(1) });
const extended = schema.safeExtend({ name: z.string().min(2) });
expect(() => extended.parse({ name: "" })).toThrow();
expect(extended.parse({ name: "ab" })).toEqual({ name: "ab" });
type Extended = z.infer<typeof extended>;
expectTypeOf<Extended>().toEqualTypeOf<{ name: string }>();
// @ts-expect-error
schema.safeExtend({ name: z.number() });
});
test("passthrough index signature", () => {
const a = z.object({ a: z.string() });
type a = z.infer<typeof a>;
expectTypeOf<a>().toEqualTypeOf<{ a: string }>();
const b = a.passthrough();
type b = z.infer<typeof b>;
expectTypeOf<b>().toEqualTypeOf<{ a: string; [k: string]: unknown }>();
});
// test("xor", () => {
// type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
// type XOR<T, U> = T extends object ? (U extends object ? (Without<T, U> & U) | (Without<U, T> & T) : U) : T;
// type A = { name: string; a: number };
// type B = { name: string; b: number };
// type C = XOR<A, B>;
// type Outer = { data: C };
// const Outer = z.object({
// data: z.union([z.object({ name: z.string(), a: z.number() }), z.object({ name: z.string(), b: z.number() })]),
// }) satisfies z.ZodType<Outer, any>;
// });
test("assignability", () => {
z.object({ a: z.string() }) satisfies z.ZodObject<{ a: z.ZodString }>;
z.object({ a: z.string() }).catchall(z.number()) satisfies z.ZodObject<{ a: z.ZodString }>;
z.object({ a: z.string() }).strict() satisfies z.ZodObject;
z.object({}) satisfies z.ZodObject;
z.looseObject({ name: z.string() }) satisfies z.ZodObject<
{
name: z.ZodString;
},
z.core.$loose
>;
z.looseObject({ name: z.string() }) satisfies z.ZodObject<{
name: z.ZodString;
}>;
z.strictObject({ name: z.string() }) satisfies z.ZodObject<
{
name: z.ZodString;
},
z.core.$loose
>;
z.strictObject({ name: z.string() }) satisfies z.ZodObject<
{
name: z.ZodString;
},
z.core.$strict
>;
z.object({ name: z.string() }) satisfies z.ZodObject<{
name: z.ZodString;
}>;
z.object({
a: z.string(),
b: z.number(),
c: z.boolean(),
}) satisfies z.core.$ZodObject;
});
test("null prototype", () => {
const schema = z.object({ a: z.string() });
const obj = Object.create(null);
obj.a = "foo";
expect(schema.parse(obj)).toEqual({ a: "foo" });
});
test("empty objects", () => {
const A = z.looseObject({});
type Ain = z.input<typeof A>;
expectTypeOf<Ain>().toEqualTypeOf<Record<string, unknown>>();
type Aout = z.output<typeof A>;
expectTypeOf<Aout>().toEqualTypeOf<Record<string, unknown>>();
const B = z.object({});
type Bout = z.output<typeof B>;
expectTypeOf<Bout>().toEqualTypeOf<Record<string, never>>();
type Bin = z.input<typeof B>;
expectTypeOf<Bin>().toEqualTypeOf<Record<string, never>>();
const C = z.strictObject({});
type Cout = z.output<typeof C>;
expectTypeOf<Cout>().toEqualTypeOf<Record<string, never>>();
type Cin = z.input<typeof C>;
expectTypeOf<Cin>().toEqualTypeOf<Record<string, never>>();
});
test("preserve key order", () => {
const schema = z.object({
a: z.string().optional(),
b: z.string(),
});
const r1 = schema.safeParse({ a: "asdf", b: "qwer" });
const r2 = schema.safeParse({ a: "asdf", b: "qwer" }, { jitless: true });
expect(Object.keys(r1.data!)).toMatchInlineSnapshot(`
[
"a",
"b",
]
`);
expect(Object.keys(r1.data!)).toEqual(Object.keys(r2.data!));
});
test("empty shape", () => {
const a = z.object({});
a.parse({});
a.parse({}, { jitless: true });
a.parse(Object.create(null));
a.parse(Object.create(null), { jitless: true });
expect(() => a.parse([])).toThrow();
expect(() => a.parse([], { jitless: true })).toThrow();
});
test("zodtype assignability", () => {
// Does not error
z.object({ hello: z.string().optional() }) satisfies z.ZodType<{ hello?: string | undefined }>;
z.object({ hello: z.string() }) satisfies z.ZodType<{ hello?: string | undefined }>;
// @ts-expect-error
z.object({}) satisfies z.ZodType<{ hello: string | undefined }>;
// @ts-expect-error
z.object({ hello: z.string().optional() }) satisfies z.ZodType<{ hello: string | undefined }>;
// @ts-expect-error
z.object({ hello: z.string().optional() }) satisfies z.ZodType<{ hello: string }>;
// @ts-expect-error
z.object({ hello: z.number() }) satisfies z.ZodType<{ hello?: string | undefined }>;
});
test("index signature in shape", () => {
function makeZodObj<const T extends string>(key: T) {
return z.looseObject({
[key]: z.string(),
});
}
const schema = makeZodObj("foo");
type schema = z.infer<typeof schema>;
expectTypeOf<schema>().toEqualTypeOf<Record<string, string>>();
});
test("extend() on object with refinements should throw when overwriting properties", () => {
const schema = z
.object({
a: z.string(),
})
.refine(() => true);
expect(() => schema.extend({ a: z.number() })).toThrow();
});
test("extend() on object with refinements should not throw when adding new properties", () => {
const schema = z
.object({
a: z.string(),
})
.refine((data) => data.a.length > 0);
// Should not throw since 'b' doesn't overlap with 'a'
const extended = schema.extend({ b: z.number() });
// Verify the extended schema works correctly
expect(extended.parse({ a: "hello", b: 42 })).toEqual({ a: "hello", b: 42 });
// Verify the original refinement still applies
expect(() => extended.parse({ a: "", b: 42 })).toThrow();
});
test("safeExtend() on object with refinements should not throw", () => {
const schema = z
.object({
a: z.string(),
})
.refine(() => true);
expect(() => schema.safeExtend({ b: z.string() })).not.toThrow();
});
// __proto__ in input must not replace the prototype of the parsed object via
// the assignment setter on the result {}.
// https://github.com/colinhacks/zod/security/advisories/GHSA-r34p-xfmx-58wv
// https://github.com/colinhacks/zod/security/advisories/GHSA-84jv-fqfx-wxhr
describe("__proto__ in object catchall paths", () => {
const protoInput = () => JSON.parse('{"__proto__":{"isAdmin":true},"name":"alice"}');
test("looseObject drops __proto__ and preserves Object.prototype", () => {
const schema = z.looseObject({ name: z.string() });
const parsed = schema.parse(protoInput());
expect(Object.keys(parsed)).toEqual(["name"]);
expect((parsed as any).isAdmin).toBeUndefined();
expect(Object.getPrototypeOf(parsed)).toBe(Object.prototype);
});
test("passthrough drops __proto__", () => {
const schema = z.object({ name: z.string() }).passthrough();
const parsed = schema.parse(protoInput());
expect((parsed as any).isAdmin).toBeUndefined();
expect(Object.getPrototypeOf(parsed)).toBe(Object.prototype);
});
test("catchall(unknown) drops __proto__", () => {
const schema = z.object({ name: z.string() }).catchall(z.unknown());
const parsed = schema.parse(protoInput());
expect((parsed as any).isAdmin).toBeUndefined();
expect(Object.getPrototypeOf(parsed)).toBe(Object.prototype);
});
test("safeParseAsync + jitless drops __proto__", async () => {
const schema = z.looseObject({ name: z.string() });
const result = await schema.safeParseAsync(protoInput(), { jitless: true } as any);
expect(result.success).toBe(true);
if (result.success) {
expect((result.data as any).isAdmin).toBeUndefined();
expect(Object.getPrototypeOf(result.data)).toBe(Object.prototype);
}
});
test("strict does not surface __proto__ as unrecognized", () => {
const schema = z.object({ name: z.string() }).strict();
const result = schema.safeParse(protoInput());
expect(result.success).toBe(true);
});
});

View File

@@ -0,0 +1,14 @@
/* eslint-disable no-new-func, camelcase */
/* globals __non_webpack__require__ */
const realImport = new Function('modulePath', 'return import(modulePath)')
function realRequire(modulePath) {
if (typeof __non_webpack__require__ === 'function') {
return __non_webpack__require__(modulePath)
}
return require(modulePath)
}
module.exports = { realImport, realRequire }

View File

@@ -0,0 +1,381 @@
import { expect, test } from "vitest";
import * as z from "zod/v4";
/// string
const stringSchema = z.string();
test("string async parse", async () => {
const goodData = "XXX";
const badData = 12;
const goodResult = await stringSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await stringSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// number
const numberSchema = z.number();
test("number async parse", async () => {
const goodData = 1234.2353;
const badData = "1234";
const goodResult = await numberSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await numberSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// bigInt
const bigIntSchema = z.bigint();
test("bigInt async parse", async () => {
const goodData = BigInt(145);
const badData = 134;
const goodResult = await bigIntSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await bigIntSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// boolean
const booleanSchema = z.boolean();
test("boolean async parse", async () => {
const goodData = true;
const badData = 1;
const goodResult = await booleanSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await booleanSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// date
const dateSchema = z.date();
test("date async parse", async () => {
const goodData = new Date();
const badData = new Date().toISOString();
const goodResult = await dateSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await dateSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// undefined
const undefinedSchema = z.undefined();
test("undefined async parse", async () => {
const goodData = undefined;
const badData = "XXX";
const goodResult = await undefinedSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(undefined);
const badResult = await undefinedSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// null
const nullSchema = z.null();
test("null async parse", async () => {
const goodData = null;
const badData = undefined;
const goodResult = await nullSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await nullSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// any
const anySchema = z.any();
test("any async parse", async () => {
const goodData = [{}];
// const badData = 'XXX';
const goodResult = await anySchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
// const badResult = await anySchema.safeParseAsync(badData);
// expect(badResult.success).toBe(false);
// if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// unknown
const unknownSchema = z.unknown();
test("unknown async parse", async () => {
const goodData = ["asdf", 124, () => {}];
// const badData = 'XXX';
const goodResult = await unknownSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
// const badResult = await unknownSchema.safeParseAsync(badData);
// expect(badResult.success).toBe(false);
// if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// void
const voidSchema = z.void();
test("void async parse", async () => {
const goodData = undefined;
const badData = 0;
const goodResult = await voidSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await voidSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// array
const arraySchema = z.array(z.string());
test("array async parse", async () => {
const goodData = ["XXX"];
const badData = "XXX";
const goodResult = await arraySchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await arraySchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// object
const objectSchema = z.object({ string: z.string() });
test("object async parse", async () => {
const goodData = { string: "XXX" };
const badData = { string: 12 };
const goodResult = await objectSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await objectSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// union
const unionSchema = z.union([z.string(), z.undefined()]);
test("union async parse", async () => {
const goodData = undefined;
const badData = null;
const goodResult = await unionSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await unionSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// record
const recordSchema = z.record(z.string(), z.object({}));
test("record async parse", async () => {
const goodData = { adsf: {}, asdf: {} };
const badData = [{}];
const goodResult = await recordSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await recordSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// function
// const functionSchema = z.function();
// test("function async parse", async () => {
// const goodData = () => {};
// const badData = "XXX";
// const goodResult = await functionSchema.safeParseAsync(goodData);
// expect(goodResult.success).toBe(true);
// if (goodResult.success) expect(typeof goodResult.data).toEqual("function");
// const badResult = await functionSchema.safeParseAsync(badData);
// expect(badResult.success).toBe(false);
// if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
// });
/// literal
const literalSchema = z.literal("asdf");
test("literal async parse", async () => {
const goodData = "asdf";
const badData = "asdff";
const goodResult = await literalSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await literalSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// enum
const enumSchema = z.enum(["fish", "whale"]);
test("enum async parse", async () => {
const goodData = "whale";
const badData = "leopard";
const goodResult = await enumSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await enumSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// nativeEnum
enum nativeEnumTest {
asdf = "qwer",
}
// @ts-ignore
const nativeEnumSchema = z.nativeEnum(nativeEnumTest);
test("nativeEnum async parse", async () => {
const goodData = nativeEnumTest.asdf;
const badData = "asdf";
const goodResult = await nativeEnumSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await nativeEnumSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// promise
const promiseSchema = z.promise(z.number());
test("promise async parse good", async () => {
const goodData = Promise.resolve(123);
const goodResult = await promiseSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
expect(typeof goodResult.data).toEqual("number");
expect(goodResult.data).toEqual(123);
});
test("promise async parse bad", async () => {
const badData = Promise.resolve("XXX");
const badResult = await promiseSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
expect(badResult.error).toBeInstanceOf(z.ZodError);
});
test("async validation non-empty strings", async () => {
const base = z.object({
hello: z.string().refine((x) => x && x.length > 0),
foo: z.string().refine((x) => x && x.length > 0),
});
const testval = { hello: "", foo: "" };
const result1 = base.safeParse(testval);
const result2 = base.safeParseAsync(testval);
const r1 = result1;
await result2.then((r2) => {
expect(r1.error!.issues.length).toBe(r2.error!.issues.length);
});
});
test("async validation multiple errors 1", async () => {
const base = z.object({
hello: z.string(),
foo: z.number(),
});
const testval = { hello: 3, foo: "hello" };
const result1 = base.safeParse(testval);
const result2 = base.safeParseAsync(testval);
await result2.then((result2) => {
expect(result2.error!.issues.length).toBe(result1.error!.issues.length);
});
});
test("async validation multiple errors 2", async () => {
const base = (is_async?: boolean) =>
z.object({
hello: z.string(),
foo: z.object({
bar: z.number().refine(
is_async
? async () =>
new Promise((resolve) => {
setTimeout(() => resolve(false), 500);
})
: () => false
),
}),
});
const testval = { hello: 3, foo: { bar: 4 } };
const result1 = base().safeParse(testval);
const result2 = base(true).safeParseAsync(testval);
await result2.then((result2) => {
expect(result1.error!.issues.length).toBe(result2.error!.issues.length);
});
});
test("ensure early async failure prevents follow-up refinement checks", async () => {
let count = 0;
const base = z.object({
hello: z.string(),
foo: z
.number()
.refine(async () => {
count++;
return true;
})
.refine(async () => {
count++;
return true;
}, "Good"),
});
const testval = { hello: "bye", foo: 3 };
const result = await base.safeParseAsync(testval);
if (result.success === false) {
expect(result.error.issues.length).toBe(1);
expect(count).toBe(1);
}
// await result.then((r) => {
// if (r.success === false) expect(r.error.issues.length).toBe(1);
// expect(count).toBe(2);
// });
});

View File

@@ -0,0 +1 @@
{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;;;;;;;;GAkBG;AAEI,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,IAAI,MACgD,EAAE,EACxE,EAAE;IACF,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,oBAAoB,CAAC,CAAC;YACzB,CAAC,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC;YAClC,CAAC,CAAC,CAAC;iBACE,OAAO,CAAC,0BAA0B,EAAE,MAAM,CAAC;iBAC3C,OAAO,CAAC,WAAW,EAAE,IAAI,CAAC,CAAA;IACnC,CAAC;IACD,OAAO,oBAAoB,CAAC,CAAC;QACzB,CAAC,CAAC,OAAO,CAAC,iBAAiB,EAAE,IAAI,CAAC;QACpC,CAAC,CAAC,CAAC;aACE,OAAO,CAAC,4BAA4B,EAAE,MAAM,CAAC;aAC7C,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA;AAnBY,QAAA,QAAQ,YAmBpB","sourcesContent":["import type { MinimatchOptions } from './index.js'\n\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then\n * square-bracket escapes are removed, but not backslash escapes.\n *\n * For example, it will turn the string `'[*]'` into `*`, but it will not\n * turn `'\\\\*'` into `'*'`, because `\\` is a path separator in\n * `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n *\n * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be\n * unescaped.\n */\n\nexport const unescape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n magicalBraces = true,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape' | 'magicalBraces'> = {},\n) => {\n if (magicalBraces) {\n return windowsPathsNoEscape ?\n s.replace(/\\[([^/\\\\])\\]/g, '$1')\n : s\n .replace(/((?!\\\\).|^)\\[([^/\\\\])\\]/g, '$1$2')\n .replace(/\\\\([^/])/g, '$1')\n }\n return windowsPathsNoEscape ?\n s.replace(/\\[([^/\\\\{}])\\]/g, '$1')\n : s\n .replace(/((?!\\\\).|^)\\[([^/\\\\{}])\\]/g, '$1$2')\n .replace(/\\\\([^/{}])/g, '$1')\n}\n"]}

View File

@@ -0,0 +1,270 @@
'use strict';
var URI = require('uri-js')
, equal = require('fast-deep-equal')
, util = require('./util')
, SchemaObject = require('./schema_obj')
, traverse = require('json-schema-traverse');
module.exports = resolve;
resolve.normalizeId = normalizeId;
resolve.fullPath = getFullPath;
resolve.url = resolveUrl;
resolve.ids = resolveIds;
resolve.inlineRef = inlineRef;
resolve.schema = resolveSchema;
/**
* [resolve and compile the references ($ref)]
* @this Ajv
* @param {Function} compile reference to schema compilation funciton (localCompile)
* @param {Object} root object with information about the root schema for the current schema
* @param {String} ref reference to resolve
* @return {Object|Function} schema object (if the schema can be inlined) or validation function
*/
function resolve(compile, root, ref) {
/* jshint validthis: true */
var refVal = this._refs[ref];
if (typeof refVal == 'string') {
if (this._refs[refVal]) refVal = this._refs[refVal];
else return resolve.call(this, compile, root, refVal);
}
refVal = refVal || this._schemas[ref];
if (refVal instanceof SchemaObject) {
return inlineRef(refVal.schema, this._opts.inlineRefs)
? refVal.schema
: refVal.validate || this._compile(refVal);
}
var res = resolveSchema.call(this, root, ref);
var schema, v, baseId;
if (res) {
schema = res.schema;
root = res.root;
baseId = res.baseId;
}
if (schema instanceof SchemaObject) {
v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
} else if (schema !== undefined) {
v = inlineRef(schema, this._opts.inlineRefs)
? schema
: compile.call(this, schema, root, undefined, baseId);
}
return v;
}
/**
* Resolve schema, its root and baseId
* @this Ajv
* @param {Object} root root object with properties schema, refVal, refs
* @param {String} ref reference to resolve
* @return {Object} object with properties schema, root, baseId
*/
function resolveSchema(root, ref) {
/* jshint validthis: true */
var p = URI.parse(ref)
, refPath = _getFullPath(p)
, baseId = getFullPath(this._getId(root.schema));
if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
var id = normalizeId(refPath);
var refVal = this._refs[id];
if (typeof refVal == 'string') {
return resolveRecursive.call(this, root, refVal, p);
} else if (refVal instanceof SchemaObject) {
if (!refVal.validate) this._compile(refVal);
root = refVal;
} else {
refVal = this._schemas[id];
if (refVal instanceof SchemaObject) {
if (!refVal.validate) this._compile(refVal);
if (id == normalizeId(ref))
return { schema: refVal, root: root, baseId: baseId };
root = refVal;
} else {
return;
}
}
if (!root.schema) return;
baseId = getFullPath(this._getId(root.schema));
}
return getJsonPointer.call(this, p, baseId, root.schema, root);
}
/* @this Ajv */
function resolveRecursive(root, ref, parsedRef) {
/* jshint validthis: true */
var res = resolveSchema.call(this, root, ref);
if (res) {
var schema = res.schema;
var baseId = res.baseId;
root = res.root;
var id = this._getId(schema);
if (id) baseId = resolveUrl(baseId, id);
return getJsonPointer.call(this, parsedRef, baseId, schema, root);
}
}
var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
/* @this Ajv */
function getJsonPointer(parsedRef, baseId, schema, root) {
/* jshint validthis: true */
parsedRef.fragment = parsedRef.fragment || '';
if (parsedRef.fragment.slice(0,1) != '/') return;
var parts = parsedRef.fragment.split('/');
for (var i = 1; i < parts.length; i++) {
var part = parts[i];
if (part) {
part = util.unescapeFragment(part);
schema = schema[part];
if (schema === undefined) break;
var id;
if (!PREVENT_SCOPE_CHANGE[part]) {
id = this._getId(schema);
if (id) baseId = resolveUrl(baseId, id);
if (schema.$ref) {
var $ref = resolveUrl(baseId, schema.$ref);
var res = resolveSchema.call(this, root, $ref);
if (res) {
schema = res.schema;
root = res.root;
baseId = res.baseId;
}
}
}
}
}
if (schema !== undefined && schema !== root.schema)
return { schema: schema, root: root, baseId: baseId };
}
var SIMPLE_INLINED = util.toHash([
'type', 'format', 'pattern',
'maxLength', 'minLength',
'maxProperties', 'minProperties',
'maxItems', 'minItems',
'maximum', 'minimum',
'uniqueItems', 'multipleOf',
'required', 'enum'
]);
function inlineRef(schema, limit) {
if (limit === false) return false;
if (limit === undefined || limit === true) return checkNoRef(schema);
else if (limit) return countKeys(schema) <= limit;
}
function checkNoRef(schema) {
var item;
if (Array.isArray(schema)) {
for (var i=0; i<schema.length; i++) {
item = schema[i];
if (typeof item == 'object' && !checkNoRef(item)) return false;
}
} else {
for (var key in schema) {
if (key == '$ref') return false;
item = schema[key];
if (typeof item == 'object' && !checkNoRef(item)) return false;
}
}
return true;
}
function countKeys(schema) {
var count = 0, item;
if (Array.isArray(schema)) {
for (var i=0; i<schema.length; i++) {
item = schema[i];
if (typeof item == 'object') count += countKeys(item);
if (count == Infinity) return Infinity;
}
} else {
for (var key in schema) {
if (key == '$ref') return Infinity;
if (SIMPLE_INLINED[key]) {
count++;
} else {
item = schema[key];
if (typeof item == 'object') count += countKeys(item) + 1;
if (count == Infinity) return Infinity;
}
}
}
return count;
}
function getFullPath(id, normalize) {
if (normalize !== false) id = normalizeId(id);
var p = URI.parse(id);
return _getFullPath(p);
}
function _getFullPath(p) {
return URI.serialize(p).split('#')[0] + '#';
}
var TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
}
function resolveUrl(baseId, id) {
id = normalizeId(id);
return URI.resolve(baseId, id);
}
/* @this Ajv */
function resolveIds(schema) {
var schemaId = normalizeId(this._getId(schema));
var baseIds = {'': schemaId};
var fullPaths = {'': getFullPath(schemaId, false)};
var localRefs = {};
var self = this;
traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
if (jsonPtr === '') return;
var id = self._getId(sch);
var baseId = baseIds[parentJsonPtr];
var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
if (keyIndex !== undefined)
fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));
if (typeof id == 'string') {
id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);
var refVal = self._refs[id];
if (typeof refVal == 'string') refVal = self._refs[refVal];
if (refVal && refVal.schema) {
if (!equal(sch, refVal.schema))
throw new Error('id "' + id + '" resolves to more than one schema');
} else if (id != normalizeId(fullPath)) {
if (id[0] == '#') {
if (localRefs[id] && !equal(sch, localRefs[id]))
throw new Error('id "' + id + '" resolves to more than one schema');
localRefs[id] = sch;
} else {
self._refs[id] = fullPath;
}
}
}
baseIds[jsonPtr] = baseId;
fullPaths[jsonPtr] = fullPath;
});
return localRefs;
}

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2014-2022 Matteo Collina
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const esnext_weakref: LibDefinition;

View File

@@ -0,0 +1,2 @@
export { G as GlobalConstructors, M as MockObjectOptions, m as mockObject } from './index.d-B41z0AuW.js';
export { A as AutomockedModule, g as AutomockedModuleSerialized, h as AutospiedModule, i as AutospiedModuleSerialized, j as ManualMockedModule, k as ManualMockedModuleSerialized, a as MockedModule, l as MockedModuleSerialized, d as MockedModuleType, M as MockerRegistry, e as ModuleMockContext, m as ModuleMockFactory, c as ModuleMockFactoryWithHelper, b as ModuleMockOptions, R as RedirectedModule, n as RedirectedModuleSerialized, f as ServerIdResolution, S as ServerMockResolution, T as TestModuleMocker } from './types.d-BjI5eAwu.js';

View File

@@ -0,0 +1,137 @@
export type BuiltInMergeStrategy = $typests.BuiltInMergeStrategy;
export type BuiltInValidationStrategy = $typests.BuiltInValidationStrategy;
export type CustomMergeStrategy = $typests.CustomMergeStrategy;
export type CustomValidationStrategy = $typests.CustomValidationStrategy;
export type ObjectDefinition = $typests.ObjectDefinition;
export type PropertyDefinition = $typests.PropertyDefinition;
export type PropertyDefinitionWithSchema = $typests.PropertyDefinitionWithSchema;
export type PropertyDefinitionWithStrategies = $typests.PropertyDefinitionWithStrategies;
/**
* @fileoverview Merge Strategy
*/
/**
* Container class for several different merge strategies.
*/
export class MergeStrategy {
/**
* Merges two keys by overwriting the first with the second.
* @template TValue1 The type of the value from the first object key.
* @template TValue2 The type of the value from the second object key.
* @param {TValue1} value1 The value from the first object key.
* @param {TValue2} value2 The value from the second object key.
* @returns {TValue2} The second value.
*/
static overwrite<TValue1, TValue2>(value1: TValue1, value2: TValue2): TValue2;
/**
* Merges two keys by replacing the first with the second only if the
* second is defined.
* @template TValue1 The type of the value from the first object key.
* @template TValue2 The type of the value from the second object key.
* @param {TValue1} value1 The value from the first object key.
* @param {TValue2} value2 The value from the second object key.
* @returns {TValue1 | TValue2} The second value if it is defined.
*/
static replace<TValue1, TValue2>(value1: TValue1, value2: TValue2): TValue1 | TValue2;
/**
* Merges two properties by assigning properties from the second to the first.
* @template {Record<string | number | symbol, unknown> | undefined} TValue1 The type of the value from the first object key.
* @template {Record<string | number | symbol, unknown>} TValue2 The type of the value from the second object key.
* @param {TValue1} value1 The value from the first object key.
* @param {TValue2} value2 The value from the second object key.
* @returns {Omit<TValue1, keyof TValue2> & TValue2} A new object containing properties from both value1 and
* value2.
*/
static assign<TValue1 extends Record<string | number | symbol, unknown> | undefined, TValue2 extends Record<string | number | symbol, unknown>>(value1: TValue1, value2: TValue2): Omit<TValue1, keyof TValue2> & TValue2;
}
/**
* Represents an object validation/merging schema.
*/
export class ObjectSchema {
/**
* Creates a new instance.
* @param {ObjectDefinition} definitions The schema definitions.
* @throws {Error} When the definitions are missing or invalid.
*/
constructor(definitions: ObjectDefinition);
/**
* Determines if a strategy has been registered for the given object key.
* @param {string} key The object key to find a strategy for.
* @returns {boolean} True if the key has a strategy registered, false if not.
*/
hasKey(key: string): boolean;
/**
* Merges objects together to create a new object comprised of the keys
* of the all objects. Keys are merged based on the each key's merge
* strategy.
* @param {...Object} objects The objects to merge.
* @returns {Object} A new object with a mix of all objects' keys.
* @throws {TypeError} If any object is invalid.
*/
merge(...objects: any[]): any;
/**
* Validates an object's keys based on the validate strategy for each key.
* @param {Object} object The object to validate.
* @returns {void}
* @throws {Error} When the object is invalid.
*/
validate(object: any): void;
#private;
}
/**
* @fileoverview Validation Strategy
*/
/**
* Container class for several different validation strategies.
*/
export class ValidationStrategy {
/**
* Validates that a value is an array.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static array(value: unknown): void;
/**
* Validates that a value is a boolean.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static boolean(value: unknown): void;
/**
* Validates that a value is a number.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static number(value: unknown): void;
/**
* Validates that a value is an object.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static object(value: unknown): void;
/**
* Validates that a value is an object or null.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static "object?"(value: unknown): void;
/**
* Validates that a value is a string.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static string(value: unknown): void;
/**
* Validates that a value is a non-empty string.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static "string!"(value: unknown): void;
}
import type * as $typests from "./types.ts";

View File

@@ -0,0 +1,41 @@
export type Options = {
/**
Strip trailing commas in addition to comments.
@default false
*/
readonly trailingCommas?: boolean;
/**
Replace comments and trailing commas with whitespace instead of stripping them entirely.
@default true
*/
readonly whitespace?: boolean;
};
/**
Strip comments from JSON. Lets you use comments in your JSON files!
It will replace single-line comments `//` and multi-line comments `/**\/` with whitespace. This allows JSON error positions to remain as close as possible to the original source.
@param jsonString - Accepts a string with JSON.
@returns A JSON string without comments.
@example
```
import stripJsonComments from 'strip-json-comments';
const json = `{
// Rainbows
"unicorn": "cake"
}`;
JSON.parse(stripJsonComments(json));
//=> {unicorn: 'cake'}
```
*/
export default function stripJsonComments(
jsonString: string,
options?: Options
): string;

View File

@@ -0,0 +1,47 @@
export declare function scrypt(password: string, salt: string): Uint8Array;
export declare function pbkdf2(password: string, salt: string): Uint8Array;
/**
* Derives main seed. Takes a lot of time. Prefer `eskdf` method instead.
*/
export declare function deriveMainSeed(username: string, password: string): Uint8Array;
type AccountID = number | string;
type OptsLength = {
keyLength: number;
};
type OptsMod = {
modulus: bigint;
};
type KeyOpts = undefined | OptsLength | OptsMod;
export interface ESKDF {
/**
* Derives a child key. Child key will not be associated with any
* other child key because of properties of underlying KDF.
*
* @param protocol - 3-15 character protocol name
* @param accountId - numeric identifier of account
* @param options - `keyLength: 64` or `modulus: 41920438n`
* @example deriveChildKey('aes', 0)
*/
deriveChildKey: (protocol: string, accountId: AccountID, options?: KeyOpts) => Uint8Array;
/**
* Deletes the main seed from eskdf instance
*/
expire: () => void;
/**
* Account fingerprint
*/
fingerprint: string;
}
/**
* ESKDF
* @param username - username, email, or identifier, min: 8 characters, should have enough entropy
* @param password - password, min: 8 characters, should have enough entropy
* @example
* const kdf = await eskdf('example-university', 'beginning-new-example');
* const key = kdf.deriveChildKey('aes', 0);
* console.log(kdf.fingerprint);
* kdf.expire();
*/
export declare function eskdf(username: string, password: string): Promise<ESKDF>;
export {};
//# sourceMappingURL=eskdf.d.ts.map

View File

@@ -0,0 +1,91 @@
{
"name": "rpc-websockets",
"version": "9.3.9",
"description": "JSON-RPC 2.0 implementation over WebSockets for Node.js",
"exports": {
"browser": {
"import": "./dist/index.browser.mjs",
"require": "./dist/index.browser.cjs"
},
"node": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"browser": {
"./dist/index.cjs": "./dist/index.browser.cjs",
"./dist/index.mjs": "./dist/index.browser.mjs"
},
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"type": "commonjs",
"files": [
"dist/"
],
"scripts": {
"build": "npm run typecheck && mkdir -p ./dist && eslint --fix './src/**/*.ts' && tsup",
"typecheck": "tsc",
"pretest": "npm run-script build",
"test": "mocha --exit test/*spec.js",
"test:client": "mocha --exit test/client.spec.js",
"test:server": "mocha --exit test/server.spec.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/elpheria/rpc-websockets.git"
},
"dependencies": {
"@swc/helpers": "^0.5.11",
"@types/uuid": "^10.0.0",
"@types/ws": "^8.2.2",
"buffer": "^6.0.3",
"eventemitter3": "^5.0.1",
"uuid": "^14.0.0",
"ws": "^8.5.0"
},
"optionalDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": "^6.0.0"
},
"devDependencies": {
"@microsoft/api-extractor": "^7.58.2",
"@typescript-eslint/eslint-plugin": "^8.0.0",
"@typescript-eslint/parser": "^8.0.0",
"async": "^3.2.3",
"chai": "^6.0.0",
"esbuild-plugin-polyfill-node": "^0.3.0",
"eslint": "^8.57.0",
"istanbul": "^0.4.5",
"mocha": "^11.3.0",
"mocha-lcov-reporter": "^1.3.0",
"tsup": "^8.1.0",
"typescript": "^5.0.0",
"url": "^0.11.3"
},
"keywords": [
"json",
"rpc",
"websocket",
"ws",
"client",
"server"
],
"author": "Elpheria",
"license": "LGPL-3.0-only",
"bugs": {
"url": "https://github.com/elpheria/rpc-websockets/issues"
},
"homepage": "https://github.com/elpheria/rpc-websockets#readme",
"funding": {
"type": "paypal",
"url": "https://paypal.me/kozjak"
},
"overrides": {
"form-data": "4.0.4",
"diff": "^8.0.2",
"minimatch": "^10.2.4",
"serialize-javascript": "^7.0.3",
"validator": "^13.15.26"
}
}

View File

@@ -0,0 +1,87 @@
import type { NodeWithParent, TSESTree } from '@typescript-eslint/types';
import type { Scope } from '../scope';
import type { Variable } from '../variable';
export declare enum ReferenceFlag {
Read = 1,
Write = 2,
ReadWrite = 3
}
export interface ReferenceImplicitGlobal {
node: NodeWithParent;
pattern: TSESTree.BindingName;
ref?: Reference;
}
export declare enum ReferenceTypeFlag {
Value = 1,
Type = 2
}
/**
* A Reference represents a single occurrence of an identifier in code.
*/
export declare class Reference {
#private;
/**
* A unique ID for this instance - primarily used to help debugging and testing
*/
readonly $id: number;
/**
* Reference to the enclosing Scope.
* @public
*/
readonly from: Scope;
/**
* Identifier syntax node.
* @public
*/
readonly identifier: TSESTree.Identifier | TSESTree.JSXIdentifier;
/**
* `true` if this writing reference is a variable initializer or a default value.
* @public
*/
readonly init?: boolean;
readonly maybeImplicitGlobal?: ReferenceImplicitGlobal | null;
/**
* The {@link Variable} object that this reference refers to. If such variable was not defined, this is `null`.
* @public
*/
resolved: Variable | null;
/**
* If reference is writeable, this is the node being written to it.
* @public
*/
readonly writeExpr?: TSESTree.Node | null;
constructor(identifier: TSESTree.Identifier | TSESTree.JSXIdentifier, scope: Scope, flag: ReferenceFlag, writeExpr?: TSESTree.Node | null, maybeImplicitGlobal?: ReferenceImplicitGlobal | null, init?: boolean, referenceType?: ReferenceTypeFlag);
/**
* True if this reference can reference types
*/
get isTypeReference(): boolean;
/**
* True if this reference can reference values
*/
get isValueReference(): boolean;
/**
* Whether the reference is writeable.
* @public
*/
isWrite(): boolean;
/**
* Whether the reference is readable.
* @public
*/
isRead(): boolean;
/**
* Whether the reference is read-only.
* @public
*/
isReadOnly(): boolean;
/**
* Whether the reference is write-only.
* @public
*/
isWriteOnly(): boolean;
/**
* Whether the reference is read-write.
* @public
*/
isReadWrite(): boolean;
}

View File

@@ -0,0 +1,33 @@
{
"name": "once",
"version": "1.4.0",
"description": "Run a function exactly one time",
"main": "once.js",
"directories": {
"test": "test"
},
"dependencies": {
"wrappy": "1"
},
"devDependencies": {
"tap": "^7.0.1"
},
"scripts": {
"test": "tap test/*.js"
},
"files": [
"once.js"
],
"repository": {
"type": "git",
"url": "git://github.com/isaacs/once"
},
"keywords": [
"once",
"function",
"one",
"single"
],
"author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)",
"license": "ISC"
}

View File

@@ -0,0 +1,21 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare namespace Intl {
// Empty
}

View File

@@ -0,0 +1,5 @@
var setPrototypeOf = require("./setPrototypeOf.js");
function _inheritsLoose(t, o) {
t.prototype = Object.create(o.prototype), t.prototype.constructor = t, setPrototypeOf(t, o);
}
module.exports = _inheritsLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;