diff --git a/package.json b/package.json index 50030f274a..c6b3303250 100644 --- a/package.json +++ b/package.json @@ -267,7 +267,7 @@ "y-protocols": "^1.0.6", "yauzl": "^3.2.0", "yjs": "^13.6.1", - "zod": "^3.25.76" + "zod": "^4.2.1" }, "devDependencies": { "@babel/cli": "^7.28.3", @@ -382,7 +382,8 @@ "js-yaml": "^3.14.1", "qs": "6.14.1", "prismjs": "1.30.0", - "cheerio": "1.0.0-rc.12" + "cheerio": "1.0.0-rc.12", + "zod": "^4.2.1" }, "version": "1.5.0", "packageManager": "yarn@4.11.0" diff --git a/plugins/email/server/auth/email.test.ts b/plugins/email/server/auth/email.test.ts index bc3fc4d362..901ea2dc85 100644 --- a/plugins/email/server/auth/email.test.ts +++ b/plugins/email/server/auth/email.test.ts @@ -14,7 +14,7 @@ describe("email", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("email: Invalid email"); + expect(body.message).toEqual("email: Invalid email address"); }); it("should require email param", async () => { diff --git a/plugins/email/server/auth/schema.ts b/plugins/email/server/auth/schema.ts index 572ca5452e..68fe8a0430 100644 --- a/plugins/email/server/auth/schema.ts +++ b/plugins/email/server/auth/schema.ts @@ -4,9 +4,9 @@ import { BaseSchema } from "@server/routes/api/schema"; export const EmailSchema = BaseSchema.extend({ body: z.object({ - email: z.string().email(), - client: z.nativeEnum(Client).default(Client.Web), - preferOTP: z.boolean().default(false), + email: z.email(), + client: z.enum(Client).prefault(Client.Web), + preferOTP: z.boolean().prefault(false), }), }); @@ -16,15 +16,15 @@ const callbackDataSchema = z .object({ token: z.string().optional(), code: z.string().optional(), - email: z.string().email().optional(), - client: z.nativeEnum(Client).optional(), - follow: z.string().default(""), + email: z.email().optional(), + client: z.enum(Client).optional(), + follow: z.string().prefault(""), }) .refine( (data: { code?: string; email?: string; token?: string }) => !(data.code && !data.email) && !(data.email && !data.code && !data.token), { - message: "Both code and email must be provided together", + error: "Both code and email must be provided together", } ); diff --git a/plugins/figma/server/api/schema.ts b/plugins/figma/server/api/schema.ts index cec86235db..f8682d12ef 100644 --- a/plugins/figma/server/api/schema.ts +++ b/plugins/figma/server/api/schema.ts @@ -10,10 +10,10 @@ export const FigmaCallbackSchema = BaseSchema.extend({ error: z.string().nullish(), }) .refine((req) => !(isEmpty(req.code) && isEmpty(req.error)), { - message: "one of code or error is required", + error: "one of code or error is required", }) .refine((req) => isEmpty(req.code) || isEmpty(req.error), { - message: "code and error cannot both be present", + error: "code and error cannot both be present", }), }); diff --git a/plugins/github/server/api/schema.ts b/plugins/github/server/api/schema.ts index 6abb4b842d..f7430b986b 100644 --- a/plugins/github/server/api/schema.ts +++ b/plugins/github/server/api/schema.ts @@ -12,16 +12,16 @@ export const GitHubCallbackSchema = BaseSchema.extend({ query: z .object({ code: z.string().nullish(), - state: z.string().uuid().nullish(), + state: z.uuid().nullish(), error: z.string().nullish(), installation_id: z.coerce.number().optional(), - setup_action: z.nativeEnum(SetupAction), + setup_action: z.enum(SetupAction), }) .refine((req) => !(isEmpty(req.code) && isEmpty(req.error)), { - message: "one of code or error is required", + error: "one of code or error is required", }) .refine((req) => isEmpty(req.code) || isEmpty(req.error), { - message: "code and error cannot both be present", + error: "code and error cannot both be present", }) .refine( (req) => @@ -29,7 +29,9 @@ export const GitHubCallbackSchema = BaseSchema.extend({ req.setup_action === SetupAction.install && isUndefined(req.installation_id) ), - { message: "installation_id is required for installation" } + { + error: "installation_id is required for installation", + } ), }); diff --git a/plugins/linear/server/api/schema.ts b/plugins/linear/server/api/schema.ts index bac1855a6a..fdea51ae65 100644 --- a/plugins/linear/server/api/schema.ts +++ b/plugins/linear/server/api/schema.ts @@ -10,10 +10,10 @@ export const LinearCallbackSchema = BaseSchema.extend({ error: z.string().nullish(), }) .refine((req) => !(isEmpty(req.code) && isEmpty(req.error)), { - message: "one of code or error is required", + error: "one of code or error is required", }) .refine((req) => isEmpty(req.code) || isEmpty(req.error), { - message: "code and error cannot both be present", + error: "code and error cannot both be present", }), }); diff --git a/plugins/notion/server/api/schema.ts b/plugins/notion/server/api/schema.ts index ee8005e2cf..0428e3e80a 100644 --- a/plugins/notion/server/api/schema.ts +++ b/plugins/notion/server/api/schema.ts @@ -10,10 +10,10 @@ export const NotionCallbackSchema = BaseSchema.extend({ error: z.string().nullish(), }) .refine((req) => !(isEmpty(req.code) && isEmpty(req.error)), { - message: "one of code or error is required", + error: "one of code or error is required", }) .refine((req) => isEmpty(req.code) || isEmpty(req.error), { - message: "code and error cannot both be present", + error: "code and error cannot both be present", }), }); @@ -21,7 +21,7 @@ export type NotionCallbackReq = z.infer; export const NotionSearchSchema = BaseSchema.extend({ body: z.object({ - integrationId: z.string().uuid(), + integrationId: z.uuid(), }), }); diff --git a/plugins/passkeys/server/api/schema.ts b/plugins/passkeys/server/api/schema.ts index 6a70f65d85..2d9e81ac35 100644 --- a/plugins/passkeys/server/api/schema.ts +++ b/plugins/passkeys/server/api/schema.ts @@ -10,7 +10,7 @@ export type PasskeysListReq = z.infer; export const PasskeysDeleteSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), }), }); @@ -18,7 +18,7 @@ export type PasskeysDeleteReq = z.infer; export const PasskeysUpdateSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), name: z .string() .trim() diff --git a/plugins/passkeys/server/auth/schema.ts b/plugins/passkeys/server/auth/schema.ts index 38d81ebd18..fe6c103b60 100644 --- a/plugins/passkeys/server/auth/schema.ts +++ b/plugins/passkeys/server/auth/schema.ts @@ -5,7 +5,7 @@ import { BaseSchema } from "@server/routes/api/schema"; export const PasskeysGenerateAuthenticationOptionsSchema = BaseSchema.extend({ body: z.object({}), query: z.object({ - client: z.nativeEnum(Client).optional(), + client: z.enum(Client).optional(), }), }); @@ -16,7 +16,7 @@ export type PasskeysGenerateAuthenticationOptionsReq = z.infer< export const PasskeysVerifyAuthenticationSchema = BaseSchema.extend({ body: z.object({ challengeId: z.string(), - client: z.nativeEnum(Client).optional(), + client: z.enum(Client).optional(), id: z.string(), rawId: z.string(), response: z.object({ @@ -32,7 +32,7 @@ export const PasskeysVerifyAuthenticationSchema = BaseSchema.extend({ appid: z.boolean().optional(), hmacCreateSecret: z.boolean().optional(), }) - .default({}), + .prefault({}), }), }); diff --git a/plugins/slack/server/api/schema.ts b/plugins/slack/server/api/schema.ts index bed68e7574..621c621e0d 100644 --- a/plugins/slack/server/api/schema.ts +++ b/plugins/slack/server/api/schema.ts @@ -30,7 +30,7 @@ export const HooksSlackCommandSchema = z.object({ token: z.string(), team_id: z.string(), user_id: z.string(), - text: z.string().optional().default(""), + text: z.string().prefault(""), }), }); diff --git a/plugins/slack/server/auth/schema.ts b/plugins/slack/server/auth/schema.ts index d98176b624..29157ef466 100644 --- a/plugins/slack/server/auth/schema.ts +++ b/plugins/slack/server/auth/schema.ts @@ -10,10 +10,10 @@ export const SlackPostSchema = BaseSchema.extend({ error: z.string().nullish(), }) .refine((req) => !(isEmpty(req.code) && isEmpty(req.error)), { - message: "one of code or error is required", + error: "one of code or error is required", }) .refine((req) => isEmpty(req.code) || isEmpty(req.error), { - message: "code and error cannot both be present", + error: "code and error cannot both be present", }), }); diff --git a/plugins/storage/server/api/schema.ts b/plugins/storage/server/api/schema.ts index 20ff529311..8482bd8e13 100644 --- a/plugins/storage/server/api/schema.ts +++ b/plugins/storage/server/api/schema.ts @@ -27,7 +27,7 @@ export const FilesGetSchema = z.object({ download: z.string().optional(), }) .refine((obj) => !(isEmpty(obj.key) && isEmpty(obj.sig)), { - message: "One of key or sig is required", + error: "One of key or sig is required", }), }); diff --git a/plugins/webhooks/server/api/schema.ts b/plugins/webhooks/server/api/schema.ts index 5d00a4d5c0..a6c3b35258 100644 --- a/plugins/webhooks/server/api/schema.ts +++ b/plugins/webhooks/server/api/schema.ts @@ -3,7 +3,7 @@ import { z } from "zod"; export const WebhookSubscriptionsCreateSchema = z.object({ body: z.object({ name: z.string(), - url: z.string().url(), + url: z.url(), secret: z.string().optional(), events: z.array(z.string()), }), @@ -15,9 +15,9 @@ export type WebhookSubscriptionsCreateReq = z.infer< export const WebhookSubscriptionsUpdateSchema = z.object({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), name: z.string(), - url: z.string().url(), + url: z.url(), secret: z.string().optional(), events: z.array(z.string()), }), @@ -29,7 +29,7 @@ export type WebhookSubscriptionsUpdateReq = z.infer< export const WebhookSubscriptionsDeleteSchema = z.object({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), }), }); diff --git a/server/middlewares/validate.ts b/server/middlewares/validate.ts index ca4b39b5dd..b44bb08695 100644 --- a/server/middlewares/validate.ts +++ b/server/middlewares/validate.ts @@ -2,9 +2,11 @@ import type { Next } from "koa"; import type { z } from "zod"; import { ZodError } from "zod"; import { ValidationError } from "@server/errors"; -import type { APIContext, BaseReq } from "@server/types"; +import type { APIContext } from "@server/types"; -export default function validate>(schema: T) { +export default function validate>>( + schema: T +) { return async function validateMiddleware(ctx: APIContext, next: Next) { try { ctx.input = { @@ -15,7 +17,9 @@ export default function validate>(schema: T) { if (err instanceof ZodError) { const { path, message } = err.issues[0]; const errMessage = - path.length > 0 ? `${path[path.length - 1]}: ${message}` : message; + path.length > 0 + ? `${String(path[path.length - 1])}: ${message}` + : message; throw ValidationError(errMessage); } ctx.throw(err); diff --git a/server/routes/api/apiKeys/schema.ts b/server/routes/api/apiKeys/schema.ts index db5ef1251f..edaf683477 100644 --- a/server/routes/api/apiKeys/schema.ts +++ b/server/routes/api/apiKeys/schema.ts @@ -22,7 +22,7 @@ export type APIKeysCreateReq = z.infer; export const APIKeysListSchema = BaseSchema.extend({ body: z.object({ /** The owner of the API key */ - userId: z.string().uuid().optional(), + userId: z.uuid().optional(), }), }); @@ -31,7 +31,7 @@ export type APIKeysListReq = z.infer; export const APIKeysDeleteSchema = BaseSchema.extend({ body: z.object({ /** API Key Id */ - id: z.string().uuid(), + id: z.uuid(), }), }); diff --git a/server/routes/api/attachments/schema.ts b/server/routes/api/attachments/schema.ts index 215a0fb33a..35d81abe34 100644 --- a/server/routes/api/attachments/schema.ts +++ b/server/routes/api/attachments/schema.ts @@ -6,9 +6,9 @@ import { BaseSchema } from "@server/routes/api/schema"; export const AttachmentsListSchema = BaseSchema.extend({ body: z.object({ /** Id of the document to which the Attachment belongs */ - documentId: z.string().uuid().optional(), + documentId: z.uuid().optional(), /** Id of the user that uploaded the Attachment */ - userId: z.string().uuid().optional(), + userId: z.uuid().optional(), }), }); @@ -17,24 +17,24 @@ export type AttachmentsListReq = z.infer; export const AttachmentsCreateSchema = BaseSchema.extend({ body: z.object({ /** Attachment id */ - id: z.string().uuid().optional(), + id: z.uuid().optional(), /** Attachment name */ name: z.string(), /** Id of the document to which the Attachment belongs */ - documentId: z.string().uuid().optional(), + documentId: z.uuid().optional(), /** File size of the Attachment */ size: z.number(), /** Content-Type of the Attachment */ - contentType: z.string().optional().default("application/octet-stream"), + contentType: z.string().optional().prefault("application/octet-stream"), /** Attachment type */ preset: z - .nativeEnum(AttachmentPreset) - .default(AttachmentPreset.DocumentAttachment), + .enum(AttachmentPreset) + .prefault(AttachmentPreset.DocumentAttachment), }), }); @@ -43,18 +43,18 @@ export type AttachmentCreateReq = z.infer; export const AttachmentsCreateFromUrlSchema = BaseSchema.extend({ body: z.object({ /** Attachment id */ - id: z.string().uuid().optional(), + id: z.uuid().optional(), /** Attachment url */ url: z.string(), /** Id of the document to which the Attachment belongs */ - documentId: z.string().uuid().optional(), + documentId: z.uuid().optional(), /** Attachment type */ preset: z - .nativeEnum(AttachmentPreset) - .default(AttachmentPreset.DocumentAttachment), + .enum(AttachmentPreset) + .prefault(AttachmentPreset.DocumentAttachment), }), }); @@ -65,7 +65,7 @@ export type AttachmentCreateFromUrlReq = z.infer< export const AttachmentDeleteSchema = BaseSchema.extend({ body: z.object({ /** Id of the attachment to be deleted */ - id: z.string().uuid(), + id: z.uuid(), }), }); @@ -74,11 +74,11 @@ export type AttachmentDeleteReq = z.infer; export const AttachmentsRedirectSchema = BaseSchema.extend({ body: z.object({ /** Id of the attachment to be deleted */ - id: z.string().uuid().optional(), + id: z.uuid().optional(), }), query: z.object({ /** Id of the attachment to be deleted */ - id: z.string().uuid().optional(), + id: z.uuid().optional(), }), }).refine((req) => !(isEmpty(req.body.id) && isEmpty(req.query.id)), { message: "id is required", diff --git a/server/routes/api/authenticationProviders/schema.ts b/server/routes/api/authenticationProviders/schema.ts index 78cf5a4800..efcba01201 100644 --- a/server/routes/api/authenticationProviders/schema.ts +++ b/server/routes/api/authenticationProviders/schema.ts @@ -4,7 +4,7 @@ import { BaseSchema } from "@server/routes/api/schema"; export const AuthenticationProvidersInfoSchema = BaseSchema.extend({ body: z.object({ /** Authentication Provider Id */ - id: z.string().uuid(), + id: z.uuid(), }), }); @@ -15,7 +15,7 @@ export type AuthenticationProvidersInfoReq = z.infer< export const AuthenticationProvidersUpdateSchema = BaseSchema.extend({ body: z.object({ /** Authentication Provider Id */ - id: z.string().uuid(), + id: z.uuid(), /** Whether the Authentication Provider is enabled or not */ isEnabled: z.boolean(), @@ -29,7 +29,7 @@ export type AuthenticationProvidersUpdateReq = z.infer< export const AuthenticationProvidersDeleteSchema = BaseSchema.extend({ body: z.object({ /** Authentication Provider Id */ - id: z.string().uuid(), + id: z.uuid(), }), }); diff --git a/server/routes/api/collections/collections.test.ts b/server/routes/api/collections/collections.test.ts index 26baadf17f..d6d723f857 100644 --- a/server/routes/api/collections/collections.test.ts +++ b/server/routes/api/collections/collections.test.ts @@ -703,7 +703,7 @@ describe("#collections.add_group", () => { const body = await res.json(); expect(res.status).toEqual(400); expect(body.message).toEqual( - "permission: Expected 'read' | 'read_write' | 'admin', received null" + 'permission: Invalid option: expected one of "read"|"read_write"|"admin"' ); }); diff --git a/server/routes/api/collections/schema.ts b/server/routes/api/collections/schema.ts index e053cbaca0..37322b9244 100644 --- a/server/routes/api/collections/schema.ts +++ b/server/routes/api/collections/schema.ts @@ -25,17 +25,17 @@ export const CollectionsCreateSchema = BaseSchema.extend({ description: z.string().nullish(), data: ProsemirrorSchema({ allowEmpty: true }).nullish(), permission: z - .nativeEnum(CollectionPermission) + .enum(CollectionPermission) .nullish() .transform((val) => (isUndefined(val) ? null : val)), - sharing: z.boolean().default(true), + sharing: z.boolean().prefault(true), icon: zodIconType().optional(), sort: z .object({ field: z.union([z.literal("title"), z.literal("index")]), direction: z.union([z.literal("asc"), z.literal("desc")]), }) - .default(Collection.DEFAULT_SORT), + .prefault(Collection.DEFAULT_SORT), index: z .string() .regex(ValidateIndex.regex, { message: ValidateIndex.message }) @@ -69,13 +69,13 @@ export type CollectionsDocumentsReq = z.infer< export const CollectionsImportSchema = BaseSchema.extend({ body: z.object({ permission: z - .nativeEnum(CollectionPermission) + .enum(CollectionPermission) .nullish() .transform((val) => (isUndefined(val) ? null : val)), - attachmentId: z.string().uuid(), + attachmentId: z.uuid(), format: z - .nativeEnum(FileOperationFormat) - .default(FileOperationFormat.MarkdownZip), + .enum(FileOperationFormat) + .prefault(FileOperationFormat.MarkdownZip), }), }); @@ -83,10 +83,10 @@ export type CollectionsImportReq = z.infer; export const CollectionsAddGroupSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ - groupId: z.string().uuid(), + groupId: z.uuid(), permission: z - .nativeEnum(CollectionPermission) - .default(CollectionPermission.ReadWrite), + .enum(CollectionPermission) + .prefault(CollectionPermission.ReadWrite), }), }); @@ -94,7 +94,7 @@ export type CollectionsAddGroupsReq = z.infer; export const CollectionsRemoveGroupSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ - groupId: z.string().uuid(), + groupId: z.uuid(), }), }); @@ -104,8 +104,8 @@ export type CollectionsRemoveGroupReq = z.infer< export const CollectionsAddUserSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ - userId: z.string().uuid(), - permission: z.nativeEnum(CollectionPermission).optional(), + userId: z.uuid(), + permission: z.enum(CollectionPermission).optional(), }), }); @@ -113,7 +113,7 @@ export type CollectionsAddUserReq = z.infer; export const CollectionsRemoveUserSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ - userId: z.string().uuid(), + userId: z.uuid(), }), }); @@ -124,7 +124,7 @@ export type CollectionsRemoveUserReq = z.infer< export const CollectionsMembershipsSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ query: z.string().optional(), - permission: z.nativeEnum(CollectionPermission).optional(), + permission: z.enum(CollectionPermission).optional(), }), }); @@ -135,9 +135,9 @@ export type CollectionsMembershipsReq = z.infer< export const CollectionsExportSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ format: z - .nativeEnum(FileOperationFormat) - .default(FileOperationFormat.MarkdownZip), - includeAttachments: z.boolean().default(true), + .enum(FileOperationFormat) + .prefault(FileOperationFormat.MarkdownZip), + includeAttachments: z.boolean().prefault(true), }), }); @@ -146,10 +146,10 @@ export type CollectionsExportReq = z.infer; export const CollectionsExportAllSchema = BaseSchema.extend({ body: z.object({ format: z - .nativeEnum(FileOperationFormat) - .default(FileOperationFormat.MarkdownZip), - includeAttachments: z.boolean().default(true), - includePrivate: z.boolean().default(true), + .enum(FileOperationFormat) + .prefault(FileOperationFormat.MarkdownZip), + includeAttachments: z.boolean().prefault(true), + includePrivate: z.boolean().prefault(true), }), }); @@ -163,7 +163,7 @@ export const CollectionsUpdateSchema = BaseSchema.extend({ description: z.string().nullish(), data: ProsemirrorSchema({ allowEmpty: true }).nullish(), icon: zodIconType().nullish(), - permission: z.nativeEnum(CollectionPermission).nullish(), + permission: z.enum(CollectionPermission).nullish(), color: z .string() .regex(ValidateColor.regex, { message: ValidateColor.message }) @@ -183,12 +183,12 @@ export type CollectionsUpdateReq = z.infer; export const CollectionsListSchema = BaseSchema.extend({ body: z.object({ - includeListOnly: z.boolean().default(false), + includeListOnly: z.boolean().prefault(false), query: z.string().optional(), /** Collection statuses to include in results */ - statusFilter: z.nativeEnum(CollectionStatusFilter).array().optional(), + statusFilter: z.enum(CollectionStatusFilter).array().optional(), }), }); diff --git a/server/routes/api/comments/schema.ts b/server/routes/api/comments/schema.ts index 6427975afc..0cbad755c1 100644 --- a/server/routes/api/comments/schema.ts +++ b/server/routes/api/comments/schema.ts @@ -7,7 +7,7 @@ import { zodEmojiType } from "@server/utils/zod"; const BaseIdSchema = z.object({ /** Comment Id */ - id: z.string().uuid(), + id: z.uuid(), }); const CommentsSortParamsSchema = z.object({ @@ -15,7 +15,7 @@ const CommentsSortParamsSchema = z.object({ sort: z .string() .refine((val) => ["createdAt", "updatedAt"].includes(val)) - .default("createdAt"), + .prefault("createdAt"), /** Specifies the sort order with respect to sort field */ direction: z @@ -28,13 +28,13 @@ export const CommentsCreateSchema = BaseSchema.extend({ body: z .object({ /** Allow creation with a specific ID */ - id: z.string().uuid().optional(), + id: z.uuid().optional(), /** Create comment for this document */ - documentId: z.string().uuid(), + documentId: z.uuid(), /** Create comment under this parent */ - parentCommentId: z.string().uuid().optional(), + parentCommentId: z.uuid().optional(), /** Create comment with this data */ data: ProsemirrorSchema({ schema: commentSchema }).optional(), @@ -43,7 +43,7 @@ export const CommentsCreateSchema = BaseSchema.extend({ text: z.string().optional(), }) .refine((obj) => !(isEmpty(obj.data) && isEmpty(obj.text)), { - message: "One of data or text is required", + error: "One of data or text is required", }), }); @@ -71,9 +71,9 @@ export const CommentsListSchema = BaseSchema.extend({ /** Id of a collection to list comments for */ collectionId: z.string().optional(), /** Id of a parent comment to list comments for */ - parentCommentId: z.string().uuid().optional(), + parentCommentId: z.uuid().optional(), /** Comment statuses to include in results */ - statusFilter: z.nativeEnum(CommentStatusFilter).array().optional(), + statusFilter: z.enum(CommentStatusFilter).array().optional(), /** Whether to include anchor text, if it exists */ includeAnchorText: z.boolean().optional(), }), diff --git a/server/routes/api/cron/cron.test.ts b/server/routes/api/cron/cron.test.ts index 3aa398178e..2c14c7f885 100644 --- a/server/routes/api/cron/cron.test.ts +++ b/server/routes/api/cron/cron.test.ts @@ -30,7 +30,7 @@ describe("POST /api/cron.daily", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toBe("limit: Number must be greater than 0"); + expect(body.message).toBe("limit: Too small: expected number to be >0"); }); }); @@ -53,7 +53,7 @@ describe("GET /api/cron.daily", () => { const res = await server.get("/api/cron.daily?limit=-1"); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toBe("limit: Number must be greater than 0"); + expect(body.message).toBe("limit: Too small: expected number to be >0"); }); }); @@ -84,7 +84,7 @@ describe("POST /api/utils.gc", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toBe("limit: Number must be greater than 0"); + expect(body.message).toBe("limit: Too small: expected number to be >0"); }); }); @@ -107,7 +107,7 @@ describe("GET /api/utils.gc", () => { const res = await server.get("/api/utils.gc?limit=-1"); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toBe("limit: Number must be greater than 0"); + expect(body.message).toBe("limit: Too small: expected number to be >0"); }); }); diff --git a/server/routes/api/cron/schema.ts b/server/routes/api/cron/schema.ts index cd742e9e56..1384dffbe6 100644 --- a/server/routes/api/cron/schema.ts +++ b/server/routes/api/cron/schema.ts @@ -5,11 +5,11 @@ import { BaseSchema } from "../schema"; export const CronSchema = BaseSchema.extend({ body: z.object({ token: z.string().optional(), - limit: z.coerce.number().gt(0).default(500), + limit: z.coerce.number().gt(0).prefault(500), }), query: z.object({ token: z.string().optional(), - limit: z.coerce.number().gt(0).default(500), + limit: z.coerce.number().gt(0).prefault(500), }), }).refine((req) => !(isEmpty(req.body.token) && isEmpty(req.query.token)), { message: "token is required", diff --git a/server/routes/api/developer/schema.ts b/server/routes/api/developer/schema.ts index b19a276c72..1ffe5e5c8c 100644 --- a/server/routes/api/developer/schema.ts +++ b/server/routes/api/developer/schema.ts @@ -3,7 +3,7 @@ import { BaseSchema } from "../schema"; export const CreateTestUsersSchema = BaseSchema.extend({ body: z.object({ - count: z.coerce.number().default(10), + count: z.coerce.number().prefault(10), }), }); diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 7e1d6ee752..28343e79e0 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -506,7 +506,7 @@ describe("#documents.info", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("shareId: Invalid uuid"); + expect(body.message).toEqual("shareId: Invalid input"); }); }); @@ -634,7 +634,7 @@ describe("#documents.list", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("userId: Invalid uuid"); + expect(body.message).toEqual("userId: Invalid UUID"); }); it("should fail for invalid collectionId", async () => { @@ -647,7 +647,7 @@ describe("#documents.list", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("collectionId: Invalid uuid"); + expect(body.message).toEqual("collectionId: Invalid UUID"); }); it("should fail for invalid parentDocumentId", async () => { @@ -660,7 +660,7 @@ describe("#documents.list", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("parentDocumentId: Invalid uuid"); + expect(body.message).toEqual("parentDocumentId: Invalid UUID"); }); it("should fail for invalid backlinkDocumentId", async () => { @@ -673,7 +673,7 @@ describe("#documents.list", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("backlinkDocumentId: Invalid uuid"); + expect(body.message).toEqual("backlinkDocumentId: Invalid UUID"); }); it("should return documents", async () => { @@ -1096,7 +1096,7 @@ describe("#documents.drafts", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("collectionId: Invalid uuid"); + expect(body.message).toEqual("collectionId: Invalid UUID"); }); it("should fail for invalid dateFilter", async () => { @@ -1270,7 +1270,9 @@ describe("#documents.search_titles", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("query: Required"); + expect(body.message).toEqual( + "query: Invalid input: expected string, received undefined" + ); }); it("should return case insensitive results for partial query", async () => { @@ -2089,7 +2091,9 @@ describe("#documents.templatize", () => { }); const body = await res.json(); expect(res.status).toBe(400); - expect(body.message).toBe("publish: Required"); + expect(body.message).toBe( + "publish: Invalid input: expected boolean, received undefined" + ); }); it("should create a published non-workspace template", async () => { const user = await buildUser(); @@ -2693,9 +2697,7 @@ describe("#documents.move", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual( - "index: Number must be greater than or equal to 0" - ); + expect(body.message).toEqual("index: Too small: expected number to be >=0"); }); it("should move doc to the top of collection as its first child", async () => { @@ -2942,7 +2944,7 @@ describe("#documents.restore", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("collectionId: Invalid uuid"); + expect(body.message).toEqual("collectionId: Invalid UUID"); }); it("should allow restore of trashed drafts of a collection", async () => { @@ -3572,7 +3574,7 @@ describe("#documents.create", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("collectionId: Invalid uuid"); + expect(body.message).toEqual("collectionId: Invalid UUID"); }); it("should succeed if collectionId is null", async () => { @@ -3633,7 +3635,7 @@ describe("#documents.create", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("parentDocumentId: Invalid uuid"); + expect(body.message).toEqual("parentDocumentId: Invalid UUID"); }); it("should create as a new document with icon", async () => { @@ -3996,7 +3998,7 @@ describe("#documents.update", () => { const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toBe("icon: Invalid"); + expect(body.message).toBe("icon: Invalid input"); }); it("should successfully update the icon", async () => { @@ -4400,7 +4402,7 @@ describe("#documents.update", () => { }); const body = await res.json(); expect(res.status).toBe(400); - expect(body.message).toBe("collectionId: Invalid uuid"); + expect(body.message).toBe("collectionId: Invalid UUID"); }); it("should require id", async () => { diff --git a/server/routes/api/documents/schema.ts b/server/routes/api/documents/schema.ts index b441739c26..7d31235597 100644 --- a/server/routes/api/documents/schema.ts +++ b/server/routes/api/documents/schema.ts @@ -26,7 +26,7 @@ const DocumentsSortParamsSchema = z.object({ "popularityScore", ].includes(val) ) - .default("updatedAt"), + .prefault("updatedAt"), /** Specifies the sort order with respect to sort field */ direction: z @@ -49,25 +49,25 @@ const DateFilterSchema = z.object({ const BaseSearchSchema = DateFilterSchema.extend({ /** Filter results for team based on the collection */ - collectionId: z.string().uuid().optional(), + collectionId: z.uuid().optional(), /** Filter results based on user */ - userId: z.string().uuid().optional(), + userId: z.uuid().optional(), /** Filter results based on content within a document and it's children */ - documentId: z.string().uuid().optional(), + documentId: z.uuid().optional(), /** Document statuses to include in results */ - statusFilter: z.nativeEnum(StatusFilter).array().optional(), + statusFilter: z.enum(StatusFilter).array().optional(), /** Filter results for the team derived from shareId */ shareId: zodShareIdType().optional(), /** Min words to be shown in the results snippets */ - snippetMinWords: z.number().default(20), + snippetMinWords: z.number().prefault(20), /** Max words to be accomodated in the results snippets */ - snippetMaxWords: z.number().default(30), + snippetMaxWords: z.number().prefault(30), }); const BaseIdSchema = z.object({ @@ -78,28 +78,28 @@ const BaseIdSchema = z.object({ export const DocumentsListSchema = BaseSchema.extend({ body: DocumentsSortParamsSchema.extend({ /** Id of the user who created the doc */ - userId: z.string().uuid().optional(), + userId: z.uuid().optional(), /** Alias for userId - kept for backwards compatibility */ - user: z.string().uuid().optional(), + user: z.uuid().optional(), /** Id of the collection to which the document belongs */ - collectionId: z.string().uuid().optional(), + collectionId: z.uuid().optional(), /** Alias for collectionId - kept for backwards compatibility */ - collection: z.string().uuid().optional(), + collection: z.uuid().optional(), /** Id of the backlinked document */ - backlinkDocumentId: z.string().uuid().optional(), + backlinkDocumentId: z.uuid().optional(), /** Id of the parent document to which the document belongs */ - parentDocumentId: z.string().uuid().nullish(), + parentDocumentId: z.uuid().nullish(), /** Boolean which denotes whether the document is a template */ template: z.boolean().optional(), /** Document statuses to include in results */ - statusFilter: z.nativeEnum(StatusFilter).array().optional(), + statusFilter: z.enum(StatusFilter).array().optional(), }), // Maintains backwards compatibility }).transform((req) => { @@ -116,7 +116,7 @@ export type DocumentsListReq = z.infer; export const DocumentsArchivedSchema = BaseSchema.extend({ body: DocumentsSortParamsSchema.extend({ /** Id of the collection to which archived documents should belong */ - collectionId: z.string().uuid().optional(), + collectionId: z.uuid().optional(), }), }); @@ -135,9 +135,9 @@ export const DocumentsViewedSchema = BaseSchema.extend({ export type DocumentsViewedReq = z.infer; export const DocumentsDraftsSchema = BaseSchema.extend({ - body: DocumentsSortParamsSchema.merge(DateFilterSchema).extend({ + body: DocumentsSortParamsSchema.extend(DateFilterSchema.shape).extend({ /** Id of the collection to which the document belongs */ - collectionId: z.string().uuid().optional(), + collectionId: z.uuid().optional(), }), }); @@ -160,7 +160,7 @@ export type DocumentsInfoReq = z.infer; export const DocumentsExportSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ signedUrls: z.number().optional(), - includeChildDocuments: z.boolean().default(false), + includeChildDocuments: z.boolean().prefault(false), }), }); @@ -169,10 +169,10 @@ export type DocumentsExportReq = z.infer; export const DocumentsRestoreSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ /** Id of the collection to which the document belongs */ - collectionId: z.string().uuid().optional(), + collectionId: z.uuid().optional(), /** Id of document revision */ - revisionId: z.string().uuid().optional(), + revisionId: z.uuid().optional(), }), }); @@ -223,9 +223,9 @@ export const DocumentsDuplicateSchema = BaseSchema.extend({ /** Whether the new document should be published */ publish: z.boolean().optional(), /** Id of the collection to which the document should be copied */ - collectionId: z.string().uuid().optional(), + collectionId: z.uuid().optional(), /** Id of the parent document to which the document should be copied */ - parentDocumentId: z.string().uuid().optional(), + parentDocumentId: z.uuid().optional(), }), }); @@ -269,16 +269,16 @@ export const DocumentsUpdateSchema = BaseSchema.extend({ publish: z.boolean().optional(), /** Doc template Id */ - templateId: z.string().uuid().nullish(), + templateId: z.uuid().nullish(), /** Doc collection Id */ - collectionId: z.string().uuid().nullish(), + collectionId: z.uuid().nullish(), /** @deprecated Use editMode instead */ append: z.boolean().optional(), /** The edit mode for text updates: "replace", "append", or "prepend" */ - editMode: z.nativeEnum(TextEditMode).optional(), + editMode: z.enum(TextEditMode).optional(), /** @deprecated Version of the API to be used, remove in a few releases */ apiVersion: z.number().optional(), @@ -313,10 +313,10 @@ export type DocumentsUpdateReq = z.infer; export const DocumentsMoveSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ /** Id of collection to which the doc is supposed to be moved */ - collectionId: z.string().uuid().optional().nullish(), + collectionId: z.uuid().optional().nullish(), /** Parent Id, in case if the doc is moved to a new parent */ - parentDocumentId: z.string().uuid().nullish(), + parentDocumentId: z.uuid().nullish(), /** Helps evaluate the new index in collection structure upon move */ index: z.number().gte(0).optional(), @@ -345,7 +345,7 @@ export type DocumentsDeleteReq = z.infer; export const DocumentsUnpublishSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ /** Whether to detach the document from the collection */ - detach: z.boolean().default(false), + detach: z.boolean().prefault(false), /** @deprecated Version of the API to be used, remove in a few releases */ apiVersion: z.number().optional(), @@ -366,18 +366,18 @@ export const DocumentsImportSchema = BaseSchema.extend({ .optional(), /** Import docs to this collection */ - collectionId: z.string().uuid().nullish(), + collectionId: z.uuid().nullish(), /** Import under this parent doc */ - parentDocumentId: z.string().uuid().nullish(), + parentDocumentId: z.uuid().nullish(), /** ID of a pre-uploaded attachment to import from */ - attachmentId: z.string().uuid().optional(), + attachmentId: z.uuid().optional(), }) .refine( (req) => !(isEmpty(req.collectionId) && isEmpty(req.parentDocumentId)), { - message: "one of collectionId or parentDocumentId is required", + error: "one of collectionId or parentDocumentId is required", } ), file: z.custom().optional(), @@ -411,23 +411,23 @@ export const DocumentsCreateSchema = BaseSchema.extend({ publish: z.boolean().optional(), /** Collection to create document within */ - collectionId: z.string().uuid().nullish(), + collectionId: z.uuid().nullish(), /** Index to create the document at within the collection */ index: z.number().optional(), /** Parent document to create within */ - parentDocumentId: z.string().uuid().nullish(), + parentDocumentId: z.uuid().nullish(), /** A template to create the document from */ - templateId: z.string().uuid().optional(), + templateId: z.uuid().optional(), /** Optionally set the created date in the past */ createdAt: z.coerce .date() .optional() .refine((data) => !data || data < new Date(), { - message: "createdAt must be in the past", + error: "createdAt must be in the past", }), /** Boolean to denote if the document should occupy full width */ @@ -451,7 +451,7 @@ export const DocumentsUsersSchema = BaseSchema.extend({ /** Query term to search users by name */ query: z.string().optional(), /** Id of the user to search within document access */ - userId: z.string().uuid().optional(), + userId: z.uuid().optional(), }), }); @@ -466,9 +466,9 @@ export type DocumentsChildrenReq = z.infer; export const DocumentsAddUserSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ /** Id of the user who is to be added */ - userId: z.string().uuid(), + userId: z.uuid(), /** Permission to be granted to the added user */ - permission: z.nativeEnum(DocumentPermission).optional(), + permission: z.enum(DocumentPermission).optional(), }), }); @@ -477,7 +477,7 @@ export type DocumentsAddUserReq = z.infer; export const DocumentsRemoveUserSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ /** Id of the user who is to be removed */ - userId: z.string().uuid(), + userId: z.uuid(), }), }); @@ -485,10 +485,10 @@ export type DocumentsRemoveUserReq = z.infer; export const DocumentsAddGroupSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ - groupId: z.string().uuid(), + groupId: z.uuid(), permission: z - .nativeEnum(DocumentPermission) - .default(DocumentPermission.ReadWrite), + .enum(DocumentPermission) + .prefault(DocumentPermission.ReadWrite), }), }); @@ -496,7 +496,7 @@ export type DocumentsAddGroupsReq = z.infer; export const DocumentsRemoveGroupSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ - groupId: z.string().uuid(), + groupId: z.uuid(), }), }); @@ -515,7 +515,7 @@ export type DocumentsSharedWithUserReq = z.infer< export const DocumentsMembershipsSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ query: z.string().optional(), - permission: z.nativeEnum(DocumentPermission).optional(), + permission: z.enum(DocumentPermission).optional(), }), }); diff --git a/server/routes/api/emojis/schema.ts b/server/routes/api/emojis/schema.ts index 37da0ec61f..a2af24aa15 100644 --- a/server/routes/api/emojis/schema.ts +++ b/server/routes/api/emojis/schema.ts @@ -7,12 +7,12 @@ export const EmojisInfoSchema = BaseSchema.extend({ body: z .object({ /** ID of the emoji to fetch */ - id: z.string().uuid().optional(), + id: z.uuid().optional(), /** Name of the emoji to fetch */ name: z.string().min(1).max(EmojiValidation.maxNameLength).optional(), }) .refine((data) => data.id || data.name, { - message: "Either id or name is required", + error: "Either id or name is required", }), }); @@ -27,21 +27,21 @@ export const EmojisCreateSchema = BaseSchema.extend({ /** Name/shortcode for the emoji (e.g., "awesome") */ name: z.string().min(1).max(EmojiValidation.maxNameLength), /** URL to the emoji image */ - attachmentId: z.string().uuid(), + attachmentId: z.uuid(), }), }); export const EmojisDeleteSchema = BaseSchema.extend({ body: z.object({ /** ID of the emoji to delete */ - id: z.string().uuid(), + id: z.uuid(), }), }); export const EmojisRedirectSchema = BaseSchema.extend({ query: z.object({ /** Id of the emoji */ - id: z.string().uuid(), + id: z.uuid(), /** Share Id, if available */ shareId: zodShareIdType().optional(), }), diff --git a/server/routes/api/events/schema.ts b/server/routes/api/events/schema.ts index 624011f160..70842345a9 100644 --- a/server/routes/api/events/schema.ts +++ b/server/routes/api/events/schema.ts @@ -15,16 +15,16 @@ export const EventsListSchema = BaseSchema.extend({ .optional(), /** Id of the user who performed the action */ - actorId: z.string().uuid().optional(), + actorId: z.uuid().optional(), /** Id of the document to filter the events for */ - documentId: z.string().uuid().optional(), + documentId: z.uuid().optional(), /** Id of the collection to filter the events for */ - collectionId: z.string().uuid().optional(), + collectionId: z.uuid().optional(), /** Whether to include audit events */ - auditLog: z.boolean().default(false), + auditLog: z.boolean().prefault(false), /** @deprecated, use 'events' parameter instead * Name of the event to retrieve @@ -35,7 +35,7 @@ export const EventsListSchema = BaseSchema.extend({ sort: z .string() .refine((val) => ["name", "createdAt"].includes(val)) - .default("createdAt"), + .prefault("createdAt"), /** The direction to sort the events */ direction: z diff --git a/server/routes/api/fileOperations/schema.ts b/server/routes/api/fileOperations/schema.ts index 5560193749..b25c1b9285 100644 --- a/server/routes/api/fileOperations/schema.ts +++ b/server/routes/api/fileOperations/schema.ts @@ -23,7 +23,7 @@ const CollectionsSortParamsSchema = z.object({ export const FileOperationsInfoSchema = BaseSchema.extend({ body: z.object({ /** Id of the file operation to be retrieved */ - id: z.string().uuid(), + id: z.uuid(), }), }); @@ -41,11 +41,11 @@ export type FileOperationsListReq = z.infer; export const FileOperationsRedirectSchema = BaseSchema.extend({ body: z.object({ /** Id of the file operation to access */ - id: z.string().uuid().optional(), + id: z.uuid().optional(), }), query: z.object({ /** Id of the file operation to access */ - id: z.string().uuid().optional(), + id: z.uuid().optional(), }), }).refine((req) => !(isEmpty(req.body.id) && isEmpty(req.query.id)), { message: "id is required", @@ -58,7 +58,7 @@ export type FileOperationsRedirectReq = z.infer< export const FileOperationsDeleteSchema = BaseSchema.extend({ body: z.object({ /** Id of the file operation to delete */ - id: z.string().uuid(), + id: z.uuid(), }), }); diff --git a/server/routes/api/groupMemberships/schema.ts b/server/routes/api/groupMemberships/schema.ts index 6229215dff..90013291cf 100644 --- a/server/routes/api/groupMemberships/schema.ts +++ b/server/routes/api/groupMemberships/schema.ts @@ -3,7 +3,7 @@ import { BaseSchema } from "@server/routes/api/schema"; export const GroupMembershipsListSchema = BaseSchema.extend({ body: z.object({ - groupId: z.string().uuid().optional(), + groupId: z.uuid().optional(), }), }); diff --git a/server/routes/api/groups/schema.ts b/server/routes/api/groups/schema.ts index 319693fcef..5c3d5d1f11 100644 --- a/server/routes/api/groups/schema.ts +++ b/server/routes/api/groups/schema.ts @@ -5,7 +5,7 @@ import { Group } from "@server/models"; const BaseIdSchema = z.object({ /** Group Id */ - id: z.string().uuid(), + id: z.uuid(), }); export const GroupsListSchema = z.object({ @@ -19,11 +19,11 @@ export const GroupsListSchema = z.object({ sort: z .string() .refine((val) => Object.keys(Group.getAttributes()).includes(val), { - message: "Invalid sort parameter", + error: "Invalid sort parameter", }) - .default("updatedAt"), + .prefault("updatedAt"), /** Only list groups where this user is a member */ - userId: z.string().uuid().optional(), + userId: z.uuid().optional(), /** Find group matching externalId */ externalId: z.string().optional(), /** @deprecated Find group with matching name */ @@ -38,7 +38,7 @@ export type GroupsListReq = z.infer; export const GroupsInfoSchema = z.object({ body: z.object({ /** Group Id */ - id: z.string().uuid().optional(), + id: z.uuid().optional(), /** External source. */ externalId: z.string().optional(), }), @@ -58,7 +58,7 @@ export const GroupsCreateSchema = z.object({ /** Optionally link this group to an external source. */ externalId: z.string().optional(), /** Whether mentions are disabled for this group */ - disableMentions: z.boolean().optional().default(false), + disableMentions: z.boolean().optional().prefault(false), }), }); @@ -100,12 +100,12 @@ export type GroupsMembershipsReq = z.infer; export const GroupsAddUserSchema = z.object({ body: BaseIdSchema.extend({ /** User Id */ - userId: z.string().uuid(), + userId: z.uuid(), /** The permission of the user in the group */ permission: z - .nativeEnum(GroupPermission) + .enum(GroupPermission) .optional() - .default(GroupPermission.Member), + .prefault(GroupPermission.Member), }), }); @@ -114,7 +114,7 @@ export type GroupsAddUserReq = z.infer; export const GroupsRemoveUserSchema = z.object({ body: BaseIdSchema.extend({ /** User Id */ - userId: z.string().uuid(), + userId: z.uuid(), }), }); @@ -123,9 +123,9 @@ export type GroupsRemoveUserReq = z.infer; export const GroupsUpdateUserSchema = z.object({ body: BaseIdSchema.extend({ /** User Id */ - userId: z.string().uuid(), + userId: z.uuid(), /** The permission of the user in the group */ - permission: z.nativeEnum(GroupPermission), + permission: z.enum(GroupPermission), }), }); diff --git a/server/routes/api/imports/schema.ts b/server/routes/api/imports/schema.ts index b3bb012c8d..522695c8c2 100644 --- a/server/routes/api/imports/schema.ts +++ b/server/routes/api/imports/schema.ts @@ -8,7 +8,7 @@ import { BaseSchema } from "../schema"; const BaseIdSchema = z.object({ /** Id of the import */ - id: z.string().uuid(), + id: z.uuid(), }); const ImportsSortParamsSchema = z.object({ @@ -16,9 +16,9 @@ const ImportsSortParamsSchema = z.object({ sort: z .string() .refine((val) => ["createdAt", "updatedAt", "service"].includes(val), { - message: "Invalid sort parameter", + error: "Invalid sort parameter", }) - .default("createdAt"), + .prefault("createdAt"), /** Specifies the sort order with respect to sort field. */ direction: z @@ -28,7 +28,7 @@ const ImportsSortParamsSchema = z.object({ }); const BaseBodySchema = z.object({ - integrationId: z.string().uuid(), + integrationId: z.uuid(), }); export const ImportsCreateSchema = BaseSchema.extend({ @@ -44,7 +44,7 @@ export type ImportsCreateReq = z.infer; export const ImportsListSchema = BaseSchema.extend({ body: ImportsSortParamsSchema.extend({ - service: z.nativeEnum(ImportableIntegrationService).optional(), + service: z.enum(ImportableIntegrationService).optional(), }), }); diff --git a/server/routes/api/installation/schema.ts b/server/routes/api/installation/schema.ts index b67d4cec64..4c068e16d1 100644 --- a/server/routes/api/installation/schema.ts +++ b/server/routes/api/installation/schema.ts @@ -9,7 +9,7 @@ export const InstallationCreateSchema = BaseSchema.extend({ /** User name */ userName: z.string().min(1).max(UserValidation.maxNameLength), /** User email */ - userEmail: z.string().email().max(UserValidation.maxEmailLength), + userEmail: z.email().max(UserValidation.maxEmailLength), }), }); diff --git a/server/routes/api/integrations/integrations.test.ts b/server/routes/api/integrations/integrations.test.ts index 3743632b24..604d2e2721 100644 --- a/server/routes/api/integrations/integrations.test.ts +++ b/server/routes/api/integrations/integrations.test.ts @@ -110,7 +110,7 @@ describe("#integrations.create", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("url: Invalid url"); + expect(body.message).toEqual("url: Invalid URL"); }); it("should succeed with status 200 ok for an integration without url", async () => { @@ -189,7 +189,9 @@ describe("#integrations.delete", () => { const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("id: Required"); + expect(body.message).toEqual( + "id: Invalid input: expected string, received undefined" + ); }); it("should succeed as user deleting own linked account integration", async () => { diff --git a/server/routes/api/integrations/schema.ts b/server/routes/api/integrations/schema.ts index 5da920a6cf..be70929e0f 100644 --- a/server/routes/api/integrations/schema.ts +++ b/server/routes/api/integrations/schema.ts @@ -19,15 +19,15 @@ export const IntegrationsListSchema = BaseSchema.extend({ sort: z .string() .refine((val) => Object.keys(Integration.getAttributes()).includes(val), { - message: "Invalid sort parameter", + error: "Invalid sort parameter", }) - .default("updatedAt"), + .prefault("updatedAt"), /** Integration type */ - type: z.nativeEnum(IntegrationType).optional(), + type: z.enum(IntegrationType).optional(), /** Integration service */ - service: z.nativeEnum(IntegrationService).optional(), + service: z.enum(IntegrationService).optional(), }), }); @@ -36,17 +36,17 @@ export type IntegrationsListReq = z.infer; export const IntegrationsCreateSchema = BaseSchema.extend({ body: z.object({ /** Integration type */ - type: z.nativeEnum(IntegrationType), + type: z.enum(IntegrationType), /** Integration service */ - service: z.nativeEnum(UserCreatableIntegrationService), + service: z.enum(UserCreatableIntegrationService), /** Integration config/settings */ settings: z - .object({ url: z.string().url() }) + .object({ url: z.url() }) .or( z.object({ - url: z.string().url(), + url: z.url(), channel: z.string(), channelId: z.string(), }) @@ -54,13 +54,13 @@ export const IntegrationsCreateSchema = BaseSchema.extend({ .or( z.object({ measurementId: z.string(), - instanceUrl: z.string().url().optional(), + instanceUrl: z.url().optional(), scriptName: z.string().optional(), }) ) .or( z.object({ - diagrams: z.object({ url: z.string().url() }), + diagrams: z.object({ url: z.url() }), }) ) .or(z.object({ serviceTeamId: z.string() })) @@ -73,14 +73,14 @@ export type IntegrationsCreateReq = z.infer; export const IntegrationsUpdateSchema = BaseSchema.extend({ body: z.object({ /** Id of integration that needs update */ - id: z.string().uuid(), + id: z.uuid(), /** Integration config/settings */ settings: z - .object({ url: z.string().url() }) + .object({ url: z.url() }) .or( z.object({ - url: z.string().url(), + url: z.url(), channel: z.string(), channelId: z.string(), }) @@ -88,20 +88,20 @@ export const IntegrationsUpdateSchema = BaseSchema.extend({ .or( z.object({ measurementId: z.string(), - instanceUrl: z.string().url().optional(), + instanceUrl: z.url().optional(), scriptName: z.string().optional(), }) ) .or( z.object({ - diagrams: z.object({ url: z.string().url() }), + diagrams: z.object({ url: z.url() }), }) ) .or(z.object({ serviceTeamId: z.string() })) .optional(), /** Integration events */ - events: z.array(z.string()).optional().default([]), + events: z.array(z.string()).optional().prefault([]), }), }); @@ -110,7 +110,7 @@ export type IntegrationsUpdateReq = z.infer; export const IntegrationsInfoSchema = BaseSchema.extend({ body: z.object({ /** Id of integration to find */ - id: z.string().uuid(), + id: z.uuid(), }), }); @@ -119,7 +119,7 @@ export type IntegrationsInfoReq = z.infer; export const IntegrationsDeleteSchema = BaseSchema.extend({ body: z.object({ /** Id of integration to be deleted */ - id: z.string().uuid(), + id: z.uuid(), }), }); diff --git a/server/routes/api/notifications/schema.ts b/server/routes/api/notifications/schema.ts index ecc8dfd352..c0dadc92cb 100644 --- a/server/routes/api/notifications/schema.ts +++ b/server/routes/api/notifications/schema.ts @@ -5,7 +5,7 @@ import { BaseSchema } from "../schema"; export const NotificationSettingsCreateSchema = BaseSchema.extend({ body: z.object({ - eventType: z.nativeEnum(NotificationEventType), + eventType: z.enum(NotificationEventType), }), }); @@ -15,7 +15,7 @@ export type NotificationSettingsCreateReq = z.infer< export const NotificationSettingsDeleteSchema = BaseSchema.extend({ body: z.object({ - eventType: z.nativeEnum(NotificationEventType), + eventType: z.enum(NotificationEventType), }), }); @@ -25,15 +25,15 @@ export type NotificationSettingsDeleteReq = z.infer< export const NotificationsUnsubscribeSchema = BaseSchema.extend({ body: z.object({ - userId: z.string().uuid().optional(), + userId: z.uuid().optional(), token: z.string().optional(), - eventType: z.nativeEnum(NotificationEventType).optional(), + eventType: z.enum(NotificationEventType).optional(), }), query: z.object({ - follow: z.string().default(""), - userId: z.string().uuid().optional(), + follow: z.string().prefault(""), + userId: z.uuid().optional(), token: z.string().optional(), - eventType: z.nativeEnum(NotificationEventType).optional(), + eventType: z.enum(NotificationEventType).optional(), }), }).refine((req) => !(isEmpty(req.body.userId) && isEmpty(req.query.userId)), { message: "userId is required", @@ -45,7 +45,7 @@ export type NotificationsUnsubscribeReq = z.infer< export const NotificationsListSchema = BaseSchema.extend({ body: z.object({ - eventType: z.nativeEnum(NotificationEventType).nullish(), + eventType: z.enum(NotificationEventType).nullish(), archived: z.boolean().nullish(), }), }); @@ -54,7 +54,7 @@ export type NotificationsListReq = z.infer; export const NotificationsUpdateSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), viewedAt: z.coerce.date().nullish(), archivedAt: z.coerce.date().nullish(), }), @@ -75,7 +75,7 @@ export type NotificationsUpdateAllReq = z.infer< export const NotificationsPixelSchema = BaseSchema.extend({ query: z.object({ - id: z.string().uuid(), + id: z.uuid(), token: z.string(), }), }); diff --git a/server/routes/api/oauthClients/schema.ts b/server/routes/api/oauthClients/schema.ts index 719fff1f5b..b4894d1db5 100644 --- a/server/routes/api/oauthClients/schema.ts +++ b/server/routes/api/oauthClients/schema.ts @@ -6,7 +6,7 @@ export const OAuthClientsInfoSchema = BaseSchema.extend({ body: z .object({ /** OAuth client id */ - id: z.string().uuid().optional(), + id: z.uuid().optional(), /** OAuth clientId */ clientId: z.string().optional(), @@ -14,7 +14,7 @@ export const OAuthClientsInfoSchema = BaseSchema.extend({ redirectUri: z.string().optional(), }) .refine((data) => data.id || data.clientId, { - message: "Either id or clientId is required", + error: "Either id or clientId is required", }), }); @@ -25,7 +25,7 @@ export const OAuthClientsCreateSchema = BaseSchema.extend({ /** OAuth client type */ clientType: z .enum(OAuthClientValidation.clientTypes) - .default("confidential"), + .prefault("confidential"), /** OAuth client name */ name: z.string(), @@ -44,9 +44,13 @@ export const OAuthClientsCreateSchema = BaseSchema.extend({ /** OAuth client redirect uri */ redirectUris: z - .array(z.string().url()) - .min(1, { message: "At least one redirect uri is required" }) - .max(10, { message: "A maximum of 10 redirect uris are allowed" }) + .array(z.url()) + .min(1, { + error: "At least one redirect uri is required", + }) + .max(10, { + error: "A maximum of 10 redirect uris are allowed", + }) .refine( (uris) => uris.every( @@ -58,7 +62,7 @@ export const OAuthClientsCreateSchema = BaseSchema.extend({ ), /** OAuth client published */ - published: z.boolean().default(false), + published: z.boolean().prefault(false), }), }); @@ -66,7 +70,7 @@ export type OAuthClientsCreateReq = z.infer; export const OAuthClientsUpdateSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), /** OAuth client type */ clientType: z.enum(OAuthClientValidation.clientTypes).optional(), @@ -88,9 +92,13 @@ export const OAuthClientsUpdateSchema = BaseSchema.extend({ /** OAuth client redirect uri */ redirectUris: z - .array(z.string().url()) - .min(1, { message: "At least one redirect uri is required" }) - .max(10, { message: "A maximum of 10 redirect uris are allowed" }) + .array(z.url()) + .min(1, { + error: "At least one redirect uri is required", + }) + .max(10, { + error: "A maximum of 10 redirect uris are allowed", + }) .refine( (uris) => uris.every( @@ -112,7 +120,7 @@ export type OAuthClientsUpdateReq = z.infer; export const OAuthClientsDeleteSchema = BaseSchema.extend({ body: z.object({ /** OAuth client id */ - id: z.string().uuid(), + id: z.uuid(), }), }); @@ -121,7 +129,7 @@ export type OAuthClientsDeleteReq = z.infer; export const OAuthClientsRotateSecretSchema = BaseSchema.extend({ body: z.object({ /** OAuth client id */ - id: z.string().uuid(), + id: z.uuid(), }), }); diff --git a/server/routes/api/pins/pins.test.ts b/server/routes/api/pins/pins.test.ts index e231687eff..cb48f4fd47 100644 --- a/server/routes/api/pins/pins.test.ts +++ b/server/routes/api/pins/pins.test.ts @@ -444,7 +444,9 @@ describe("#pins.update", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("id: Required"); + expect(body.message).toEqual( + "id: Invalid input: expected string, received undefined" + ); }); it("should fail with status 400 bad request when index is missing", async () => { @@ -456,7 +458,9 @@ describe("#pins.update", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("index: Required"); + expect(body.message).toEqual( + "index: Invalid input: expected string, received undefined" + ); }); it("should fail with status 400 bad request when an invalid index is sent", async () => { @@ -530,7 +534,9 @@ describe("#pins.delete", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("id: Required"); + expect(body.message).toEqual( + "id: Invalid input: expected string, received undefined" + ); }); it("should fail with status 403 forbidden when user is disallowed to delete the pin", async () => { diff --git a/server/routes/api/pins/schema.ts b/server/routes/api/pins/schema.ts index 823953ff92..7217ccd066 100644 --- a/server/routes/api/pins/schema.ts +++ b/server/routes/api/pins/schema.ts @@ -8,16 +8,16 @@ export const PinsCreateSchema = BaseSchema.extend({ body: z.object({ documentId: z .string({ - required_error: "required", + error: (issue) => (issue.input === undefined ? "required" : undefined), }) .refine((val) => isUUID(val) || UrlHelper.SLUG_URL_REGEX.test(val), { - message: "must be uuid or url slug", + error: "must be uuid or url slug", }), - collectionId: z.string().uuid().nullish(), + collectionId: z.uuid().nullish(), index: z .string() .regex(new RegExp("^[\x20-\x7E]+$"), { - message: "must be between x20 to x7E ASCII", + error: "must be between x20 to x7E ASCII", }) .optional(), }), @@ -30,7 +30,7 @@ export const PinsInfoSchema = BaseSchema.extend({ /** Document to get the pin info for. */ documentId: zodIdType(), /** Collection to which the pin belongs to. If not set, it's considered as "Home" pin. */ - collectionId: z.string().uuid().nullish(), + collectionId: z.uuid().nullish(), }), }); @@ -38,7 +38,7 @@ export type PinsInfoReq = z.infer; export const PinsListSchema = BaseSchema.extend({ body: z.object({ - collectionId: z.string().uuid().nullish(), + collectionId: z.uuid().nullish(), }), }); @@ -46,9 +46,9 @@ export type PinsListReq = z.infer; export const PinsUpdateSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), index: z.string().regex(new RegExp("^[\x20-\x7E]+$"), { - message: "must be between x20 to x7E ASCII", + error: "must be between x20 to x7E ASCII", }), }), }); @@ -57,7 +57,7 @@ export type PinsUpdateReq = z.infer; export const PinsDeleteSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), }), }); diff --git a/server/routes/api/reactions/schema.ts b/server/routes/api/reactions/schema.ts index b5b3534684..18574203f8 100644 --- a/server/routes/api/reactions/schema.ts +++ b/server/routes/api/reactions/schema.ts @@ -4,7 +4,7 @@ import { BaseSchema } from "../schema"; export const ReactionsListSchema = BaseSchema.extend({ body: z.object({ /** Id of the comment to list reactions for. */ - commentId: z.string().uuid(), + commentId: z.uuid(), }), }); diff --git a/server/routes/api/relationships/relationships.test.ts b/server/routes/api/relationships/relationships.test.ts index effc6436b7..db96327212 100644 --- a/server/routes/api/relationships/relationships.test.ts +++ b/server/routes/api/relationships/relationships.test.ts @@ -62,7 +62,9 @@ describe("#relationships.info", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("id: Required"); + expect(body.message).toEqual( + "id: Invalid input: expected string, received undefined" + ); }); it("should fail with status 400 bad request when id is not a valid UUID", async () => { @@ -74,7 +76,7 @@ describe("#relationships.info", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("id: Invalid uuid"); + expect(body.message).toEqual("id: Invalid UUID"); }); it("should fail with status 404 not found when relationship does not exist", async () => { diff --git a/server/routes/api/relationships/schema.ts b/server/routes/api/relationships/schema.ts index 63cd31be98..ae76c11499 100644 --- a/server/routes/api/relationships/schema.ts +++ b/server/routes/api/relationships/schema.ts @@ -5,7 +5,7 @@ import { BaseSchema } from "../schema"; export const RelationshipsInfoSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), }), }); @@ -14,7 +14,7 @@ export type RelationshipsInfoReq = z.infer; export const RelationshipsListSchema = BaseSchema.extend({ body: z .object({ - type: z.nativeEnum(RelationshipType).optional(), + type: z.enum(RelationshipType).optional(), documentId: z .string() .refine(ValidateDocumentId.isValid, { diff --git a/server/routes/api/revisions/schema.ts b/server/routes/api/revisions/schema.ts index 5227b1081f..eb2058cb42 100644 --- a/server/routes/api/revisions/schema.ts +++ b/server/routes/api/revisions/schema.ts @@ -7,11 +7,11 @@ import { BaseSchema } from "@server/routes/api/schema"; export const RevisionsInfoSchema = BaseSchema.extend({ body: z .object({ - id: z.string().uuid().optional(), - documentId: z.string().uuid().optional(), + id: z.uuid().optional(), + documentId: z.uuid().optional(), }) .refine((req) => !(isEmpty(req.id) && isEmpty(req.documentId)), { - message: "id or documentId is required", + error: "id or documentId is required", }), }); @@ -19,7 +19,7 @@ export type RevisionsInfoReq = z.infer; export const RevisionsUpdateSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), name: z .string() @@ -41,11 +41,11 @@ export const RevisionsListSchema = z.object({ sort: z .string() .refine((val) => Object.keys(Revision.getAttributes()).includes(val), { - message: "Invalid sort parameter", + error: "Invalid sort parameter", }) - .default("createdAt"), + .prefault("createdAt"), - documentId: z.string().uuid(), + documentId: z.uuid(), }), }); @@ -53,7 +53,7 @@ export type RevisionsListReq = z.infer; export const RevisionsDeleteSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), }), }); @@ -61,7 +61,7 @@ export type RevisionsDeleteReq = z.infer; export const RevisionsExportSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), }), }); diff --git a/server/routes/api/searches/schema.ts b/server/routes/api/searches/schema.ts index 7568e9425f..61184f0d55 100644 --- a/server/routes/api/searches/schema.ts +++ b/server/routes/api/searches/schema.ts @@ -4,7 +4,7 @@ import { BaseSchema } from "../schema"; export const SearchesDeleteSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid().optional(), + id: z.uuid().optional(), query: z.string().optional(), }), }).refine((req) => !(isEmpty(req.body.id) && isEmpty(req.body.query)), { @@ -15,7 +15,7 @@ export type SearchesDeleteReq = z.infer; export const SearchesUpdateSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), score: z.number().min(-1).max(1), }), }); diff --git a/server/routes/api/searches/searches.test.ts b/server/routes/api/searches/searches.test.ts index db0f8d4d75..4532160a29 100644 --- a/server/routes/api/searches/searches.test.ts +++ b/server/routes/api/searches/searches.test.ts @@ -144,7 +144,7 @@ describe("#searches.delete", () => { const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("id: Invalid uuid"); + expect(body.message).toEqual("id: Invalid UUID"); }); it("should succeed with status 200 ok and successfully delete the query", async () => { diff --git a/server/routes/api/shares/schema.ts b/server/routes/api/shares/schema.ts index 5371b3f506..2215191c08 100644 --- a/server/routes/api/shares/schema.ts +++ b/server/routes/api/shares/schema.ts @@ -20,7 +20,7 @@ export const SharesInfoSchema = BaseSchema.extend({ isEmpty(body.documentId) ), { - message: "one of id, collectionId, or documentId is required", + error: "one of id, collectionId, or documentId is required", } ), }); @@ -37,7 +37,7 @@ export const SharesListSchema = BaseSchema.extend({ ", " )}`, }) - .default("updatedAt"), + .prefault("updatedAt"), direction: z .string() .optional() @@ -49,7 +49,7 @@ export type SharesListReq = z.infer; export const SharesUpdateSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), includeChildDocuments: z.boolean().optional(), published: z.boolean().optional(), allowIndexing: z.boolean().optional(), @@ -58,7 +58,7 @@ export const SharesUpdateSchema = BaseSchema.extend({ urlId: z .string() .regex(UrlHelper.SHARE_URL_SLUG_REGEX, { - message: "must contain only alphanumeric and dashes", + error: "must contain only alphanumeric and dashes", }) .nullish(), }), @@ -71,20 +71,20 @@ export const SharesCreateSchema = BaseSchema.extend({ .object({ collectionId: zodIdType().optional(), documentId: zodIdType().optional(), - published: z.boolean().default(false), + published: z.boolean().prefault(false), allowIndexing: z.boolean().optional(), showLastUpdated: z.boolean().optional(), showTOC: z.boolean().optional(), urlId: z .string() .regex(UrlHelper.SHARE_URL_SLUG_REGEX, { - message: "must contain only alphanumeric and dashes", + error: "must contain only alphanumeric and dashes", }) .optional(), - includeChildDocuments: z.boolean().default(false), + includeChildDocuments: z.boolean().prefault(false), }) .refine((obj) => !(isEmpty(obj.collectionId) && isEmpty(obj.documentId)), { - message: "one of collectionId or documentId is required", + error: "one of collectionId or documentId is required", }), }); @@ -92,7 +92,7 @@ export type SharesCreateReq = z.infer; export const SharesRevokeSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), }), }); diff --git a/server/routes/api/shares/shares.test.ts b/server/routes/api/shares/shares.test.ts index d76f69902c..2febeb3521 100644 --- a/server/routes/api/shares/shares.test.ts +++ b/server/routes/api/shares/shares.test.ts @@ -260,7 +260,7 @@ describe("#shares.create", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("documentId: Invalid"); + expect(body.message).toEqual("documentId: Must be a valid UUID or slug"); }); it("should allow creating a share record for collection", async () => { @@ -576,7 +576,7 @@ describe("#shares.info", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("documentId: Invalid"); + expect(body.message).toEqual("documentId: Must be a valid UUID or slug"); }); it("should not find share by documentId in private collection", async () => { @@ -848,7 +848,9 @@ describe("#shares.update", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("id: Required"); + expect(body.message).toEqual( + "id: Invalid input: expected string, received undefined" + ); }); it("should update urlId", async () => { @@ -1026,7 +1028,9 @@ describe("#shares.revoke", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("id: Required"); + expect(body.message).toEqual( + "id: Invalid input: expected string, received undefined" + ); }); it("should allow author to revoke a share", async () => { diff --git a/server/routes/api/stars/schema.ts b/server/routes/api/stars/schema.ts index 6fa67ae68f..8799d3ce91 100644 --- a/server/routes/api/stars/schema.ts +++ b/server/routes/api/stars/schema.ts @@ -12,7 +12,7 @@ export const StarsCreateSchema = BaseSchema.extend({ message: ValidateDocumentId.message, }) .optional(), - collectionId: z.string().uuid().optional(), + collectionId: z.uuid().optional(), index: z .string() .regex(ValidateIndex.regex, { @@ -23,7 +23,7 @@ export const StarsCreateSchema = BaseSchema.extend({ .refine( (body) => !(isEmpty(body.documentId) && isEmpty(body.collectionId)), { - message: "One of documentId or collectionId is required", + error: "One of documentId or collectionId is required", } ), }); @@ -36,7 +36,7 @@ export type StarsListReq = z.infer; export const StarsUpdateSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), index: z.string().regex(ValidateIndex.regex, { message: ValidateIndex.message, }), @@ -47,7 +47,7 @@ export type StarsUpdateReq = z.infer; export const StarsDeleteSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), }), }); diff --git a/server/routes/api/stars/stars.test.ts b/server/routes/api/stars/stars.test.ts index 58ffb01e2a..a3b1b5e948 100644 --- a/server/routes/api/stars/stars.test.ts +++ b/server/routes/api/stars/stars.test.ts @@ -83,7 +83,9 @@ describe("#stars.update", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("id: Required"); + expect(body.message).toEqual( + "id: Invalid input: expected string, received undefined" + ); }); it("should succeed with status 200 ok", async () => { @@ -116,7 +118,9 @@ describe("#stars.delete", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("id: Required"); + expect(body.message).toEqual( + "id: Invalid input: expected string, received undefined" + ); }); it("should delete users star", async () => { diff --git a/server/routes/api/subscriptions/schema.ts b/server/routes/api/subscriptions/schema.ts index e4624ad1eb..0bcc05ec26 100644 --- a/server/routes/api/subscriptions/schema.ts +++ b/server/routes/api/subscriptions/schema.ts @@ -7,7 +7,7 @@ import { BaseSchema } from "../schema"; const SubscriptionBody = z .object({ event: z.literal(SubscriptionType.Document), - collectionId: z.string().uuid().optional(), + collectionId: z.uuid().optional(), documentId: z .string() .refine(ValidateDocumentId.isValid, { @@ -16,7 +16,7 @@ const SubscriptionBody = z .optional(), }) .refine((obj) => !(isEmpty(obj.collectionId) && isEmpty(obj.documentId)), { - message: "one of collectionId or documentId is required", + error: "one of collectionId or documentId is required", }); export const SubscriptionsListSchema = BaseSchema.extend({ @@ -39,7 +39,7 @@ export type SubscriptionsCreateReq = z.infer; export const SubscriptionsDeleteSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), }), }); @@ -47,9 +47,9 @@ export type SubscriptionsDeleteReq = z.infer; export const SubscriptionsDeleteTokenSchema = BaseSchema.extend({ query: z.object({ - follow: z.string().default(""), - userId: z.string().uuid(), - documentId: z.string().uuid(), + follow: z.string().prefault(""), + userId: z.uuid(), + documentId: z.uuid(), token: z.string(), }), }); diff --git a/server/routes/api/subscriptions/subscriptions.test.ts b/server/routes/api/subscriptions/subscriptions.test.ts index 7c3b612cdf..488a42b965 100644 --- a/server/routes/api/subscriptions/subscriptions.test.ts +++ b/server/routes/api/subscriptions/subscriptions.test.ts @@ -171,7 +171,7 @@ describe("#subscriptions.create", () => { expect(body.ok).toEqual(false); expect(body.error).toEqual("validation_error"); expect(body.message).toEqual( - `event: Invalid literal value, expected "documents.update"` + `event: Invalid input: expected "documents.update"` ); }); @@ -440,7 +440,7 @@ describe("#subscriptions.info", () => { expect(response0.ok).toEqual(false); expect(response0.error).toEqual("validation_error"); expect(response0.message).toEqual( - `event: Invalid literal value, expected "documents.update"` + `event: Invalid input: expected "documents.update"` ); // `viewer` wants info about `subscriber`'s @@ -460,7 +460,7 @@ describe("#subscriptions.info", () => { expect(response1.ok).toEqual(false); expect(response1.error).toEqual("validation_error"); expect(response1.message).toEqual( - `event: Invalid literal value, expected "documents.update"` + `event: Invalid input: expected "documents.update"` ); }); }); @@ -629,7 +629,7 @@ describe("#subscriptions.list", () => { expect(body.ok).toEqual(false); expect(body.error).toEqual("validation_error"); expect(body.message).toEqual( - `event: Invalid literal value, expected "documents.update"` + `event: Invalid input: expected "documents.update"` ); }); diff --git a/server/routes/api/teams/schema.ts b/server/routes/api/teams/schema.ts index 3e7e58996b..42c027e6b0 100644 --- a/server/routes/api/teams/schema.ts +++ b/server/routes/api/teams/schema.ts @@ -25,9 +25,9 @@ export const TeamsUpdateSchema = BaseSchema.extend({ /** Whether team members are able to create new workspaces */ memberTeamCreate: z.boolean().optional(), /** The default landing collection for the team */ - defaultCollectionId: z.string().uuid().nullish(), + defaultCollectionId: z.uuid().nullish(), /** The default user role */ - defaultUserRole: z.nativeEnum(UserRole).optional(), + defaultUserRole: z.enum(UserRole).optional(), /** Whether new users must be invited to join the team */ inviteRequired: z.boolean().optional(), /** Domains allowed to sign-in with SSO */ @@ -59,8 +59,8 @@ export const TeamsUpdateSchema = BaseSchema.extend({ }) .optional(), /** Side to display the document's table of contents in relation to the main content. */ - tocPosition: z.nativeEnum(TOCPosition).optional(), - emailDisplay: z.nativeEnum(EmailDisplay).optional(), + tocPosition: z.enum(TOCPosition).optional(), + emailDisplay: z.enum(EmailDisplay).optional(), /** Whether to prevent shared documents from being embedded in iframes on external websites. */ preventDocumentEmbedding: z.boolean().optional(), }) diff --git a/server/routes/api/urls/schema.ts b/server/routes/api/urls/schema.ts index d710300201..addb74cd4d 100644 --- a/server/routes/api/urls/schema.ts +++ b/server/routes/api/urls/schema.ts @@ -9,23 +9,20 @@ import { BaseSchema } from "../schema"; export const UrlsUnfurlSchema = BaseSchema.extend({ body: z .object({ - url: z - .string() - .url() - .refine( - (val) => { - try { - const url = new URL(val); - if (url.protocol === "mention:") { - return ValidateURL.isValidMentionUrl(val); - } - return isUrl(val); - } catch (_err) { - return false; + url: z.url().refine( + (val) => { + try { + const url = new URL(val); + if (url.protocol === "mention:") { + return ValidateURL.isValidMentionUrl(val); } - }, - { message: ValidateURL.message } - ), + return isUrl(val); + } catch (_err) { + return false; + } + }, + { message: ValidateURL.message } + ), documentId: z .string() .optional() @@ -33,14 +30,16 @@ export const UrlsUnfurlSchema = BaseSchema.extend({ (val) => val ? isUUID(val) || UrlHelper.SLUG_URL_REGEX.test(val) : true, { - message: "must be uuid or url slug", + error: "must be uuid or url slug", } ), }) .refine( (val) => !(ValidateURL.isValidMentionUrl(val.url) && isNil(val.documentId)), - { message: "documentId required" } + { + error: "documentId required", + } ), }); @@ -56,10 +55,7 @@ export type UrlsCheckCnameReq = z.infer; export const UrlsCheckEmbedSchema = BaseSchema.extend({ body: z.object({ - url: z - .string() - .url() - .refine((val) => isUrl(val), { message: ValidateURL.message }), + url: z.url().refine((val) => isUrl(val), { message: ValidateURL.message }), }), }); diff --git a/server/routes/api/urls/urls.test.ts b/server/routes/api/urls/urls.test.ts index 0237adf381..30feb99aef 100644 --- a/server/routes/api/urls/urls.test.ts +++ b/server/routes/api/urls/urls.test.ts @@ -40,7 +40,7 @@ describe("#urls.unfurl", () => { const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("url: Invalid url"); + expect(body.message).toEqual("url: Invalid URL"); }); it("should fail with status 400 bad request when mention url is invalid", async () => { diff --git a/server/routes/api/userMemberships/schema.ts b/server/routes/api/userMemberships/schema.ts index f17ac0987f..2922801c56 100644 --- a/server/routes/api/userMemberships/schema.ts +++ b/server/routes/api/userMemberships/schema.ts @@ -8,7 +8,7 @@ export type UserMembershipsListReq = z.infer; export const UserMembershipsUpdateSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid(), + id: z.uuid(), index: z.string().regex(ValidateIndex.regex, { message: ValidateIndex.message, }), diff --git a/server/routes/api/users/schema.ts b/server/routes/api/users/schema.ts index 525b9fb38e..bb587e6211 100644 --- a/server/routes/api/users/schema.ts +++ b/server/routes/api/users/schema.ts @@ -11,7 +11,7 @@ import { zodEnumFromObjectKeys, zodTimezone } from "@server/utils/zod"; import { BaseSchema } from "../schema"; const BaseIdSchema = z.object({ - id: z.string().uuid(), + id: z.uuid(), }); export const UsersListSchema = z.object({ @@ -26,25 +26,20 @@ export const UsersListSchema = z.object({ sort: z .string() .refine((val) => Object.keys(User.getAttributes()).includes(val), { - message: "Invalid sort parameter", + error: "Invalid sort parameter", }) - .default("createdAt"), + .prefault("createdAt"), - ids: z.array(z.string().uuid()).optional(), + ids: z.array(z.uuid()).optional(), emails: z - .array( - z - .string() - .email() - .transform((email) => email.toLowerCase()) - ) + .array(z.email().transform((email) => email.toLowerCase())) .optional(), query: z.string().optional(), /** The user's role */ - role: z.nativeEnum(UserRole).optional(), + role: z.enum(UserRole).optional(), /** * Filter the users by their status – passing a user role is deprecated here, instead use the @@ -71,7 +66,7 @@ export type UsersListReq = z.infer; export const UsersNotificationsSubscribeSchema = z.object({ body: z.object({ - eventType: z.nativeEnum(NotificationEventType), + eventType: z.enum(NotificationEventType), }), }); @@ -81,7 +76,7 @@ export type UsersNotificationsSubscribeReq = z.infer< export const UsersNotificationsUnsubscribeSchema = z.object({ body: z.object({ - eventType: z.nativeEnum(NotificationEventType), + eventType: z.enum(NotificationEventType), }), }); @@ -91,14 +86,14 @@ export type UsersNotificationsUnsubscribeReq = z.infer< export const UsersUpdateSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid().optional(), + id: z.uuid().optional(), name: z.string().optional(), avatarUrl: z.string().nullish(), language: zodEnumFromObjectKeys(locales).optional(), preferences: z - .record( - z.nativeEnum(UserPreference), - z.union([z.boolean(), z.nativeEnum(NotificationBadgeType)]) + .partialRecord( + z.enum(UserPreference), + z.union([z.boolean(), z.enum(NotificationBadgeType)]) ) .optional(), timezone: zodTimezone().optional(), @@ -110,7 +105,7 @@ export type UsersUpdateReq = z.infer; export const UsersDeleteSchema = BaseSchema.extend({ body: z.object({ code: z.string().optional(), - id: z.string().uuid().optional(), + id: z.uuid().optional(), }), }); @@ -118,8 +113,8 @@ export type UsersDeleteSchemaReq = z.infer; export const UsersUpdateEmailSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid().optional(), - email: z.string().email(), + id: z.uuid().optional(), + email: z.email(), }), }); @@ -128,7 +123,7 @@ export type UsersUpdateEmailReq = z.infer; export const UsersUpdateEmailConfirmSchema = BaseSchema.extend({ query: z.object({ code: z.string(), - follow: z.string().default(""), + follow: z.string().prefault(""), }), }); @@ -138,7 +133,7 @@ export type UsersUpdateEmailConfirmReq = z.infer< export const UsersInfoSchema = BaseSchema.extend({ body: z.object({ - id: z.string().uuid().optional(), + id: z.uuid().optional(), }), }); @@ -152,7 +147,7 @@ export type UsersActivateReq = z.infer; export const UsersChangeRoleSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ - role: z.nativeEnum(UserRole), + role: z.enum(UserRole), }), }); @@ -166,7 +161,7 @@ export type UsersPromoteReq = z.infer; export const UsersDemoteSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ - to: z.nativeEnum(UserRole).default(UserRole.Member), + to: z.enum(UserRole).prefault(UserRole.Member), }), }); @@ -188,9 +183,9 @@ export const UsersInviteSchema = z.object({ body: z.object({ invites: z.array( z.object({ - email: z.string().email(), + email: z.email(), name: z.string(), - role: z.nativeEnum(UserRole), + role: z.enum(UserRole), }) ), }), diff --git a/server/routes/api/users/users.ts b/server/routes/api/users/users.ts index 54632a8b9a..d7f6ca794e 100644 --- a/server/routes/api/users/users.ts +++ b/server/routes/api/users/users.ts @@ -366,6 +366,7 @@ router.post( (ctx: APIContext) => { const forward = ctx as unknown as APIContext; forward.input = { + ...ctx.input, body: { id: ctx.input.body.id, role: UserRole.Admin, @@ -389,6 +390,7 @@ router.post( (ctx: APIContext) => { const forward = ctx as unknown as APIContext; forward.input = { + ...ctx.input, body: { id: ctx.input.body.id, role: ctx.input.body.to, diff --git a/server/routes/api/views/schema.ts b/server/routes/api/views/schema.ts index dd2ad9f380..ce8e8824b3 100644 --- a/server/routes/api/views/schema.ts +++ b/server/routes/api/views/schema.ts @@ -4,7 +4,7 @@ import { BaseSchema } from "../schema"; export const ViewsListSchema = BaseSchema.extend({ body: z.object({ /** Id of the document to retrieve the views for */ - documentId: z.string().uuid(), + documentId: z.uuid(), /** Whether to include views by suspended users */ includeSuspended: z.boolean().default(false), @@ -16,7 +16,7 @@ export type ViewsListReq = z.infer; export const ViewsCreateSchema = BaseSchema.extend({ body: z.object({ /** Id of the document to create the view for */ - documentId: z.string().uuid(), + documentId: z.uuid(), }), }); diff --git a/server/types.ts b/server/types.ts index 31630b040b..a366d13ae6 100644 --- a/server/types.ts +++ b/server/types.ts @@ -81,7 +81,7 @@ export type BaseReq = z.infer; export type BaseRes = unknown; export interface APIContext< - ReqT = BaseReq, + ReqT = Partial, ResT = BaseRes, > extends ParameterizedContext< AppState, diff --git a/server/utils/zod.ts b/server/utils/zod.ts index 106c0b43cd..9ed4c17acb 100644 --- a/server/utils/zod.ts +++ b/server/utils/zod.ts @@ -4,33 +4,30 @@ import { IconLibrary } from "@shared/utils/IconLibrary"; import { UrlHelper } from "@shared/utils/UrlHelper"; export function zodEnumFromObjectKeys< - TI extends Record, - R extends string = TI extends Record ? R : never, ->(input: TI): z.ZodEnum<[R, ...R[]]> { - const [firstKey, ...otherKeys] = Object.keys(input) as [R, ...R[]]; - return z.enum([firstKey, ...otherKeys]); + TI extends Record, + K extends string & keyof TI = string & keyof TI, +>(input: TI) { + const keys = Object.keys(input) as [K, ...K[]]; + return z.enum(keys); } export const zodIdType = () => - z.union([z.string().regex(UrlHelper.SLUG_URL_REGEX), z.string().uuid()], { - message: "Must be a valid UUID or slug", + z.union([z.string().regex(UrlHelper.SLUG_URL_REGEX), z.uuid()], { + error: "Must be a valid UUID or slug", }); export const zodIconType = () => z.union([ z.string().regex(emojiRegex()), zodEnumFromObjectKeys(IconLibrary.mapping), - z.string().uuid(), + z.uuid(), ]); export const zodEmojiType = () => - z.union([z.string().regex(emojiRegex()), z.string().uuid()]); + z.union([z.string().regex(emojiRegex()), z.uuid()]); export const zodShareIdType = () => - z.union([ - z.string().uuid(), - z.string().regex(UrlHelper.SHARE_URL_SLUG_REGEX), - ]); + z.union([z.uuid(), z.string().regex(UrlHelper.SHARE_URL_SLUG_REGEX)]); export const zodTimezone = () => z.string().refine( @@ -42,5 +39,7 @@ export const zodTimezone = () => return false; } }, - { message: "invalid timezone" } + { + error: "invalid timezone", + } ); diff --git a/shared/schema.ts b/shared/schema.ts index b3e790de9a..d1e3953559 100644 --- a/shared/schema.ts +++ b/shared/schema.ts @@ -8,13 +8,13 @@ import { import { PageType } from "plugins/notion/shared/types"; const BaseImportInputItemSchema = z.object({ - permission: z.nativeEnum(CollectionPermission).optional(), + permission: z.enum(CollectionPermission).optional(), }); export type BaseImportInput = z.infer[]; export const NotionImportInputItemSchema = BaseImportInputItemSchema.extend({ - type: z.nativeEnum(PageType).optional(), + type: z.enum(PageType).optional(), externalId: z.string().optional(), }); @@ -35,7 +35,7 @@ export type BaseImportTaskInput = z.infer< export const NotionImportTaskInputItemSchema = BaseImportTaskInputItemSchema.extend({ - type: z.nativeEnum(PageType), + type: z.enum(PageType), }); export type NotionImportTaskInput = z.infer< @@ -65,7 +65,7 @@ export const IssueSource = z.object({ id: z.string().nonempty(), name: z.string().nonempty(), }), - service: z.nativeEnum(IssueTrackerIntegrationService), + service: z.enum(IssueTrackerIntegrationService), }); export type IssueSource = z.infer; diff --git a/yarn.lock b/yarn.lock index 39b5594279..bf89516922 100644 --- a/yarn.lock +++ b/yarn.lock @@ -17581,7 +17581,7 @@ __metadata: y-protocols: "npm:^1.0.6" yauzl: "npm:^3.2.0" yjs: "npm:^13.6.1" - zod: "npm:^3.25.76" + zod: "npm:^4.2.1" languageName: unknown linkType: soft @@ -22910,9 +22910,9 @@ __metadata: languageName: node linkType: hard -"zod@npm:^3.19.1, zod@npm:^3.25.76": - version: 3.25.76 - resolution: "zod@npm:3.25.76" - checksum: 10c0/5718ec35e3c40b600316c5b4c5e4976f7fee68151bc8f8d90ec18a469be9571f072e1bbaace10f1e85cf8892ea12d90821b200e980ab46916a6166a4260a983c +"zod@npm:^4.2.1": + version: 4.2.1 + resolution: "zod@npm:4.2.1" + checksum: 10c0/ecb5219bddf76a42d092a843fb98ad4cb78f1e1077082772b03ef032ee5cbc80790a4051836b962d26fb4af854323bc784d628bd1b8d9898149eba7af21c5560 languageName: node linkType: hard