@ddex-workbench/sdk
Version:
Official SDK for DDEX Workbench - Open-source DDEX validation and processing tools
750 lines (745 loc) • 20.6 kB
text/typescript
/**
* DDEX Client configuration options
*/
interface DDEXClientConfig {
/** API base URL */
baseURL?: string;
/** API key for authentication */
apiKey?: string;
/** Request timeout in milliseconds */
timeout?: number;
/** Environment (development, staging, production) */
environment?: "development" | "staging" | "production";
/** Maximum number of retry attempts */
maxRetries?: number;
/** Delay between retries in milliseconds */
retryDelay?: number;
/** Custom headers */
headers?: Record<string, string>;
}
/**
* Supported ERN versions
*/
type ERNVersion = "3.8.2" | "4.2" | "4.3";
/**
* Supported ERN profiles
*/
type ERNProfile = "AudioAlbum" | "AudioSingle" | "Video" | "Mixed" | "Classical" | "Ringtone" | "DJ" | "ReleaseByRelease";
/**
* DDEX message types
*/
type DDEXType = "ERN" | "DSR" | "RIN" | "MLC";
/**
* Validation options
*/
interface ValidationOptions {
/** ERN version to validate against */
version: ERNVersion;
/** Optional profile for profile-specific validation */
profile?: ERNProfile;
/** Generate SVRL (Schematron Validation Report Language) report */
generateSVRL?: boolean;
/** Include passed rules in the response */
verbose?: boolean;
/** Custom validation rules to apply */
customRules?: CustomValidationRule[];
}
/**
* Custom validation rule
*/
interface CustomValidationRule {
/** Rule identifier */
id: string;
/** Rule description */
description: string;
/** XPath or JSONPath expression */
path: string;
/** Expected value or pattern */
expected?: string | RegExp;
/** Error message if rule fails */
message: string;
/** Severity level */
severity?: "error" | "warning" | "info";
}
/**
* Validation error detail
*/
interface ValidationErrorDetail {
/** Line number where error occurred */
line: number;
/** Column number where error occurred */
column: number;
/** Error message */
message: string;
/** Error severity */
severity: "error" | "warning" | "info" | "fatal";
/** Validation rule that failed */
rule?: string;
/** Context where error occurred */
context?: string;
/** Suggested fix */
suggestion?: string;
/** XPath to the error location */
xpath?: string;
}
/**
* Validation warning (subset of ValidationErrorDetail)
*/
interface ValidationWarning extends ValidationErrorDetail {
severity: "warning" | "info";
}
/**
* Successfully passed validation rule
*/
interface PassedRule {
/** Rule name/identifier */
name: string;
/** Rule description */
description: string;
/** Rule severity level */
severity: string;
/** Context where rule was applied */
context: string;
/** Number of times rule passed */
occurrences?: number;
}
/**
* Validation step information
*/
interface ValidationStep {
/** Type of validation performed */
type: "XSD" | "BusinessRules" | "Schematron" | "Custom";
/** Duration in milliseconds */
duration: number;
/** Number of errors found */
errorCount: number;
/** Number of warnings found */
warningCount?: number;
/** Step status */
status?: "passed" | "failed" | "skipped";
}
/**
* Validation metadata
*/
interface ValidationMetadata {
/** Processing time in milliseconds */
processingTime: number;
/** Schema version used */
schemaVersion: string;
/** Profile used for validation */
profile?: string;
/** Timestamp of validation */
validatedAt: string;
/** Total error count */
errorCount: number;
/** Total warning count */
warningCount: number;
/** Validation steps performed */
validationSteps: ValidationStep[];
/** File information if applicable */
fileInfo?: {
name: string;
size: number;
hash?: string;
};
/** Validator version */
validatorVersion?: string;
}
/**
* Validation result
*/
interface ValidationResult {
/** Whether the document is valid */
valid: boolean;
/** List of validation errors */
errors: ValidationErrorDetail[];
/** List of validation warnings */
warnings: ValidationWarning[];
/** Validation metadata */
metadata: ValidationMetadata;
/** SVRL (Schematron Validation Report Language) XML report */
svrl?: string;
/** Successfully passed rules (when verbose=true) */
passedRules?: PassedRule[];
/** Summary statistics */
summary?: ValidationSummary;
}
/**
* Validation summary statistics
*/
interface ValidationSummary {
/** Total number of rules checked */
totalRules: number;
/** Number of rules passed */
passedRules: number;
/** Number of rules failed */
failedRules: number;
/** Compliance percentage */
complianceRate: number;
/** Profile compliance status */
profileCompliant?: boolean;
/** Schema compliance status */
schemaCompliant: boolean;
}
/**
* API key information
*/
interface ApiKey {
/** Unique key identifier */
id: string;
/** API key value (only shown once) */
key?: string;
/** Key name/description */
name: string;
/** Creation timestamp */
createdAt: string;
/** Last used timestamp */
lastUsed?: string;
/** Whether key is active */
active: boolean;
/** Usage statistics */
usage?: {
requests: number;
lastRequest?: string;
};
}
/**
* Supported formats response
*/
interface SupportedFormats {
/** Supported DDEX types */
types: DDEXType[];
/** Supported versions by type */
versions: Record<DDEXType, ERNVersion[]>;
/** Supported profiles by version */
profiles: Record<ERNVersion, ERNProfile[]>;
/** Feature support matrix */
features?: Record<string, boolean>;
}
/**
* Health check response
*/
interface HealthStatus {
/** Service status */
status: "healthy" | "degraded" | "unhealthy";
/** Response timestamp */
timestamp: string;
/** Service version */
version: string;
/** Individual service checks */
services?: {
api: boolean;
validation: boolean;
database?: boolean;
};
/** Response time in milliseconds */
responseTime?: number;
}
/**
* Batch validation options
*/
interface BatchValidationOptions {
/** Maximum parallel validations */
concurrency?: number;
/** Stop on first error */
stopOnError?: boolean;
/** Progress callback */
onProgress?: (completed: number, total: number) => void;
}
/**
* Batch validation result
*/
interface BatchValidationResult {
/** Total files processed */
totalFiles: number;
/** Number of valid files */
validFiles: number;
/** Number of invalid files */
invalidFiles: number;
/** Individual file results */
results: Array<{
filename: string;
result: ValidationResult;
}>;
/** Total processing time */
processingTime: number;
}
/**
* SVRL statistics parsed from report
*/
interface SVRLStatistics {
/** Number of successful assertions */
assertions: number;
/** Number of failed assertions */
failures: number;
/** Number of warnings */
warnings: number;
/** Number of fired rules */
firedRules: number;
/** Profile tested */
profile?: string;
/** Schema version */
schemaVersion?: string;
}
/**
* File validation options
*/
interface FileValidationOptions extends ValidationOptions {
/** File encoding */
encoding?: BufferEncoding;
/** Include file hash in metadata */
includeHash?: boolean;
}
/**
* URL validation options
*/
interface URLValidationOptions extends ValidationOptions {
/** Custom headers for fetching URL */
headers?: Record<string, string>;
/** Timeout for fetching URL */
fetchTimeout?: number;
}
/**
* DDEX Validator - High-level validation helper
*
* @example
* ```typescript
* const validator = client.validator;
*
* // Auto-detect version
* const version = validator.detectVersion(xmlContent);
*
* // Validate with SVRL
* const result = await validator.validateWithSVRL(xmlContent, {
* version: '4.3',
* profile: 'AudioAlbum'
* });
* ```
*/
declare class DDEXValidator {
private readonly client;
constructor(client: DDEXClient);
/**
* Validate with automatic version detection
*
* @param content - XML content
* @param profile - Optional profile
* @returns Validation result
*/
validateAuto(content: string, profile?: ERNProfile): Promise<ValidationResult>;
/**
* Validate with SVRL report generation
*
* @param content - XML content
* @param options - Validation options
* @returns Validation result with SVRL
*/
validateWithSVRL(content: string, options: ValidationOptions): Promise<ValidationResult>;
/**
* Validate multiple files in batch
*
* @param items - Array of content and options
* @param batchOptions - Batch processing options
* @returns Batch validation results
*/
validateBatch(items: Array<{
content: string;
options: ValidationOptions;
}>, batchOptions?: BatchValidationOptions): Promise<BatchValidationResult>;
/**
* Check if content is valid (simplified check)
*
* @param content - XML content
* @param options - Validation options
* @returns Boolean indicating validity
*/
isValid(content: string, options: ValidationOptions): Promise<boolean>;
/**
* Get only errors (no warnings)
*
* @param content - XML content
* @param options - Validation options
* @returns Array of errors
*/
getErrors(content: string, options: ValidationOptions): Promise<ValidationErrorDetail[]>;
/**
* Get only critical errors (severity: error or fatal)
*
* @param result - Validation result
* @returns Array of critical errors
*/
getCriticalErrors(result: ValidationResult): ValidationErrorDetail[];
/**
* Get only schematron-specific errors
*
* @param result - Validation result
* @returns Array of schematron errors
*/
getSchematronErrors(result: ValidationResult): ValidationErrorDetail[];
/**
* Get only XSD schema errors
*
* @param result - Validation result
* @returns Array of XSD errors
*/
getXSDErrors(result: ValidationResult): ValidationErrorDetail[];
/**
* Get only business rule errors
*
* @param result - Validation result
* @returns Array of business rule errors
*/
getBusinessRuleErrors(result: ValidationResult): ValidationErrorDetail[];
/**
* Parse SVRL report to extract statistics
*
* @param svrl - SVRL XML string
* @returns SVRL statistics
*/
parseSVRL(svrl: string): SVRLStatistics;
/**
* Get profile compliance report
*
* @param content - XML content
* @param version - ERN version
* @param profile - ERN profile
* @returns Detailed compliance report
*/
getProfileCompliance(content: string, version: ERNVersion, profile: ERNProfile): Promise<{
compliant: boolean;
profile: string;
version: string;
errors: number;
warnings: number;
passedRules: number;
failedRules: number;
complianceRate: number;
svrlAvailable: boolean;
details?: PassedRule[];
}>;
/**
* Generate validation summary
*
* @param result - Validation result
* @returns Validation summary
*/
generateSummary(result: ValidationResult): ValidationSummary;
/**
* Format validation errors for display
*
* @param errors - Array of errors
* @param options - Formatting options
* @returns Formatted error string
*/
formatErrors(errors: ValidationErrorDetail[], options?: {
includeContext?: boolean;
includeSuggestions?: boolean;
groupByRule?: boolean;
maxErrors?: number;
}): string;
/**
* Format a single error
*/
private formatSingleError;
/**
* Group errors by rule
*/
private groupErrorsByRule;
/**
* Detect ERN version from XML content
*
* @param content - XML content
* @returns Detected version or null
*/
detectVersion(content: string): ERNVersion | null;
/**
* Detect profile from XML content
*
* @param content - XML content
* @returns Detected profile or null
*/
detectProfile(content: string): ERNProfile | null;
/**
* Extract metadata from XML content
*
* @param content - XML content
* @returns Extracted metadata
*/
extractMetadata(content: string): {
version?: ERNVersion;
profile?: ERNProfile;
messageId?: string;
createdDate?: string;
releaseCount?: number;
};
}
/**
* DDEX Workbench API Client
*
* @example
* ```typescript
* import { DDEXClient } from '@ddex-workbench/sdk';
*
* const client = new DDEXClient({
* apiKey: 'ddex_your-api-key',
* environment: 'production'
* });
*
* const result = await client.validate(xmlContent, {
* version: '4.3',
* profile: 'AudioAlbum'
* });
* ```
*/
declare class DDEXClient {
private readonly client;
private readonly config;
readonly validator: DDEXValidator;
constructor(config?: Partial<DDEXClientConfig>);
/**
* Validate DDEX XML content
*
* @param content - XML content as string
* @param options - Validation options
* @returns Validation result with errors and metadata
*
* @example
* ```typescript
* const result = await client.validate(xmlContent, {
* version: '4.3',
* profile: 'AudioAlbum',
* generateSVRL: true
* });
* ```
*/
validate(content: string, options: ValidationOptions): Promise<ValidationResult>;
/**
* Validate with SVRL report generation
*
* @param content - XML content as string
* @param options - Validation options
* @returns Validation result with SVRL report
*
* @example
* ```typescript
* const result = await client.validateWithSVRL(xmlContent, {
* version: '4.3',
* profile: 'AudioAlbum'
* });
*
* if (result.svrl) {
* console.log('SVRL report generated');
* }
* ```
*/
validateWithSVRL(content: string, options: ValidationOptions): Promise<ValidationResult>;
/**
* Validate a file
*
* @param filePath - Path to XML file
* @param options - Validation options
* @returns Validation result
*/
validateFile(filePath: string, options: FileValidationOptions): Promise<ValidationResult>;
/**
* Validate XML from URL
*
* @param url - URL to fetch XML from
* @param options - Validation options
* @returns Validation result
*/
validateURL(url: string, options: URLValidationOptions): Promise<ValidationResult>;
/**
* Batch validate multiple XML contents
*
* @param items - Array of XML contents with their options
* @param batchOptions - Batch processing options
* @returns Batch validation results
*/
validateBatch(items: Array<{
content: string;
options: ValidationOptions;
filename?: string;
}>, batchOptions?: BatchValidationOptions): Promise<BatchValidationResult>;
/**
* Get supported formats and versions
*
* @returns Supported formats information
*/
getSupportedFormats(): Promise<SupportedFormats>;
/**
* Check API health status
*
* @returns Health status information
*/
checkHealth(): Promise<HealthStatus>;
/**
* List API keys (requires authentication)
*
* @returns List of API keys
*/
listApiKeys(): Promise<ApiKey[]>;
/**
* Create a new API key (requires authentication)
*
* @param name - Name for the API key
* @returns Created API key
*/
createApiKey(name: string): Promise<ApiKey>;
/**
* Revoke an API key (requires authentication)
*
* @param keyId - ID of the key to revoke
*/
revokeApiKey(keyId: string): Promise<void>;
/**
* Setup axios interceptors for retry logic
*/
private setupInterceptors;
/**
* Execute request with retry logic
*/
private retryableRequest;
/**
* Check if request should be retried
*/
private shouldRetry;
/**
* Delay helper for retry logic
*/
private delay;
/**
* Handle and transform axios errors
*/
private handleError;
/**
* Get current environment
*/
private getEnvironment;
/**
* Update API key
*
* @param apiKey - New API key
*/
setApiKey(apiKey: string): void;
/**
* Remove API key
*/
clearApiKey(): void;
/**
* Get current configuration
*/
getConfig(): Readonly<DDEXClientConfig>;
}
/**
* Base error class for DDEX SDK errors
*/
declare class DDEXError extends Error {
readonly code?: string | undefined;
readonly details?: unknown;
constructor(message: string, code?: string | undefined, details?: unknown);
}
/**
* Rate limit error
*/
declare class RateLimitError extends DDEXError {
readonly retryAfter: number;
constructor(message: string, retryAfter: number);
/**
* Get a formatted retry message
*/
getRetryMessage(): string;
}
/**
* Authentication error
*/
declare class AuthenticationError extends DDEXError {
constructor(message: string);
}
/**
* Validation error
*/
declare class ValidationError extends DDEXError {
readonly validationErrors?: {
field?: string | undefined;
message: string;
code?: string | undefined;
}[] | undefined;
constructor(message: string, validationErrors?: {
field?: string | undefined;
message: string;
code?: string | undefined;
}[] | undefined);
/**
* Get a summary of validation errors
*/
getSummary(): string;
}
/**
* Network error
*/
declare class NetworkError extends DDEXError {
readonly statusCode?: number | undefined;
constructor(message: string, statusCode?: number | undefined);
/**
* Check if error is retryable
*/
isRetryable(): boolean;
}
/**
* Not found error
*/
declare class NotFoundError extends DDEXError {
readonly resource?: string | undefined;
constructor(message: string, resource?: string | undefined);
}
/**
* Configuration error
*/
declare class ConfigurationError extends DDEXError {
readonly field?: string | undefined;
constructor(message: string, field?: string | undefined);
}
/**
* Timeout error
*/
declare class TimeoutError extends DDEXError {
readonly timeout: number;
constructor(message: string, timeout: number);
}
/**
* File error
*/
declare class FileError extends DDEXError {
readonly filePath?: string | undefined;
constructor(message: string, filePath?: string | undefined);
}
/**
* Parse error for XML parsing issues
*/
declare class ParseError extends DDEXError {
readonly line?: number | undefined;
readonly column?: number | undefined;
constructor(message: string, line?: number | undefined, column?: number | undefined);
/**
* Get formatted error location
*/
getLocation(): string;
}
/**
* API error wrapper for server errors
*/
declare class APIError extends DDEXError {
readonly statusCode: number;
readonly response?: unknown;
constructor(message: string, statusCode: number, response?: unknown);
/**
* Check if error is client error (4xx)
*/
isClientError(): boolean;
/**
* Check if error is server error (5xx)
*/
isServerError(): boolean;
}
export { APIError, type ApiKey, AuthenticationError, type BatchValidationOptions, type BatchValidationResult, ConfigurationError, type CustomValidationRule, DDEXClient, type DDEXClientConfig, DDEXError, type DDEXType, DDEXValidator, type ERNProfile, type ERNVersion, FileError, type FileValidationOptions, type HealthStatus, NetworkError, NotFoundError, ParseError, type PassedRule, RateLimitError, type SVRLStatistics, type SupportedFormats, TimeoutError, type URLValidationOptions, ValidationError, type ValidationErrorDetail, type ValidationMetadata, type ValidationOptions, type ValidationResult, type ValidationStep, type ValidationSummary, type ValidationWarning };