some updates

This commit is contained in:
2024-04-05 18:04:29 +02:00
parent 45decc60a7
commit e82b753dfb
19 changed files with 5343 additions and 17922 deletions

8124
backend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -14,7 +14,7 @@
},
"license": "MIT",
"dependencies": {
"@koa/cors": "^4.0.0",
"@koa/cors": "^5",
"@koa/router": "^12.0.0",
"bcrypt": "^5.1.0",
"class-validator": "^0.14.0",
@@ -43,16 +43,17 @@
"@types/deasync": "^0.1.2",
"@types/eslint": "^8.44.1",
"@types/eslint-config-prettier": "^6.11.0",
"@types/eslint-plugin-mocha": "^10.4.0",
"@types/eslint-plugin-prettier": "^3.1.0",
"@types/hasha": "^3.0.1",
"@types/jsonwebtoken": "^9.0.2",
"@types/koa": "^2.13.7",
"@types/koa__cors": "^4.0.0",
"@types/koa__router": "^12.0.0",
"@types/koa-logger": "^3.1.2",
"@types/koa-send": "^4.1.3",
"@types/koa-sslify": "^4.0.3",
"@types/koa-static": "^4.0.2",
"@types/koa__cors": "^4.0.0",
"@types/koa__router": "^12.0.0",
"@types/mime-types": "^2.1.1",
"@types/mocha": "^10.0.1",
"@types/mysql": "^2.15.21",

View File

@@ -52,7 +52,7 @@ export async function getConfigValue(key: ConfigKey): Promise<string> {
}
try {
const pair = await Config.findOneOrFail({ key });
const pair = await Config.findOneOrFail({ key }, {});
return pair.value;
} catch (e) {
return defaultValues[key];
@@ -67,7 +67,7 @@ export async function setConfigValue(
throw new Error(`${key} is not valid config key`);
}
let pair = await Config.findOne({ key });
let pair = await Config.findOne({ key }, {});
if (!pair) {
pair = new Config(key, val);
} else {

View File

@@ -1,26 +1,26 @@
import * as Router from "@koa/router";
import { Photo } from "~entity/Photo";
import {
TPhotoReqJSON,
TPhotosNewRespBody,
TPhotoByIDDeleteRespBody,
TPhotosUploadRespBody,
TPhotosListRespBody,
TPhotosByIDGetRespBody,
TPhotosDeleteRespBody,
PhotoJSON,
PhotosDeleteBody,
PhotosListPagination,
PhotosNewPostBody,
PhotoJSON,
TPhotoByIDDeleteRespBody,
TPhotoReqJSON,
TPhotosByIDGetRespBody,
TPhotosDeleteRespBody,
TPhotosGetShowTokenByIDRespBody,
PhotosDeleteBody,
TPhotosListRespBody,
TPhotosNewRespBody,
TPhotosUploadRespBody,
} from "~/shared/types";
import send = require("koa-send");
import { getHash, getSize } from "~util";
import * as jwt from "jsonwebtoken";
import { config } from "~config";
import { ValidationError } from "class-validator";
import { In } from "typeorm";
import { IAppContext, IAppState } from "~app";
import send = require("koa-send");
export const photosRouter = new Router<IAppState, IAppContext>();
@@ -44,7 +44,7 @@ photosRouter.post("/photos/new", async (ctx: ContextType) => {
await photo.save();
} catch (e) {
if (e.code === "ER_DUP_ENTRY") {
const photo = await Photo.findOne({ hash, size, user });
const photo = await Photo.findOne({ hash, size, user }, {});
if (!photo) {
ctx.throw(404);
}
@@ -85,7 +85,7 @@ photosRouter.post("/photos/upload/:id", async (ctx: ContextType) => {
}
const { user } = ctx.state;
const photo = await Photo.findOne({ id: parseInt(id), user });
const photo = await Photo.findOne({ id: parseInt(id), user }, {});
if (!photo) {
ctx.throw(404);
}
@@ -131,47 +131,47 @@ photosRouter.post("/photos/upload/:id", async (ctx: ContextType) => {
});
/**
export interface TPhotosByIDPatchBody {
}
export type TPhotosByIDPatchRespBody = IAPIResponse<TPhotoReqJSON>;
photosRouter.patch("/photos/byID/:id", async (ctx: ContextType) => {
if (!ctx.state.user) {
ctx.throw(401);
return;
}
export interface TPhotosByIDPatchBody {
}
export type TPhotosByIDPatchRespBody = IAPIResponse<TPhotoReqJSON>;
photosRouter.patch("/photos/byID/:id", async (ctx: ContextType) => {
if (!ctx.state.user) {
ctx.throw(401);
return;
}
const { user } = ctx.state;
const { id } = ctx.params as {
id: number | undefined;
};
const { user } = ctx.state;
const { id } = ctx.params as {
id: number | undefined;
};
if (!id) {
ctx.throw(400);
return;
}
if (!id) {
ctx.throw(400);
return;
}
const photo = await Photo.findOne({ id, user });
const photo = await Photo.findOne({ id, user },{});
if (!photo) {
ctx.throw(404);
return;
}
if (!photo) {
ctx.throw(404);
return;
}
// TODO: Some actual editing
// TODO: Some actual editing
try {
photo.editedAt = new Date();
await photo.save();
} catch (e) {
ctx.throw(400);
}
try {
photo.editedAt = new Date();
await photo.save();
} catch (e) {
ctx.throw(400);
}
ctx.body = {
error: false,
data: photo.toReqJSON(),
};
});
*/
ctx.body = {
error: false,
data: photo.toReqJSON(),
};
});
*/
photosRouter.get("/photos/list", async (ctx: ContextType) => {
if (!ctx.state.user) {
@@ -229,7 +229,7 @@ photosRouter.get("/photos/byID/:id", async (ctx: ContextType) => {
const { user } = ctx.state;
const photo = await Photo.findOne({ id: parseInt(id), user });
const photo = await Photo.findOne({ id: parseInt(id), user }, {});
if (!photo) {
ctx.throw(404);
@@ -260,10 +260,13 @@ photosRouter.get("/photos/showByID/:id/:token", async (ctx: ContextType) => {
const photoReqJSON = PhotoJSON.parse(jwt.decode(token));
const { user } = photoReqJSON;
const photo = await Photo.findOne({
id: parseInt(id),
user: { id: user },
});
const photo = await Photo.findOne(
{
id: parseInt(id),
user: { id: user },
},
{},
);
if (!photo) {
ctx.throw(404);
@@ -296,7 +299,7 @@ photosRouter.get("/photos/showByID/:id", async (ctx: ContextType) => {
const { user } = ctx.state;
const photo = await Photo.findOne({ id: parseInt(id), user });
const photo = await Photo.findOne({ id: parseInt(id), user }, {});
if (!photo) {
ctx.throw(404);
@@ -329,7 +332,7 @@ photosRouter.get("/photos/getShowByIDToken/:id", async (ctx: ContextType) => {
const { user } = ctx.state;
const photo = await Photo.findOne({ id: parseInt(id), user });
const photo = await Photo.findOne({ id: parseInt(id), user }, {});
if (!photo) {
ctx.throw(404);
}
@@ -354,7 +357,7 @@ photosRouter.delete("/photos/byID/:id", async (ctx: ContextType) => {
const { user } = ctx.state;
const photo = await Photo.findOne({ id: parseInt(id), user });
const photo = await Photo.findOne({ id: parseInt(id), user }, {});
if (!photo) {
ctx.throw(404);

View File

@@ -1,18 +1,14 @@
import * as Router from "@koa/router";
import { getConfigValue, ConfigKey } from "~entity/Config";
import { ConfigKey, getConfigValue } from "~entity/Config";
import { User } from "~entity/User";
import {
TUserJWT,
TUserGetRespBody,
TUserEditRespBody,
TUserSignupBody,
TUserSignupRespBody,
TUserGetRespBody,
TUserLoginRespBody,
TUserEditBody,
TUserLoginBody,
TUserSignupRespBody,
UserEditBody,
UserLoginBody,
UserSignupBody,
UserEditBody,
} from "~/shared/types";
import { IAppContext, IAppState } from "~app";
@@ -28,7 +24,7 @@ userRouter.get("/users/user", async (ctx: ContextType) => {
}
const jwt = ctx.state.user;
const user = await User.findOne(jwt.id);
const user = await User.findOne(jwt.id, {});
if (!user) {
ctx.throw(401);
@@ -45,7 +41,7 @@ userRouter.post("/users/login", async (ctx: ContextType) => {
}
const { username, password } = UserLoginBody.parse(request.body);
const user = await User.findOne({ username });
const user = await User.findOne({ username }, {});
if (!user || !(await user.verifyPassword(password))) {
ctx.throw(404, "User not found");
}
@@ -95,7 +91,7 @@ userRouter.post("/users/edit", async (ctx: ContextType) => {
}
const jwt = ctx.state.user;
const user = await User.findOne(jwt.id);
const user = await User.findOne(jwt.id, {});
const request = ctx.request;
if (!user) {

View File

@@ -86,7 +86,9 @@ describe("photos", function () {
Authorization: `Bearer ${seed.user2.toJWT()}`,
})
.expect(200);
expect(parseInt(response.get("content-length"))).to.equal(dogFileSize);
expect(parseInt(response.get("content-length") ?? "")).to.equal(
dogFileSize,
);
});
it("should delete a photo after file has been deleted", async function () {
@@ -96,7 +98,9 @@ describe("photos", function () {
Authorization: `Bearer ${seed.user2.toJWT()}`,
})
.expect(200);
expect(parseInt(response.get("content-length"))).to.equal(dogFileSize);
expect(parseInt(response.get("content-length") ?? "")).to.equal(
dogFileSize,
);
await fs.unlink(await seed.dogPhoto.getReadyPath("original"));
await request(callback)
@@ -119,7 +123,7 @@ describe("photos", function () {
const dogSmallThumbSize = (
await fs.stat(seed.dogPhoto.getThumbPath("512"))
).size;
expect(parseInt(response.get("content-length"))).to.equal(
expect(parseInt(response.get("content-length") ?? "")).to.equal(
dogSmallThumbSize,
);
@@ -143,7 +147,7 @@ describe("photos", function () {
Authorization: `Bearer ${seed.user2.toJWT()}`,
})
.expect(200);
expect(parseInt(response.get("content-length"))).to.be.lessThan(
expect(parseInt(response.get("content-length") ?? "")).to.be.lessThan(
dogFileSize,
);
});
@@ -158,7 +162,7 @@ describe("photos", function () {
const dogSmallThumbSize = (
await fs.stat(seed.dogPhoto.getThumbPath("512"))
).size;
expect(parseInt(response.get("content-length"))).to.equal(
expect(parseInt(response.get("content-length") ?? "")).to.equal(
dogSmallThumbSize,
);
@@ -172,7 +176,7 @@ describe("photos", function () {
const dogSmallThumbSize2 = (
await fs.stat(seed.dogPhoto.getThumbPath("512"))
).size;
expect(parseInt(response.get("content-length"))).to.equal(
expect(parseInt(response.get("content-length") ?? "")).to.equal(
dogSmallThumbSize2,
);
});
@@ -198,7 +202,7 @@ describe("photos", function () {
const listAnyResp = await request(callback)
.get(`/photos/showByID/${photos[0].id}/${photos[0].accessToken}`)
.expect(200);
expect(parseInt(listAnyResp.get("content-length"))).to.be.oneOf([
expect(parseInt(listAnyResp.get("content-length") ?? "")).to.be.oneOf([
dogFileSize,
catFileSize,
]);
@@ -216,7 +220,9 @@ describe("photos", function () {
const response = await request(callback)
.get(`/photos/showByID/${seed.dogPhoto.id}/${token}`)
.expect(200);
expect(parseInt(response.get("content-length"))).to.equal(dogFileSize);
expect(parseInt(response.get("content-length") ?? "")).to.equal(
dogFileSize,
);
const tokenSelfSigned = jwt.sign(
await seed.dogPhoto.toReqJSON(),
@@ -229,7 +235,7 @@ describe("photos", function () {
const responseSS = await request(callback)
.get(`/photos/showByID/${seed.dogPhoto.id}/${tokenSelfSigned}`)
.expect(200);
expect(parseInt(responseSS.get("content-length"))).to.equal(
expect(parseInt(responseSS.get("content-length") ?? "")).to.equal(
dogFileSize,
);
});
@@ -312,7 +318,9 @@ describe("photos", function () {
})
.expect(200);
expect(parseInt(showResp.get("content-length"))).to.equal(dogFileSize);
expect(parseInt(showResp.get("content-length") ?? "")).to.equal(
dogFileSize,
);
});
it("should create, upload and show a png file", async function () {
@@ -370,7 +378,9 @@ describe("photos", function () {
})
.expect(200);
expect(parseInt(showResp.get("content-length"))).to.equal(pngFileSize);
expect(parseInt(showResp.get("content-length") ?? "")).to.equal(
pngFileSize,
);
});
it("should not create a photo twice", async function () {
@@ -464,7 +474,9 @@ describe("photos", function () {
})
.expect(200);
expect(parseInt(showResp.get("content-length"))).to.equal(dogFileSize);
expect(parseInt(showResp.get("content-length") ?? "")).to.equal(
dogFileSize,
);
});
it("should not upload a wrong photo", async function () {

13408
frontend/package-lock.json generated

File diff suppressed because it is too large Load Diff

337
package-lock.json generated
View File

@@ -1,6 +1,6 @@
{
"name": "photos-root",
"lockfileVersion": 2,
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
@@ -11,12 +11,12 @@
}
},
"node_modules/@babel/runtime": {
"version": "7.22.6",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.22.6.tgz",
"integrity": "sha512-wDb5pWm4WDdF6LFUde3Jl8WzPA+3ZbxYqkC6xAXuD3irdEHN1k0NfTRrJD8ZD378SJ61miMLCqIOXYhd8x+AJQ==",
"version": "7.24.4",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.24.4.tgz",
"integrity": "sha512-dkxf7+hn8mFBwKjs9bvBlArzLVxVbS8usaPUDd5p2a9JCL9tB8OaOVN1isD4+Xyk4ns89/xeOmbQvgdK7IIVdA==",
"dev": true,
"dependencies": {
"regenerator-runtime": "^0.13.11"
"regenerator-runtime": "^0.14.0"
},
"engines": {
"node": ">=6.9.0"
@@ -107,9 +107,9 @@
"dev": true
},
"node_modules/concurrently": {
"version": "8.2.0",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-8.2.0.tgz",
"integrity": "sha512-nnLMxO2LU492mTUj9qX/az/lESonSZu81UznYDoXtz1IQf996ixVqPAgHXwvHiHCAef/7S8HIK+fTFK7Ifk8YA==",
"version": "8.2.2",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-8.2.2.tgz",
"integrity": "sha512-1dP4gpXFhei8IOtlXRE/T/4H88ElHgTiUzh71YUmtjTEHMSRS2Z/fgOxHSxxusGHogsRfxNq1vyAwxSC+EVyDg==",
"dev": true,
"dependencies": {
"chalk": "^4.1.2",
@@ -188,9 +188,9 @@
"dev": true
},
"node_modules/escalade": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz",
"integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==",
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz",
"integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==",
"dev": true,
"engines": {
"node": ">=6"
@@ -245,9 +245,9 @@
}
},
"node_modules/regenerator-runtime": {
"version": "0.13.11",
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz",
"integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==",
"version": "0.14.1",
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz",
"integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==",
"dev": true
},
"node_modules/require-directory": {
@@ -355,9 +355,9 @@
}
},
"node_modules/tslib": {
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.1.tgz",
"integrity": "sha512-t0hLfiEKfMUoqhG+U1oid7Pva4bbDPHYfJNiB7BiIjRkj1pyC++4N3huJfqY6aRH6VTB0rvtzQwjM4K6qpfOig==",
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz",
"integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==",
"dev": true
},
"node_modules/which": {
@@ -428,308 +428,5 @@
"node": ">=12"
}
}
},
"dependencies": {
"@babel/runtime": {
"version": "7.22.6",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.22.6.tgz",
"integrity": "sha512-wDb5pWm4WDdF6LFUde3Jl8WzPA+3ZbxYqkC6xAXuD3irdEHN1k0NfTRrJD8ZD378SJ61miMLCqIOXYhd8x+AJQ==",
"dev": true,
"requires": {
"regenerator-runtime": "^0.13.11"
}
},
"ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true
},
"ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"dev": true,
"requires": {
"color-convert": "^2.0.1"
}
},
"chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"dev": true,
"requires": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"dependencies": {
"supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"requires": {
"has-flag": "^4.0.0"
}
}
}
},
"cliui": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
"integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
"dev": true,
"requires": {
"string-width": "^4.2.0",
"strip-ansi": "^6.0.1",
"wrap-ansi": "^7.0.0"
}
},
"color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dev": true,
"requires": {
"color-name": "~1.1.4"
}
},
"color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true
},
"concurrently": {
"version": "8.2.0",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-8.2.0.tgz",
"integrity": "sha512-nnLMxO2LU492mTUj9qX/az/lESonSZu81UznYDoXtz1IQf996ixVqPAgHXwvHiHCAef/7S8HIK+fTFK7Ifk8YA==",
"dev": true,
"requires": {
"chalk": "^4.1.2",
"date-fns": "^2.30.0",
"lodash": "^4.17.21",
"rxjs": "^7.8.1",
"shell-quote": "^1.8.1",
"spawn-command": "0.0.2",
"supports-color": "^8.1.1",
"tree-kill": "^1.2.2",
"yargs": "^17.7.2"
}
},
"cross-env": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
"integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==",
"dev": true,
"requires": {
"cross-spawn": "^7.0.1"
}
},
"cross-spawn": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",
"integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==",
"dev": true,
"requires": {
"path-key": "^3.1.0",
"shebang-command": "^2.0.0",
"which": "^2.0.1"
}
},
"date-fns": {
"version": "2.30.0",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.30.0.tgz",
"integrity": "sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==",
"dev": true,
"requires": {
"@babel/runtime": "^7.21.0"
}
},
"emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true
},
"escalade": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz",
"integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==",
"dev": true
},
"get-caller-file": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
"dev": true
},
"has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true
},
"is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"dev": true
},
"isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"dev": true
},
"lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
"dev": true
},
"path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
"dev": true
},
"regenerator-runtime": {
"version": "0.13.11",
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz",
"integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==",
"dev": true
},
"require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
"dev": true
},
"rxjs": {
"version": "7.8.1",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz",
"integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==",
"dev": true,
"requires": {
"tslib": "^2.1.0"
}
},
"shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
"dev": true,
"requires": {
"shebang-regex": "^3.0.0"
}
},
"shebang-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
"dev": true
},
"shell-quote": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.1.tgz",
"integrity": "sha512-6j1W9l1iAs/4xYBI1SYOVZyFcCis9b4KCLQ8fgAGG07QvzaRLVVRQvAy85yNmmZSjYjg4MWh4gNvlPujU/5LpA==",
"dev": true
},
"spawn-command": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/spawn-command/-/spawn-command-0.0.2.tgz",
"integrity": "sha512-zC8zGoGkmc8J9ndvml8Xksr1Amk9qBujgbF0JAIWO7kXr43w0h/0GJNM/Vustixu+YE8N/MTrQ7N31FvHUACxQ==",
"dev": true
},
"string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"requires": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
}
},
"strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"requires": {
"ansi-regex": "^5.0.1"
}
},
"supports-color": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
"integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
"dev": true,
"requires": {
"has-flag": "^4.0.0"
}
},
"tree-kill": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
"integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==",
"dev": true
},
"tslib": {
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.1.tgz",
"integrity": "sha512-t0hLfiEKfMUoqhG+U1oid7Pva4bbDPHYfJNiB7BiIjRkj1pyC++4N3huJfqY6aRH6VTB0rvtzQwjM4K6qpfOig==",
"dev": true
},
"which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
"dev": true,
"requires": {
"isexe": "^2.0.0"
}
},
"wrap-ansi": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
"dev": true,
"requires": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
"strip-ansi": "^6.0.0"
}
},
"y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
"dev": true
},
"yargs": {
"version": "17.7.2",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
"integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==",
"dev": true,
"requires": {
"cliui": "^8.0.1",
"escalade": "^3.1.1",
"get-caller-file": "^2.0.5",
"require-directory": "^2.1.1",
"string-width": "^4.2.3",
"y18n": "^5.0.5",
"yargs-parser": "^21.1.1"
}
},
"yargs-parser": {
"version": "21.1.1",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
"integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
"dev": true
}
}
}

View File

@@ -1,12 +1,12 @@
{
"name": "photos-shared",
"lockfileVersion": 2,
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/zod": {
"version": "3.21.4",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.21.4.tgz",
"integrity": "sha512-m46AKbrzKVzOzs/DZgVnG5H55N1sv1M8qZU3A8RIKbs3mrACDNeIOeilDymVb2HdmP8uwshOCF4uJ8uM9rCqJw==",
"version": "3.22.4",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.22.4.tgz",
"integrity": "sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}

339
shared/node_modules/zod/README.md generated vendored
View File

@@ -45,20 +45,32 @@
#### Go to [zod.js.org](https://zod.js.org) >> -->
- [Table of contents](#table-of-contents)
- [Introduction](#introduction)
- [Sponsors](#sponsors)
- [Gold](#gold)
- [Silver](#silver)
- [Bronze](#bronze)
- [Ecosystem](#ecosystem)
- [Resources](#resources)
- [API libraries](#api-libraries)
- [Form integrations](#form-integrations)
- [Zod to X](#zod-to-x)
- [X to Zod](#x-to-zod)
- [Mocking](#mocking)
- [Powered by Zod](#powered-by-zod)
- [Utilities for Zod](#utilities-for-zod)
- [Installation](#installation)
- [Requirements](#requirements)
- [Node/npm](#from-npm-nodebun)
- [Deno](#from-denolandx-deno)
- [From `npm` (Node/Bun)](#from-npm-nodebun)
- [From `deno.land/x` (Deno)](#from-denolandx-deno)
- [Basic usage](#basic-usage)
- [Primitives](#primitives)
- [Coercion for primitives](#coercion-for-primitives)
- [Literals](#literals)
- [Strings](#strings)
- [Datetime](#datetime-validation)
- [IP](#ip-address-validation)
- [ISO datetimes](#iso-datetimes)
- [IP addresses](#ip-addresses)
- [Numbers](#numbers)
- [BigInts](#bigints)
- [NaNs](#nans)
@@ -69,59 +81,75 @@
- [Optionals](#optionals)
- [Nullables](#nullables)
- [Objects](#objects)
- [.shape](#shape)
- [.keyof](#keyof)
- [.extend](#extend)
- [.merge](#merge)
- [.pick/.omit](#pickomit)
- [.partial](#partial)
- [.deepPartial](#deepPartial)
- [.passthrough](#passthrough)
- [.strict](#strict)
- [.strip](#strip)
- [.catchall](#catchall)
- [`.shape`](#shape)
- [`.keyof`](#keyof)
- [`.extend`](#extend)
- [`.merge`](#merge)
- [`.pick/.omit`](#pickomit)
- [`.partial`](#partial)
- [`.deepPartial`](#deeppartial)
- [`.required`](#required)
- [`.passthrough`](#passthrough)
- [`.strict`](#strict)
- [`.strip`](#strip)
- [`.catchall`](#catchall)
- [Arrays](#arrays)
- [.element](#element)
- [.nonempty](#nonempty)
- [.min/.max/.length](#minmaxlength)
- [`.element`](#element)
- [`.nonempty`](#nonempty)
- [`.min/.max/.length`](#minmaxlength)
- [Tuples](#tuples)
- [Unions](#unions)
- [Discriminated Unions](#discriminated-unions)
- [Discriminated unions](#discriminated-unions)
- [Records](#records)
- [Record key type](#record-key-type)
- [Maps](#maps)
- [Sets](#sets)
- [Intersections](#intersections)
- [Recursive types](#recursive-types)
- [ZodType with ZodEffects](#zodtype-with-zodeffects)
- [JSON type](#json-type)
- [Cyclical data](#cyclical-objects)
- [Cyclical objects](#cyclical-objects)
- [Promises](#promises)
- [Instanceof](#instanceof)
- [Functions](#functions)
- [Preprocess](#preprocess)
- [Custom](#custom-schemas)
- [Custom schemas](#custom-schemas)
- [Schema methods](#schema-methods)
- [.parse](#parse)
- [.parseAsync](#parseasync)
- [.safeParse](#safeparse)
- [.safeParseAsync](#safeparseasync)
- [.refine](#refine)
- [.superRefine](#superRefine)
- [.transform](#transform)
- [.default](#default)
- [.describe](#describe)
- [.catch](#catch)
- [.optional](#optional)
- [.nullable](#nullable)
- [.nullish](#nullish)
- [.array](#array)
- [.promise](#promise)
- [.or](#or)
- [.and](#and)
- [.brand](#brand)
- [.pipe](#pipe)
- [`.parse`](#parse)
- [`.parseAsync`](#parseasync)
- [`.safeParse`](#safeparse)
- [`.safeParseAsync`](#safeparseasync)
- [`.refine`](#refine)
- [Arguments](#arguments)
- [Customize error path](#customize-error-path)
- [Asynchronous refinements](#asynchronous-refinements)
- [Relationship to transforms](#relationship-to-transforms)
- [`.superRefine`](#superrefine)
- [Abort early](#abort-early)
- [Type refinements](#type-refinements)
- [`.transform`](#transform)
- [Chaining order](#chaining-order)
- [Validating during transform](#validating-during-transform)
- [Relationship to refinements](#relationship-to-refinements)
- [Async transforms](#async-transforms)
- [`.default`](#default)
- [`.describe`](#describe)
- [`.catch`](#catch)
- [`.optional`](#optional)
- [`.nullable`](#nullable)
- [`.nullish`](#nullish)
- [`.array`](#array)
- [`.promise`](#promise)
- [`.or`](#or)
- [`.and`](#and)
- [`.brand`](#brand)
- [`.readonly`](#readonly)
- [`.pipe`](#pipe)
- [You can use `.pipe()` to fix common issues with `z.coerce`.](#you-can-use-pipe-to-fix-common-issues-with-zcoerce)
- [Guides and concepts](#guides-and-concepts)
- [Type inference](#type-inference)
- [Writing generic functions](#writing-generic-functions)
- [Constraining allowable inputs](#constraining-allowable-inputs)
- [Error handling](#error-handling)
- [Error formatting](#error-formatting)
- [Comparison](#comparison)
@@ -129,10 +157,9 @@
- [Yup](#yup)
- [io-ts](#io-ts)
- [Runtypes](#runtypes)
- [Ow](#ow)
- [Changelog](#changelog)
<!-- **Zod 2 is coming! Follow [@colinhacks](https://twitter.com/colinhacks) to stay updated and discuss the future of Zod.** -->
## Introduction
Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a simple `string` to a complex nested object.
@@ -158,23 +185,19 @@ Sponsorship at any level is appreciated and encouraged. For individual developer
<table>
<tr>
<td align="center">
<a href="https://astro.build/">
<img src="https://avatars.githubusercontent.com/u/44914786?s=200&v=4" width="200px;" alt="Astro" />
<a href="https://speakeasyapi.dev/">
<img src="https://avatars.githubusercontent.com/u/91446104?s=200&v=4" width="200px;" alt="Speakeasy API" />
</a>
<br />
<b>Astro</b>
<b>Speakeasy</b>
<br />
<a href="https://astro.build">astro.build</a>
<a href="https://speakeasyapi.dev/">speakeasyapi.dev</a>
<br />
<p width="200px">
Astro is a new kind of static <br/>
site builder for the modern web. <br/>
Powerful developer experience meets <br/>
lightweight output.</p>
<p width="200px">SDKs, Terraform, Docs.<br/>Your API made enterprise-ready.</p>
</td>
<td align="center">
<a href="https://glow.app/">
<img src="https://i.imgur.com/R0R43S2.jpg" width="200px;" alt="" />
<img src="https://i.imgur.com/R0R43S2.jpg" width="200px;" alt="Glow Wallet" />
</a>
<br />
<b>Glow Wallet</b>
@@ -196,17 +219,6 @@ Sponsorship at any level is appreciated and encouraged. For individual developer
<br />
<a href="https://deletype.com">deletype.com</a>
</td>
<td align="center">
<a href="https://proxy.com/">
<img src="https://avatars.githubusercontent.com/u/14321439?s=200&v=4" width="200px;" alt="Proxy logo" />
</a>
<br />
<b>Proxy</b>
<br />
<a href="https://proxy.com">proxy.com</a>
</td>
</tr>
<tr>
<td align="center">
<a href="https://trigger.dev/">
<img src="https://avatars.githubusercontent.com/u/95297378?s=200&v=4" width="200px;" alt="Trigger.dev logo" />
@@ -215,24 +227,53 @@ Sponsorship at any level is appreciated and encouraged. For individual developer
<b>Trigger.dev</b>
<br />
<a href="https://trigger.dev">trigger.dev</a>
<br/>
<p>Effortless automation for developers.</p>
</td>
<!-- <td align="center">
<a href="https://proxy.com/">
<img src="https://avatars.githubusercontent.com/u/14321439?s=200&v=4" width="200px;" alt="Proxy logo" />
</tr>
<tr>
<td align="center">
<a href="https://transloadit.com/?utm_source=zod&utm_medium=referral&utm_campaign=sponsorship&utm_content=github">
<img src="https://avatars.githubusercontent.com/u/125754?s=200&v=4" width="200px;" alt="Transloadit logo" />
</a>
<br />
<b>Proxy</b>
<b>Transloadit</b>
<br />
<a href="https://proxy.com">proxy.com</a>
</td> -->
<a href="https://transloadit.com/?utm_source=zod&utm_medium=referral&utm_campaign=sponsorship&utm_content=github">transloadit.com</a>
<br/>
<p>Simple file processing for developers.</p>
</td>
<td align="center">
<a href="https://infisical.com">
<img src="https://avatars.githubusercontent.com/u/107880645?s=200&v=4" width="200px;" alt="Infisical logo" />
</a>
<br />
<b>Infisical</b>
<br />
<a href="https://infisical.com">infisical.com</a>
<br/>
<p>Open-source platform for secret<br/>management: sync secrets across your<br/>team/infrastructure and prevent secret leaks.</p>
</td>
</tr>
<tr>
<td align="center">
<a href="https://whop.com/">
<img src="https://avatars.githubusercontent.com/u/91036480?s=200&v=4" width="200px;" alt="Whop logo" />
</a>
<br />
<b>Whop</b>
<br />
<a href="https://whop.com/">whop.com</a>
<br />
<p width="200px">A marketplace for really cool internet products.</p>
</td>
</table>
#### Silver
<table>
<tr>
<td align="center" colspan="2">
<td align="center" colspan="2">
<a href="https://www.numeric.io">
<img src="https://i.imgur.com/kTiLtZt.png" width="250px;" alt="Numeric logo" />
</a>
@@ -242,17 +283,6 @@ Sponsorship at any level is appreciated and encouraged. For individual developer
<a href="https://www.numeric.io">numeric.io</a>
</td>
<td align="center">
<a href="https://snaplet.dev">
<img src="https://avatars.githubusercontent.com/u/69029941?s=200&v=4" width="150px;" alt="Snaplet logo" />
</a>
<br />
<b>Snaplet</b>
<br />
<a href="https://snaplet.dev">snaplet.dev</a>
</td>
</tr>
<tr>
<td align="center">
<a href="https://marcatopartners.com/">
<img src="https://avatars.githubusercontent.com/u/84106192?s=200&v=4" width="150px;" alt="Marcato Partners" />
</a>
@@ -261,7 +291,9 @@ Sponsorship at any level is appreciated and encouraged. For individual developer
<br />
<a href="https://marcatopartners.com/">marcatopartners.com</a>
</td>
<td align="center">
</tr>
<tr>
<td align="center">
<a href="https://interval.com">
<img src="https://avatars.githubusercontent.com/u/67802063?s=200&v=4" width="150px;" alt="" />
</a>
@@ -279,8 +311,6 @@ Sponsorship at any level is appreciated and encouraged. For individual developer
<br />
<a href="https://seasoned.cc">seasoned.cc</a>
</td>
</tr>
<tr>
<td align="center">
<a href="https://www.bamboocreative.nz/">
<img src="https://avatars.githubusercontent.com/u/41406870?v=4" width="150px;" alt="Bamboo Creative logo" />
@@ -362,7 +392,7 @@ Sponsorship at any level is appreciated and encouraged. For individual developer
</td>
</tr>
<tr>
<td align="center">
<td align="center">
<a href="https://learnwithjason.dev">
<img src="https://avatars.githubusercontent.com/u/66575486?s=200&v=4" width="100px;" alt="Learn with Jason logo"/>
</a>
@@ -382,17 +412,16 @@ Sponsorship at any level is appreciated and encouraged. For individual developer
<a href="https://ill.inc/">ill.inc</a>
<br />
</td>
<!-- <td align="center">
<a href="https://www.avanawallet.com/">
<img src="https://avatars.githubusercontent.com/u/105452197?s=200&v=4" width="100px;" alt="Avana Wallet logo"/>
<td align="center">
<a href="https://www.masterborn.com/career?utm_source=github&utm_medium=referral&utm_campaign=zodsponsoring">
<img src="https://avatars.githubusercontent.com/u/48984031?s=200&v=4" width="100px;" alt="MasterBorn logo"/>
</a>
<br />
<b>Avana Wallet</b>
<b>MasterBorn</b>
<br/>
<a href="https://www.avanawallet.com/">avanawallet.com</a><br/>
<span>Solana non-custodial wallet</span>
<a href="https://www.masterborn.com/career?utm_source=github&utm_medium=referral&utm_campaign=zodsponsoring">masterborn.com</a>
<br />
</td> -->
</td>
</tr>
</table>
@@ -413,9 +442,12 @@ There are a growing number of tools that are built atop or support Zod natively!
- [`domain-functions`](https://github.com/SeasonedSoftware/domain-functions/): Decouple your business logic from your framework using composable functions. With first-class type inference from end to end powered by Zod schemas.
- [`@zodios/core`](https://github.com/ecyrbe/zodios): A typescript API client with runtime and compile time validation backed by axios and zod.
- [`express-zod-api`](https://github.com/RobinTail/express-zod-api): Build Express-based APIs with I/O schema validation and custom middlewares.
- [`tapiduck`](https://github.com/sumukhbarve/monoduck/blob/main/src/tapiduck/README.md): End-to-end typesafe JSON APIs with Zod and Express; a bit like tRPC, but simpler.
- [`koa-zod-router`](https://github.com/JakeFenley/koa-zod-router): Create typesafe routes in Koa with I/O validation using Zod.
#### Form integrations
- [`conform`](https://conform.guide/api/zod): A progressive enhancement first form validation library for Remix and React Router
- [`react-hook-form`](https://github.com/react-hook-form/resolvers#zod): A first-party Zod resolver for React Hook Form.
- [`zod-validation-error`](https://github.com/causaly/zod-validation-error): Generate user-friendly error messages from `ZodError`s.
- [`zod-formik-adapter`](https://github.com/robertLichtnow/zod-formik-adapter): A community-maintained Formik adapter for Zod.
@@ -426,6 +458,9 @@ There are a growing number of tools that are built atop or support Zod natively!
- [`zod-i18n-map`](https://github.com/aiji42/zod-i18n): Useful for translating Zod error messages.
- [`@modular-forms/solid`](https://github.com/fabian-hiller/modular-forms): Modular form library for SolidJS that supports Zod for validation.
- [`houseform`](https://github.com/crutchcorn/houseform/): A React form library that uses Zod for validation.
- [`sveltekit-superforms`](https://github.com/ciscoheat/sveltekit-superforms): Supercharged form library for SvelteKit with Zod validation.
- [`mobx-zod-form`](https://github.com/MonoidDev/mobx-zod-form): Data-first form builder based on MobX & Zod.
- [`@vee-validate/zod`](https://github.com/logaretm/vee-validate/tree/main/packages/zod): Form library for Vue.js with Zod schema validation.
#### Zod to X
@@ -437,6 +472,9 @@ There are a growing number of tools that are built atop or support Zod natively!
- [`fastify-type-provider-zod`](https://github.com/turkerdev/fastify-type-provider-zod): Create Fastify type providers from Zod schemas.
- [`zod-to-openapi`](https://github.com/asteasolutions/zod-to-openapi): Generate full OpenAPI (Swagger) docs from Zod, including schemas, endpoints & parameters.
- [`nestjs-graphql-zod`](https://github.com/incetarik/nestjs-graphql-zod): Generates NestJS GraphQL model classes from Zod schemas. Provides GraphQL method decorators working with Zod schemas.
- [`zod-openapi`](https://github.com/samchungy/zod-openapi): Create full OpenAPI v3.x documentation from Zod schemas.
- [`fastify-zod-openapi`](https://github.com/samchungy/fastify-zod-openapi): Fastify type provider, validation, serialization and @fastify/swagger support for Zod schemas.
- [`typeschema`](https://typeschema.com/): Universal adapter for schema validation.
#### X to Zod
@@ -450,14 +488,20 @@ There are a growing number of tools that are built atop or support Zod natively!
- [`prisma-zod-generator`](https://github.com/omar-dulaimi/prisma-zod-generator): Emit Zod schemas from your Prisma schema.
- [`prisma-trpc-generator`](https://github.com/omar-dulaimi/prisma-trpc-generator): Emit fully implemented tRPC routers and their validation schemas using Zod.
- [`zod-prisma-types`](https://github.com/chrishoermann/zod-prisma-types) Create Zod types from your Prisma models.
- [`quicktype`](https://app.quicktype.io/): Convert JSON objects and JSON schemas into Zod schemas.
- [`@sanity-typed/zod`](https://github.com/saiichihashimoto/sanity-typed/tree/main/packages/zod): Generate Zod Schemas from [Sanity Schemas](https://www.sanity.io/docs/schema-types).
#### Mocking
- [`@anatine/zod-mock`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-mock): Generate mock data from a Zod schema. Powered by [faker.js](https://github.com/faker-js/faker).
- [`zod-mocking`](https://github.com/dipasqualew/zod-mocking): Generate mock data from your Zod schemas.
- [`zod-fixture`](https://github.com/timdeschryver/zod-fixture): Use your zod schemas to automate the generation of non-relevant test fixtures in a deterministic way.
- [`zocker`](https://zocker.sigrist.dev): Generate plausible mock-data from your schemas.
- [`zodock`](https://github.com/ItMaga/zodock) Generate mock data based on Zod schemas.
#### Powered by Zod
- [`freerstore`](https://github.com/JacobWeisenburger/freerstore): Firestore cost optimizer.
- [`slonik`](https://github.com/gajus/slonik/tree/gajus/add-zod-validation-backwards-compatible#runtime-validation-and-static-type-inference): Node.js Postgres client with strong Zod integration.
- [`soly`](https://github.com/mdbetancourt/soly): Create CLI applications with zod.
- [`zod-xlsx`](https://github.com/sidwebworks/zod-xlsx): A xlsx based resource validator using Zod schemas.
@@ -466,6 +510,7 @@ There are a growing number of tools that are built atop or support Zod natively!
#### Utilities for Zod
- [`zod_utilz`](https://github.com/JacobWeisenburger/zod_utilz): Framework agnostic utilities for Zod.
- [`zod-sandbox`](https://github.com/nereumelo/zod-sandbox): Controlled environment for testing zod schemas. [Live demo](https://zod-sandbox.vercel.app/).
## Installation
@@ -494,6 +539,15 @@ bun add zod # bun
pnpm add zod # pnpm
```
Zod also publishes a canary version on every commit. To install the canary:
```sh
npm install zod@canary # npm
yarn add zod@canary # yarn
bun add zod@canary # bun
pnpm add zod@canary # pnpm
```
### From `deno.land/x` (Deno)
Unlike Node, Deno relies on direct URL imports instead of a package manager like NPM. Zod is available on [deno.land/x](https://deno.land/x). The latest version can be imported like so:
@@ -618,7 +672,7 @@ z.coerce.boolean().parse(null); // => false
## Literals
Literal schemas represent a [literal type](https://www.typescriptlang.org/docs/handbook/literal-types.html), like `"hello world"` or `5`.
Literal schemas represent a [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types), like `"hello world"` or `5`.
```ts
const tuna = z.literal("tuna");
@@ -655,7 +709,7 @@ z.string().regex(regex);
z.string().includes(string);
z.string().startsWith(string);
z.string().endsWith(string);
z.string().datetime(); // defaults to UTC, see below for options
z.string().datetime(); // ISO 8601; default is without UTC offset, see below for options
z.string().ip(); // defaults to IPv4 and IPv6, see below for options
// transformations
@@ -694,7 +748,7 @@ z.string().ip({ message: "Invalid IP address" });
### ISO datetimes
The `z.string().datetime()` method defaults to UTC validation: no timezone offsets with arbitrary sub-second decimal precision.
The `z.string().datetime()` method enforces ISO 8601; default is no timezone offsets and arbitrary sub-second decimal precision.
```ts
const datetime = z.string().datetime();
@@ -966,7 +1020,7 @@ FruitEnum.parse("Cantaloupe"); // fails
**Const enums**
The `.nativeEnum()` function works for `as const` objects as well. ⚠️ `as const` required TypeScript 3.4+!
The `.nativeEnum()` function works for `as const` objects as well. ⚠️ `as const` requires TypeScript 3.4+!
```ts
const Fruits = {
@@ -1137,13 +1191,13 @@ type NoIDRecipe = z.infer<typeof NoIDRecipe>;
### `.partial`
Inspired by the built-in TypeScript utility type [Partial](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialt), the `.partial` method makes all properties optional.
Inspired by the built-in TypeScript utility type [Partial](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype), the `.partial` method makes all properties optional.
Starting from this object:
```ts
const user = z.object({
email: z.string()
email: z.string(),
username: z.string(),
});
// { email: string; username: string }
@@ -1207,10 +1261,12 @@ Contrary to the `.partial` method, the `.required` method makes all properties r
Starting from this object:
```ts
const user = z.object({
email: z.string()
username: z.string(),
}).partial();
const user = z
.object({
email: z.string(),
username: z.string(),
})
.partial();
// { email?: string | undefined; username?: string | undefined }
```
@@ -1464,6 +1520,12 @@ type NumberCache = z.infer<typeof NumberCache>;
This is particularly useful for storing or caching items by ID.
```ts
const userSchema = z.object({ name: z.string() });
const userStoreSchema = z.record(userSchema);
type UserStore = z.infer<typeof userStoreSchema>;
// => type UserStore = { [ x: string ]: { name: string } }
const userStore: UserStore = {};
userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = {
@@ -1819,7 +1881,7 @@ You can create a Zod schema for any TypeScript type by using `z.custom()`. This
```ts
const px = z.custom<`${number}px`>((val) => {
return /^\d+px$/.test(val as string);
return typeof val === "string" ? /^\d+px$/.test(val) : false;
});
type px = z.infer<typeof px>; // `${number}px`
@@ -2292,7 +2354,7 @@ A convenience method that returns a "nullish" version of a schema. Nullish schem
const nullishString = z.string().nullish(); // string | null | undefined
// equivalent to
z.string().optional().nullable();
z.string().nullable().optional();
```
### `.array`
@@ -2382,7 +2444,38 @@ type Cat = z.infer<typeof Cat>;
Note that branded types do not affect the runtime result of `.parse`. It is a static-only construct.
### `.pipe()`
### `.readonly`
`.readonly() => ZodReadonly<this>`
This method returns a `ZodReadonly` schema instance that parses the input using the base schema, then calls `Object.freeze()` on the result. The inferred type is also marked as `readonly`.
```ts
const schema = z.object({ name: string }).readonly();
type schema = z.infer<typeof schema>;
// Readonly<{name: string}>
const result = schema.parse({ name: "fido" });
result.name = "simba"; // error
```
The inferred type uses TypeScript's built-in readonly types when relevant.
```ts
z.array(z.string()).readonly();
// readonly string[]
z.tuple([z.string(), z.number()]).readonly();
// readonly [string, number]
z.map(z.string(), z.date()).readonly();
// ReadonlyMap<string, Date>
z.set(z.string()).readonly();
// ReadonlySet<Promise<string>>
```
### `.pipe`
Schemas can be chained into validation "pipelines". It's useful for easily validating the result after a `.transform()`:
@@ -2399,51 +2492,55 @@ The `.pipe()` method returns a `ZodPipeline` instance.
You can constrain the input to types that work well with your chosen coercion. Then use `.pipe()` to apply the coercion.
without constrained input:
```ts
const toDate = z.coerce.date()
const toDate = z.coerce.date();
// works intuitively
console.log(toDate.safeParse('2023-01-01').success) // true
console.log(toDate.safeParse("2023-01-01").success); // true
// might not be what you want
console.log(toDate.safeParse(null).success) // true
console.log(toDate.safeParse(null).success); // true
```
with constrained input:
```ts
const datelike = z.union([z.number(), z.string(), z.date()])
const datelikeToDate = datelike.pipe(z.coerce.date())
const datelike = z.union([z.number(), z.string(), z.date()]);
const datelikeToDate = datelike.pipe(z.coerce.date());
// still works intuitively
console.log(datelikeToDate.safeParse('2023-01-01').success) // true
console.log(datelikeToDate.safeParse("2023-01-01").success); // true
// more likely what you want
console.log(datelikeToDate.safeParse(null).success) // false
console.log(datelikeToDate.safeParse(null).success); // false
```
You can also use this technique to avoid coercions that throw uncaught errors.
without constrained input:
```ts
const toBigInt = z.coerce.bigint()
const toBigInt = z.coerce.bigint();
// works intuitively
console.log( toBigInt.safeParse( '42' ) ) // true
console.log(toBigInt.safeParse("42")); // true
// probably not what you want
console.log( toBigInt.safeParse( null ) ) // throws uncaught error
console.log(toBigInt.safeParse(null)); // throws uncaught error
```
with constrained input:
```ts
const toNumber = z.number().or( z.string() ).pipe( z.coerce.number() )
const toBigInt = z.bigint().or( toNumber ).pipe( z.coerce.bigint() )
const toNumber = z.number().or(z.string()).pipe(z.coerce.number());
const toBigInt = z.bigint().or(toNumber).pipe(z.coerce.bigint());
// still works intuitively
console.log( toBigInt.safeParse( '42' ).success ) // true
console.log(toBigInt.safeParse("42").success); // true
// error handled by zod, more likely what you want
console.log( toBigInt.safeParse( null ).success ) // false
console.log(toBigInt.safeParse(null).success); // false
```
## Guides and concepts
@@ -2654,7 +2751,6 @@ Yup is a full-featured library that was implemented first in vanilla JS, and lat
- Supports casting and transforms
- All object fields are optional by default
- Missing object methods: (partial, deepPartial)
<!-- - Missing nonempty arrays with proper typing (`[T, ...T[]]`) -->
- Missing promise schemas
- Missing function schemas
@@ -2717,10 +2813,9 @@ This more declarative API makes schema definitions vastly more concise.
[https://github.com/pelotom/runtypes](https://github.com/pelotom/runtypes)
Good type inference support, but limited options for object type masking (no `.pick` , `.omit` , `.extend` , etc.). No support for `Record` s (their `Record` is equivalent to Zod's `object` ). They DO support readonly types, which Zod does not.
Good type inference support.
- Supports "pattern matching": computed properties that distribute over unions
- Supports readonly types
- Missing object methods: (deepPartial, merge)
- Missing nonempty arrays with proper typing (`[T, ...T[]]`)
- Missing promise schemas

View File

@@ -37,6 +37,7 @@ class ZodError extends Error {
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
// eslint-disable-next-line ban/ban
Object.setPrototypeOf(this, actualProto);
}
else {
@@ -76,6 +77,13 @@ class ZodError extends Error {
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
// if (typeof el === "string") {
// curr[el] = curr[el] || { _errors: [] };
// } else if (typeof el === "number") {
// const errorArray: any = [];
// errorArray._errors = [];
// curr[el] = curr[el] || errorArray;
// }
}
else {
curr[el] = curr[el] || { _errors: [] };

View File

@@ -38,7 +38,7 @@ function addIssueToContext(ctx, issueData) {
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
(0, errors_1.getErrorMap)(),
en_1.default,
en_1.default, // then global default map
].filter((x) => !!x),
});
ctx.common.issues.push(issue);
@@ -89,7 +89,8 @@ class ParseStatus {
status.dirty();
if (value.status === "dirty")
status.dirty();
if (typeof value.value !== "undefined" || pair.alwaysSet) {
if (key.value !== "__proto__" &&
(typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}

View File

@@ -30,8 +30,8 @@ var util;
return obj[e];
});
};
util.objectKeys = typeof Object.keys === "function"
? (obj) => Object.keys(obj)
util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
: (object) => {
const keys = [];
for (const key in object) {
@@ -49,7 +49,7 @@ var util;
return undefined;
};
util.isInteger = typeof Number.isInteger === "function"
? (val) => Number.isInteger(val)
? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
: (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array
@@ -69,7 +69,7 @@ var objectUtil;
objectUtil.mergeShapes = (first, second) => {
return {
...first,
...second,
...second, // second overwrites first
};
};
})(objectUtil = exports.objectUtil || (exports.objectUtil = {}));

178
shared/node_modules/zod/lib/index.mjs generated vendored
View File

@@ -478,7 +478,8 @@ class ParseStatus {
status.dirty();
if (value.status === "dirty")
status.dirty();
if (typeof value.value !== "undefined" || pair.alwaysSet) {
if (key.value !== "__proto__" &&
(typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}
@@ -586,6 +587,7 @@ class ZodType {
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
}
@@ -802,6 +804,9 @@ class ZodType {
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(undefined).success;
}
@@ -811,17 +816,28 @@ class ZodType {
}
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[a-z][a-z0-9]*$/;
const ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/;
const uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
// const uuidRegex =
// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
// from https://stackoverflow.com/a/46181/1550155
// old version: too slow, didn't support unicode
// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
//old email regex
// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
// eslint-disable-next-line
const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
// const emailRegex =
// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
// const emailRegex =
// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
// const emailRegex =
// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
// const emailRegex =
// /^[a-z0-9.!#$%&*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
const emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u;
const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
let emojiRegex;
const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
// Adapted from https://stackoverflow.com/a/3143231
@@ -861,31 +877,6 @@ function isValidIP(ip, version) {
return false;
}
class ZodString extends ZodType {
constructor() {
super(...arguments);
this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message),
});
/**
* @deprecated Use z.string().min(1) instead.
* @see {@link ZodString.min}
*/
this.nonempty = (message) => this.min(1, errorUtil.errToObj(message));
this.trim = () => new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }],
});
this.toLowerCase = () => new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }],
});
this.toUpperCase = () => new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }],
});
}
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
@@ -973,6 +964,9 @@ class ZodString extends ZodType {
}
}
else if (check.kind === "emoji") {
if (!emojiRegex) {
emojiRegex = new RegExp(_emojiRegex, "u");
}
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
@@ -1125,6 +1119,13 @@ class ZodString extends ZodType {
}
return { status: status.value, value: input.data };
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message),
});
}
_addCheck(check) {
return new ZodString({
...this._def,
@@ -1222,6 +1223,31 @@ class ZodString extends ZodType {
...errorUtil.errToObj(message),
});
}
/**
* @deprecated Use z.string().min(1) instead.
* @see {@link ZodString.min}
*/
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }],
});
}
toLowerCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }],
});
}
toUpperCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }],
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
@@ -2930,6 +2956,12 @@ class ZodRecord extends ZodType {
}
}
class ZodMap extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
@@ -3126,16 +3158,20 @@ class ZodFunction extends ZodType {
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
return OK(async (...args) => {
// Would love a way to avoid disabling this rule, but we need
// an alias (using an arrow function was what caused 2651).
// eslint-disable-next-line @typescript-eslint/no-this-alias
const me = this;
return OK(async function (...args) {
const error = new ZodError([]);
const parsedArgs = await this._def.args
const parsedArgs = await me._def.args
.parseAsync(args, params)
.catch((e) => {
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = await fn(...parsedArgs);
const parsedReturns = await this._def.returns._def.type
const result = await Reflect.apply(fn, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type
.parseAsync(result, params)
.catch((e) => {
error.addIssue(makeReturnsIssue(result, e));
@@ -3145,13 +3181,17 @@ class ZodFunction extends ZodType {
});
}
else {
return OK((...args) => {
const parsedArgs = this._def.args.safeParse(args, params);
// Would love a way to avoid disabling this rule, but we need
// an alias (using an arrow function was what caused 2651).
// eslint-disable-next-line @typescript-eslint/no-this-alias
const me = this;
return OK(function (...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) {
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
}
const result = fn(...parsedArgs.data);
const parsedReturns = this._def.returns.safeParse(result, params);
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) {
throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
}
@@ -3239,7 +3279,7 @@ ZodLiteral.create = (value, params) => {
};
function createZodEnum(values, params) {
return new ZodEnum({
values: values,
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params),
});
@@ -3381,8 +3421,29 @@ class ZodEffects extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status.abort();
}
else {
status.dirty();
}
},
get path() {
return ctx.path;
},
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data);
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.issues.length) {
return {
status: "dirty",
value: ctx.data,
};
}
if (ctx.common.async) {
return Promise.resolve(processed).then((processed) => {
return this._def.schema._parseAsync({
@@ -3400,21 +3461,6 @@ class ZodEffects extends ZodType {
});
}
}
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status.abort();
}
else {
status.dirty();
}
},
get path() {
return ctx.path;
},
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "refinement") {
const executeRefinement = (acc
// effect: RefinementEffect<any>
@@ -3718,8 +3764,24 @@ class ZodPipeline extends ZodType {
});
}
}
class ZodReadonly extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
if (isValid(result)) {
result.value = Object.freeze(result.value);
}
return result;
}
}
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params),
});
};
const custom = (check, params = {},
/*
/**
* @deprecated
*
* Pass `fatal` into the params object instead:
@@ -3786,6 +3848,7 @@ var ZodFirstPartyTypeKind;
ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
const instanceOfType = (
// const instanceOfType = <T extends new (...args: any[]) => any>(
@@ -3899,6 +3962,7 @@ var z = /*#__PURE__*/Object.freeze({
BRAND: BRAND,
ZodBranded: ZodBranded,
ZodPipeline: ZodPipeline,
ZodReadonly: ZodReadonly,
custom: custom,
Schema: ZodType,
ZodSchema: ZodType,
@@ -3950,4 +4014,4 @@ var z = /*#__PURE__*/Object.freeze({
ZodError: ZodError
});
export { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z };
export { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z };

View File

@@ -484,7 +484,8 @@
status.dirty();
if (value.status === "dirty")
status.dirty();
if (typeof value.value !== "undefined" || pair.alwaysSet) {
if (key.value !== "__proto__" &&
(typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}
@@ -592,6 +593,7 @@
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
}
@@ -808,6 +810,9 @@
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(undefined).success;
}
@@ -817,17 +822,28 @@
}
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[a-z][a-z0-9]*$/;
const ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/;
const uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
// const uuidRegex =
// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
// from https://stackoverflow.com/a/46181/1550155
// old version: too slow, didn't support unicode
// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
//old email regex
// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
// eslint-disable-next-line
const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
// const emailRegex =
// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
// const emailRegex =
// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
// const emailRegex =
// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
// const emailRegex =
// /^[a-z0-9.!#$%&*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
const emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u;
const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
let emojiRegex;
const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
// Adapted from https://stackoverflow.com/a/3143231
@@ -867,31 +883,6 @@
return false;
}
class ZodString extends ZodType {
constructor() {
super(...arguments);
this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message),
});
/**
* @deprecated Use z.string().min(1) instead.
* @see {@link ZodString.min}
*/
this.nonempty = (message) => this.min(1, errorUtil.errToObj(message));
this.trim = () => new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }],
});
this.toLowerCase = () => new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }],
});
this.toUpperCase = () => new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }],
});
}
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
@@ -979,6 +970,9 @@
}
}
else if (check.kind === "emoji") {
if (!emojiRegex) {
emojiRegex = new RegExp(_emojiRegex, "u");
}
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
@@ -1131,6 +1125,13 @@
}
return { status: status.value, value: input.data };
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message),
});
}
_addCheck(check) {
return new ZodString({
...this._def,
@@ -1228,6 +1229,31 @@
...errorUtil.errToObj(message),
});
}
/**
* @deprecated Use z.string().min(1) instead.
* @see {@link ZodString.min}
*/
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }],
});
}
toLowerCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }],
});
}
toUpperCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }],
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
@@ -2936,6 +2962,12 @@
}
}
class ZodMap extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
@@ -3132,16 +3164,20 @@
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
return OK(async (...args) => {
// Would love a way to avoid disabling this rule, but we need
// an alias (using an arrow function was what caused 2651).
// eslint-disable-next-line @typescript-eslint/no-this-alias
const me = this;
return OK(async function (...args) {
const error = new ZodError([]);
const parsedArgs = await this._def.args
const parsedArgs = await me._def.args
.parseAsync(args, params)
.catch((e) => {
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = await fn(...parsedArgs);
const parsedReturns = await this._def.returns._def.type
const result = await Reflect.apply(fn, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type
.parseAsync(result, params)
.catch((e) => {
error.addIssue(makeReturnsIssue(result, e));
@@ -3151,13 +3187,17 @@
});
}
else {
return OK((...args) => {
const parsedArgs = this._def.args.safeParse(args, params);
// Would love a way to avoid disabling this rule, but we need
// an alias (using an arrow function was what caused 2651).
// eslint-disable-next-line @typescript-eslint/no-this-alias
const me = this;
return OK(function (...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) {
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
}
const result = fn(...parsedArgs.data);
const parsedReturns = this._def.returns.safeParse(result, params);
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) {
throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
}
@@ -3245,7 +3285,7 @@
};
function createZodEnum(values, params) {
return new ZodEnum({
values: values,
values,
typeName: exports.ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params),
});
@@ -3387,8 +3427,29 @@
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status.abort();
}
else {
status.dirty();
}
},
get path() {
return ctx.path;
},
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data);
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.issues.length) {
return {
status: "dirty",
value: ctx.data,
};
}
if (ctx.common.async) {
return Promise.resolve(processed).then((processed) => {
return this._def.schema._parseAsync({
@@ -3406,21 +3467,6 @@
});
}
}
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status.abort();
}
else {
status.dirty();
}
},
get path() {
return ctx.path;
},
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "refinement") {
const executeRefinement = (acc
// effect: RefinementEffect<any>
@@ -3724,8 +3770,24 @@
});
}
}
class ZodReadonly extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
if (isValid(result)) {
result.value = Object.freeze(result.value);
}
return result;
}
}
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: exports.ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params),
});
};
const custom = (check, params = {},
/*
/**
* @deprecated
*
* Pass `fatal` into the params object instead:
@@ -3792,6 +3854,7 @@
ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
})(exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
const instanceOfType = (
// const instanceOfType = <T extends new (...args: any[]) => any>(
@@ -3905,6 +3968,7 @@
BRAND: BRAND,
ZodBranded: ZodBranded,
ZodPipeline: ZodPipeline,
ZodReadonly: ZodReadonly,
custom: custom,
Schema: ZodType,
ZodSchema: ZodType,
@@ -3993,6 +4057,7 @@
exports.ZodParsedType = ZodParsedType;
exports.ZodPipeline = ZodPipeline;
exports.ZodPromise = ZodPromise;
exports.ZodReadonly = ZodReadonly;
exports.ZodRecord = ZodRecord;
exports.ZodSchema = ZodType;
exports.ZodSet = ZodSet;

View File

@@ -60,6 +60,7 @@ export declare abstract class ZodType<Output = any, Def extends ZodTypeDef = Zod
safeParse(data: unknown, params?: Partial<ParseParams>): SafeParseReturnType<Input, Output>;
parseAsync(data: unknown, params?: Partial<ParseParams>): Promise<Output>;
safeParseAsync(data: unknown, params?: Partial<ParseParams>): Promise<SafeParseReturnType<Input, Output>>;
/** Alias of safeParseAsync */
spa: (data: unknown, params?: Partial<ParseParams> | undefined) => Promise<SafeParseReturnType<Input, Output>>;
refine<RefinedOutput extends Output>(check: (arg: Output) => arg is RefinedOutput, message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)): ZodEffects<this, RefinedOutput, Input>;
refine(check: (arg: Output) => unknown | Promise<unknown>, message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)): ZodEffects<this, Output, Input>;
@@ -68,6 +69,7 @@ export declare abstract class ZodType<Output = any, Def extends ZodTypeDef = Zod
_refinement(refinement: RefinementEffect<Output>["refinement"]): ZodEffects<this, Output, Input>;
superRefine<RefinedOutput extends Output>(refinement: (arg: Output, ctx: RefinementCtx) => arg is RefinedOutput): ZodEffects<this, RefinedOutput, Input>;
superRefine(refinement: (arg: Output, ctx: RefinementCtx) => void): ZodEffects<this, Output, Input>;
superRefine(refinement: (arg: Output, ctx: RefinementCtx) => Promise<void>): ZodEffects<this, Output, Input>;
constructor(def: Def);
optional(): ZodOptional<this>;
nullable(): ZodNullable<this>;
@@ -87,6 +89,7 @@ export declare abstract class ZodType<Output = any, Def extends ZodTypeDef = Zod
}) => Output): ZodCatch<this>;
describe(description: string): this;
pipe<T extends ZodTypeAny>(target: T): ZodPipeline<this, T>;
readonly(): ZodReadonly<this>;
isOptional(): boolean;
isNullable(): boolean;
}
@@ -167,7 +170,7 @@ export interface ZodStringDef extends ZodTypeDef {
}
export declare class ZodString extends ZodType<string, ZodStringDef> {
_parse(input: ParseInput): ParseReturnType<string>;
protected _regex: (regex: RegExp, validation: StringValidation, message?: errorUtil.ErrMessage | undefined) => ZodEffects<this, string, string>;
protected _regex(regex: RegExp, validation: StringValidation, message?: errorUtil.ErrMessage): ZodEffects<this, string, string>;
_addCheck(check: ZodStringCheck): ZodString;
email(message?: errorUtil.ErrMessage): ZodString;
url(message?: errorUtil.ErrMessage): ZodString;
@@ -195,10 +198,14 @@ export declare class ZodString extends ZodType<string, ZodStringDef> {
min(minLength: number, message?: errorUtil.ErrMessage): ZodString;
max(maxLength: number, message?: errorUtil.ErrMessage): ZodString;
length(len: number, message?: errorUtil.ErrMessage): ZodString;
nonempty: (message?: errorUtil.ErrMessage | undefined) => ZodString;
trim: () => ZodString;
toLowerCase: () => ZodString;
toUpperCase: () => ZodString;
/**
* @deprecated Use z.string().min(1) instead.
* @see {@link ZodString.min}
*/
nonempty(message?: errorUtil.ErrMessage): ZodString;
trim(): ZodString;
toLowerCase(): ZodString;
toUpperCase(): ZodString;
get isDatetime(): boolean;
get isEmail(): boolean;
get isURL(): boolean;
@@ -491,9 +498,21 @@ export declare class ZodObject<T extends ZodRawShape, UnknownKeys extends Unknow
strict(message?: errorUtil.ErrMessage): ZodObject<T, "strict", Catchall>;
strip(): ZodObject<T, "strip", Catchall>;
passthrough(): ZodObject<T, "passthrough", Catchall>;
/**
* @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
* If you want to pass through unknown properties, use `.passthrough()` instead.
*/
nonstrict: () => ZodObject<T, "passthrough", Catchall>;
extend<Augmentation extends ZodRawShape>(augmentation: Augmentation): ZodObject<objectUtil.extendShape<T, Augmentation>, UnknownKeys, Catchall>;
/**
* @deprecated Use `.extend` instead
* */
augment: <Augmentation extends ZodRawShape>(augmentation: Augmentation) => ZodObject<{ [k in keyof (Omit<T, keyof Augmentation> & Augmentation)]: (Omit<T, keyof Augmentation> & Augmentation)[k]; }, UnknownKeys, Catchall, objectOutputType<{ [k in keyof (Omit<T, keyof Augmentation> & Augmentation)]: (Omit<T, keyof Augmentation> & Augmentation)[k]; }, Catchall, UnknownKeys>, objectInputType<{ [k in keyof (Omit<T, keyof Augmentation> & Augmentation)]: (Omit<T, keyof Augmentation> & Augmentation)[k]; }, Catchall, UnknownKeys>>;
/**
* Prior to zod@1.0.12 there was a bug in the
* inferred type of merged objects. Please
* upgrade if you are experiencing issues.
*/
merge<Incoming extends AnyZodObject, Augmentation extends Incoming["shape"]>(merging: Incoming): ZodObject<objectUtil.extendShape<T, Augmentation>, Incoming["_def"]["unknownKeys"], Incoming["_def"]["catchall"]>;
setKey<Key extends string, Schema extends ZodTypeAny>(key: Key, schema: Schema): ZodObject<T & {
[k in Key]: Schema;
@@ -505,6 +524,9 @@ export declare class ZodObject<T extends ZodRawShape, UnknownKeys extends Unknow
omit<Mask extends {
[k in keyof T]?: true;
}>(mask: Mask): ZodObject<Omit<T, keyof Mask>, UnknownKeys, Catchall>;
/**
* @deprecated
*/
deepPartial(): partialUtil.DeepPartial<this>;
partial(): ZodObject<{
[k in keyof T]: ZodOptional<T[k]>;
@@ -556,6 +578,14 @@ export declare class ZodDiscriminatedUnion<Discriminator extends string, Options
get discriminator(): Discriminator;
get options(): Options;
get optionsMap(): Map<Primitive, ZodDiscriminatedUnionOption<any>>;
/**
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
* have a different value for each object in the union.
* @param discriminator the name of the discriminator property
* @param types an array of object schemas
* @param params
*/
static create<Discriminator extends string, Types extends [
ZodDiscriminatedUnionOption<Discriminator>,
...ZodDiscriminatedUnionOption<Discriminator>[]
@@ -618,6 +648,8 @@ export interface ZodMapDef<Key extends ZodTypeAny = ZodTypeAny, Value extends Zo
typeName: ZodFirstPartyTypeKind.ZodMap;
}
export declare class ZodMap<Key extends ZodTypeAny = ZodTypeAny, Value extends ZodTypeAny = ZodTypeAny> extends ZodType<Map<Key["_output"], Value["_output"]>, ZodMapDef<Key, Value>, Map<Key["_input"], Value["_input"]>> {
get keySchema(): Key;
get valueSchema(): Value;
_parse(input: ParseInput): ParseReturnType<this["_output"]>;
static create: <Key_1 extends ZodTypeAny = ZodTypeAny, Value_1 extends ZodTypeAny = ZodTypeAny>(keyType: Key_1, valueType: Value_1, params?: RawCreateParams) => ZodMap<Key_1, Value_1>;
}
@@ -730,7 +762,7 @@ export declare class ZodPromise<T extends ZodTypeAny> extends ZodType<Promise<T[
static create: <T_1 extends ZodTypeAny>(schema: T_1, params?: RawCreateParams) => ZodPromise<T_1>;
}
export declare type Refinement<T> = (arg: T, ctx: RefinementCtx) => any;
export declare type SuperRefinement<T> = (arg: T, ctx: RefinementCtx) => void;
export declare type SuperRefinement<T> = (arg: T, ctx: RefinementCtx) => void | Promise<void>;
export declare type RefinementEffect<T> = {
type: "refinement";
refinement: (arg: T, ctx: RefinementCtx) => any;
@@ -741,7 +773,7 @@ export declare type TransformEffect<T> = {
};
export declare type PreprocessEffect<T> = {
type: "preprocess";
transform: (arg: T) => any;
transform: (arg: T, ctx: RefinementCtx) => any;
};
export declare type Effect<T> = RefinementEffect<T> | TransformEffect<T> | PreprocessEffect<T>;
export interface ZodEffectsDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef {
@@ -754,7 +786,7 @@ export declare class ZodEffects<T extends ZodTypeAny, Output = output<T>, Input
sourceType(): T;
_parse(input: ParseInput): ParseReturnType<this["_output"]>;
static create: <I extends ZodTypeAny>(schema: I, effect: Effect<I["_output"]>, params?: RawCreateParams) => ZodEffects<I, I["_output"], input<I>>;
static createWithPreprocess: <I extends ZodTypeAny>(preprocess: (arg: unknown) => unknown, schema: I, params?: RawCreateParams) => ZodEffects<I, I["_output"], unknown>;
static createWithPreprocess: <I extends ZodTypeAny>(preprocess: (arg: unknown, ctx: RefinementCtx) => unknown, schema: I, params?: RawCreateParams) => ZodEffects<I, I["_output"], unknown>;
}
export { ZodEffects as ZodTransformer };
export interface ZodOptionalDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef {
@@ -844,6 +876,18 @@ export declare class ZodPipeline<A extends ZodTypeAny, B extends ZodTypeAny> ext
_parse(input: ParseInput): ParseReturnType<any>;
static create<A extends ZodTypeAny, B extends ZodTypeAny>(a: A, b: B): ZodPipeline<A, B>;
}
declare type BuiltIn = (((...args: any[]) => any) | (new (...args: any[]) => any)) | {
readonly [Symbol.toStringTag]: string;
} | Date | Error | Generator | Promise<unknown> | RegExp;
declare type MakeReadonly<T> = T extends Map<infer K, infer V> ? ReadonlyMap<K, V> : T extends Set<infer V> ? ReadonlySet<V> : T extends [infer Head, ...infer Tail] ? readonly [Head, ...Tail] : T extends Array<infer V> ? ReadonlyArray<V> : T extends BuiltIn ? T : Readonly<T>;
export interface ZodReadonlyDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef {
innerType: T;
typeName: ZodFirstPartyTypeKind.ZodReadonly;
}
export declare class ZodReadonly<T extends ZodTypeAny> extends ZodType<MakeReadonly<T["_output"]>, ZodReadonlyDef<T>, T["_input"]> {
_parse(input: ParseInput): ParseReturnType<this["_output"]>;
static create: <T_1 extends ZodTypeAny>(type: T_1, params?: RawCreateParams) => ZodReadonly<T_1>;
}
declare type CustomParams = CustomErrorParams & {
fatal?: boolean;
};
@@ -887,7 +931,8 @@ export declare enum ZodFirstPartyTypeKind {
ZodCatch = "ZodCatch",
ZodPromise = "ZodPromise",
ZodBranded = "ZodBranded",
ZodPipeline = "ZodPipeline"
ZodPipeline = "ZodPipeline",
ZodReadonly = "ZodReadonly"
}
export declare type ZodFirstPartySchemaTypes = ZodString | ZodNumber | ZodNaN | ZodBigInt | ZodBoolean | ZodDate | ZodUndefined | ZodNull | ZodAny | ZodUnknown | ZodNever | ZodVoid | ZodArray<any, any> | ZodObject<any, any, any> | ZodUnion<any> | ZodDiscriminatedUnion<any, any> | ZodIntersection<any, any> | ZodTuple<any, any> | ZodRecord<any, any> | ZodMap<any> | ZodSet<any> | ZodFunction<any, any> | ZodLazy<any> | ZodLiteral<any> | ZodEnum<any> | ZodEffects<any, any, any> | ZodNativeEnum<any> | ZodOptional<any> | ZodNullable<any> | ZodDefault<any> | ZodCatch<any> | ZodPromise<any> | ZodBranded<any, any> | ZodPipeline<any, any>;
declare abstract class Class {
@@ -961,7 +1006,7 @@ declare const promiseType: <T extends ZodTypeAny>(schema: T, params?: RawCreateP
declare const effectsType: <I extends ZodTypeAny>(schema: I, effect: Effect<I["_output"]>, params?: RawCreateParams) => ZodEffects<I, I["_output"], input<I>>;
declare const optionalType: <T extends ZodTypeAny>(type: T, params?: RawCreateParams) => ZodOptional<T>;
declare const nullableType: <T extends ZodTypeAny>(type: T, params?: RawCreateParams) => ZodNullable<T>;
declare const preprocessType: <I extends ZodTypeAny>(preprocess: (arg: unknown) => unknown, schema: I, params?: RawCreateParams) => ZodEffects<I, I["_output"], unknown>;
declare const preprocessType: <I extends ZodTypeAny>(preprocess: (arg: unknown, ctx: RefinementCtx) => unknown, schema: I, params?: RawCreateParams) => ZodEffects<I, I["_output"], unknown>;
declare const pipelineType: typeof ZodPipeline.create;
declare const ostring: () => ZodOptional<ZodString>;
declare const onumber: () => ZodOptional<ZodNumber>;

359
shared/node_modules/zod/lib/types.js generated vendored
View File

@@ -1,7 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.discriminatedUnion = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0;
exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = void 0;
exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0;
exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = exports.discriminatedUnion = void 0;
const errors_1 = require("./errors");
const errorUtil_1 = require("./helpers/errorUtil");
const parseUtil_1 = require("./helpers/parseUtil");
@@ -68,6 +68,7 @@ function processCreateParams(params) {
}
class ZodType {
constructor(def) {
/** Alias of safeParseAsync */
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
@@ -91,6 +92,7 @@ class ZodType {
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
}
@@ -307,6 +309,9 @@ class ZodType {
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(undefined).success;
}
@@ -319,12 +324,31 @@ exports.Schema = ZodType;
exports.ZodSchema = ZodType;
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[a-z][a-z0-9]*$/;
const ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/;
const uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
const emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
// const uuidRegex =
// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
// from https://stackoverflow.com/a/46181/1550155
// old version: too slow, didn't support unicode
// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
//old email regex
// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
// eslint-disable-next-line
// const emailRegex =
// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
// const emailRegex =
// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
// const emailRegex =
// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
// const emailRegex =
// /^[a-z0-9.!#$%&*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
let emojiRegex;
const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
// Adapted from https://stackoverflow.com/a/3143231
const datetimeRegex = (args) => {
if (args.precision) {
if (args.offset) {
@@ -361,27 +385,6 @@ function isValidIP(ip, version) {
return false;
}
class ZodString extends ZodType {
constructor() {
super(...arguments);
this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), {
validation,
code: ZodError_1.ZodIssueCode.invalid_string,
...errorUtil_1.errorUtil.errToObj(message),
});
this.nonempty = (message) => this.min(1, errorUtil_1.errorUtil.errToObj(message));
this.trim = () => new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }],
});
this.toLowerCase = () => new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }],
});
this.toUpperCase = () => new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }],
});
}
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
@@ -393,7 +396,9 @@ class ZodString extends ZodType {
code: ZodError_1.ZodIssueCode.invalid_type,
expected: util_1.ZodParsedType.string,
received: ctx.parsedType,
});
}
//
);
return parseUtil_1.INVALID;
}
const status = new parseUtil_1.ParseStatus();
@@ -467,6 +472,9 @@ class ZodString extends ZodType {
}
}
else if (check.kind === "emoji") {
if (!emojiRegex) {
emojiRegex = new RegExp(_emojiRegex, "u");
}
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
(0, parseUtil_1.addIssueToContext)(ctx, {
@@ -619,6 +627,13 @@ class ZodString extends ZodType {
}
return { status: status.value, value: input.data };
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), {
validation,
code: ZodError_1.ZodIssueCode.invalid_string,
...errorUtil_1.errorUtil.errToObj(message),
});
}
_addCheck(check) {
return new ZodString({
...this._def,
@@ -716,6 +731,31 @@ class ZodString extends ZodType {
...errorUtil_1.errorUtil.errToObj(message),
});
}
/**
* @deprecated Use z.string().min(1) instead.
* @see {@link ZodString.min}
*/
nonempty(message) {
return this.min(1, errorUtil_1.errorUtil.errToObj(message));
}
trim() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }],
});
}
toLowerCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }],
});
}
toUpperCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }],
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
@@ -774,6 +814,7 @@ ZodString.create = (params) => {
...processCreateParams(params),
});
};
// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
@@ -1409,6 +1450,7 @@ ZodNull.create = (params) => {
class ZodAny extends ZodType {
constructor() {
super(...arguments);
// to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
this._any = true;
}
_parse(input) {
@@ -1425,6 +1467,7 @@ ZodAny.create = (params) => {
class ZodUnknown extends ZodType {
constructor() {
super(...arguments);
// required
this._unknown = true;
}
_parse(input) {
@@ -1615,7 +1658,47 @@ class ZodObject extends ZodType {
constructor() {
super(...arguments);
this._cached = null;
/**
* @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
* If you want to pass through unknown properties, use `.passthrough()` instead.
*/
this.nonstrict = this.passthrough;
// extend<
// Augmentation extends ZodRawShape,
// NewOutput extends util.flatten<{
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// }>,
// NewInput extends util.flatten<{
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }>
// >(
// augmentation: Augmentation
// ): ZodObject<
// extendShape<T, Augmentation>,
// UnknownKeys,
// Catchall,
// NewOutput,
// NewInput
// > {
// return new ZodObject({
// ...this._def,
// shape: () => ({
// ...this._def.shape(),
// ...augmentation,
// }),
// }) as any;
// }
/**
* @deprecated Use `.extend` instead
* */
this.augment = this.extend;
}
_getCached() {
@@ -1683,12 +1766,14 @@ class ZodObject extends ZodType {
}
}
else {
// run catchall validation
const catchall = this._def.catchall;
for (const key of extraKeys) {
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
),
alwaysSet: key in ctx.data,
});
}
@@ -1752,6 +1837,23 @@ class ZodObject extends ZodType {
unknownKeys: "passthrough",
});
}
// const AugmentFactory =
// <Def extends ZodObjectDef>(def: Def) =>
// <Augmentation extends ZodRawShape>(
// augmentation: Augmentation
// ): ZodObject<
// extendShape<ReturnType<Def["shape"]>, Augmentation>,
// Def["unknownKeys"],
// Def["catchall"]
// > => {
// return new ZodObject({
// ...def,
// shape: () => ({
// ...def.shape(),
// ...augmentation,
// }),
// }) as any;
// };
extend(augmentation) {
return new ZodObject({
...this._def,
@@ -1761,6 +1863,11 @@ class ZodObject extends ZodType {
}),
});
}
/**
* Prior to zod@1.0.12 there was a bug in the
* inferred type of merged objects. Please
* upgrade if you are experiencing issues.
*/
merge(merging) {
const merged = new ZodObject({
unknownKeys: merging._def.unknownKeys,
@@ -1773,9 +1880,65 @@ class ZodObject extends ZodType {
});
return merged;
}
// merge<
// Incoming extends AnyZodObject,
// Augmentation extends Incoming["shape"],
// NewOutput extends {
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// },
// NewInput extends {
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }
// >(
// merging: Incoming
// ): ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"],
// NewOutput,
// NewInput
// > {
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
setKey(key, schema) {
return this.augment({ [key]: schema });
}
// merge<Incoming extends AnyZodObject>(
// merging: Incoming
// ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
// ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"]
// > {
// // const mergedShape = objectUtil.mergeShapes(
// // this._def.shape(),
// // merging._def.shape()
// // );
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
catchall(index) {
return new ZodObject({
...this._def,
@@ -1806,6 +1969,9 @@ class ZodObject extends ZodType {
shape: () => shape,
});
}
/**
* @deprecated
*/
deepPartial() {
return deepPartialify(this);
}
@@ -1882,6 +2048,7 @@ class ZodUnion extends ZodType {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
// return first issue-free validation if it exists
for (const result of results) {
if (result.result.status === "valid") {
return result.result;
@@ -1889,10 +2056,12 @@ class ZodUnion extends ZodType {
}
for (const result of results) {
if (result.result.status === "dirty") {
// add issues from dirty option
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
}
// return invalid
const unionErrors = results.map((result) => new ZodError_1.ZodError(result.ctx.common.issues));
(0, parseUtil_1.addIssueToContext)(ctx, {
code: ZodError_1.ZodIssueCode.invalid_union,
@@ -1971,6 +2140,13 @@ ZodUnion.create = (types, params) => {
...processCreateParams(params),
});
};
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
////////// //////////
////////// ZodDiscriminatedUnion //////////
////////// //////////
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
const getDiscriminator = (type) => {
if (type instanceof ZodLazy) {
return getDiscriminator(type.schema);
@@ -1985,6 +2161,7 @@ const getDiscriminator = (type) => {
return type.options;
}
else if (type instanceof ZodNativeEnum) {
// eslint-disable-next-line ban/ban
return Object.keys(type.enum);
}
else if (type instanceof ZodDefault) {
@@ -2046,8 +2223,18 @@ class ZodDiscriminatedUnion extends ZodType {
get optionsMap() {
return this._def.optionsMap;
}
/**
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
* have a different value for each object in the union.
* @param discriminator the name of the discriminator property
* @param types an array of object schemas
* @param params
*/
static create(discriminator, options, params) {
// Get all the valid discriminator values
const optionsMap = new Map();
// try {
for (const type of options) {
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues) {
@@ -2210,7 +2397,7 @@ class ZodTuple extends ZodType {
return null;
return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
})
.filter((x) => !!x);
.filter((x) => !!x); // filter nulls
if (ctx.common.async) {
return Promise.all(items).then((results) => {
return parseUtil_1.ParseStatus.mergeArray(status, results);
@@ -2297,6 +2484,12 @@ class ZodRecord extends ZodType {
}
exports.ZodRecord = ZodRecord;
class ZodMap extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== util_1.ZodParsedType.map) {
@@ -2495,16 +2688,20 @@ class ZodFunction extends ZodType {
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
return (0, parseUtil_1.OK)(async (...args) => {
// Would love a way to avoid disabling this rule, but we need
// an alias (using an arrow function was what caused 2651).
// eslint-disable-next-line @typescript-eslint/no-this-alias
const me = this;
return (0, parseUtil_1.OK)(async function (...args) {
const error = new ZodError_1.ZodError([]);
const parsedArgs = await this._def.args
const parsedArgs = await me._def.args
.parseAsync(args, params)
.catch((e) => {
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = await fn(...parsedArgs);
const parsedReturns = await this._def.returns._def.type
const result = await Reflect.apply(fn, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type
.parseAsync(result, params)
.catch((e) => {
error.addIssue(makeReturnsIssue(result, e));
@@ -2514,13 +2711,17 @@ class ZodFunction extends ZodType {
});
}
else {
return (0, parseUtil_1.OK)((...args) => {
const parsedArgs = this._def.args.safeParse(args, params);
// Would love a way to avoid disabling this rule, but we need
// an alias (using an arrow function was what caused 2651).
// eslint-disable-next-line @typescript-eslint/no-this-alias
const me = this;
return (0, parseUtil_1.OK)(function (...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) {
throw new ZodError_1.ZodError([makeArgsIssue(args, parsedArgs.error)]);
}
const result = fn(...parsedArgs.data);
const parsedReturns = this._def.returns.safeParse(result, params);
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) {
throw new ZodError_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]);
}
@@ -2611,7 +2812,7 @@ ZodLiteral.create = (value, params) => {
};
function createZodEnum(values, params) {
return new ZodEnum({
values: values,
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params),
});
@@ -2756,8 +2957,29 @@ class ZodEffects extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
(0, parseUtil_1.addIssueToContext)(ctx, arg);
if (arg.fatal) {
status.abort();
}
else {
status.dirty();
}
},
get path() {
return ctx.path;
},
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data);
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.issues.length) {
return {
status: "dirty",
value: ctx.data,
};
}
if (ctx.common.async) {
return Promise.resolve(processed).then((processed) => {
return this._def.schema._parseAsync({
@@ -2775,23 +2997,10 @@ class ZodEffects extends ZodType {
});
}
}
const checkCtx = {
addIssue: (arg) => {
(0, parseUtil_1.addIssueToContext)(ctx, arg);
if (arg.fatal) {
status.abort();
}
else {
status.dirty();
}
},
get path() {
return ctx.path;
},
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "refinement") {
const executeRefinement = (acc) => {
const executeRefinement = (acc
// effect: RefinementEffect<any>
) => {
const result = effect.refinement(acc, checkCtx);
if (ctx.common.async) {
return Promise.resolve(result);
@@ -2811,6 +3020,7 @@ class ZodEffects extends ZodType {
return parseUtil_1.INVALID;
if (inner.status === "dirty")
status.dirty();
// return value is ignored
executeRefinement(inner.value);
return { status: status.value, value: inner.value };
}
@@ -2945,6 +3155,7 @@ ZodDefault.create = (type, params) => {
class ZodCatch extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
// newCtx is used to not collect issues from inner types in ctx
const newCtx = {
...ctx,
common: {
@@ -3098,7 +3309,35 @@ class ZodPipeline extends ZodType {
}
}
exports.ZodPipeline = ZodPipeline;
const custom = (check, params = {}, fatal) => {
class ZodReadonly extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
if ((0, parseUtil_1.isValid)(result)) {
result.value = Object.freeze(result.value);
}
return result;
}
}
exports.ZodReadonly = ZodReadonly;
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params),
});
};
const custom = (check, params = {},
/**
* @deprecated
*
* Pass `fatal` into the params object instead:
*
* ```ts
* z.string().custom((val) => val.length > 5, { fatal: false })
* ```
*
*/
fatal) => {
if (check)
return ZodAny.create().superRefine((data, ctx) => {
var _a, _b;
@@ -3156,11 +3395,15 @@ var ZodFirstPartyTypeKind;
ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind = exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
// requires TS 4.4+
class Class {
constructor(..._) { }
}
const instanceOfType = (cls, params = {
const instanceOfType = (
// const instanceOfType = <T extends new (...args: any[]) => any>(
cls, params = {
message: `Input not instance of ${cls.name}`,
}) => (0, exports.custom)((data) => data instanceof cls, params);
exports.instanceof = instanceOfType;

44
shared/node_modules/zod/package.json generated vendored
View File

@@ -1,6 +1,6 @@
{
"name": "zod",
"version": "3.21.4",
"version": "3.22.4",
"author": "Colin McDonnell <colin@colinhacks.com>",
"repository": {
"type": "git",
@@ -9,12 +9,18 @@
"main": "./lib/index.js",
"module": "./lib/index.mjs",
"devDependencies": {
"@babel/core": "^7.22.5",
"@babel/preset-env": "^7.22.5",
"@babel/preset-typescript": "^7.22.5",
"@rollup/plugin-typescript": "^8.2.0",
"@swc/core": "^1.3.66",
"@swc/jest": "^0.2.26",
"@types/benchmark": "^2.1.0",
"@types/jest": "^29.2.2",
"@types/node": "14",
"@typescript-eslint/eslint-plugin": "^5.15.0",
"@typescript-eslint/parser": "^5.15.0",
"babel-jest": "^29.5.0",
"benchmark": "^2.1.4",
"dependency-cruiser": "^9.19.0",
"eslint": "^8.11.0",
@@ -30,18 +36,19 @@
"prettier": "^2.6.0",
"pretty-quick": "^3.1.3",
"rollup": "^2.70.1",
"ts-jest": "^29.0.3",
"ts-jest": "^29.1.0",
"ts-morph": "^14.0.0",
"ts-node": "^10.9.1",
"tslib": "^2.3.1",
"tsx": "^3.8.0",
"typescript": "~4.5.0"
"typescript": "~4.5.0",
"vitest": "^0.32.2"
},
"exports": {
".": {
"types": "./index.d.ts",
"require": "./lib/index.js",
"import": "./lib/index.mjs",
"types": "./index.d.ts"
"import": "./lib/index.mjs"
},
"./package.json": "./package.json",
"./locales/*": "./lib/locales/*"
@@ -68,25 +75,32 @@
"src/*.ts": [
"eslint --cache --fix",
"prettier --ignore-unknown --write"
],
"*.md": [
"prettier --ignore-unknown --write"
]
},
"scripts": {
"prettier:check": "prettier --check src/**/*.ts deno/lib/**/*.ts --no-error-on-unmatched-pattern",
"prettier:fix": "prettier --write src/**/*.ts deno/lib/**/*.ts --ignore-unknown --no-error-on-unmatched-pattern",
"prettier:check": "prettier --check src/**/*.ts deno/lib/**/*.ts *.md --no-error-on-unmatched-pattern",
"prettier:fix": "prettier --write src/**/*.ts deno/lib/**/*.ts *.md --ignore-unknown --no-error-on-unmatched-pattern",
"lint:check": "eslint --cache --ext .ts ./src",
"lint:fix": "eslint --cache --fix --ext .ts ./src",
"check": "yarn lint:check && yarn prettier:check",
"fix": "yarn lint:fix && yarn prettier:fix",
"clean": "rm -rf lib/* deno/lib/*",
"build": "yarn run clean && npm run build:cjs && npm run build:esm && npm run build:deno",
"build:deno": "node ./deno/build.mjs && cp ./README.md ./deno/lib",
"build:esm": "rollup --config rollup.config.js",
"build:cjs": "tsc -p tsconfig.cjs.json",
"build:types": "tsc -p tsconfig.types.json",
"build:test": "tsc -p tsconfig.test.json",
"rollup": "rollup --config rollup.config.js",
"test:watch": "jest --watch",
"test": "jest --coverage",
"build:deno": "node ./deno-build.mjs && cp ./README.md ./deno/lib",
"build:esm": "rollup --config ./configs/rollup.config.js",
"build:cjs": "tsc -p ./configs/tsconfig.cjs.json",
"build:types": "tsc -p ./configs/tsconfig.types.json",
"build:test": "tsc -p ./configs/tsconfig.test.json",
"test:watch": "yarn test:ts-jest --watch",
"test": "yarn test:ts-jest",
"test:babel": "jest --coverage --config ./configs/babel-jest.config.json",
"test:bun": "bun test",
"test:vitest": "npx vitest --config ./configs/vitest.config.ts",
"test:ts-jest": "npx jest --config ./configs/ts-jest.config.json",
"test:swc": "npx jest --config ./configs/swc-jest.config.json",
"test:deno": "cd deno && deno test",
"prepublishOnly": "npm run test && npm run build && npm run build:deno",
"play": "nodemon -e ts -w . -x tsx playground.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "photos-shared",
"lockfileVersion": 2,
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
@@ -10,19 +10,12 @@
}
},
"node_modules/zod": {
"version": "3.21.4",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.21.4.tgz",
"integrity": "sha512-m46AKbrzKVzOzs/DZgVnG5H55N1sv1M8qZU3A8RIKbs3mrACDNeIOeilDymVb2HdmP8uwshOCF4uJ8uM9rCqJw==",
"version": "3.22.4",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.22.4.tgz",
"integrity": "sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
}
},
"dependencies": {
"zod": {
"version": "3.21.4",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.21.4.tgz",
"integrity": "sha512-m46AKbrzKVzOzs/DZgVnG5H55N1sv1M8qZU3A8RIKbs3mrACDNeIOeilDymVb2HdmP8uwshOCF4uJ8uM9rCqJw=="
}
}
}