JSPM

one-protocol

1.0.3
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 16
  • Score
    100M100P100Q36087F
  • License MIT

Universal Protocol Layer for the Internet - Type-safe, AI-native API standard

Package Exports

  • one-protocol
  • one-protocol/ontology
  • one-protocol/protocols
  • one-protocol/schemas

Readme

one-protocol

The Universal Protocol Layer for the Internet.

ONE Protocol is an open standard for protocol-agnostic application architecture. It defines a universal data model and registry pattern that enables applications to integrate with infinite protocols without code changes.

Installation

npm install one-protocol zod
# or
pnpm add one-protocol zod
# or
bun add one-protocol zod

Note: zod is a peer dependency

Quick Start

import {
  createRegistry,
  ProtocolError,
  ErrorCodes,
} from "one-protocol";
import { z } from "zod";

// Create a registry
const registry = createRegistry();

// Register a protocol
registry.register({
  name: "payment_process",
  version: "1.0",
  category: "payment",
  description: "Process a payment",
  schema: {
    input: z.object({
      amount: z.number().positive(),
      currency: z.string().length(3),
      recipient: z.string(),
    }),
    output: z.object({
      transactionId: z.string(),
      status: z.enum(["pending", "completed", "failed"]),
    }),
  },
  handler: async (data, ctx) => {
    // Your payment logic here
    return {
      transactionId: `tx_${Date.now()}`,
      status: "completed",
    };
  },
});

// Execute a request
const result = await registry.execute(
  {
    protocol: "payment_process",
    data: {
      amount: 100,
      currency: "USD",
      recipient: "alice@example.com",
    },
  },
  { userId: "user_123" } // context
);

console.log(result);
// { success: true, data: { transactionId: 'tx_...', status: 'completed' }, ... }

Core Concepts

Protocol Registry

The registry is the central hub for all protocols. It handles:

  • Registration: Define protocols with schemas and handlers
  • Discovery: List and introspect available protocols
  • Execution: Execute requests with validation and error handling
  • Middleware: Add cross-cutting concerns
const registry = createRegistry({
  validateOutput: true, // Validate handler outputs (recommended for development)
  onError: (error) => console.error(error),
  generateRequestId: () => crypto.randomUUID(),
});

Protocol Definition

A protocol is defined by:

interface ProtocolDefinition {
  name: string; // Unique identifier (e.g., 'payment_process')
  version: string; // Semantic version (e.g., '1.0')
  category: string; // Category for organization
  description: string; // Human-readable description
  schema: {
    input: ZodSchema; // Input validation schema
    output: ZodSchema; // Output validation schema
  };
  handler: Handler; // Implementation function
  capabilities?: string[]; // Optional feature flags
  metadata?: object; // Optional additional data
}

Error Handling

ONE Protocol provides structured errors:

import { ProtocolError, ErrorCodes, Errors } from "one-protocol";

// Create specific errors
throw Errors.protocolNotFound("unknown_protocol");
throw Errors.validationFailed("Invalid amount", { field: "amount" });

// Check error types
if (error instanceof ProtocolError) {
  console.log(error.code); // 'PROTOCOL_NOT_FOUND'
  console.log(error.message); // 'Protocol not found: unknown_protocol'
  console.log(error.details); // Additional error details
}

// Use error codes
if (error.code === ErrorCodes.VALIDATION_FAILED) {
  // Handle validation error
}

Middleware

Add middleware for cross-cutting concerns:

// Logging middleware
registry.use(async (request, context, next) => {
  console.log(`Executing: ${request.protocol}`);
  const start = Date.now();
  const result = await next(request, context);
  console.log(`Completed in ${Date.now() - start}ms`);
  return result;
});

// Authentication middleware
registry.use(async (request, context, next) => {
  if (!context.user) {
    throw Errors.unauthorized("User not authenticated");
  }
  return next(request, context);
});

The 6 Ontology Dimensions

ONE Protocol defines 6 dimensions that model all digital interactions:

1. Things

Entities in the system (people, products, content, etc.):

import {
  DefaultThingTypes,
  ThingTypeSchema,
  BaseThingSchema,
} from "one-protocol";

// 66 default types including:
// - 'creator', 'ai_clone', 'agent'
// - 'blog_post', 'video', 'course'
// - 'product', 'order', 'invoice'
// - 'wallet', 'smart_contract', 'transaction'

const thing = BaseThingSchema.parse({
  id: "550e8400-e29b-41d4-a716-446655440000",
  type: "product",
  name: "Premium Course",
  createdAt: new Date().toISOString(),
  updatedAt: new Date().toISOString(),
});

