Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions sdks/typescript/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@

All notable changes to `@nightmoose/contractgate-sdk`.

## Unreleased

- `Contract.fromYaml` accepts ODCS v3.x documents (no `ontology`): fields are
read from `schema[0].properties[]` (`logicalType`, or `physicalType` when it
is absent; `required`, `primaryKey`, `enum`, `logicalTypeOptions`), a map
`description` is read as text, and unknown ODCS fields are ignored. Mirrors
the Python SDK and the gateway.
- `ontology` is optional in native contracts.
- ODCS `date` and `timestamp` read as strings, and `unique` / quality rules are
not checked locally (this SDK has no date type or quality rules).
- Needs a version bump (0.4.2, to line up with DataContractGate 0.4.2) before
the next npm publish.

## 0.4.1 — 2026-10-28

Version alignment with DataContractGate 0.4.1. No SDK API changes.
Expand Down
2 changes: 2 additions & 0 deletions sdks/typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ const compiled = contract.compile();
const { passed, violations } = compiled.validate({ user_id: "alice", timestamp: 1700000000 });
```

`Contract.fromYaml` also reads an ODCS v3.x document directly (no `ontology` needed): fields come from `schema[0].properties[]`, a map `description` is read as text, and unknown ODCS fields are ignored. `ontology` is optional in native contracts too.

The local validator mirrors the Rust engine exactly. Conformance is enforced via a shared fixture corpus under `tests/conformance/`.

## Error hierarchy
Expand Down
140 changes: 135 additions & 5 deletions sdks/typescript/src/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,134 @@ function parseGlossaryEntry(raw: unknown): GlossaryEntry {
// Contract + CompiledContract
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// ODCS v3.x input
// ---------------------------------------------------------------------------

type Json = Record<string, unknown>;

const isMap = (v: unknown): v is Json =>
v !== null && typeof v === 'object' && !Array.isArray(v);

// ODCS logicalType -> field type. This SDK has no date or timestamp type, so
// those read as strings (the shape is not checked locally).
const ODCS_LOGICAL: Record<string, string> = {
integer: 'integer', long: 'integer', int: 'integer',
number: 'float', double: 'float', float: 'float', decimal: 'float',
boolean: 'boolean', bool: 'boolean',
object: 'object', record: 'object', struct: 'object', map: 'object',
array: 'array', list: 'array',
any: 'any',
};

// Used only when a property has no logicalType.
const ODCS_PHYSICAL: Record<string, string> = {
int: 'integer', integer: 'integer', bigint: 'integer', smallint: 'integer',
tinyint: 'integer', long: 'integer', short: 'integer',
float: 'float', double: 'float', real: 'float', decimal: 'float',
numeric: 'float', number: 'float',
boolean: 'boolean', bool: 'boolean',
struct: 'object', record: 'object', object: 'object', map: 'object',
json: 'object', jsonb: 'object', variant: 'object',
array: 'array', list: 'array',
};

/** A document with no `ontology` and an `apiVersion: v3*`, `kind: DataContract`
* or a `schema` list. */
function isOdcs(r: Json): boolean {
if ('ontology' in r) return false;
const api = r['apiVersion'];
return (
(typeof api === 'string' && api.startsWith('v3')) ||
r['kind'] === 'DataContract' ||
Array.isArray(r['schema'])
);
}

function odcsDescription(v: unknown): string | undefined {
if (typeof v === 'string') return v;
if (isMap(v)) {
for (const k of ['purpose', 'usage', 'limitations']) {
if (typeof v[k] === 'string') return v[k] as string;
}
}
return undefined;
}

function odcsEnum(v: unknown): unknown[] | undefined {
if (!Array.isArray(v)) return undefined;
const out = v
.map((i) => (isMap(i) ? i['value'] : i))
.filter((i) => ['string', 'number', 'boolean'].includes(typeof i));
return out.length ? out : undefined;
}

function odcsProp(p: Json): Json {
const logical = p['logicalType'];
let type: string;
if (typeof logical === 'string') {
type = ODCS_LOGICAL[logical] ?? 'string';
} else {
const base = String(p['physicalType'] ?? '').toLowerCase().split(/[(< ]/)[0] ?? '';
type = ODCS_PHYSICAL[base] ?? 'string';
}
const opts = isMap(p['logicalTypeOptions']) ? p['logicalTypeOptions'] : {};
const ent: Json = {
name: String(p['name']),
type,
required: p['required'] === true || p['primaryKey'] === true,
};
const en = odcsEnum(p['enum']) ?? odcsEnum(opts['enum']);
if (en) ent['enum'] = en;
for (const [src, dst] of [
['pattern', 'pattern'],
['minLength', 'min_length'],
['maxLength', 'max_length'],
['minimum', 'min'],
['maximum', 'max'],
] as const) {
if (opts[src] !== undefined && opts[src] !== null) ent[dst] = opts[src];
}
return ent;
}

/** Map an ODCS v3.x document (`schema[0].properties[]`) to the native contract
* mapping. Unknown ODCS fields are ignored. */
function odcsToNative(r: Json): Json {
const api = r['apiVersion'];
if (typeof api === 'string' && !api.startsWith('v3')) {
throw new ContractCompileError(`unsupported ODCS apiVersion ${JSON.stringify(api)}; supported: v3.x`);
}
let version = r['version'];
if (typeof version === 'number') version = String(version);
if (typeof version !== 'string' || !version) {
throw new ContractCompileError("ODCS document is missing the required 'version' field");
}
const schema = r['schema'];
if (!Array.isArray(schema) || schema.length === 0 || !isMap(schema[0])) {
throw new ContractCompileError(
"ODCS document has no 'schema' array; fields are read from schema[].properties[]",
);
}
const s0 = schema[0];
const props = s0['properties'];
if (!Array.isArray(props) || props.length === 0) {
throw new ContractCompileError(
`ODCS schema[0] (${JSON.stringify(s0['name'])}) has no properties; nothing to validate`,
);
}
// Same order as the Rust importer: dataProduct, schema[0].name, root name.
const name =
[r['dataProduct'], s0['name'], r['name']].find(
(v): v is string => typeof v === 'string' && v.trim() !== '',
) ?? 'imported_contract';
const entities = props.filter((p): p is Json => isMap(p) && !!p['name']).map(odcsProp);
const native: Json = { version, name, ontology: { entities } };
const desc = odcsDescription(r['description']) ?? odcsDescription(s0['description']);
if (desc) native['description'] = desc;
return native;
}

export interface ContractData {
version: string;
name: string;
Expand Down Expand Up @@ -254,7 +382,8 @@ export class Contract {
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
throw new ContractCompileError('contract YAML must be a mapping at the top level');
}
const r = raw as Record<string, unknown>;
let r = raw as Record<string, unknown>;
if (isOdcs(r)) r = odcsToNative(r);

const version = r['version'];
const name = r['name'];
Expand All @@ -265,11 +394,12 @@ export class Contract {
throw new ContractCompileError('contract.name is required');
}

const ontologyRaw = r['ontology'];
// `ontology` is optional; a contract may have none.
const ontologyRaw = r['ontology'] ?? {};
if (ontologyRaw === null || typeof ontologyRaw !== 'object' || Array.isArray(ontologyRaw)) {
throw new ContractCompileError('contract.ontology is required and must be a mapping');
throw new ContractCompileError('contract.ontology must be a mapping');
}
const entitiesRaw = (ontologyRaw as Record<string, unknown>)['entities'];
const entitiesRaw = (ontologyRaw as Record<string, unknown>)['entities'] ?? [];
if (!Array.isArray(entitiesRaw)) {
throw new ContractCompileError('contract.ontology.entities must be a list');
}
Expand All @@ -285,7 +415,7 @@ export class Contract {
return new Contract({
version,
name,
description: typeof r['description'] === 'string' ? r['description'] : undefined,
description: odcsDescription(r['description']),
complianceMode: r['compliance_mode'] === true,
entities,
glossary,
Expand Down
90 changes: 90 additions & 0 deletions sdks/typescript/tests/odcs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { Contract } from '../src/contract.js';
import { ContractCompileError } from '../src/errors.js';

const load = (n: string) => readFileSync(fileURLToPath(new URL(`./${n}`, import.meta.url)), 'utf8');

describe('ODCS input', () => {
it('parses a minimal ODCS contract with no ontology and validates events', () => {
const c = Contract.fromYaml(load('odcs_minimal.yaml')).compile();
assert.equal(c.contract.name, 'orders');
assert.equal(c.contract.description, 'Minimal orders contract');
assert.deepEqual(
c.contract.entities.map((e) => e.name),
['order_id', 'amount', 'status'],
);
assert.equal(c.contract.entities[1]!.fieldType, 'float');
assert.ok(c.validate({ order_id: 'a', amount: 2.5, status: 'open' }).passed);
assert.ok(!c.validate({ order_id: 'a', amount: -1, status: 'open' }).passed);
assert.ok(!c.validate({ order_id: 'a', amount: 1, status: 'nope' }).passed);
});

it('parses the official full example (map description, v3.2 enum, primaryKey)', () => {
const c = Contract.fromYaml(load('odcs_full_example.yaml')).compile();
assert.equal(c.contract.description, 'Views built on top of the seller tables.');
const by = Object.fromEntries(c.contract.entities.map((e) => [e.name, e]));
assert.deepEqual(by['rcvr_cntry_code']!.allowedValues, ['US', 'CA', 'MX']);
assert.equal(by['rcvr_id']!.required, true);
assert.ok(c.validate({ rcvr_id: 'x', rcvr_cntry_code: 'US' }).passed);
assert.ok(!c.validate({ rcvr_id: 'x', rcvr_cntry_code: 'ZZ' }).passed);
});

it('reads physicalType when logicalType is absent and ignores unknown fields', () => {
const c = Contract.fromYaml(`
apiVersion: v3.1.0
kind: DataContract
version: 2
name: t
futureKey: {a: 1}
schema:
- name: t
properties:
- name: id
physicalType: BIGINT
primaryKey: true
- name: price
physicalType: DECIMAL(10,2)
- name: attrs
logicalType: map
`).compile();
const types = c.contract.entities.map((e) => e.fieldType);
assert.deepEqual(types, ['integer', 'float', 'object']);
assert.equal(c.contract.version, '2');
});

it('keeps ontology optional for native contracts', () => {
const c = Contract.fromYaml('version: "1.0"\nname: bare\n').compile();
assert.deepEqual(c.contract.entities, []);
});

it('native contracts still need a mapping ontology when one is given', () => {
assert.throws(
() => Contract.fromYaml('version: "1.0"\nname: x\nontology: 5\n'),
/ontology must be a mapping/,
);
});

it('gives clear errors for unsupported ODCS', () => {
assert.throws(
() => Contract.fromYaml('apiVersion: v3.1.0\nkind: DataContract\nname: n\nversion: 1.0.0\n'),
(e: unknown) => e instanceof ContractCompileError && /no 'schema' array/.test(e.message),
);
assert.throws(
() =>
Contract.fromYaml(
'apiVersion: v2.2.2\nkind: DataContract\nname: n\nversion: 1\nschema: []\n',
),
/unsupported ODCS apiVersion/,
);
assert.throws(
() =>
Contract.fromYaml(
'apiVersion: v3.1.0\nname: n\nversion: 1\nschema:\n - name: t\n',
),
/no properties/,
);
});
});
Loading
Loading