From 52adde0cb04df7819c4ff24f1676eade59e6c0b7 Mon Sep 17 00:00:00 2001 From: ContractGate Lead Date: Thu, 26 Nov 2026 10:54:49 -0500 Subject: [PATCH] feat(sdk-ts): accept ODCS v3.x contracts and make ontology optional Mirrors the Python SDK and the gateway. Tests with the official full example and a minimal contract. No version bump or publish; changelog notes the 0.4.2 bump needed. --- sdks/typescript/CHANGELOG.md | 13 + sdks/typescript/README.md | 2 + sdks/typescript/src/contract.ts | 140 ++++++- sdks/typescript/tests/odcs.test.ts | 90 +++++ sdks/typescript/tests/odcs_full_example.yaml | 362 +++++++++++++++++++ sdks/typescript/tests/odcs_minimal.yaml | 24 ++ 6 files changed, 626 insertions(+), 5 deletions(-) create mode 100644 sdks/typescript/tests/odcs.test.ts create mode 100644 sdks/typescript/tests/odcs_full_example.yaml create mode 100644 sdks/typescript/tests/odcs_minimal.yaml diff --git a/sdks/typescript/CHANGELOG.md b/sdks/typescript/CHANGELOG.md index b81c4eab..5abaed2e 100644 --- a/sdks/typescript/CHANGELOG.md +++ b/sdks/typescript/CHANGELOG.md @@ -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. diff --git a/sdks/typescript/README.md b/sdks/typescript/README.md index 6933f712..d3256e2e 100644 --- a/sdks/typescript/README.md +++ b/sdks/typescript/README.md @@ -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 diff --git a/sdks/typescript/src/contract.ts b/sdks/typescript/src/contract.ts index c3843680..53a6f769 100644 --- a/sdks/typescript/src/contract.ts +++ b/sdks/typescript/src/contract.ts @@ -224,6 +224,134 @@ function parseGlossaryEntry(raw: unknown): GlossaryEntry { // Contract + CompiledContract // --------------------------------------------------------------------------- +// --------------------------------------------------------------------------- +// ODCS v3.x input +// --------------------------------------------------------------------------- + +type Json = Record; + +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 = { + 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 = { + 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; @@ -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; + let r = raw as Record; + if (isOdcs(r)) r = odcsToNative(r); const version = r['version']; const name = r['name']; @@ -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)['entities']; + const entitiesRaw = (ontologyRaw as Record)['entities'] ?? []; if (!Array.isArray(entitiesRaw)) { throw new ContractCompileError('contract.ontology.entities must be a list'); } @@ -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, diff --git a/sdks/typescript/tests/odcs.test.ts b/sdks/typescript/tests/odcs.test.ts new file mode 100644 index 00000000..fe073d86 --- /dev/null +++ b/sdks/typescript/tests/odcs.test.ts @@ -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/, + ); + }); +}); diff --git a/sdks/typescript/tests/odcs_full_example.yaml b/sdks/typescript/tests/odcs_full_example.yaml new file mode 100644 index 00000000..f1c072bd --- /dev/null +++ b/sdks/typescript/tests/odcs_full_example.yaml @@ -0,0 +1,362 @@ +# Copyright 2026 The Bitol Contributors +# SPDX-License-Identifier: Apache-2.0 + +# What's this data contract about? +domain: seller # Domain +dataProduct: my quantum # Data product name +version: 1.1.0 # Version (follows semantic versioning) +status: active +id: 53581432-6c55-4ba2-a65f-72344a91553a + +authoritativeDefinitions: +- type: canonical + url: https://github.com/bitol-io/open-data-contract-standard/blob/main/docs/examples/all/full-example.odcs.yaml + description: Canonical URL to the latest version of the contract. + +# Lots of information +description: + purpose: Views built on top of the seller tables. + limitations: Data based on seller perspective, no buyer information + usage: Predict sales over time + authoritativeDefinitions: + - type: privacy-statement + url: https://example.com/gdpr.pdf +tenant: ClimateQuantumInc + +kind: DataContract +apiVersion: v3.2.0 # Standard version (follows semantic versioning) + +# Infrastructure & servers +servers: + - server: my-postgres + type: postgres + host: localhost + port: 5432 + database: pypl-edw + schema: pp_access_views + +# Dataset, schema, and quality +schema: + - id: tbl_obj + name: tbl + physicalName: tbl_1 + physicalType: table + businessName: Core Payment Metrics + description: Provides core payment metrics + authoritativeDefinitions: + - url: https://catalog.data.gov/dataset/air-quality + type: businessDefinition + - url: https://youtu.be/jbY1BKFj9ec + type: videoTutorial + tags: [ 'finance', 'payments'] + dataGranularityDescription: Aggregation on columns txn_ref_dt, pmt_txn_id + # Schema-level relationships (for composite keys) + relationships: + - type: foreignKey + from: + - tbl.rcvr_id + - tbl.rcvr_cntry_code + to: + - receivers.id + - receivers.country_code + customProperties: + - property: description + value: "Composite key linking to receivers table" + - property: cardinality + value: "many-to-one" + properties: + - id: txn_ref_dt_prop + name: transaction_reference_date + physicalName: txn_ref_dt + primaryKey: false + primaryKeyPosition: -1 + businessName: transaction reference date + logicalType: date + physicalType: date + required: false + description: Reference date for transaction + partitioned: true + partitionKeyPosition: 1 + criticalDataElement: false + tags: [ ] + classification: public + transformSourceObjects: + - table_name_1 + - table_name_2 + - table_name_3 + transformLogic: sel t1.txn_dt as txn_ref_dt from table_name_1 as t1, table_name_2 as t2, table_name_3 as t3 where t1.txn_dt=date-3 + transformDescription: defines the logic in business terms; logic for dummies + examples: + - "2022-10-03" + - "2020-01-28" + customProperties: + - property: anonymizationStrategy + value: none + - id: rcvr_id_prop + name: rcvr_id + primaryKey: true + primaryKeyPosition: 1 + businessName: receiver id + logicalType: string + physicalType: varchar(18) + required: false + description: A description for column rcvr_id. + partitioned: false + partitionKeyPosition: -1 + criticalDataElement: false + tags: [ 'uid' ] + classification: restricted + # Property-level relationship (from is implicit) + relationships: + - to: receivers.id + type: foreignKey + customProperties: + - property: description + value: "Links to receiver master data" + - id: rcvr_cntry_code_prop + name: rcvr_cntry_code + primaryKey: false + primaryKeyPosition: -1 + businessName: receiver country code + logicalType: string + physicalType: varchar(2) + required: false + description: Country code + partitioned: false + partitionKeyPosition: -1 + criticalDataElement: false + tags: [ ] + classification: public + # Enumeration of allowed values (RFC 0033, ODCS v3.2.0+) + enum: + - value: US + label: United States + description: ISO 3166-1 alpha-2 code for the United States. + - value: CA + label: Canada + - value: MX + label: Mexico + customProperties: + - property: languageEs + value: México + authoritativeDefinitions: + - url: https://collibra.com/asset/742b358f-71a5-4ab1-bda4-dcdba9418c25 + type: businessDefinition + - url: https://github.com/myorg/myrepo + type: transformationImplementation + - url: jdbc:postgresql://localhost:5432/adventureworks/tbl_1/rcvr_cntry_code + type: implementation + encryptedName: rcvr_cntry_code_encrypted + quality: + - metric: nullValues + mustBe: 0 + description: column should not contain null values + dimension: completeness + type: library + severity: error + businessImpact: operational + schedule: 0 20 * * * + scheduler: cron + customProperties: + - property: FIELD_NAME + value: + - property: COMPARE_TO + value: + - property: COMPARISON_TYPE + value: Greater than + quality: + - metric: rowCount + mustBeGreaterThan: 1000000 + type: library + description: Ensure row count is within expected volume range + dimension: completeness + method: reconciliation + severity: error + businessImpact: operational + schedule: 0 20 * * * + scheduler: cron + customProperties: + - property: business-key + value: + - txn_ref_dt + - rcvr_id + + # Receivers master table + - id: receivers_obj + name: receivers + physicalName: receivers_master + physicalType: table + businessName: Receivers Master Data + description: Master data for all receivers + tags: [ 'master-data', 'receivers' ] + properties: + - id: receiver_id_prop + name: id + primaryKey: true + primaryKeyPosition: 1 + businessName: receiver identifier + logicalType: string + physicalType: varchar(18) + required: true + description: Unique identifier for receiver + unique: true + classification: restricted + - id: country_code_prop + name: country_code + primaryKey: true + primaryKeyPosition: 2 + businessName: receiver country + logicalType: string + physicalType: varchar(2) + required: true + description: Country code of the receiver + classification: public + - id: receiver_name_prop + name: receiver_name + businessName: receiver name + logicalType: string + physicalType: varchar(255) + required: true + description: Name of the receiver + classification: restricted + - id: receiver_type_prop + name: receiver_type + businessName: receiver type + logicalType: string + physicalType: varchar(20) + required: false + description: Type of receiver (individual, business, etc.) + classification: public + # Example of nested reference + relationships: + - to: receiver_types.type_code + customProperties: + - property: description + value: "Links to receiver type definitions" + # Map-typed property (RFC 0030, ODCS v3.2.0+) + - id: receiver_attributes_prop + name: receiver_attributes + businessName: receiver attributes + logicalType: map + physicalType: "MAP" + required: false + description: Free-form attributes attached to a receiver, keyed by attribute name. + classification: restricted + map: + key: + logicalType: string + description: Attribute name. + value: + logicalType: string + description: Attribute value. + + +# Pricing +price: + priceAmount: 9.95 + priceCurrency: USD + priceUnit: megabyte + + +# Team +team: + name: my-team + description: The team owning the data contract + members: + - username: ceastwood + role: Data Scientist + dateIn: "2022-08-02" + dateOut: "2022-10-01" + replacedByUsername: mhopper + - username: mhopper + role: Data Scientist + dateIn: "2022-10-01" + - username: daustin + role: Owner + description: Keeper of the grail + dateIn: "2022-10-01" + + +# Roles +roles: + - role: microstrategy_user_opr + access: read + firstLevelApprovers: Reporting Manager + secondLevelApprovers: 'mandolorian' + - role: bq_queryman_user_opr + access: read + firstLevelApprovers: Reporting Manager + secondLevelApprovers: na + - role: risk_data_access_opr + access: read + firstLevelApprovers: Reporting Manager + secondLevelApprovers: 'dathvador' + - role: bq_unica_user_opr + access: write + firstLevelApprovers: Reporting Manager + secondLevelApprovers: 'mickey' + +# SLA +slaProperties: + - property: latency # Property, see list of values in DP QoS + value: 4 + unit: d # d, day, days for days; y, yr, years for years + element: tab1.txn_ref_dt # This would not be needed as it is the same table.column as the default one + - property: generalAvailability + value: "2022-05-12T09:30:10-08:00" + - property: endOfSupport + value: "2032-05-12T09:30:10-08:00" + - property: endOfLife + value: "2042-05-12T09:30:10-08:00" + - property: retention + value: 3 + unit: y + element: tab1.txn_ref_dt + - property: frequency + value: 1 + valueExt: 1 + unit: d + element: tab1.txn_ref_dt + - property: timeOfAvailability + value: 09:00-08:00 + element: tab1.txn_ref_dt + driver: regulatory # Describes the importance of the SLA: [regulatory|analytics|operational|...] + - property: timeOfAvailability + value: 08:00-08:00 + element: tab1.txn_ref_dt + driver: analytics + + +# Support +support: + - channel: '#product-help' # Simple Slack communication channel + tool: slack + - channel: datacontract-ann # Simple distribution list + tool: email + url: mailto:datacontract-ann@bitol.io + - channel: Feedback # Product Feedback + description: General Product Feedback (Public) + url: https://product-feedback.com + - channel: 'product-issues' + tool: teams + scope: issues + customProperties: + - property: servicehours + value: 9-5 CET + + +# Tags +tags: + - transactions + + +# Custom properties +customProperties: + - property: refRulesetName + value: gcsc.ruleset.name + - property: somePropertyName + value: property.value + - property: dataprocClusterName # Used for specific applications like Elevate + value: [ cluster name ] + +contractCreatedTs: "2022-11-15T02:59:43+00:00" diff --git a/sdks/typescript/tests/odcs_minimal.yaml b/sdks/typescript/tests/odcs_minimal.yaml new file mode 100644 index 00000000..87ce5996 --- /dev/null +++ b/sdks/typescript/tests/odcs_minimal.yaml @@ -0,0 +1,24 @@ +apiVersion: v3.2.0 +kind: DataContract +id: 11111111-2222-3333-4444-555555555555 +name: orders +version: 1.0.0 +status: active +description: + purpose: Minimal orders contract +schema: + - name: orders + physicalType: table + properties: + - name: order_id + logicalType: string + required: true + unique: true + - name: amount + logicalType: number + required: true + logicalTypeOptions: + minimum: 0 + - name: status + logicalType: string + enum: [open, closed]