2. Connections

Relationships between things:

import {
  DefaultConnectionTypes,
  ConnectionTypeSchema,
} from "one-protocol";

// 25 default types including:
// - 'owns', 'created_by'
// - 'member_of', 'following'
// - 'purchased', 'enrolled_in'
// - 'holds_tokens', 'staked_in'

3. Events

Audit log of actions:

import { DefaultEventTypes, EventTypeSchema } from "one-protocol";

// 52 default types including:
// - 'thing_created', 'thing_updated'
// - 'user_registered', 'user_login'
// - 'payment_event', 'subscription_event'
// - 'token_minted', 'nft_transferred'

4. Groups

Organizational structures:

import { GroupTypes, GroupSchema } from "one-protocol";

// Types: 'friend_circle', 'business', 'community', 'dao', 'government', 'organization'

const group = GroupSchema.parse({
  id: "...",
  type: "business",
  name: "Acme Corp",
  ownerId: "user_123",
  createdAt: new Date().toISOString(),
  updatedAt: new Date().toISOString(),
});

5. People

Users with roles:

import { RoleTypes, PersonSchema } from "one-protocol";

// Roles: 'platform_owner', 'group_owner', 'group_user', 'customer'

const person = PersonSchema.parse({
  id: "...",
  role: "customer",
  email: "alice@example.com",
  name: "Alice",
  createdAt: new Date().toISOString(),
  updatedAt: new Date().toISOString(),
});

6. Knowledge

RAG and AI knowledge entries:

import { KnowledgeTypes, KnowledgeSchema } from "one-protocol";

// Types: 'label', 'document', 'chunk', 'vector_only'

const knowledge = KnowledgeSchema.parse({
  id: "...",
  knowledgeType: "document",
  groupId: "group_123",
  content: "Full document content...",
  createdAt: new Date().toISOString(),
  updatedAt: new Date().toISOString(),
});

Type Extensibility

All types are extensible. Use the utilities to add your own:

import {
  extendTypes,
  createTypeSchema,
  DefaultThingTypes,
} from "one-protocol";

// Add custom types
const MyThingTypes = extendTypes(DefaultThingTypes, [
  "custom_entity",
  "my_product",
] as const);

// Create a schema that validates custom types
const MyThingTypeSchema = createTypeSchema(MyThingTypes);

type MyThingType = (typeof MyThingTypes)[number];

Protocol Validation

Validate protocol definitions and data:

import { validateProtocolMetadata, validateData } from "one-protocol";

// Validate a protocol definition
const result = validateProtocolMetadata({
  name: "my_protocol",
  version: "1.0",
  category: "custom",
  description: "My custom protocol",
  schema: {
    required: ["name", "value"],
    optional: ["metadata"],
    types: {
      name: "string",
      value: "number",
      metadata: "object",
    },
  },
});

if (!result.valid) {
  console.error("Validation errors:", result.errors);
}

// Warnings for best practices
if (result.warnings.length > 0) {
  console.warn("Warnings:", result.warnings);
}

Common Schemas

Pre-built schemas for common patterns:

import {
  AddressSchema, // Blockchain address
  TxHashSchema, // Transaction hash
  PaymentChainSchema, // Supported payment chains
  TimestampSchema, // ISO datetime
  UuidSchema, // UUID v4
  AmountSchema, // Positive decimal string
  EmailSchema, // Email address
  UrlSchema, // URL
  createEntitySchema, // Entity with id, timestamps
} from "one-protocol";

// Create entity schemas easily
const ProductSchema = createEntitySchema({
  name: z.string(),
  price: AmountSchema,
  category: z.string(),
});

Universal Request/Response

All protocols use the same request/response format:

// Request
{
  protocol: 'payment_process',  // Required: protocol name
  data: { ... },                // Required: protocol-specific data
  version: '1.0',               // Optional: specific version
  requestId: 'req_...',         // Optional: request tracking
  metadata: { ... },            // Optional: additional metadata
}

// Response
{
  success: true,
  protocol: 'payment_process',
  version: '1.0',
  requestId: 'req_...',
  data: { ... },                // Handler result
  executionTime: 42,            // Milliseconds
  metadata: { ... },
}

Bundle Size

  • ESM: ~4KB gzipped
  • CommonJS: ~5KB gzipped
  • Zero runtime dependencies (zod is peer)

Environments

Works in all JavaScript environments:

  • Node.js 18+
  • Bun
  • Deno
  • Browser (modern)
  • Cloudflare Workers
  • Vercel Edge
  • AWS Lambda

License

MIT