npm workspaces (packages/*, apps/*) with shared TypeScript, ESLint and
Jest setup and `npm run check`. @crosscode/contracts builds to CommonJS
and ESM (tsup) with the crosscode.<name>/<major> schema-name helpers.
packages/ui and apps/{accounts,website,app} are placeholders.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
38 lines
1.5 KiB
TypeScript
38 lines
1.5 KiB
TypeScript
/**
|
|
* Every payload that crosses between products carries its `schema` name, so a consumer always
|
|
* knows what it's reading (ROADMAP-v3 §2): `crosscode.<name>/<major>`, e.g. `crosscode.event/1`.
|
|
*
|
|
* Versioning:
|
|
* - Adding an optional field keeps the major version. Consumers ignore fields they don't know.
|
|
* - Removing or renaming a field, or changing its meaning, needs the next major (`/2`), served
|
|
* alongside the old one until every install has updated.
|
|
*/
|
|
|
|
const SCHEMA_NAME = /^crosscode\.([a-z][a-z0-9-]*)\/([1-9][0-9]*)$/;
|
|
|
|
export interface SchemaName {
|
|
name: string;
|
|
major: number;
|
|
}
|
|
|
|
/** Builds a schema name: `schemaName("event", 1)` → `"crosscode.event/1"`. */
|
|
export function schemaName<N extends string, M extends number>(name: N, major: M): `crosscode.${N}/${M}` {
|
|
const result = `crosscode.${name}/${major}` as const;
|
|
if (!SCHEMA_NAME.test(result)) throw new Error(`Invalid schema name: ${result}`);
|
|
return result;
|
|
}
|
|
|
|
/** Splits a schema name into its name and major version, or returns `null` if it isn't one. */
|
|
export function parseSchemaName(value: unknown): SchemaName | null {
|
|
if (typeof value !== "string") return null;
|
|
const match = SCHEMA_NAME.exec(value);
|
|
if (!match) return null;
|
|
return { name: match[1]!, major: Number(match[2]) };
|
|
}
|
|
|
|
/** True when `value` is a payload's `schema` for the given name and major version. */
|
|
export function isSchema(value: unknown, name: string, major: number): boolean {
|
|
const parsed = parseSchemaName(value);
|
|
return parsed !== null && parsed.name === name && parsed.major === major;
|
|
}
|