or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

browser.mdfiles.mdindex.mdschemas.mdservices.mdstreams.mdtypes.md
tile.json

types.mddocs/

Type System

Core serialization engine with support for all Avro primitive and complex types, providing schema parsing, type creation, and data serialization/deserialization with full Avro specification compliance.

Capabilities

Main Parse Function

Parse a schema or protocol and return the corresponding type or service.

/**
 * Parse a schema and return the corresponding type or service
 * @param schema - Avro schema object, JSON string, or IDL string
 * @param opts - Parsing options
 * @returns Type or Service instance
 */
function parse(schema, opts);

Usage Examples:

const avsc = require('avsc');

// Parse a simple schema
const stringType = avsc.parse('string');

// Parse a record schema
const userType = avsc.parse({
  type: 'record',
  name: 'User',
  fields: [
    {name: 'name', type: 'string'},
    {name: 'age', type: 'int'},
    {name: 'email', type: ['null', 'string'], default: null}
  ]
});

// Parse with options
const type = avsc.parse(schema, {
  wrapUnions: true,
  namespace: 'com.example'
});

Type Class

Abstract base class for all Avro types providing serialization, validation, and schema operations.

class Type {
  /**
   * Create type from schema
   * @param schema - Avro schema
   * @param opts - Type creation options
   * @returns Type instance
   */
  static forSchema(schema, opts);
  
  /**
   * Create union type from multiple types
   * @param types - Array of types or schemas
   * @param opts - Type creation options
   * @returns Union type instance
   */
  static forTypes(types, opts);
  
  /**
   * Infer type from JavaScript value
   * @param value - JavaScript value to analyze
   * @param opts - Inference options
   * @returns Inferred type
   */
  static forValue(value, opts);
  
  /**
   * Check if object is a Type instance
   * @param obj - Object to check
   * @param prefixes - Optional type name prefixes to match
   * @returns Boolean indicating if object is a Type
   */
  static isType(obj, ...prefixes);
  
  /**
   * Serialize value to buffer
   * @param value - JavaScript value to serialize
   * @returns Buffer containing serialized data
   */
  toBuffer(value);
  
  /**
   * Deserialize value from buffer
   * @param buffer - Buffer containing serialized data
   * @param resolver - Optional schema resolver for evolution
   * @param noCheck - Skip validation if true
   * @returns Deserialized JavaScript value
   */
  fromBuffer(buffer, resolver, noCheck);
  
  /**
   * Parse value from string representation
   * @param str - String representation of value
   * @returns Parsed JavaScript value
   */
  fromString(str);
  
  /**
   * Validate value against schema
   * @param value - Value to validate
   * @param opts - Validation options
   * @returns Boolean indicating validity
   */
  isValid(value, opts);
  
  /**
   * Clone value with optional transformations
   * @param value - Value to clone
   * @param opts - Clone options
   * @returns Cloned value
   */
  clone(value, opts);
  
  /**
   * Compare two values according to Avro specification
   * @param val1 - First value
   * @param val2 - Second value
   * @returns -1, 0, or 1 for less than, equal, or greater than
   */
  compare(val1, val2);
  
  /**
   * Compare two buffers containing serialized data
   * @param buf1 - First buffer
   * @param buf2 - Second buffer
   * @returns -1, 0, or 1 for comparison result
   */
  compareBuffers(buf1, buf2);
  
  /**
   * Create resolver for schema evolution
   * @param type - Target type for evolution
   * @param opts - Resolver options
   * @returns Schema resolver
   */
  createResolver(type, opts);
  
  /**
   * Check equality with another type
   * @param type - Type to compare with
   * @returns Boolean indicating equality
   */
  equals(type);
  
  /**
   * Get type fingerprint
   * @param algorithm - Hash algorithm (default: 'sha256')
   * @returns Buffer containing fingerprint
   */
  fingerprint(algorithm);
  
  /**
   * Get schema object representation
   * @param opts - Schema options
   * @returns Schema object
   */
  schema(opts);
  
