Validation

Zod Validation

Validation and parsing is provided by the Zod library due to its light weight and native TypeScript focus.
You can read about Zod validation in their documentation.
Note that Masquerade uses the Zod v2 tree, so make sure to reference the version 2 documentation.

Why you should validate...

Why validating and parsing unknown data is important is similar to the reason TypeScript is important. A well developed bot needs to be able to have certainty around inbound data, be that from .env variables, command line input, or data returned by the bot.
Without verifying (and providing fall-back defaults where appropriate) our code will be prone to bugs, tracing them becomes more difficult than it otherwise might have been.
Additionally, without a central validation process and schema, developers (especially when working in teams) begin to add validation ad-hoc throughout the application not just making it painful to debug, but also leading to different validation expectations being set in different places for the same variable (not to mention the additional weight of duplicated code!).

Composing Schemas

Validation schemas should be located in your application's schemas directory and exported via the index.
You can define schemas however makes sense for your application, but we recommend limiting one scope to one file.

Example Validator

1
export const AUTOMATION_VIEWPORT_WIDTH = 1280
2
export const AUTOMATION_VIEWPORT_HEIGHT = 1024
3
export const AUTOMATION_LANG = "en-GB,en-US;q=0.9,en;q=0.8"
4
5
export const EnvSchema = BaseEnvSchema.merge(
6
z.object({
7
// App
8
APP_NAME: z.string().default("MyAppName"),
9
// Logging
10
LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"),
11
// Automation
12
AUTOMATION_HEADLESS: z.boolean().default(false),
13
AUTOMATION_HIDE_SCROLLBARS: z.boolean().default(false),
14
AUTOMATION_LANG: z.string().default(AUTOMATION_LANG),
15
})
16
)
17
Copied!

Merging Schemas

You can merge custom schemas with core framework schemas, or schemas provided by third-party plugins. Documentation on merging is located here.

Using Validators

Parsing with a validator is fairly simple and the Zod library provides many useful tweaks.
1
import z from "zod"
2
import { EnvSchema } from "../schemas"
3
4
const env = {
5
APP_NAME: "FooApp",
6
LOG_LEVEL: "invalid-level",
7
EXTRA_PARAM: "bar"
8
}
9
10
export type EnvContract = z.infer(FooSchema)
11
export const parsedEnv: EnvContract =
12
FooSchema
13
.omit({ AUTOMATION_LANG: true }) // Omit a schema validation
14
.passthrough() // Allow unknown params to pass through
15
.parse(env) // Parse the object
16
Copied!