# Juniper
A JSON Schema builder for TypeScript that infers each schema's type and catches schema mistakes at compile time, with JSON Schema 2020-12 and OpenAPI 3.0 output.
[](https://www.npmjs.com/package/juniper)
[](https://github.com/JacobLey/leyman/blob/main/apps/juniper/LICENSE)
[JSON Schema](https://json-schema.org/) is a vocabulary for describing data formats that is both human and machine readable. Validators accept almost any schema, though, so a mistake like `maxLength` on an array (instead of `maxItems`), or a `required` key that doesn't match one in `properties`, quietly changes what the schema accepts. And since a schema is just JSON, the TypeScript type for the same data has to be written and kept in sync by hand.
Juniper is a JSON Schema generator that focuses on solving two problems:
1. Writing strict and maintainable JSON Schemas.
2. Using those enforced schemas as TypeScript types.
Each schema type (`objectSchema()`, `arraySchema()`, ...) only exposes the keywords that apply to it, so mistakes like the ones above fail to compile. The schemas it emits pass [Ajv's strict mode](https://ajv.js.org/strict-mode.html). `SchemaType` is the TypeScript type of the data a schema accepts, so the schema is the only place the shape is written down.
Other features:
- The same schema renders as JSON Schema 2020-12 (which OpenAPI 3.1 uses), or as OpenAPI 3.0 with `toJSON({ openApi30: true })`. Keywords 3.0 lacks are rewritten where possible, and dropped otherwise.
- `.define('User')` makes a schema a reusable definition. It is emitted as a `$ref`, and added to `$defs` (or OpenAPI `components`) for you.
- Schemas are immutable, since every method returns a new one. A shared base schema can be narrowed with `pick`, `omit` and `partial`, or combined with `extend`, without changing it.
- The output is deterministic, so a committed spec only changes when a schema does.
- Every schema implements [Standard JSON Schema](https://standardschema.dev/), so tools that accept it can take Juniper schemas directly.
Juniper builds schemas, and doesn't validate data. Pair it with [Ajv](https://ajv.js.org/) or [juniper-validator](https://www.npmjs.com/package/juniper-validator) for that.
Guides and the full reference are on the [docs site](https://jacobley.github.io/leyman/packages/juniper/). For the full motivation, design goals and non-goals, see [WHY-JUNIPER.md](https://github.com/JacobLey/leyman/blob/main/apps/juniper/WHY-JUNIPER.md).
## Contents
- [Install](#install)
- [Example](#example)
- [Usage](#usage)
- [Schemas](#schemas)
- [Reusing schemas with define](#reusing-schemas-with-define)
- [API](#api)
- [Recipes](#recipes)
- [ESLint rules](#eslint-rules)
- [Compared to alternatives](#compared-to-alternatives)
- [Also See](#also-see)
## Install
```sh
npm i juniper
```
Requires Node.js 22.13 or later. `eslint` is an optional peer dependency, only needed for the [ESLint rules](#eslint-rules). The Example below also needs `npm i ajv`.
Juniper writes the `format` keyword as given, and does not check it. If a schema uses `format`, use a validator that supports the formats you need. juniper-validator does, and Ajv needs [ajv-formats](https://www.npmjs.com/package/ajv-formats) (with `strict: true`, compiling a schema with `format: 'email'` throws `unknown format "email" ignored` without it).
## Example
```ts
import { Ajv2020 } from 'ajv/dist/2020.js';
import { SchemaType, stringSchema, objectSchema } from 'juniper';
const schema = objectSchema({
properties: {
foo: stringSchema({
maxLength: 10,
}).startsWith('abc'),
bar: stringSchema().nullable(),
anything: true,
},
required: ['foo'],
additionalProperties: false,
});
/**
* {
* foo: `abc${string}`;
* bar?: string | null;
* anything?: unknown;
* }
*/
type ISchema = SchemaType;
/**
* {
* type: 'object',
* properties: {
* foo: {
* type: 'string',
* maxLength: 10,
* pattern: '^abc',
* },
* bar: {
* type: ['string', 'null'],
* },
* anything: true,
* },
* required: ['foo'],
* additionalProperties: false,
* }
*/
const jsonSchema = schema.toJSON();
const validator = new Ajv2020({ strict: true }).compile(jsonSchema);
const unknownUserInput: unknown = getUserInput();
if (validator(unknownUserInput)) {
console.log(unknownUserInput.foo); // abc123
}
```
## Usage
Juniper is an ESM module. That means it _must_ be `import`ed. To load from a CJS module, use dynamic import `const { stringSchema } = await import('juniper');`.
For every schema exported, there is both a class and functional constructor. The class can be instantiated directly via the `new` keyword, or via the static `create` method. The functional constructor is a reference to the `create` method. All three are equivalent:
```ts
import { StringSchema, stringSchema } from 'juniper';
// All methods are logically the same
const schema1 = new StringSchema({ maxLength: 10 });
const schema2 = StringSchema.create({ maxLength: 10 });
const schema3 = stringSchema({ maxLength: 10 })
console.log(schema3 instanceof StringSchema); // true
```
Juniper instances are **immutable**. Calling an instance method does not alter the existing instance. Every method that "alters" the schema returns a clone:
```ts
import { numberSchema } from 'juniper';
const schema1 = numberSchema({ type: 'integer' });
const schema2 = schema1.multipleOf(5);
console.log(schema1 === schema2); // false
console.log(schema1.toJSON()); // { type: 'integer' }
console.log(schema2.toJSON()); // { type: 'integer', multipleOf: 5 }
```
Juniper is designed to be used with TypeScript. It can be used from JavaScript, but much of its value, including type inference and the compile-time checks on schemas, needs TypeScript. Many schema restrictions are enforced only by the types:
```ts
import { booleanSchema, objectSchema } from 'juniper';
const bool = booleanSchema().anyOf([
booleanSchema({ description: 'provides no extra benefit' })
]);
const obj = objectSchema({
properties: {
foo: 123,
},
// FOO does not exist in properties
required: ['FOO'],
}).properties({
// already assigned above
foo: booleanSchema(),
}).oneOf([
// An object cannot also be a boolean
bool
]);
```
The above code fails TypeScript validation. It does not necessarily fail at runtime, and the resulting JSON Schema may be nonsensical.
### Type traps
TypeScript's errors for these don't say what to change:
- **Enum values need `as const`.** `enumSchema({ enum: ['a', 'b'] })` is typed `string`, not `'a' | 'b'`. Write `enumSchema({ enum: ['a', 'b'] as const })`.
- **`required` needs literal keys.** `const keys = ['id']; objectSchema({ properties, required: keys })` fails with `Type 'string[]' is not assignable to type '"id"[]'`. Write `required: ['id']` in place, or declare the variable `as const`.
- **`Schema` cannot be nested.** `Schema` is for accepting a schema and rendering it (`toJSON`, `components`, `serializeSpec`, `anyOf`). Inside `properties`, `arraySchema(...)` or other builders, `const item: Schema- = ...; arraySchema(item)` fails with `Type 'Schema
- ' is missing the following properties from type 'AbstractSchema<...>'`. Annotate a schema you'll build on as `NestableSchema
- `, or keep its inferred type.
- **`SchemaType` is the validated shape, not your class.** Dates are strings (`stringSchema({ format: 'date-time' })` is `string`), and with `exactOptionalPropertyTypes` an optional property cannot be `undefined`.
- **`EnumSchema` has no `nullable()`** (it is typed `never`, so calling it reports `This expression is not callable`). Put `null` in the enum, or use `mergeSchema().anyOf([enumSchema(...), nullSchema()])`.
## Schemas
Juniper exports the following schema classes with their JSON Schema and TypeScript equivalents:
| Juniper Class | JSON Schema | TypeScript |
| --------------- | ------------------------------------- | ------------------------------------------ |
| `ArraySchema` | `type: 'array'` | `unknown[]` |
| `BooleanSchema` | `type: 'boolean'` | `boolean` |
| `CustomSchema` | N/A (whatever is provided) | N/A (whatever is provided) |
| `EnumSchema` | `enum: []` | Union `\|` of provided literals |
| `MergeSchema` | N/A (compositional schema) | `unknown`, then `\|` or `&` as appropriate |
| `NeverSchema` | `not: {}` | `never` |
| `NullSchema` | `type: 'null'` | `null` |
| `NumberSchema` | `type: 'number'` OR `type: 'integer'` | `number` |
| `ObjectSchema` | `type: 'object'` | `{}` |
| `StringSchema` | `type: 'string'` | `string` |
| `TupleSchema` | `type: 'array'` | `[unknown]` |
Notes:
- `NumberSchema` can emit type `integer` or `number` (default) based on the `type` field. This does not impact TypeScript typings.
- `MergeSchema` without merging anything is a generic `unknown`. Methods like `allOf` and `anyOf` can produce unions such as `number | string`.
- `TupleSchema` is a convenience wrapper around `ArraySchema` that enforces strict tuples. The same result can be achieved with `ArraySchema` directly.
- `CustomSchema` is for breaking out of the Juniper environment. Its use is discouraged but may be the best option when integrating with existing JSON Schemas or for gradual adoption.
- There is no `any` schema. Use `MergeSchema` for `unknown`. If `any` is truly required, use `CustomSchema` (default output is an always-valid empty schema).
## Reusing schemas with define
`.define(name)` makes a schema a reusable definition. Wherever it is used, it is emitted as a `$ref`, and `toJSON()` adds every definition it references to `$defs`. You reference the schema variable itself, so types flow exactly as they do without `define`, and a reference can never point at a missing definition.
```ts
import { arraySchema, objectSchema, SchemaType, stringSchema } from 'juniper';
const address = objectSchema({
properties: { city: stringSchema() },
required: ['city'],
}).define('Address');
const user = objectSchema({
properties: { home: address, work: address.nullable() },
}).define('User');
arraySchema(user).toJSON();
/**
* {
* type: 'array',
* items: { $ref: '#/$defs/User' },
* $defs: {
* Address: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] },
* User: {
* type: 'object',
* properties: {
* home: { $ref: '#/$defs/Address' },
* work: { anyOf: [{ $ref: '#/$defs/Address' }, { type: 'null' }] },
* },
* },
* },
* }
*/
// { home?: { city: string }; work?: { city: string } | null }
type User = SchemaType;
```
- A schema derived from a definition keeps the `$ref` when it only adds annotations (`description`, `title`, `examples`, ...) or is made `nullable()`. Any other change, such as `omit()` or an extra constraint, makes it a different schema, so it is emitted inline. Define it under its own name to share it too: `user.omit(['id']).define('NewUser')`.
- Definition names are unique. Two different schemas defined with the same name throw when serialized. The same schema can be used any number of times.
- `.ref(path)` is still there for schemas Juniper doesn't own, where the path is up to you.
### Recursive schemas
`defineRecursive` defines a schema that references itself, such as a tree or a comment thread. TypeScript can't infer a recursive type from a builder that uses itself, so declare the type, and the built schema is checked against it.
```ts
import { arraySchema, defineRecursive, numberSchema, objectSchema } from 'juniper';
interface TreeNode {
value: number;
children: TreeNode[];
parent?: TreeNode | null;
}
const tree = defineRecursive('TreeNode', self =>
objectSchema({
properties: {
value: numberSchema(),
children: arraySchema(self),
parent: self.nullable(),
},
required: ['value', 'children'],
})
);
tree.toJSON();
/**
* {
* $ref: '#/$defs/TreeNode',
* $defs: {
* TreeNode: {
* type: 'object',
* properties: {
* value: { type: 'number' },
* children: { type: 'array', items: { $ref: '#/$defs/TreeNode' } },
* parent: { anyOf: [{ $ref: '#/$defs/TreeNode' }, { type: 'null' }] },
* },
* required: ['value', 'children'],
* },
* },
* }
*/
```
`self`, and the returned schema, are references to the definition: they support `nullable()` and annotations such as `description()`, and are used like any other defined schema. Definitions can also reference each other by nesting `defineRecursive` calls.
### OpenAPI
OpenAPI keeps shared schemas in `components.schemas`. `components()` collects every definition reachable from the given schemas, ready to place there. With `openApi30: true`, references already point at `#/components/schemas/`. For OpenAPI 3.1 (JSON Schema 2020-12), pass `definitionsPath`.
```ts
import { components } from 'juniper';
// OpenAPI 3.0: { openApi30: true }
const options = { definitionsPath: '#/components/schemas/' };
const spec = {
openapi: '3.1.0',
components: { schemas: components([user, newUser, post], options) },
paths: {
'/users/{userId}': {
get: {
responses: {
200: {
description: 'User',
content: { 'application/json': { schema: user.toJSON(options) } },
},
},
},
},
},
};
```
Or write the spec with schemas in place, and let `serializeSpec()` serialize them and fill `components.schemas`. The dialect follows `openapi`, and no schema has to be listed, so no `$ref` can dangle:
```ts
import { serializeSpec } from 'juniper';
const spec = serializeSpec({
openapi: '3.1.0',
info: { title: 'Blog', version: '1.0.0' },
paths: {
'/users/{userId}': {
get: {
responses: {
200: { description: 'User', content: { 'application/json': { schema: user } } },
},
},
},
},
});
// spec.components.schemas: { User: { ... } }
```
A complete users and posts API, built both ways, with [openapi3-ts](https://www.npmjs.com/package/openapi3-ts) and with `serializeSpec()`, and checked to be valid OpenAPI 3.0 and 3.1, is in [e2e/juniper-openapi](https://github.com/JacobLey/leyman/blob/main/e2e/juniper-openapi/test/data/api.ts).
## API
### Helper Types
| Type | Interface | Description |
| --------------------- | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SchemaType` | `SchemaType` \| `SchemaType` | Extracts the TypeScript type from a Juniper class or JSON Schema object. |
| `Schema` | `Schema` | A Juniper Schema instance describing a TypeScript type. Accept it as a parameter to render it, or to pass to `components`, `serializeSpec`, `anyOf` and the like. It can't be passed to `properties` or `arraySchema`; see [Type traps](#type-traps). |
| `JsonSchema` | `JsonSchema` | A JSON Schema object describing the specified TypeScript type. |
| `OpenApi30JsonSchema` | `OpenApi30JsonSchema` | What `toJSON({ openApi30: true })` returns: no `true`/`false` sub-schemas, and a single `type`, so it can be assigned to OpenAPI libraries' 3.0 schema types (e.g. openapi3-ts's `oas30.SchemaObject`) without a cast. |
| `EmptyObject` | `EmptyObject` | Describes an actually-empty object. Mostly internal but exposed for convenience. |
| `PatternProperties` | ``PatternProperties<`abc${string}`>`` | Describes a string pattern type. See [`ObjectSchema.patternProperties`](#objectschema). |
| `KnownFormat` | `KnownFormat` | String formats defined by JSON Schema and OpenAPI 3.0. See [`StringSchema.format`](#stringschema). |
| `RecursiveSchema` | `RecursiveSchema` | What [`defineRecursive`](#definerecursivetname-build) returns, and its `self` argument. |
`isSchema(value)` is a type guard for whether `value` is a Juniper schema (`value is Schema`). `ComponentsParams`, `SerializedSpec`, `SerializedSpecValue`, `JsonSchemaType` and `EmptyIndex` are also exported, for typing the parameters and results of the functions above.
### Constructors
Every schema can be created three ways:
- `new` keyword — `new StringSchema({ maxLength: 5 })`
- static `create` method — `StringSchema.create({ maxLength: 5 })`
- functional constructor — `stringSchema({ maxLength: 5 })`
All three are equivalent. Every constructor takes a single options object. Every parameter is optional and can also be set via a method of the same name:
```ts
stringSchema({ maxLength: 5 }) == StringSchema.create().maxLength(5) == new StringSchema({}).maxLength(5)
```
Not every property can be set in the constructor. Some must be set with a method, because of limits on what TypeScript can infer. Schema constructors make heavy use of TypeScript generics. These generics are internal and may change without announcement. The exception is `CustomSchema`, whose type is provided via the generic parameter.
Every method returns a clone of the original instance (immutable).
### Generic Schema Helper Methods
The following methods are available on every schema instance for rendering and typing.
---
#### `.toJSON(options?)`
Renders the JSON Schema document. The result should be immediately passed to a validator or serializer. The internal structure is not guaranteed and should not be modified.
The output is deterministic: the same schema always renders the same JSON, and `$defs` (like `components()`) are sorted by name rather than by where they are used. Committed schema or OpenAPI files only change when the schema does.
**Parameters**
| Parameter | Type | Default | Description |
| ----------------- | --------- | --------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `openApi30` | `boolean` | `false` | Output a JSON Schema compliant with OpenAPI 3.0. Keywords 3.0 lacks are rewritten where possible, and dropped otherwise, so the schema may accept more than its 2020-12 form. The OpenAPI 3.0 column of each [schema](#schemas) lists which keywords are kept. |
| `id` | `string` | — | Value to place in the `$id` field of the document. |
| `schema` | `boolean` | `false` | Include the draft as the `$schema` property. |
| `definitionsPath` | `string` | `'#/$defs/'` (`'#/components/schemas/'` with `openApi30`) | `$ref` prefix for [defined](#reusing-schemas-with-define) schemas. Only `#/$defs/` is embedded in the output; use `components()` for other paths. |
**Returns** `JsonSchema`, or `OpenApi30JsonSchema` when `openApi30` is `true` — the rendered JSON Schema document.
---
#### `['~standard']`
Every schema implements [Standard JSON Schema](https://standardschema.dev/), so libraries that accept it can render Juniper schemas themselves.
```ts
import { stringSchema } from 'juniper';
const schema = stringSchema().nullable();
schema['~standard'].jsonSchema.input({ target: 'openapi-3.0' });
// { type: 'string', nullable: true }
```
| Target | Same as |
| ----------------- | --------------------------------- |
| `'draft-2020-12'` | `toJSON()` |
| `'openapi-3.0'` | `toJSON({ openApi30: true })` |
| `'draft-07'` | `toJSON()`, rewritten as draft-07 |
`'draft-07'` is the target some tool libraries request, such as the AI SDK and Mastra. Each 2020-12 keyword is rewritten to its draft-07 form: `$defs` become `definitions`, `prefixItems` becomes the array form of `items` (with `additionalItems`), `dependentRequired` and `dependentSchemas` become `dependencies`, and a `$ref` with constraints beside it moves into `allOf`. `unevaluatedProperties` becomes `additionalProperties` when nothing else in the schema evaluates properties. A schema that has no exact draft-07 form, such as one using `maxContains`, throws, so the draft-07 schema accepts the same values as the 2020-12 one.
Other targets throw. `input` and `output` render the same schema, and accept the other `toJSON` options as a second argument.
---
#### `.ref(path)`
Returns a schema (which can be modified further) that extends the schema via the [`$ref`](https://json-schema.org/understanding-json-schema/structuring.html#ref) property.
Prefer [`.define(name)`](#reusing-schemas-with-define) for schemas you build with Juniper: it places the definition for you. `.ref(path)` is for schemas stored somewhere Juniper doesn't control.
**Parameters**
| Parameter | Type | Default | Description |
| --------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `path` | `string` | — | Required. Path to where the schema is actually stored in the document. Final document structure is implementation-specific and not verifiable. |
If referencing a JSON Schema entirely outside of Juniper's control, use `ref` on a `CustomSchema`. Otherwise it is designed for instances where common schemas are pulled into a reusable section, such as [OpenAPI's `components`](https://swagger.io/docs/specification/components/).
```ts
import { stringSchema, objectSchema } from 'juniper';
// string
const idSchema = stringSchema({
title: 'Custom ID',
pattern: '^[a-z]{32}$',
});
// { id: string } | null
const resourceSchema = objectSchema({
properties: {
id: idSchema.ref('#/components/schemas/id')
},
required: ['id'],
});
const nullableResourceSchema = resourceSchema.ref('#/components/schemas/id').nullable();
console.log({
components: {
schemas: {
id: idSchema.toJSON({ openApi30: true }),
resource: resourceSchema.toJSON({ openApi30: true }),
nullableResource: nullableResourceSchema.toJSON({ openApi30: true }),
},
},
});
/**
* {
* components: {
* schemas: {
* id: {
* type: 'string',
* title: 'Custom ID',
* pattern: '^[a-z]{32}$'
* },
* resource: {
* type: 'object',
* properties: {
* id: { $ref: '#/components/schemas/id' }
* },
* required: ['id'],
* },
* nullableResource: {
* $ref: '#/components/schemas/resource',
* nullable: true
* },
* }
* }
* }
*/
```
Note: the `nullableResource` above merges `$ref` with additional properties (allowed in Draft 2020-12 and generally supported by resolvers, but not strictly compliant with OpenAPI). For full compliance, merge with a `NullSchema` explicitly:
```ts
const nullableResourceSchema = mergeSchema().oneOf([
resourceSchema,
nullSchema
]);
```
---
#### `.define(name)`
Makes the schema a reusable definition, emitted as `$ref` and collected into `$defs`. Any name works: the `$ref` escapes it as a [JSON Pointer](https://www.rfc-editor.org/rfc/rfc6901#section-6) URI fragment, so `.define('a/b c')` is `{ "$ref": "#/$defs/a~1b%20c" }` next to `$defs: { "a/b c": ... }`. See [Reusing schemas with define](#reusing-schemas-with-define).
| Parameter | Type | Default | Description |
| --------- | -------- | ------- | --------------------------------------------------------------------------- |
| `name` | `string` | — | Required. Name of the definition, e.g. `User`. Must be unique per document. |
---
#### `defineRecursive(name, build)`
Defines a schema that references itself. See [Recursive schemas](#recursive-schemas).
| Parameter | Type | Default | Description |
| --------- | ----------------------------------------- | ------- | ------------------------------------------------------------------------------- |
| `name` | `string` | — | Required. Name of the definition. |
| `build` | `(self: RecursiveSchema) => Schema` | — | Required. Builds the definition, given a reference to itself. Must produce `T`. |
**Returns** `RecursiveSchema` — a reference to the definition.
---
#### `components(schemas, options?)`
Collects every definition used by `schemas` (including defined schemas themselves), keyed and sorted by name. For documents that keep definitions outside the schema, such as OpenAPI's `components.schemas`.
| Parameter | Type | Default | Description |
| ------------------------- | ---------- | ------------------------- | --------------------------------------------------------------------------- |
| `schemas` | `Schema[]` | — | Required. Schemas whose definitions to collect. |
| `options.openApi30` | `boolean` | `false` | Serialize definitions for OpenAPI 3.0. |
| `options.definitionsPath` | `string` | `'#/components/schemas/'` | `$ref` prefix. Pass the same options to `toJSON` for schemas that use them. |
**Throws** when different schemas are defined with the same name.
---
#### `serializeSpec(spec, options?)`
Serializes every schema in an OpenAPI document, and fills `components.schemas` with the definitions they use, so nothing has to be listed (see [OpenAPI](#openapi)).
| Parameter | Type | Default | Description |
| ------------------------- | --------- | ------------------------- | ---------------------------------------------------------------------------------- |
| `spec` | `object` | — | Required. An OpenAPI document (or any object) with Juniper schemas anywhere in it. |
| `options.openApi30` | `boolean` | from `spec.openapi` | Serialize for OpenAPI 3.0. Defaults to `true` when `openapi` is `3.0.x`. |
| `options.definitionsPath` | `string` | `'#/components/schemas/'` | `$ref` prefix. |
**Returns** a copy of `spec` with every schema replaced by its JSON Schema (typed as `JsonSchema`, or `OpenApi30JsonSchema`), and `components.schemas` holding every definition they use, sorted by name. Other components, and other entries in `components.schemas`, are kept. A defined schema placed in `components.schemas` under its own name becomes its definition, not a reference to itself.
**Throws** when different schemas are defined with the same name, or `components.schemas` already has a different schema under a definition's name.
---
#### `.cast()`
Casts the instance as a schema for a specific TypeScript type. Can only be chained with a `toJSON` call after casting. Useful when declaring a schema for JavaScript-generated objects that are not explicitly enforced in JSON Schema.
```ts
import { objectSchema } from 'juniper';
const kindSym = Symbol.for('kind');
const userSchema = objectSchema({
properties: {
id: true,
email: true,
},
additionalProperties: false,
}).cast<{
[kindSym]: 'user';
id: string;
email: string;
}>();
```
---
#### `.metadata(key, value)` / `.metadata(record)`
Attaches custom data to a JSON Schema. Useful for extensions like [`x-` prefixes in OpenAPI](https://swagger.io/specification/#specification-extensions).
**Parameters**
| Parameter | Type | Default | Description |
| --------- | --------- | ------- | ---------------------------------------------------------------------- |
| `key` | `string` | — | The metadata key. Must not overlap with existing JSON Schema keywords. |
| `value` | `unknown` | — | The metadata value. |
Alternatively, pass a single object `{ key1: val1, key2: val2 }` to set multiple metadata entries at once.
`numberSchema().metadata('maximum', 5)` is forbidden, because `maximum` is an existing keyword.
---
### Generic Schema Methods
The following methods are available on every schema. All methods return a new (cloned) instance.
| Method | Constructor Parameter | Can be Unset | Changes Types |
| ------------------------------------------------------------------------------------------------------------ | :-------------------: | :----------: | :-----------: |
| [`title`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.9.1) | ✅ | ✅ | ❌ |
| [`description`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.9.1) | ✅ | ✅ | ❌ |
| [`default`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.9.2) | ✅ | ✅ | ❌ |
| [`deprecated`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.9.3) | ✅ | ✅ | ❌ |
| [`example(s)`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.9.5) | ❌ | ❌ | ❌ |
| [`readOnly`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.9.4) | ✅ | ✅ | ❌ |
| [`writeOnly`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.9.4) | ✅ | ✅ | ❌ |
| [`allOf`](https://json-schema.org/understanding-json-schema/reference/combining.html#allof) | ❌ | ❌ | ✅ |
| [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining.html#anyof) | ❌ | ❌ | ✅ |
| [`oneOf`](https://json-schema.org/understanding-json-schema/reference/combining.html#oneof) | ❌ | ❌ | ✅ |
| [`not`](https://json-schema.org/understanding-json-schema/reference/combining.html#not) | ❌ | ❌ | ✅ |
| [`if then else`](https://json-schema.org/understanding-json-schema/reference/conditionals.html#if-then-else) | ❌ | ❌ | ✅ |
| [`nullable`](https://swagger.io/docs/specification/data-models/data-types/#null) | ❌ | ❌ | ✅ |
Individual schemas may not expose every method when the result would be nonsensical or forbidden (e.g. `EnumSchema` cannot be `nullable`).
`not(schema)` rejects everything `schema` accepts, including `null` when `schema` is nullable. To make a nullable schema non-nullable, pass `nullSchema()`:
```ts
import { nullSchema, stringSchema } from 'juniper';
// string, emitted as { type: 'string' }
const name = stringSchema().nullable().not(nullSchema());
```
By contrast, `.not(stringSchema().nullable())` rejects every string as well as `null`, so nothing passes.
---
### `ArraySchema`
Represents `type: 'array'`. TypeScript type: `unknown[]`.
| Method | Constructor Parameter | Can be Unset | Changes Types | OpenAPI 3.0 |
| ---------------------------------------------------------------------------------------------------------------- | :-------------------: | :----------: | :-----------: | :---------: |
| [`items`](https://json-schema.org/understanding-json-schema/reference/array.html#items) | ✅ | ❌ | ✅ | ✅ |
| [`maxItems`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.4.1) | ✅ | ✅ | ❌ | ✅ |
| [`minItems`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.4.2) | ✅ | ✅ | ✅ | ✅ |
| [`uniqueItems`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.4.3) | ✅ | ✅ | ❌ | ✅ |
| [`contains`](https://json-schema.org/understanding-json-schema/reference/array.html#contains) | ❌ | ❌ | ✅ | ❌ |
| [`maxContains`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.4.4) | ✅ | ✅ | ❌ | ❌ |
| [`minContains`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.4.5) | ✅ | ✅ | ❌ | ❌ |
| [`(prepend)prefixItem`](https://json-schema.org/understanding-json-schema/reference/array.html#tuple-validation) | ❌ | ❌ | ✅ | ❌ |
`minItems` up to 3 makes those items required in the type, so an empty array is rejected where the schema rejects it:
```ts
import { arraySchema, stringSchema, type SchemaType } from 'juniper';
const tags = arraySchema(stringSchema()).minItems(1);
// [string, ...string[]]
type Tags = SchemaType;
```
Prefix items are optional in the type beyond `minItems`, since `prefixItems` alone doesn't require any item to exist:
```ts
import { arraySchema, numberSchema, stringSchema, type SchemaType } from 'juniper';
const open = arraySchema(stringSchema()).prefixItem(numberSchema());
// [number?, ...string[]]
type Open = SchemaType;
const required = open.minItems(1);
// [number, ...string[]]
type Required = SchemaType;
```
`tupleSchema()` sets `minItems` itself, so all of its items are required.
Larger values, or a `number` variable, leave the type as an array. To build a value from an array of unknown length, narrow it first, as a length check alone does not:
```ts
const isNonEmpty = (array: T[]): array is [T, ...T[]] => array.length > 0;
```
---
### `EnumSchema`
Represents `enum: []`. TypeScript type: union of provided literals.
| Method | Constructor Parameter | Can be Unset | Changes Types | OpenAPI 3.0 |
| ------------------------------------------------------------------------------------------------ | :-------------------: | :----------: | :-----------: | :---------: |
| [`enum(s)`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.1.2) | ✅ | ❌ | ✅ | ✅ |
---
### `NumberSchema`
Represents `type: 'number'` or `type: 'integer'`. TypeScript type: `number`.
| Method | Constructor Parameter | Can be Unset | Changes Types | OpenAPI 3.0 |
| --------------------------------------------------------------------------------------------------------- | :-------------------: | :----------: | :-----------: | :---------: |
| [`type`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.1.1) | ✅ | ✅ | ❌ | ✅ |
| [`multipleOf`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.2.1) | ✅ | ❌ | ❌ | ✅ |
| [`maximum`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.2.2) | ✅ | ✅ | ❌ | ✅ |
| [`exclusiveMaximum`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.2.3) | ✅ | ✅ | ❌ | ✅ |
| [`minimum`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.2.4) | ✅ | ✅ | ❌ | ✅ |
| [`exclusiveMinimum`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.2.5) | ✅ | ✅ | ❌ | ✅ |
---
### `ObjectSchema`
Represents `type: 'object'`. TypeScript type: `{}`.
| Method | Constructor Parameter | Can be Unset | Changes Types | OpenAPI 3.0 |
| ------------------------------------------------------------------------------------------------------------------------- | :-------------------: | :----------: | :-----------: | :---------: |
| [`properties`](https://json-schema.org/understanding-json-schema/reference/object.html#properties) | ✅ | ✅ | ✅ | ✅ |
| [`maxProperties`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.5.1) | ✅ | ✅ | ❌ | ✅ |
| [`minProperties`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.5.2) | ✅ | ✅ | ❌ | ✅ |
| [`required`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.5.3) | ✅ | ✅ | ✅ | ✅ |
| [`additionalProperties`](https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties) | ✅ | ✅ | ✅ | ✅ |
| [`patternProperties`](https://json-schema.org/understanding-json-schema/reference/object.html#pattern-properties) | ❌ | ✅ | ✅ | ❌ |
| [`dependentRequired`](https://json-schema.org/understanding-json-schema/reference/conditionals.html#dependentrequired) | ❌ | ❌ | ✅ | ✅ |
| [`dependentSchemas`](https://json-schema.org/understanding-json-schema/reference/conditionals.html#dependentschemas) | ❌ | ❌ | ✅ | ✅ |
| [`unevaluatedProperties`](https://json-schema.org/understanding-json-schema/reference/object.html#unevaluated-properties) | ✅ | ❌ | ❌ | ❌ |
**`additionalProperties` beside other keys:** TypeScript applies an index signature to every key, where the schema only applies `additionalProperties` to keys nothing else covers. So the index signature also allows the types of `properties` and `patternProperties`: `{ properties: { a: stringSchema() }, additionalProperties: numberSchema() }` is `{ a?: string; [key: string]: number | string }`. Declared keys keep their own type when read.
**Note on `additionalProperties`:** JSON Schema interprets omitting `additionalProperties` as `additionalProperties: true`. The emitted TypeScript type includes the index signature only when `additionalProperties` is explicitly set to `true`:
```ts
import { objectSchema, SchemaType } from 'juniper';
const empty = objectSchema();
// EmptyObject — no index signature
type EmptyObject = SchemaType;
const indexed = empty.additionalProperties(true);
// Record
type IndexedObject = SchemaType;
```
**In OpenAPI 3.0**, which has no `patternProperties`, a set `additionalProperties` also allows the pattern schemas' values, for any key, so nothing the pattern covers is rejected: `additionalProperties: false` becomes the pattern's schema, and a schema becomes an `anyOf` with it. An unset or `true` `additionalProperties` stays as it is.
**Note on `patternProperties`:** The key is a regular expression pattern and cannot be interpreted directly as a TypeScript string type. Wrap the key with the `PatternProperties` helper type:
```ts
import { numberSchema, objectSchema, PatternProperties, SchemaType } from 'juniper';
const startsOrEndsWith = objectSchema()
.patternProperties(
'^abc' as PatternProperties<`abc${string}`>,
true
)
.patternProperties(
'xyz$' as PatternProperties<`${string}xyz`>,
numberSchema()
);
// Record<`abc${string}`, unknown> & Record<`${string}xyz`, number>
type Output = SchemaType;
```
**Deriving schemas with `pick`, `omit` and `partial`:** Build variants of an object schema, such as the create, update and response shapes of the same resource. They only change `properties` and `required`. Every other keyword (`additionalProperties`, `title`, ...) is kept, so reset any that no longer fit.
```ts
import { numberSchema, objectSchema, SchemaType, stringSchema } from 'juniper';
const user = objectSchema({
properties: {
id: numberSchema(),
name: stringSchema(),
email: stringSchema(),
},
required: ['id', 'name'],
additionalProperties: false,
});
const createUser = user.omit(['id']);
// { name: string; email?: string }
type CreateUser = SchemaType;
// { name?: string; email?: string }
const updateUser = createUser.partial();
// { id: number; name?: string }, only `name` is optional
const summary = user.pick(['id', 'name']).partial(['name']);
```
Keys are checked against the schema's properties, so a typo is a compile error. Constraints added by combining schemas (`allOf`, `if`, `dependentRequired`, ...) still apply to the result, in both the JSON Schema and its type. For example, a property required through `dependentRequired` stays required after `partial()`.
`required()` with no keys marks every property as required, the inverse of `partial()`:
```ts
// { id: number; name: string; email: string }
const fullUser = user.required();
```
**Combining schemas with `extend`:** Add the properties of another object schema, such as fields shared by many resources. Duplicate properties are a compile error, and `required` is combined.
```ts
const timestamps = objectSchema({
properties: { createdAt: stringSchema(), updatedAt: stringSchema() },
required: ['createdAt'],
});
// { id: number; name: string; email?: string; createdAt: string; updatedAt?: string }
const storedUser = user.extend(timestamps);
```
Unlike `allOf`, `additionalProperties` applies to the combined properties, so `storedUser` is still closed over all five. When the added schema sets `additionalProperties`, `unevaluatedProperties`, `minProperties` or `maxProperties`, its value replaces the original's, in both the JSON Schema and its type. `patternProperties`, `dependentRequired`, `dependentSchemas` and combined schemas (`allOf`, `if`, ...) of both apply. Annotations (`title`, ...), `nullable()` and `define()` come from the schema `extend` is called on.
**Discriminated unions:** Pass `discriminator` to `oneOf` to name the property that tells the branches apart. Every branch must require it, as a string enum of one value that no other branch uses, or it's a compile error. The output gets OpenAPI's `discriminator` keyword:
```ts
const cat = objectSchema({
properties: { kind: enumSchema({ enum: ['cat'] as const }), lives: numberSchema() },
required: ['kind'],
});
const dog = objectSchema({
properties: { kind: enumSchema({ enum: ['dog'] as const }), goodBoy: booleanSchema() },
required: ['kind'],
});
// { kind: 'cat'; lives?: number } | { kind: 'dog'; goodBoy?: boolean }
const pet = objectSchema().oneOf([cat, dog], { discriminator: 'kind' });
pet.toJSON();
// { type: 'object', oneOf: [...], discriminator: { propertyName: 'kind' } }
```
`discriminator` is emitted in every output, so Ajv needs its `discriminator: true` option, which also makes it check only the branch the property selects. [`juniper-validator`](https://www.npmjs.com/package/juniper-validator) turns it on.
---
### `StringSchema`
Represents `type: 'string'`. TypeScript type: `string`.
| Method | Constructor Parameter | Can be Unset | Changes Types | OpenAPI 3.0 |
| --------------------------------------------------------------------------------------------------------------------- | :-------------------: | :----------: | :-----------: | :---------: |
| [`format`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.7) | ✅ | ✅ | ❌ | ✅ |
| [`maxLength`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.3.1) | ✅ | ✅ | ❌ | ✅ |
| [`minLength`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.3.1) | ✅ | ✅ | ❌ | ✅ |
| [`pattern`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.3.3) | ✅ | ❌ | ❌ | ✅ |
| `startsWith` | ❌ | ❌ | ✅ | ✅ |
| `endsWith` | ❌ | ❌ | ✅ | ✅ |
| `contains` | ❌ | ❌ | ✅ | ✅ |
| [`contentEncoding`](https://json-schema.org/understanding-json-schema/reference/non_json_data.html#contentencoding) | ✅ | ✅ | ❌ | ❌ |
| [`contentMediaType`](https://json-schema.org/understanding-json-schema/reference/non_json_data.html#contentmediatype) | ✅ | ✅ | ❌ | ❌ |
OpenAPI 3.0 has no `contentEncoding` or `contentMediaType`, so they are left out of its output. Use `format('byte')` (base64) or `format('binary')` instead.
`startsWith`, `endsWith`, and `contains` are wrappers around the `pattern` property with special TypeScript handling to narrow the inferred string type (e.g. `startsWith('abc')` produces `` `abc${string}` ``).
`format` autocompletes the formats defined by JSON Schema and OpenAPI 3.0 (`date-time`, `email`, `uuid`, `uri`, ..., exported as the `KnownFormat` type), and accepts any other string as a custom format.
---
### `TupleSchema`
Represents `type: 'array'` with strict tuple semantics. TypeScript type: `[unknown]`. A convenience wrapper around `ArraySchema` that prevents editing `items` directly. Every `TupleSchema` is an `ArraySchema`.
Items are added in order with `prefixItem` (or in front with `prependPrefixItem`). The constructor has no item option, and `minItems`, `maxItems` and `items` are set for you (the length is fixed, with no extra items):
```ts
import { numberSchema, stringSchema, tupleSchema, type SchemaType } from 'juniper';
const pair = tupleSchema().prefixItem(stringSchema()).prefixItem(numberSchema());
// [string, number]
type Pair = SchemaType;
pair.toJSON();
// { type: 'array', minItems: 2, maxItems: 2, items: false, prefixItems: [{ type: 'string' }, { type: 'number' }] }
```
| Method | Constructor Parameter | Can be Unset | Changes Types | OpenAPI 3.0 |
| ---------------------------------------------------------------------------------------------------------------- | :-------------------: | :----------: | :-----------: | :---------: |
| [`uniqueItems`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.4.3) | ✅ | ✅ | ❌ | ✅ |
| [`contains`](https://json-schema.org/understanding-json-schema/reference/array.html#contains) | ❌ | ❌ | ✅ | ❌ |
| [`maxContains`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.4.4) | ✅ | ✅ | ❌ | ❌ |
| [`minContains`](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.4.5) | ✅ | ✅ | ❌ | ❌ |
| [`(prepend)prefixItem`](https://json-schema.org/understanding-json-schema/reference/array.html#tuple-validation) | ❌ | ❌ | ✅ | ❌ |
---
### `BooleanSchema`
Represents `type: 'boolean'`. TypeScript type: `boolean`.
Exposes all [generic schema methods](#generic-schema-methods). Does not expose `not` (use `EnumSchema` to restrict boolean values).
---
### `NullSchema`
Represents `type: 'null'`. TypeScript type: `null`.
Exposes all [generic schema methods](#generic-schema-methods).
---
### `NeverSchema`
Represents `not: {}`. TypeScript type: `never`.
Exposes all [generic schema methods](#generic-schema-methods).
---
### `MergeSchema`
A compositional schema with no inherent type constraint. TypeScript type: `unknown` initially, narrowed to `|` or `&` via `anyOf`/`allOf`. Use this for generic `unknown` types or to combine unrelated schemas.
Exposes all [generic schema methods](#generic-schema-methods).
---
### `CustomSchema`
Accepts arbitrary JSON Schema content. TypeScript type is provided via the generic parameter.
```ts
import { customSchema } from 'juniper';
const mySchema = customSchema<{ foo: string }>({ foo: { type: 'string' } });
```
Use `CustomSchema` when integrating with pre-existing JSON Schemas or adopting Juniper incrementally. Its use is discouraged in greenfield code.
## Recipes
### TypeScript Enum
TypeScript `enums` are object dictionaries that sometimes have [reverse mappings](https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings), so you cannot trivially get all values via `Object.values`. The [enum-to-array](https://www.npmjs.com/package/enum-to-array) package resolves this:
```ts
import { enumToValues } from 'enum-to-array';
import { enumSchema } from 'juniper';
enum MyEnum {
FOO = 'BAR',
ABC = 123,
}
enumSchema({
enum: enumToValues(MyEnum)
}).toJSON();
// { enum: ['BAR', 123] }
```
## ESLint rules
The plugin is a separate entry point, so importing `juniper` never loads it, and `eslint` is only needed when you use it:
```js
// eslint.config.js
import juniper from 'juniper/eslint';
export default [juniper.configs.recommended];
```
`configs.recommended` registers the plugin (namespace `juniper`) and turns on every rule below as an error.
### `juniper/top-level-schema`
Reports a schema built inside a function, or in a class instance field, rather than once at module scope. Every builder call clones the schema, so a schema built per call is wasted work at best. At worst, `toJSON()` throws because two different instances are defined under the same `.define()` name.
```ts
import { objectSchema, stringSchema } from 'juniper';
// ❌ built on every request
const handler = (body: unknown) => objectSchema({ properties: { name: stringSchema() } });
// ✅ built once
const bodySchema = objectSchema({ properties: { name: stringSchema() } });
const handler = (body: unknown) => bodySchema;
```
It checks calls to the schema factories (`objectSchema()`, `ObjectSchema.create()`, `defineRecursive()`, ...) imported from `juniper`. Schemas built in a `defineRecursive` callback, or in a function called immediately at module scope, are fine, since those run once. Methods called on an existing schema (`.toJSON()`, `.pick()`, ...) aren't checked.
A helper that builds a schema from its arguments, called only at module scope, is reported too. Disable the rule for that helper with a comment saying so.
## Compared to alternatives
- [TypeBox](https://www.npmjs.com/package/typebox) — also builds JSON Schema and types together, and ships a validator. But its options accept any keyword, so `maxLength` on an array compiles, and it has no OpenAPI 3.0 output.
- [zod](https://zod.dev/) / [Valibot](https://valibot.dev/) / [joi](https://www.npmjs.com/package/joi) — validation libraries with their own schema formats. Zod and Valibot export JSON Schema, but refinements and transforms don't carry over, so the export isn't the source of truth.
- [json-schema-to-ts](https://www.npmjs.com/package/json-schema-to-ts) / [json-schema-to-typescript](https://www.npmjs.com/package/json-schema-to-typescript) — derive types from a plain JSON Schema, so nothing checks the schema itself.
- [ts-json-schema-generator](https://www.npmjs.com/package/ts-json-schema-generator) — the other direction: generates JSON Schema from TypeScript types as a build step, with constraints like `maxLength` written as unchecked JSDoc tags.
## Also See
- [WHY-JUNIPER.md](https://github.com/JacobLey/leyman/blob/main/apps/juniper/WHY-JUNIPER.md) — Motivation, design decisions, and comparison to alternative libraries.
- [juniper-validator](https://www.npmjs.com/package/juniper-validator) — Validation companion for Juniper schemas.
- [genever](https://www.npmjs.com/package/genever) — the reverse: generates TypeScript types from a JSON Schema file, matching the types Juniper infers.