UNPKG

mcard-js

Version:

MCard - Content-addressable storage with cryptographic hashing, handle resolution, and vector search for Node.js and browsers

783 lines (761 loc) 22.3 kB
import { S as StorageEngine, M as MCard, P as Page } from './StorageAdapter-Dw1BeOam.js'; export { SqliteWasmEngine } from './storage/SqliteWasmEngine.js'; import { Faro } from '@grafana/faro-web-sdk'; declare class GTime { private static readonly DEFAULT_ALGORITHM; /** * Generate a GTime stamp for the current moment * Format: HASH_ALGO|TIMESTAMP|REGION_CODE */ static stampNow(hashAlgorithm?: string): string; /** * Parse a GTime string */ static parse(gtime: string): { timestamp: Date; algorithm: string; region: string; }; /** * Get the hash algorithm from a GTime string */ static getHashAlgorithm(gtime: string): string; /** * Get the timestamp from a GTime string */ static getTimestamp(gtime: string): Date; /** * Get the region code from a GTime string */ static getRegionCode(gtime: string): string; /** * Check if the provided hash function is valid. * Matches Python's GTime.is_valid_hash_function() */ static isValidHashFunction(hashFunction: string): boolean; /** * Check if the provided region code is valid. * Matches Python's GTime.is_valid_region_code() */ static isValidRegionCode(regionCode: string): boolean; /** * Check if the provided timestamp is in ISO format. * Matches Python's GTime.is_iso_format() */ static isIsoFormat(timestamp: string): boolean; } /** * ContentHandle - UTF-8 aware handle validation and management * * Supports international characters (文檔, مستند, ドキュメント, документ) * Uses Unicode categories for validation */ declare class HandleValidationError extends Error { constructor(message: string); } /** * Validate and normalize a handle string * @returns Normalized handle (NFC + lowercase) * @throws HandleValidationError if invalid */ declare function validateHandle(handle: string): string; /** * ContentHandle - Mutable pointer to immutable MCard hash */ declare class ContentHandle { readonly handle: string; currentHash: string; readonly createdAt: Date; updatedAt: Date; constructor(handle: string, currentHash: string, createdAt?: Date, updatedAt?: Date); /** * Update handle to point to new hash * @returns Previous hash for history tracking */ update(newHash: string): string; toObject(): { handle: string; currentHash: string; createdAt: string; updatedAt: string; }; } /** * Maybe Monad - Represents optional values * * Enables functional composition with .bind() chaining * Just(value) = has value, Nothing = no value */ declare class Maybe<T> { private readonly _value; private readonly _isNothing; private constructor(); /** * Create a Just (has value) */ static just<T>(value: T): Maybe<T>; /** * Create a Nothing (no value) */ static nothing<T>(): Maybe<T>; /** * Check if this is Nothing */ get isNothing(): boolean; /** * Check if this is Just */ get isJust(): boolean; /** * Get the value (throws if Nothing) */ get value(): T; /** * Monadic bind - chain operations * Short-circuits on Nothing */ bind<U>(fn: (value: T) => Maybe<U>): Maybe<U>; /** * Map a function over the value */ map<U>(fn: (value: T) => U): Maybe<U>; /** * Get value or default */ getOrElse(defaultValue: T): T; } /** * CardCollection - High-level interface for MCard operations with monadic API * * ## DOTS Vocabulary Role: CARRIER CATEGORY Car(S) * * CardCollection is the **Carrier Category** in the Double Operadic Theory of Systems. * - **Objects**: Individual MCards (data artifacts) * - **Morphisms**: Hash references between MCards (content-addressable links) * - **Composition**: Morphisms compose via hash chains (Merkle-DAG structure) * * The Carrier is where **actual systems live**. While the Target (CLM design space) * defines possible interfaces and interactions, the Carrier holds the real data. * * ## The Action: Loose(I) ⊛ Car(S) → Car(S) * * In DOTS, the **Action** is how interactions (from Target) act on systems (in Carrier) * to produce new systems. For CardCollection: * - PCard (Chart/Lens) defines the interaction pattern * - CardCollection.add() produces new MCard in the Carrier * - The result is a new Object in Car(S) * * ## Empty Schema Principle * * CardCollection embodies the Wordless Book principle: * - At t₀: Empty collection = "Wordless Book" * - At t_n: Billions of cards = "Infinite Library" * - Schema (structure) never changes; only data (content) grows * * ## CRD-Only Operations (No UPDATE) * * Following MCard design principles, this collection supports only: * - **C**reate: `add()`, `addWithHandle()` * - **R**ead: `get()`, `getByHandle()`, `getPage()`, `search*()` * - **D**elete: `delete()`, `clear()` * * There is NO `update()` method. Instead, to "update": * 1. Create a new MCard with new content * 2. Use `updateHandle()` to point the handle to the new hash * 3. The old MCard remains in the collection (immutable history) * * ## CRDT Foundation (G-Set) * * CardCollection implements **Grow-Only Set (G-Set) CRDT** semantics: * - **Commutative**: merge(A, B) = merge(B, A) * - **Associative**: merge(A, merge(B, C)) = merge(merge(A, B), C) * - **Idempotent**: merge(A, A) = A (same hash = same card) * * This enables **Strong Eventual Consistency** without coordination. * * ## Monadic API * * The `*M` methods (getM, getByHandleM, etc.) return Maybe<T> monads * for composable, null-safe operations following functional programming patterns. * * @see {@link MCard} for the individual Carrier objects * @see {@link DOTSRole.CARRIER} for DOTS vocabulary definition * @see docs/WorkingNotes/Permanent/Projects/PKC Kernel/MCard.md for full specification */ declare class CardCollection { private engine; constructor(engine: StorageEngine); /** * Add a card to the collection * Handles duplicates (same content, same hash) and collisions (diff content, same hash) */ add(card: MCard): Promise<string>; private areContentsEqual; /** * Get a card by hash */ get(hash: string): Promise<MCard | null>; /** * Delete a card by hash */ delete(hash: string): Promise<void>; /** * Get a page of cards */ getPage(pageNumber?: number, pageSize?: number): Promise<Page<MCard>>; /** * Count total cards */ count(): Promise<number>; /** * Add a card and register a handle for it */ addWithHandle(card: MCard, handle: string): Promise<string>; /** * Get card by handle */ getByHandle(handle: string): Promise<MCard | null>; /** * Resolve handle to hash */ resolveHandle(handle: string): Promise<string | null>; /** * Update handle to point to new card */ updateHandle(handle: string, newCard: MCard): Promise<string>; /** * Get version history for a handle */ getHandleHistory(handle: string): Promise<{ previousHash: string; changedAt: string; }[]>; /** * Monadic get - returns Maybe<MCard> */ getM(hash: string): Promise<Maybe<MCard>>; /** * Monadic getByHandle - returns Maybe<MCard> */ getByHandleM(handle: string): Promise<Maybe<MCard>>; /** * Monadic resolveHandle - returns Maybe<string> */ resolveHandleM(handle: string): Promise<Maybe<string>>; /** * Resolve handle and get card in one monadic operation */ resolveAndGetM(handle: string): Promise<Maybe<MCard>>; /** * Prune version history for a handle. * @param handle The handle string. * @param options Options for pruning (olderThan date, or deleteAll). * @returns Number of deleted entries. */ pruneHandleHistory(handle: string, options?: { olderThan?: string; deleteAll?: boolean; }): Promise<number>; clear(): Promise<void>; searchByString(query: string, pageNumber?: number, pageSize?: number): Promise<Page<MCard>>; searchByContent(query: string, pageNumber?: number, pageSize?: number): Promise<Page<MCard>>; searchByHash(hashPrefix: string): Promise<MCard[]>; getAllMCardsRaw(): Promise<MCard[]>; getAllCards(pageSize?: number, processCallback?: (card: MCard) => any): Promise<{ cards: MCard[]; total: number; }>; printAllCards(): Promise<void>; } declare class ContentTypeInterpreter { private static readonly MIME_TO_EXT; /** * Convenience method to detect MIME type only. * Matches the API expected by MCard/PCard/VCard. */ static detect(content: string | Uint8Array): string; /** * Detect content type and suggest extension. * * @param content Content string or binary buffer * @param fileExtension Optional file extension hint * @returns Object containing detected mimeType and suggested extension */ static detectContentType(content: string | Uint8Array, fileExtension?: string): { mimeType: string; extension: string; }; static getExtension(mimeType: string): string; /** * Check if content should be treated as binary. */ static isBinaryContent(content: string | Uint8Array, mimeType?: string): boolean; static isKnownLongLineExtension(extension?: string): boolean; static isUnstructuredBinary(sample: Uint8Array): boolean; static hasPathologicalLines(sample: Uint8Array, isKnownType: boolean): boolean; } /** * Event constants for MCard */ declare const EVENT_CONSTANTS: { TYPE: string; HASH: string; FIRST_G_TIME: string; CONTENT_SIZE: string; COLLISION_TIME: string; UPGRADED_FUNCTION: string; UPGRADED_HASH: string; DUPLICATE_TIME: string; DUPLICATE_EVENT_TYPE: string; COLLISION_EVENT_TYPE: string; }; /** * Hash Algorithm Hierarchy */ declare const ALGORITHM_HIERARCHY: { sha1: { strength: number; next: string; }; sha224: { strength: number; next: string; }; sha256: { strength: number; next: string; }; sha384: { strength: number; next: string; }; sha512: { strength: number; next: string; }; custom: { strength: number; next: null; }; }; /** * IndexedDBEngine - Browser storage using IndexedDB */ declare class IndexedDBEngine implements StorageEngine { private db; private dbName; constructor(dbName?: string); /** * Initialize the database connection */ init(): Promise<void>; private ensureDb; add(card: MCard): Promise<string>; get(hash: string): Promise<MCard | null>; delete(hash: string): Promise<void>; getPage(pageNumber: number, pageSize: number): Promise<Page<MCard>>; count(): Promise<number>; searchByHash(hashPrefix: string): Promise<MCard[]>; search(query: string, pageNumber: number, pageSize: number): Promise<Page<MCard>>; getAll(): Promise<MCard[]>; clear(): Promise<void>; registerHandle(handle: string, hash: string): Promise<void>; resolveHandle(handle: string): Promise<string | null>; getByHandle(handle: string): Promise<MCard | null>; updateHandle(handle: string, newHash: string): Promise<string>; getHandleHistory(handle: string): Promise<{ previousHash: string; changedAt: string; }[]>; } /** * HashValidator - Computes SHA-256 hashes using Web Crypto API */ declare class HashValidator { /** * Compute hash of content using specified algorithm */ static computeHash(content: Uint8Array | string, algorithm?: string): Promise<string>; /** * Validate that content matches expected hash */ static validate(content: Uint8Array | string, expectedHash: string): Promise<boolean>; } declare function computeHash(content: any): Promise<string>; /** * Either Monad - Represents success (Right) or failure (Left) * * Used for error handling without exceptions */ declare class Either<L, R> { private readonly _value; private readonly _isLeft; private constructor(); /** * Create a Left (failure/error) */ static left<L, R>(value: L): Either<L, R>; /** * Create a Right (success) */ static right<L, R>(value: R): Either<L, R>; /** * Check if Left */ get isLeft(): boolean; /** * Check if Right */ get isRight(): boolean; /** * Get Left value (throws if Right) */ get left(): L; /** * Get Right value (throws if Left) */ get right(): R; /** * Monadic bind - chain operations (short-circuits on Left) */ bind<U>(fn: (value: R) => Either<L, U>): Either<L, U>; /** * Map a function over Right value */ map<U>(fn: (value: R) => U): Either<L, U>; /** * Get Right or default */ getOrElse(defaultValue: R): R; /** * Fold: apply leftFn if Left, rightFn if Right */ fold<U>(leftFn: (l: L) => U, rightFn: (r: R) => U): U; } /** * IO Monad - Defers side effects until execution * * Enables pure functional composition of effectful operations */ declare class IO<T> { private readonly effect; private constructor(); /** * Create an IO from an effect (lazy evaluation) */ static of<T>(effect: () => T | Promise<T>): IO<T>; /** * Lift a pure value into IO */ static pure<T>(value: T): IO<T>; /** * Monadic bind - chain IO operations */ bind<U>(fn: (value: T) => IO<U>): IO<U>; /** * Map a function over the result */ map<U>(fn: (value: T) => U): IO<U>; /** * Execute the IO and get the result */ run(): Promise<T>; /** * Run multiple IOs in sequence */ static sequence<T>(ios: IO<T>[]): IO<T[]>; /** * Run multiple IOs in parallel */ static parallel<T>(ios: IO<T>[]): IO<T[]>; } /** * Reader Monad - Dependency Injection * COMPUTATION which reads from a shared environment */ declare class Reader<E, T> { private readonly run; constructor(run: (env: E) => T); /** * Lift a pure value into Reader */ static pure<E, T>(value: T): Reader<E, T>; /** * Get the environment */ static ask<E>(): Reader<E, E>; /** * Monadic bind (flatMap) */ bind<U>(fn: (value: T) => Reader<E, U>): Reader<E, U>; /** * Map over the result */ map<U>(fn: (value: T) => U): Reader<E, U>; /** * Execute the Reader logic with an environment */ evaluate(env: E): T; } /** * Writer Monad - Logging Side-Effects * Aggregates logs alongside computation values */ declare class Writer<L, T> { private readonly run; constructor(run: () => [T, L[]]); /** * Lift a pure value into Writer (empty log) */ static pure<L, T>(value: T): Writer<L, T>; /** * Write to log */ static tell<L>(log: L[]): Writer<L, void>; /** * Monadic bind */ bind<U>(fn: (value: T) => Writer<L, U>): Writer<L, U>; /** * Map */ map<U>(fn: (value: T) => U): Writer<L, U>; /** * Run the writer */ evaluate(): [T, L[]]; } /** * State Monad - State Management * Encapsulates state transitions */ declare class State<S, T> { private readonly run; constructor(run: (state: S) => [T, S]); /** * Lift pure value */ static pure<S, T>(value: T): State<S, T>; /** * Get current state */ static get<S>(): State<S, S>; /** * Set new state */ static put<S>(newState: S): State<S, void>; /** * Monadic bind */ bind<U>(fn: (value: T) => State<S, U>): State<S, U>; /** * Map */ map<U>(fn: (value: T) => U): State<S, U>; /** * Execute state transition */ evaluate(initialState: S): [T, S]; } /** * LensProtocol - JSON-RPC 2.0 communication for PTR * * Provides standardized message format for PCard execution */ interface JsonRpcRequest { jsonrpc: '2.0'; id: string | number; method: string; params?: unknown; } interface JsonRpcResponse { jsonrpc: '2.0'; id: string | number; result?: unknown; error?: { code: number; message: string; data?: unknown; }; } /** * LensProtocol - Create and parse JSON-RPC messages */ declare class LensProtocol { private static idCounter; /** * Create an execute request */ static createExecuteRequest(pcard_hash: string, target_hash: string, context?: Record<string, unknown>): JsonRpcRequest; /** * Create a verify request */ static createVerifyRequest(pcard_hash: string, target_hash: string, context?: Record<string, unknown>): JsonRpcRequest; /** * Create a reveal request */ static createRevealRequest(card_hash: string, aspect: string): JsonRpcRequest; /** * Create a system status request */ static createStatusRequest(): JsonRpcRequest; /** * Create a system health request */ static createHealthRequest(): JsonRpcRequest; /** * Create a success response */ static createSuccessResponse(id: string | number, result: unknown): JsonRpcResponse; /** * Create an error response */ static createErrorResponse(id: string | number, code: number, message: string, data?: unknown): JsonRpcResponse; /** * Parse a JSON-RPC response */ static parseResponse<T>(response: JsonRpcResponse): T; } declare const ErrorCodes: { readonly PARSE_ERROR: -32700; readonly INVALID_REQUEST: -32600; readonly METHOD_NOT_FOUND: -32601; readonly INVALID_PARAMS: -32602; readonly INTERNAL_ERROR: -32603; readonly EXECUTION_ERROR: -32000; readonly VERIFICATION_FAILED: -32001; readonly TIMEOUT: -32002; }; /** * Common types for PTR system * Matches python mcard.ptr.core.common_types */ type PrimeHash = string; interface PolynomialTerm { coefficient: PrimeHash; exponent: PrimeHash; weight: number; } interface SafetyViolation { property: string; violation_type: string; details: string; timestamp: string; } interface LivenessMetric { goal: string; progress: number; timestamp: string; } declare enum VerificationStatus { PENDING = "pending", VERIFIED = "verified", FAILED = "failed", SKIPPED = "skipped" } interface ExecutionResult { success: boolean; output: unknown; verification_vcard: string | null; execution_time_ms: number; alignment_score?: number; invariants_preserved: boolean; safety_violations: SafetyViolation[]; liveness_metrics: LivenessMetric[]; error_message?: string; } declare class MCardStore { private dbPromise; constructor(dbName?: string); putCard(hash: string, content: any): Promise<void>; getCard(hash: string): Promise<any | undefined>; setHandle(handle: string, newHash: string): Promise<void>; resolveHandle(handle: string): Promise<any | undefined>; getHandleHistory(handle: string): Promise<any[]>; getHandlesByHash(hash: string): Promise<any[]>; getAllCards(): Promise<any[]>; getAllHandles(): Promise<any[]>; getAllHistory(): Promise<any[]>; } declare class ServiceWorkerPTR { private store; private ws; constructor(serverUrl: string, wasmUrl?: string, storeName?: string); start(): void; getStore(): MCardStore; private onMeshMessage; private handleLocalRequest; private handleDirectExecution; private executeCLM; private executeJavaScript; private executePython; } /** * Configuration for the Faro Observability Sidecar */ interface FaroSidecarConfig { url: string; apiKey?: string; appName: string; appVersion: string; enableTracing?: boolean; namespace?: string; additionalInstrumentations?: any[]; } /** * FaroSidecar - Integrates Grafana Faro for Frontend Observability * * Acts as an observability sidecar for the PTR, capturing: * - Logs * - Errors * - Web Vitals * - Traces (OpenTelemetry) * - User Sessions */ declare class FaroSidecar { private static instance; private faro; private constructor(); /** * Get the singleton instance of FaroSidecar */ static getInstance(): FaroSidecar; /** * Initialize the Faro SDK * * @param config Configuration options * @returns The initialized Faro instance or null if not in a browser environment */ initialize(config: FaroSidecarConfig): Faro | null; /** * Get the underlying Faro instance */ getFaro(): Faro | null; /** * Manually push an error to Faro */ pushError(error: Error, context?: Record<string, any>): void; /** * Manually push a log message to Faro */ pushLog(message: string, context?: Record<string, any>): void; /** * Push a custom event */ pushEvent(name: string, attributes?: Record<string, string>): void; } declare class ValidationRegistry { private validators; constructor(); /** * Validate content using appropriate validator. * * @param content The content to validate * @param mimeType The detected MIME type * @throws ValidationError If content is invalid */ validate(content: string | Uint8Array, mimeType: string): void; private basicValidation; } declare const validationRegistry: ValidationRegistry; export { ALGORITHM_HIERARCHY, CardCollection, ContentHandle, ContentTypeInterpreter, EVENT_CONSTANTS, Either, ErrorCodes, type ExecutionResult, FaroSidecar, type FaroSidecarConfig, GTime, HandleValidationError, HashValidator, IO, IndexedDBEngine, type JsonRpcRequest, type JsonRpcResponse, LensProtocol, type LivenessMetric, MCard, MCardStore, Maybe, Page, type PolynomialTerm, type PrimeHash, Reader, type SafetyViolation, ServiceWorkerPTR, State, StorageEngine, ValidationRegistry, VerificationStatus, Writer, computeHash, validateHandle, validationRegistry };