  /**
   * Convert value to string representation
   * @param value - Value to convert
   * @returns String representation
   */
  toString(value);
  
  /**
   * Wrap value for union types
   * @param value - Value to wrap
   * @returns Wrapped value object
   */
  wrap(value);
  
  /**
   * Generate random value conforming to schema
   * @returns Random value
   */
  random();
  
  /**
   * Get string representation of type
   * @returns String representation
   */
  inspect();
  
  /**
   * Encode value to buffer at specific position
   * @param val - Value to encode
   * @param buf - Target buffer
   * @param pos - Position in buffer
   * @returns Updated position
   */
  encode(val, buf, pos);
  
  /**
   * Decode value from buffer at specific position
   * @param buf - Source buffer
   * @param pos - Position in buffer
   * @param resolver - Optional schema resolver
   * @returns Object with value and updated position
   */
  decode(buf, pos, resolver);
  
  /**
   * Get JSON representation of type
   * @returns JSON schema representation
   */
  toJSON();
}

Usage Examples:

// Create type from schema
const type = avsc.Type.forSchema({
  type: 'record',
  name: 'Person',
  fields: [
    {name: 'name', type: 'string'},
    {name: 'age', type: 'int'}
  ]
});

// Serialize and deserialize
const person = {name: 'Alice', age: 30};
const buffer = type.toBuffer(person);
const decoded = type.fromBuffer(buffer);

// Validation
const isValid = type.isValid({name: 'Bob', age: 25}); // true
const isInvalid = type.isValid({name: 123, age: 'young'}); // false

// Type inference
const inferredType = avsc.Type.forValue({
  id: 123,
  name: 'test',
  active: true
});

// Schema evolution
const writerType = avsc.Type.forSchema(writerSchema);
const readerType = avsc.Type.forSchema(readerSchema);
const resolver = readerType.createResolver(writerType);
const evolved = readerType.fromBuffer(buffer, resolver);

Type Properties

interface Type {
  /** Type aliases from schema */
  aliases: string[];
  
  /** Documentation string from schema */
  doc: string;
  
  /** Type name if named type */
  name: string;
  
  /** Union branch name for union types */
  branchName: string;
  
  /** String representation of type name */
  typeName: string;
}

Built-in Types

Access to all built-in Avro type constructors available through the types namespace.

namespace types {
  // Primitive types
  class NullType extends Type {
    /** Always returns null */
    random(): null;
  }
  
  class BooleanType extends Type {
    /** Returns random boolean */
    random(): boolean;
  }
  
  class IntType extends Type {
    /** Returns random 32-bit integer */
    random(): number;
  }
  
  class LongType extends Type {
    /** Returns random 64-bit integer (as number or Long object) */
    random(): number | Long;
    
    /** Create custom long type with specific methods */
    static __with(methods: LongMethods, noUnpack?: boolean): typeof LongType;
  }
  
  class FloatType extends Type {
    /** Returns random 32-bit float */
    random(): number;
  }
  
  class DoubleType extends Type {
    /** Returns random 64-bit double */
    random(): number;
  }
  
  class BytesType extends Type {
    /** Returns random Buffer */
    random(): Buffer;
  }
  
  class StringType extends Type {
    /** Returns random string */
    random(): string;
  }
  
  // Complex types
  class RecordType extends Type {
    /** Record fields */
    readonly fields: Field[];
    
    /** Record constructor function */
    readonly recordConstructor: Function;
    
    /** Get field by name */
    field(name: string): Field | undefined;
    
    /** Returns random record object */
    random(): object;
  }
  
  class EnumType extends Type {
    /** Enum symbols */
    readonly symbols: string[];
    
    /** Returns random enum symbol */
    random(): string;
  }
  
  class ArrayType extends Type {
    /** Type of array items */
    readonly itemsType: Type;
    
    /** Returns random array */
    random(): any[];
  }
  
  class MapType extends Type {
    /** Type of map values */
    readonly valuesType: Type;
    
    /** Returns random map object */
    random(): {[key: string]: any};
  }
  
  class FixedType extends Type {
    /** Fixed byte length */
    readonly size: number;
    
