📝 docs: bring README, demo and playground in line with the code; release 0.1.0

The README described a library that did not exist in places. It showed
@ValidateNested({ each: true }), which did not compile; told users to enable
emitDecoratorMetadata, which the library never reads; and documented none of the
mapping API. Its Quick Start now runs verbatim — verified by compiling and
executing it against the local source.

- README: document field-name mapping, access control, options, error helpers
  and the 30 new validators; drop the emitDecoratorMetadata instruction; add a
  Notes and Limitations section covering circular references, validate() on
  plain objects, and the fact that @JsonProperty stops the original name from
  being accepted unless you add @JsonAlias
- CHANGELOG.md: new, covering 0.1.0
- example.ts: rewritten as a tour of the current API — read-only ids, write-only
  secrets, renamed fields, conditional validation, flattened errors, and a
  base-class rule reaching a subclass
- docs: the playground hand-listed its symbol table in three parallel places and
  exposed IsEmail, which is not an export. It now derives scope from the bundle,
  so new decorators work there as soon as they ship. Bundle regenerated
- version 0.1.0

136 tests, 97% statement and 100% function coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SAcqrz3FcadkYr3xG32CjK
This commit is contained in:
Claude
2026-08-03 23:53:09 +00:00
parent 44c8f28f4b
commit 83ad2a289d
6 changed files with 481 additions and 173 deletions
+118
View File
@@ -0,0 +1,118 @@
# Changelog
All notable changes to this project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.1.0] - 2026-08-03
The first release with a working test suite. Everything below the "Fixed" heading was
found by writing tests against the previous release; the suite has grown from 40 tests
that never executed to 136 that do.
### Added
**Field-name mapping.** A library whose headline feature is "JSON mapping" could not map
a name. It can now.
- `@JsonProperty(name)` renames a property in both directions.
- `@JsonAlias(...names)` accepts extra names on input only, so a field can be renamed
without breaking older clients.
- Naming strategies — `snake_case`, `kebab-case`, `SCREAMING_SNAKE_CASE`, `PascalCase`,
`camelCase`, or your own function — applied to properties with no explicit name.
Acronyms split where a reader expects: `parseHTTPResponse` → `parse_http_response`.
**Access control.**
- `@JsonIgnore()` — excluded in both directions.
- `@JsonWriteOnly()` — accepted from input, never echoed back (passwords).
- `@JsonReadOnly()` — serialized, never settable by a client (server-owned ids).
**Transform options**, per call or globally via `configure()`.
- `validate: false` maps without validating, for lenient parsing.
- `unknownKeys: 'allow' | 'strip' | 'error'` decides what happens to undeclared keys.
- `namingStrategy` selects the JSON naming convention.
**Error ergonomics.** Turning the nested `ValidationError` tree into an HTTP 400 body used
to be the caller's problem.
- `flattenErrors(errors)` → `{ "items[0].qty": ["qty must be at least 1"] }`
- `formatErrors(errors)` → one human-readable line per failure
- `collectErrorMessages(errors)` → just the messages
- `validateOrReject(obj)` throws instead of returning an array you might forget to check
**30 validation decorators.** `@Equals`, `@NotEquals`, `@IsEmpty`, `@IsEnum`, `@IsInstance`,
`@Length`, `@IsAlpha`, `@IsAlphanumeric`, `@IsNumberString`, `@IsLowercase`, `@IsUppercase`,
`@Contains`, `@NotContains`, `@StartsWith`, `@EndsWith`, `@IsUUID`, `@IsJSON`,
`@IsDateString`, `@IsSemVer`, `@IsHexColor`, `@IsIP`, `@IsDivisibleBy`, `@IsPort`,
`@IsLatitude`, `@IsLongitude`, `@IsBigInt`, `@MinDate`, `@MaxDate`, `@ArrayUnique`,
`@ArrayContains`, `@ArrayNotContains`.
**Conditional validation.** `@ValidateIf(o => ...)` makes a property's rules depend on the
rest of the object; `@Allow()` declares a property that needs no rules of its own.
**Correctly typed array entry points.** `toInstanceArray()` and `fromJsonArray()`.
`toInstance`/`fromJson` accept arrays at runtime but type the result as `T`, so callers had
to cast to reach the elements.
**`@JsonPolymorphic` options.** `{ onUnknown: 'error' }` and `{ fallback: SomeClass }`.
**`JsonMappingError`** — raised when a value cannot be mapped at all, as distinct from
mapping fine and failing validation.
### Fixed
- **Inheritance silently discarded base-class rules.** A subclass re-decorating an inherited
property registered its constraints against its own prototype, and the engine read only the
nearest set. Constraints now merge down the whole prototype chain, base first. The
library's own example was affected: `Media`'s `@IsString() title` had never been enforced
for `Book`.
- **A circular reference exhausted the heap.** `serialize()` recursed forever, taking 8 GB
and the process with it. It now raises a `JsonMappingError` naming the cause. Diamonds
still serialize; `validate()` skips back-edges.
- **`@Matches` with a `g` or `y` flag was stateful.** `RegExp.test` advances `lastIndex`, so
validating the same value twice gave different answers. Those flags are stripped.
- **An unmatched `@JsonPolymorphic` discriminator silently dropped the value.** The
single-object branch fell through without assigning; the property came back `undefined`.
The raw value is now preserved.
- **`@JsonSerialize` serializers ran on `null`/`undefined`**, crashing on any unset optional
property. They now only see real values.
- **`serialize()` crashed on null-prototype objects.** It read `obj.constructor.prototype`;
both engines now agree on `Object.getPrototypeOf`.
- **`__proto__`, `constructor` and `prototype` in untrusted JSON** were copied onto the
instance, detaching it from its own class. They are dropped.
- **Caller-supplied messages were mangled** by the `each element in ...` prefix, producing
sentences like "each element in tags must all be strings".
- **Two rules sharing a name overwrote each other**, so only one failure was ever reported.
- **`fromRequest` leaked a raw `SyntaxError`** for a non-JSON body; it now reports a
`JsonMappingError`.
- **`@ValidateNested({ each: true })`** was documented in the README but did not compile —
`ValidateNested()` accepted no arguments. It now does, and asserts the value is an array.
### Changed
- `toPlain`, `toJson`, `toInstance`, `fromJson`, `fromJsonArray`, `toInstanceArray` and
`fromRequest` accept an optional trailing options argument. All defaults preserve the
previous behaviour.
- `src/example.ts` is no longer published in `dist`. It called `runExample()` at import
time — an import side effect in a package declaring `"sideEffects": false`.
- Minimum supported Node is 20.
### Infrastructure
- **The test suite had never run.** Vitest 4 transpiles with oxc, which does not read
`experimentalDecorators` from a tsconfig that excludes the files it is transforming, so
every decorator-using suite failed to parse and was reported as "0 test" rather than as an
error. A `vitest.config.ts` enabling legacy decorators brought all 40 existing tests back
to life.
- Test files are now type-checked, which surfaced 17 strict-mode errors.
- CI runs lint, coverage tests, build and ESM/CJS entry-point smoke checks across Node
20/22/24, and `npm ci` works because `package-lock.json` is committed.
- `npm run build:docs` regenerates the previously hand-maintained `docs/cereale.js`.
## [0.0.1]
Initial release: mapping and validation decorators, polymorphic types, custom
serializers/deserializers, and the `toJson` / `fromJson` / `toPlain` / `toInstance` API.
+183 -46
View File
@@ -4,10 +4,12 @@ Cereale is a lightweight TypeScript library that provides Spring-like decorators
## Features
- **Spring-like Decorators:** Familiar `@JsonSerialize`, `@JsonDeserialize`, `@JsonType`, and `@JsonPolymorphic`.
- **Spring-like Decorators:** Familiar `@JsonProperty`, `@JsonSerialize`, `@JsonDeserialize`, `@JsonType`, and `@JsonPolymorphic`.
- **Field-name Mapping:** Map `first_name` to `firstName` per property or with a naming strategy.
- **Access Control:** Keep passwords out of responses and server-owned ids out of requests.
- **Custom Serializers/Deserializers:** Easily handle complex types like Dates, BigInts, or custom objects.
- **Polymorphism Support:** Native handling of polymorphic types via discriminators.
- **Integrated Validation:** Automatically validates objects during serialization and deserialization.
- **Integrated Validation:** 50+ validation decorators, applied during mapping or on demand.
- **Type Safety:** Fully written in TypeScript for excellent developer experience.
- **Zero Dependencies:** Extremely lightweight and fast.
@@ -17,29 +19,27 @@ Cereale is a lightweight TypeScript library that provides Spring-like decorators
npm install cereale
```
Make sure to enable `experimentalDecorators` and `emitDecoratorMetadata` in your `tsconfig.json`:
Enable `experimentalDecorators` in your `tsconfig.json`:
```json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"target": "ES2025"
"target": "ES2022"
}
}
```
Cereale stores its own metadata, so `reflect-metadata` is not required and
`emitDecoratorMetadata` is not read. Requires Node 20 or later.
## Quick Start
### 1. Define your Models
Use decorators to define how your data should be transformed and validated.
```typescript
import {
IsString,
IsInt,
Min,
IsDate,
ValidateNested,
JsonSerialize,
@@ -52,7 +52,7 @@ import {
// Custom Date Serializer
class DateSerializer implements JsonSerializer<Date, string> {
serialize(value: Date): string {
return value.toISOString().split('T')[0];
return value.toISOString().split('T')[0]!;
}
}
@@ -94,12 +94,13 @@ class Library {
}
```
Constraints accumulate down an inheritance chain: `Book` is checked against `Media`'s
`@IsString() title` as well as its own rules.
### 2. Map JSON with Validation
Use standalone utility functions to handle the conversion process directly.
```typescript
import { fromJson, toJson, JsonValidationError } from 'cereale';
import { fromJson, toJson, JsonValidationError, flattenErrors } from 'cereale';
async function main() {
const json = '{"name": "Central Library", "items": [{"type": "book", "title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "publishedAt": "1925-04-10"}]}';
@@ -111,11 +112,11 @@ async function main() {
console.log(library.items[0] instanceof Book); // true
// Serialize Class Instance back to JSON
const outputJson = await toJson(library);
console.log(outputJson);
console.log(await toJson(library));
} catch (error) {
if (error instanceof JsonValidationError) {
console.error("Validation failed:", error.errors);
console.error(flattenErrors(error.errors));
// { "items[0].title": ["title must be a string"] }
}
}
}
@@ -135,20 +136,102 @@ app.post('/books', async (c) => {
});
```
## Field-name Mapping
JSON rarely uses the same names as your classes.
```typescript
import { JsonProperty, JsonAlias } from 'cereale';
class User {
@JsonProperty('first_name')
firstName: string; // <-> {"first_name": "Ada"}
@JsonProperty('surname')
@JsonAlias('last_name') // also accepted on input, never emitted
lastName: string;
}
```
Or convert every property at once with a naming strategy:
```typescript
import { configure, toPlain } from 'cereale';
// once, for the whole application
configure({ namingStrategy: 'snake_case' });
// or per call
await toPlain(user, { namingStrategy: 'snake_case' });
```
Built-in strategies: `identity` (default), `camelCase`, `PascalCase`, `snake_case`,
`SCREAMING_SNAKE_CASE`, `kebab-case`. You can also pass your own
`(propertyKey: string) => string`. An explicit `@JsonProperty` always wins.
Acronyms split where a reader expects them to: `parseHTTPResponse` becomes
`parse_http_response`, not `parse_h_t_t_p_response`.
## Access Control
```typescript
import { JsonIgnore, JsonReadOnly, JsonWriteOnly } from 'cereale';
class Account {
@JsonReadOnly() // sent to clients, never settable by them
id: number;
@IsString()
email: string;
@JsonWriteOnly() // accepted from clients, never echoed back
@IsString()
password: string;
@JsonIgnore() // never crosses the boundary in either direction
internalNotes: string;
}
```
## Options
Every mapping function takes an optional trailing options argument, and `configure()` sets
defaults for the whole application. Per-call options win.
| Option | Values | Default | Meaning |
| --- | --- | --- | --- |
| `validate` | `boolean` | `true` | Validate the result; throw `JsonValidationError` on failure. |
| `namingStrategy` | strategy name or function | `identity` | JSON naming convention for properties without `@JsonProperty`. |
| `unknownKeys` | `allow` \| `strip` \| `error` | `allow` | What to do with incoming keys matching no declared property. |
```typescript
// lenient parse: build the instance, inspect the damage yourself
const draft = await fromJson(Order, body, { validate: false });
const problems = flattenErrors(await validate(draft));
// strict intake: reject anything you did not declare
const order = await fromJson(Order, body, { unknownKeys: 'error' });
```
## API Reference
### Decorators
### Mapping Decorators
- `@JsonSerialize(serializer: ClassConstructor<JsonSerializer>)`: Specifies a custom serializer for a property.
- `@JsonDeserialize(deserializer: ClassConstructor<JsonDeserializer>)`: Specifies a custom deserializer for a property.
- `@JsonType(typeFunction: () => ClassConstructor<any>)`: Explicitly sets the type for nested transformations.
- `@JsonPolymorphic(discriminator: string, subTypes: { value: ClassConstructor<any>, name: string }[])`: Configures polymorphic transformation based on a discriminator field.
- `@JsonProperty(name: string)`: Renames the property in JSON, both directions.
- `@JsonAlias(...names: string[])`: Extra names accepted on input only.
- `@JsonIgnore()`: Excludes the property from mapping entirely.
- `@JsonReadOnly()`: Serialized, but never populated from incoming JSON.
- `@JsonWriteOnly()`: Populated from incoming JSON, but never serialized.
- `@JsonSerialize(serializer: ClassConstructor<JsonSerializer>)`: Custom serializer for a property. Skipped when the value is `null`/`undefined`.
- `@JsonDeserialize(deserializer: ClassConstructor<JsonDeserializer>)`: Custom deserializer for a property.
- `@JsonType(typeFunction: () => ClassConstructor<any>)`: Explicitly sets the type for nested transformations. Applies element-wise to arrays.
- `@JsonPolymorphic(discriminator, subTypes, options?)`: Polymorphic transformation based on a discriminator field. `options` accepts `{ onUnknown: 'keep' | 'error' }` (default `keep`, which preserves the raw value) and `{ fallback: ClassConstructor }`.
#### Validation Decorators
### Validation Decorators
Most validation decorators accept an optional `ValidationOptions` object:
- `each: boolean`: Apply validation to each element of an array.
- `message: string | ((args: ValidationArguments) => string)`: Custom error message.
- `message: string | ((args: ValidationArguments) => string)`: Custom error message, reported verbatim.
| Decorator | Description |
| --- | --- |
@@ -156,46 +239,88 @@ Most validation decorators accept an optional `ValidationOptions` object:
| `@IsNumber()` | Checks if value is a number (and not NaN). |
| `@IsInt()` | Checks if value is an integer. |
| `@IsBoolean()` | Checks if value is a boolean. |
| `@IsBigInt()` | Checks if value is a bigint. |
| `@IsObject()` | Checks if value is an object (not null/array). |
| `@IsDate()` | Checks if value is a valid Date object. |
| `@IsDefined()` | Checks if value is not null or undefined. |
| `@IsOptional()` | Skips other validations if value is null/undefined. |
| `@IsNotEmpty()` | Checks if value is not null/undefined/empty string. |
| `@Min(value)` | Checks if number is >= value. |
| `@Max(value)` | Checks if number is <= value. |
| `@Positive()` | Checks if number is > 0. |
| `@Negative()` | Checks if number is < 0. |
| `@MinLength(len)` | Checks if string length is >= len. |
| `@MaxLength(len)` | Checks if string length is <= len. |
| `@IsEmpty()` | Checks if value is null/undefined/`''`/`[]`/`{}`. |
| `@Equals(value)` / `@NotEquals(value)` | Strict equality against a fixed value. |
| `@IsEnum(enumObject)` | Checks membership of a TypeScript enum. |
| `@IsInstance(Class)` | Checks `value instanceof Class`. |
| `@Min(value)` / `@Max(value)` | Numeric bounds. |
| `@Positive()` / `@Negative()` | Checks sign. |
| `@IsDivisibleBy(n)` | Checks `value % n === 0`. |
| `@IsPort()` | Integer in 0–65535, as number or numeric string. |
| `@IsLatitude()` / `@IsLongitude()` | Geographic bounds. |
| `@MinLength(len)` / `@MaxLength(len)` | String length bounds. |
| `@Length(min, max?)` | Both bounds in one rule. |
| `@IsAlpha()` / `@IsAlphanumeric()` | Character-class checks. |
| `@IsLowercase()` / `@IsUppercase()` | Case checks. |
| `@IsNumberString()` | String that parses as a finite number. |
| `@Contains(s)` / `@NotContains(s)` | Substring checks. |
| `@StartsWith(s)` / `@EndsWith(s)` | Affix checks. |
| `@Email()` | Checks if string is a valid email. |
| `@IsUrl()` | Checks if string is a valid URL. |
| `@IsUUID(version?)` | Checks if string is a valid UUID. |
| `@IsIP(version?)` | Checks if string is a valid IPv4/IPv6 address. |
| `@IsJSON()` | Checks if string parses as JSON. |
| `@IsDateString()` | Checks if string is a parseable date. |
| `@IsSemVer()` | Checks if string is a semantic version. |
| `@IsHexColor()` | Checks `#rgb`, `#rrggbb`, `#rrggbbaa`. |
| `@Matches(regex)` | Checks if string matches a regular expression. |
| `@MinDate(d)` / `@MaxDate(d)` | Date bounds. Accepts `() => Date` for a moving bound. |
| `@IsArray()` | Checks if value is an array. |
| `@ArrayNotEmpty()` | Checks if array is not empty. |
| `@ArrayMinSize(n)`| Checks if array has at least n elements. |
| `@ArrayMaxSize(n)`| Checks if array has at most n elements. |
| `@IsIn(values)` | Checks if value is in the allowed list. |
| `@IsNotIn(vals)` | Checks if value is NOT in the list. |
| `@ValidateNested()`| Recursively validates nested objects/arrays. |
| `@ArrayMinSize(n)` / `@ArrayMaxSize(n)` | Array size bounds. |
| `@ArrayUnique(keyFn?)` | Checks for duplicate elements. |
| `@ArrayContains(vals)` / `@ArrayNotContains(vals)` | Membership checks. |
| `@IsIn(values)` / `@IsNotIn(values)` | Allow/deny lists. |
| `@ValidateNested(options?)` | Recursively validates nested objects/arrays. |
| `@ValidateIf(o => boolean)` | Skips this property's rules when the condition is false. |
| `@Allow()` | Declares a property with no rules of its own. |
| `@Validate(validator, constraints?, options?)` | Applies a custom validator class or function. |
Write your own with `registerDecorator({ name, target, propertyName, validator })`.
### Utilities
- `toJson(obj: any)`: Validates and serializes an instance to a JSON string (Returns `Promise<string>`).
- `toPlain(obj: any)`: Validates and transforms an instance to a plain object (Returns `Promise<any>`).
- `fromJson(clazz: ClassConstructor, json: string)`: Parses JSON and transforms it to a validated class instance (Returns `Promise<T>`).
- `toInstance(clazz: ClassConstructor, plain: any)`: Transforms a plain object to a validated class instance (Returns `Promise<T>`).
- `fromRequest(clazz: ClassConstructor, request: Request)`: Extracts JSON from a Fetch `Request` and transforms it to a validated instance (Returns `Promise<T>`).
- `validate(obj: any)`: Performs full validation on an object/instance (Returns `Promise<ValidationError[]>`).
- `toJson(obj, options?)`: Validates and serializes an instance to a JSON string (`Promise<string>`).
- `toPlain(obj, options?)`: Validates and transforms an instance to a plain object (`Promise<any>`).
- `fromJson(clazz, json, options?)`: Parses JSON to a validated class instance (`Promise<T>`).
- `fromJsonArray(clazz, json, options?)`: Same, for a JSON array (`Promise<T[]>`).
- `toInstance(clazz, plain, options?)`: Transforms a plain object to a validated class instance (`Promise<T>`).
- `toInstanceArray(clazz, plain, options?)`: Same, for an array (`Promise<T[]>`).
- `fromRequest(clazz, request, options?)`: Extracts JSON from a Fetch `Request` (`Promise<T>`).
- `validate(obj)`: Full validation, returning `Promise<ValidationError[]>`.
- `validateOrReject(obj)`: As above, but throws `JsonValidationError`.
- `configure(options)` / `getConfig()` / `resetConfig()`: Library-wide defaults.
### Error Handling
`JsonValidationError` carries a nested `ValidationError[]`. Three helpers turn it into
something you can return to a client:
```typescript
import { flattenErrors, formatErrors, collectErrorMessages } from 'cereale';
flattenErrors(errors); // { "items[0].qty": ["qty must be at least 1"] }
formatErrors(errors); // "items[0].qty: qty must be at least 1"
collectErrorMessages(errors); // ["qty must be at least 1"]
```
`JsonMappingError` is raised when a value cannot be mapped at all — a body that is not
JSON, a circular reference, an unknown discriminator under `{ onUnknown: 'error' }` — as
distinct from mapping fine and failing validation.
## Framework Integrations
Cereale is designed to be compatible with all trending web frameworks.
### Hono / Next.js / Cloudflare Workers
Use `fromRequest` for seamless integration with the Fetch `Request` API.
### NestJS
You can use Cereale inside your controllers for explicit mapping and validation without needing `reflect-metadata`.
Use Cereale inside your controllers for explicit mapping and validation without needing `reflect-metadata`.
```typescript
import { toInstance } from 'cereale';
@@ -208,21 +333,33 @@ async create(@Body() body: any) {
```
### Express / Fastify
Easily integrate with traditional Node.js frameworks.
```typescript
import { toInstance, toPlain } from 'cereale';
import { toInstance, toPlain, JsonValidationError, flattenErrors } from 'cereale';
app.post('/user', async (req, res) => {
try {
const user = await toInstance(User, req.body);
res.json(await toPlain(user));
} catch (err) {
res.status(400).json(err);
if (err instanceof JsonValidationError) {
return res.status(400).json({ errors: flattenErrors(err.errors) });
}
throw err;
}
});
```
## Notes and Limitations
- **Circular references** are rejected during serialization with a `JsonMappingError`. Break
the cycle with `@JsonIgnore()` on the back-reference.
- **`validate()` on a plain object** returns no errors: rules live on the class, so validate
the instance you get back from `toInstance`, not the raw payload.
- **Renaming is not backwards-compatible by itself.** Once a property carries
`@JsonProperty`, its original name is no longer accepted on input — add `@JsonAlias` to
keep older clients working.
## Contributing
Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute to this project.
+2 -1
View File
File diff suppressed because one or more lines are too long
+41 -41
View File
@@ -136,12 +136,23 @@
<div>
<h3 class="font-bold text-lg mb-4 text-indigo-600">Mapping</h3>
<ul class="space-y-2 text-slate-600">
<li><code class="text-sm bg-slate-100 p-1 rounded">@JsonProperty('first_name')</code></li>
<li><code class="text-sm bg-slate-100 p-1 rounded">@JsonAlias(...names)</code></li>
<li><code class="text-sm bg-slate-100 p-1 rounded">@JsonSerialize(cls)</code></li>
<li><code class="text-sm bg-slate-100 p-1 rounded">@JsonDeserialize(cls)</code></li>
<li><code class="text-sm bg-slate-100 p-1 rounded">@JsonType(() => cls)</code></li>
<li><code class="text-sm bg-slate-100 p-1 rounded">@JsonPolymorphic(field, types)</code></li>
</ul>
</div>
<div>
<h3 class="font-bold text-lg mb-4 text-indigo-600">Access Control</h3>
<ul class="space-y-2 text-slate-600">
<li><code class="text-sm bg-slate-100 p-1 rounded">@JsonIgnore()</code></li>
<li><code class="text-sm bg-slate-100 p-1 rounded">@JsonReadOnly()</code></li>
<li><code class="text-sm bg-slate-100 p-1 rounded">@JsonWriteOnly()</code></li>
<li class="text-sm pt-2">Naming strategies: <code class="text-sm bg-slate-100 p-1 rounded">snake_case</code>, <code class="text-sm bg-slate-100 p-1 rounded">kebab-case</code>, …</li>
</ul>
</div>
<div>
<h3 class="font-bold text-lg mb-4 text-purple-600">Basic Validation</h3>
<ul class="space-y-2 text-slate-600">
@@ -158,7 +169,9 @@
<li><code class="text-sm bg-slate-100 p-1 rounded">@Min(n)</code>, <code class="text-sm bg-slate-100 p-1 rounded">@Max(n)</code></li>
<li><code class="text-sm bg-slate-100 p-1 rounded">@MinLength(n)</code>, <code class="text-sm bg-slate-100 p-1 rounded">@MaxLength(n)</code></li>
<li><code class="text-sm bg-slate-100 p-1 rounded">@Email()</code>, <code class="text-sm bg-slate-100 p-1 rounded">@IsUrl()</code></li>
<li><code class="text-sm bg-slate-100 p-1 rounded">@ValidateNested()</code></li>
<li><code class="text-sm bg-slate-100 p-1 rounded">@IsUUID(v?)</code>, <code class="text-sm bg-slate-100 p-1 rounded">@IsEnum(e)</code></li>
<li><code class="text-sm bg-slate-100 p-1 rounded">@MinDate(d)</code>, <code class="text-sm bg-slate-100 p-1 rounded">@ArrayUnique()</code></li>
<li><code class="text-sm bg-slate-100 p-1 rounded">@ValidateNested()</code>, <code class="text-sm bg-slate-100 p-1 rounded">@ValidateIf(fn)</code></li>
</ul>
</div>
</div>
@@ -175,9 +188,10 @@
<script>
const initialCode = `// 1. Define your model with decorators
class User {
@JsonProperty('display_name')
@IsString()
@MinLength(3)
name;
displayName;
@IsInt()
@Min(18)
@@ -186,26 +200,36 @@ class User {
@Email()
email;
constructor(name, age, email) {
this.name = name;
// Accepted from a request, never sent back out
@JsonWriteOnly()
@IsString()
password;
constructor(displayName, age, email, password) {
this.displayName = displayName;
this.age = age;
this.email = email;
this.password = password;
}
}
async function demo() {
console.log("--- Validating valid user ---");
const user = new User("Alice", 25, "alice@example.com");
const json = await JsonMapper.toJson(user);
console.log("--- Mapping a valid user ---");
const user = new User("Alice", 25, "alice@example.com", "hunter2");
const json = await toJson(user);
console.log("JSON Output:", json);
console.log("Password withheld:", !json.includes("hunter2"));
console.log("\\n--- Testing validation failure ---");
console.log("\\n--- Reading it back ---");
const parsed = await fromJson(User, json, { validate: false });
console.log("displayName read from display_name:", parsed.displayName);
console.log("\\n--- Reporting validation failures ---");
try {
const invalidJson = '{"name": "Bo", "age": 15, "email": "not-an-email"}';
await JsonMapper.fromJson(User, invalidJson);
await fromJson(User, '{"display_name": "Bo", "age": 15, "email": "nope", "password": "x"}');
} catch (error) {
console.log("Caught Error:", error.message);
console.log("Validation Errors:", JSON.stringify(error.errors, null, 2));
console.log("Caught:", error.message);
console.log("Flattened:", flattenErrors(error.errors));
}
}
@@ -247,36 +271,12 @@ demo();`;
]
}).code;
// Create a function with the library symbols in scope
const {
IsString, IsInt, Min, Max, IsEmail, IsArray, IsDate, IsOptional, ValidateNested,
IsBoolean, IsNumber, IsObject, IsDefined, IsNotEmpty, MinLength, MaxLength,
Email, IsUrl, Matches, ArrayMinSize, ArrayMaxSize, ArrayNotEmpty, IsIn, IsNotIn,
Positive, Negative,
JsonSerialize, JsonDeserialize, JsonPolymorphic, JsonType, JsonMapper,
JsonValidationError
} = Cereale;
// Put every library export in scope. Derived from the bundle rather than
// hand-listed, so a new decorator is usable here the moment it is exported.
const exportNames = Object.keys(Cereale).filter(name => /^[A-Za-z_$][\w$]*$/.test(name));
const run = new Function(
'console',
'IsString', 'IsInt', 'Min', 'Max', 'IsEmail', 'IsArray', 'IsDate', 'IsOptional', 'ValidateNested',
'IsBoolean', 'IsNumber', 'IsObject', 'IsDefined', 'IsNotEmpty', 'MinLength', 'MaxLength',
'Email', 'IsUrl', 'Matches', 'ArrayMinSize', 'ArrayMaxSize', 'ArrayNotEmpty', 'IsIn', 'IsNotIn',
'Positive', 'Negative',
'JsonSerialize', 'JsonDeserialize', 'JsonPolymorphic', 'JsonType', 'JsonMapper',
'JsonValidationError',
transpiled
);
await run(
{ log: logToOutput },
IsString, IsInt, Min, Max, IsEmail, IsArray, IsDate, IsOptional, ValidateNested,
IsBoolean, IsNumber, IsObject, IsDefined, IsNotEmpty, MinLength, MaxLength,
Email, IsUrl, Matches, ArrayMinSize, ArrayMaxSize, ArrayNotEmpty, IsIn, IsNotIn,
Positive, Negative,
JsonSerialize, JsonDeserialize, JsonPolymorphic, JsonType, JsonMapper,
JsonValidationError
);
const run = new Function('console', ...exportNames, transpiled);
await run({ log: logToOutput }, ...exportNames.map(name => Cereale[name]));
} catch (err) {
outputElement.textContent += 'Error: ' + err.message + '\\n';
if (err.stack) {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cereale",
"version": "0.0.1",
"version": "0.1.0",
"description": "Spring-like decorators for JSON mapping and validation in TypeScript",
"type": "module",
"main": "./dist/cjs/index.js",
+107 -55
View File
@@ -5,11 +5,21 @@ import {
ValidateNested,
IsArray,
IsDate,
IsEnum,
IsUUID,
ValidateIf,
JsonProperty,
JsonAlias,
JsonReadOnly,
JsonWriteOnly,
JsonSerialize,
JsonDeserialize,
JsonPolymorphic,
toJson,
fromJson,
toPlain,
validate,
flattenErrors,
JsonSerializer,
JsonDeserializer,
Validate,
@@ -32,14 +42,14 @@ class IsLongerThan implements ValidatorConstraintInterface {
}
}
function IsUsername(options?: ValidationOptions) {
function IsSlug(options?: ValidationOptions) {
return function (object: any, propertyName: string) {
registerDecorator({
name: 'isUsername',
name: 'isSlug',
target: object.constructor,
propertyName: propertyName,
...(options ? { options } : {}),
validator: (value: any) => typeof value === 'string' && /^[a-zA-Z0-9_]+$/.test(value)
validator: (value: any) => typeof value === 'string' && /^[a-z0-9-]+$/.test(value)
});
};
}
@@ -48,11 +58,8 @@ function IsUsername(options?: ValidationOptions) {
class DateSerializer implements JsonSerializer<Date, string> {
serialize(value: Date): string {
if (value instanceof Date) {
return value.toISOString().split('T')[0] || '';
}
return String(value);
}
}
class DateDeserializer implements JsonDeserializer<string, Date> {
@@ -63,10 +70,16 @@ class DateDeserializer implements JsonDeserializer<string, Date> {
// --- Domain Models ---
enum Format {
Hardback = 'hardback',
Paperback = 'paperback',
}
abstract class Media {
@IsString()
abstract type: string;
// Declared once here. Subclasses inherit the rule without restating it.
@IsString()
title: string;
}
@@ -75,14 +88,14 @@ class Book extends Media {
@IsString()
override type: string = 'book';
@IsString()
@IsUsername({ message: 'Title must be a valid alphanumeric username' })
declare title: string;
@IsString()
@Validate(IsLongerThan, [5])
author: string;
@IsEnum(Format)
format: Format = Format.Paperback;
@JsonProperty('published_at')
@JsonSerialize(DateSerializer)
@JsonDeserialize(DateDeserializer)
@IsDate()
@@ -91,19 +104,38 @@ class Book extends Media {
class Movie extends Media {
@IsString()
type: string = 'movie';
override type: string = 'movie';
@IsInt()
@Min(1)
duration: number;
// Only checked for films that claim to be part of a series.
@ValidateIf((movie: Movie) => movie.duration > 200)
@IsString()
intermissionNote?: string;
}
class Library {
@JsonReadOnly()
@IsUUID(4)
id: string;
@IsString()
@IsSlug({ message: 'name must be a lowercase slug' })
name: string;
@JsonProperty('curator_email')
@JsonAlias('curatorEmail')
@IsString()
curatorEmail: string;
@JsonWriteOnly()
@IsString()
adminToken: string;
@IsArray()
@ValidateNested()
@ValidateNested({ each: true })
@JsonPolymorphic('type', [
{ value: Book, name: 'book' },
{ value: Movie, name: 'movie' }
@@ -114,64 +146,84 @@ class Library {
// --- Execution ---
async function runExample() {
console.log("--- Starting Example ---");
console.log('--- Starting Example ---');
// 1. Create a Library instance
const library = new Library();
library.name = "Central Library";
library.id = '9b2e4c1a-77bd-4f2e-8c33-1d9a6b0e5f21';
library.name = 'central-library';
library.curatorEmail = 'ada@example.com';
library.adminToken = 'super-secret';
const book = new Book();
book.title = "Gatsby";
book.author = "Fitzgerald";
book.publishedAt = new Date("1925-04-10");
book.title = 'Gatsby';
book.author = 'Fitzgerald';
book.format = Format.Hardback;
book.publishedAt = new Date('1925-04-10');
const movie = new Movie();
movie.title = "Inception";
movie.title = 'Inception';
movie.duration = 148;
library.items = [book, movie];
try {
// 2. Serialize to JSON
console.log("\n[1] Serializing Library to JSON...");
// 1. Serialize, honouring @JsonProperty and the write-only token
console.log('\n[1] Serializing Library to JSON...');
const json = await toJson(library);
console.log("JSON Output:", json);
console.log('JSON Output:', json);
console.log('Secret withheld from output:', !json.includes('super-secret'));
// 3. Deserialize back to Instance
console.log("\n[2] Deserializing JSON back to Library instance...");
const deserializedLibrary = await fromJson(Library, json);
console.log("Deserialized Library Name:", deserializedLibrary.name);
console.log("Items count:", deserializedLibrary.items.length);
// Check Polymorphism
deserializedLibrary.items.forEach((item, index) => {
console.log(`Item ${index} is instance of ${item.constructor.name}: ${item.title}`);
// 2. Deserialize back, resolving the polymorphic items
console.log('\n[2] Deserializing JSON back to Library instance...');
const restored = await fromJson(Library, json, { validate: false });
console.log('Curator (read via curator_email):', restored.curatorEmail);
console.log('Items count:', restored.items.length);
restored.items.forEach((item, index) => {
console.log(`Item ${index} is a ${item.constructor.name}: ${item.title}`);
if (item instanceof Book) {
console.log(` > Book Author: ${item.author}`);
console.log(` > Published At: ${item.publishedAt.toISOString()} (instanceof Date: ${item.publishedAt instanceof Date})`);
console.log(` > Author: ${item.author}, format: ${item.format}`);
console.log(` > Published: ${item.publishedAt.toISOString()} (Date: ${item.publishedAt instanceof Date})`);
} else if (item instanceof Movie) {
console.log(` > Movie Duration: ${item.duration} mins`);
console.log(` > Duration: ${item.duration} mins`);
}
});
// 4. Test Validation Failure
console.log("\n[3] Testing Validation Failure (Invalid Movie Duration)...");
const invalidJson = JSON.stringify({
name: "Invalid Library",
items: [
{ type: "movie", title: "Short Film", duration: -5 } // Invalid: duration < 1
]
// 3. A client cannot set a @JsonReadOnly field
console.log('\n[3] A client trying to set the read-only id...');
const hijacked = await fromJson(
Library,
JSON.stringify({ id: 'attacker-supplied', name: 'x', curator_email: 'a@b.c', adminToken: 't', items: [] }),
{ validate: false }
);
console.log('id after mapping (expected undefined):', hijacked.id);
// 4. Validation failures, flattened for an HTTP response
console.log('\n[4] Reporting validation failures...');
const invalid = await fromJson(
Library,
JSON.stringify({
name: 'Not A Slug',
curator_email: 'a@b.c',
adminToken: 't',
items: [{ type: 'movie', title: 'Short Film', duration: -5 }]
}),
{ validate: false }
);
console.log(flattenErrors(await validate(invalid)));
// 5. A base-class rule applies to a subclass that never restates it
console.log('\n[5] Base-class constraints reach subclasses...');
const untitled = new Book();
untitled.title = undefined as any;
untitled.author = 'Fitzgerald';
untitled.publishedAt = new Date('1925-04-10');
console.log(flattenErrors(await validate(untitled)));
// 6. Naming strategies convert every property at once
console.log('\n[6] The same movie under snake_case...');
console.log(await toPlain(movie, { namingStrategy: 'snake_case' }));
}
runExample().catch((error) => {
console.error('Example failed:', error);
process.exitCode = 1;
});
await fromJson(Library, invalidJson);
} catch (error) {
if (error instanceof Error) {
console.log("Caught expected error:", error.message);
if ((error as any).errors) {
console.log("Validation details:", JSON.stringify((error as any).errors, null, 2));
}
}
}
}
runExample();