diff --git a/src/index.ts b/src/index.ts index 347598a..79b35d6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -56,7 +56,12 @@ export { NotModified, ValidationError, TransportMismatchError, + HTTP_ERROR, + VALIDATION_ERROR, + isHttpError, + isValidationError, } from './signals'; +export type { HttpErrorLike } from './signals'; // Bus & flow export { Bus } from './bus'; diff --git a/src/signals.ts b/src/signals.ts index ef46969..1841afc 100644 --- a/src/signals.ts +++ b/src/signals.ts @@ -1,11 +1,36 @@ import type { StandardIssue } from './standard-schema'; +/** + * Brands, so an error is recognised across two copies of core — an app that installed one from npm + * and a plugin that brought another from JSR, or two npm versions npm could not dedupe. + * `instanceof` cannot do that: each copy has its own class identity. + * + * `Symbol.for` is registry-wide, so both copies resolve the same symbol. The *string* is the public + * protocol (`.specs/2026-09-15-plugin-ecosystem-design.md`, 1.2): a plugin that imports only types + * cannot import this constant, so it writes `Symbol.for('green-tea.http-error')` itself. + * + * `unique symbol` is required by TypeScript for a computed class field, and `Symbol.for` on a `const` + * satisfies it. + */ +export const HTTP_ERROR: unique symbol = Symbol.for('green-tea.http-error'); +export const VALIDATION_ERROR: unique symbol = Symbol.for('green-tea.validation-error'); + +/** The shape core reads off a branded error. Anything carrying the brand should satisfy it. */ +export interface HttpErrorLike { + status: number; + message: string; + body?: unknown; + headers?: Record; +} + /** * Error carrying an HTTP status code and optional response body. Base of all signals. * A subclass needing response headers (e.g. `location`, `retry-after`) sets `headers` * rather than requiring a special case in the error renderer. */ export class HttpError extends Error { + readonly [HTTP_ERROR] = true; + constructor( readonly status: number, message?: string, @@ -47,6 +72,8 @@ export class Redirect extends HttpError { /** 422 raised when request input fails Standard Schema validation. */ export class ValidationError extends HttpError { + readonly [VALIDATION_ERROR] = true; + constructor( public issues: StandardIssue[], public source: string, @@ -68,7 +95,12 @@ export class TransportMismatchError extends HttpError { } } -/** Type guard: true if `error` is an {@link HttpError}. */ -export function isHttpError(error: unknown): error is HttpError { - return error instanceof HttpError; +/** Type guard: true if `error` carries the HTTP-error brand — this copy's or another's. */ +export function isHttpError(error: unknown): error is HttpErrorLike { + return typeof error === 'object' && error !== null && HTTP_ERROR in error; +} + +/** Type guard: true if `error` carries the validation brand. */ +export function isValidationError(error: unknown): error is ValidationError { + return typeof error === 'object' && error !== null && VALIDATION_ERROR in error; } diff --git a/src/transformers.ts b/src/transformers.ts index 7cf7c0e..1643ccb 100644 --- a/src/transformers.ts +++ b/src/transformers.ts @@ -1,4 +1,4 @@ -import { isHttpError, ValidationError } from './signals'; +import { isHttpError, isValidationError } from './signals'; import type { TransformerFn } from './metadata'; import { flattenPath } from './standard-schema'; import type { Logger } from './logger'; @@ -35,7 +35,7 @@ export const JsonTransformer: TransformerFn = (value) => ({ * An `HttpError` carrying a `body` renders that payload instead of the default `{ error: message }`. */ export function errorToResponse(error: unknown): ErrorResponse { - if (error instanceof ValidationError) { + if (isValidationError(error)) { return { status: 422, headers: { 'content-type': 'application/json' }, diff --git a/test/signals-brand.test.ts b/test/signals-brand.test.ts new file mode 100644 index 0000000..e952c7f --- /dev/null +++ b/test/signals-brand.test.ts @@ -0,0 +1,65 @@ +// test/signals-brand.test.ts +import { describe, expect, it } from 'vitest'; + +import { errorToResponse } from '../src/transformers'; +import { HttpError, ValidationError, isHttpError, isValidationError } from '../src/signals'; + +// What a plugin published from another package throws: it never imported core, so it is not an +// `instanceof` anything of ours. The brand is the whole contract — see .specs/2026-09-15, 1.2. +const HTTP_ERROR = Symbol.for('green-tea.http-error'); + +class ForeignTooManyRequests extends Error { + readonly [HTTP_ERROR] = true; + readonly status = 429; + constructor( + message: string, + readonly headers: Record, + ) { + super(message); + } +} + +describe('the error brand', () => { + it('renders a foreign branded error with its own status and headers', () => { + const response = errorToResponse(new ForeignTooManyRequests('slow down', { 'retry-after': '30' })); + + expect(response.status).toBe(429); + expect(response.headers['retry-after']).toBe('30'); + expect(JSON.parse(response.body)).toEqual({ error: 'slow down' }); + }); + + it('recognises a foreign branded error through the guard', () => { + expect(isHttpError(new ForeignTooManyRequests('slow down', {}))).toBe(true); + }); + + it("still recognises core's own errors", () => { + expect(isHttpError(new HttpError(418, 'teapot'))).toBe(true); + expect(isValidationError(new ValidationError([], 'body'))).toBe(true); + expect(isValidationError(new HttpError(418, 'teapot'))).toBe(false); + }); + + it('does not claim an unbranded error', () => { + expect(isHttpError(new Error('plain'))).toBe(false); + expect(isHttpError(null)).toBe(false); + expect(isHttpError({ status: 429 })).toBe(false); + }); + + it('renders a foreign validation error as 422 with its issues', () => { + const foreign = Object.assign(new Error('Validation failed'), { + [Symbol.for('green-tea.http-error')]: true, + [Symbol.for('green-tea.validation-error')]: true, + status: 422, + source: 'body', + issues: [{ path: ['email'], message: 'required' }], + }); + + const response = errorToResponse(foreign); + + expect(response.status).toBe(422); + expect(JSON.parse(response.body)).toEqual({ + error: 'Validation failed', + source: 'body', + issues: [{ path: 'email', message: 'required' }], + }); + }); +});