    /** Returns random Buffer of fixed size */
    random(): Buffer;
  }
  
  class UnionType extends Type {
    /** Union branch types */
    readonly types: Type[];
    
    /** Returns random union value */
    random(): any;
  }
  
  // Union variants
  class UnwrappedUnionType extends UnionType {
    /** Returns unwrapped union value */
    random(): any;
  }
  
  class WrappedUnionType extends UnionType {
    /** Returns wrapped union value */
    random(): {[branchName: string]: any};
  }
  
  // Special types
  class LogicalType extends Type {
    /** Underlying concrete type */
    readonly underlyingType: Type;
    
    /** Convert from logical to underlying value */
    abstract _fromValue(val: any): any;
    
    /** Convert from underlying to logical value */  
    abstract _toValue(val: any): any;
    
    /** Create resolver for logical type */
    abstract _resolve(type: Type): Function;
    
    /** Export logical type schema */
    abstract _export(attrs: any): any;
  }
}

Field Class

Represents a field in a record type.

class Field {
  /** Field name */
  readonly name: string;
  
  /** Field type */
  readonly type: Type;
  
  /** Field aliases */
  readonly aliases: string[];
  
  /** Field documentation */
  readonly doc?: string;
  
  /** Field sort order */
  readonly order?: 'ascending' | 'descending' | 'ignore';
  
  /**
   * Get field default value
   * @returns Default value or undefined if no default
   */
  defaultValue(): any;
}

Types

interface ForSchemaOptions {
  /** Throw error on unknown logical types */
  assertLogicalTypes?: boolean;
  
  /** Custom logical type implementations */
  logicalTypes?: {[type: string]: LogicalTypeConstructor};
  
  /** Default namespace for named types */
  namespace?: string;
  
  /** Disallow anonymous types */
  noAnonymousTypes?: boolean;
  
  /** Omit convenience methods on records */
  omitRecordMethods?: boolean;
  
  /** Type registry for named type resolution */
  registry?: {[name: string]: Type};
  
  /** Hook for custom type creation */
  typeHook?: (schema: any, opts: ForSchemaOptions) => Type | undefined;
  
  /** Union wrapping mode */
  wrapUnions?: boolean | 'auto' | 'always' | 'never';
}

interface CloneOptions {
  /** Coerce buffers to specific type */
  coerceBuffers?: boolean;
  
  /** Hook for field-level transformations */
  fieldHook?: (field: any, value: any, type: Type) => any;
  
  /** Add namespace qualifiers to names */
  qualifyNames?: boolean;
  
  /** Skip fields missing in target schema */
  skipMissingFields?: boolean;
  
  /** Wrap union values */
  wrapUnions?: boolean;
}

interface IsValidOptions {
  /** Disallow undeclared fields in records */
  noUndeclaredFields?: boolean;
  
  /** Hook for validation errors */
  errorHook?: (path: string[], val: any, type: Type) => void;
}

interface SchemaOptions {
  /** Export schema attributes */
  exportAttrs?: boolean;
  
  /** Do not dereference named types */
  noDeref?: boolean;
}

interface LogicalTypeConstructor {
  new (schema: any, opts?: any): LogicalType;
}

interface LongMethods {
  /** Convert to number */
  toNumber?: () => number;
  
  /** Convert to string */
  toString?: () => string;
  
  /** Add operation */
  add?: (other: any) => any;
  
  /** Subtract operation */
  subtract?: (other: any) => any;
  
  /** Compare operation */
  compare?: (other: any) => number;
  
  /** Equal operation */
  equals?: (other: any) => boolean;
}

interface ResolverOptions {
  /** Skip validation during resolution */
  noCheck?: boolean;
  
  /** Coerce types during resolution */
  coerceTypes?: boolean;
}

interface Long {
  /** High 32 bits */
  high: number;
  
  /** Low 32 bits */
  low: number;
  
  /** Whether number is unsigned */
  unsigned: boolean;
  
  /** Convert to number */
  toNumber(): number;
  
  /** Convert to string */
  toString(): string;
}