CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-fluidframework--common-utils

Collection of utility functions for Fluid Framework including async operations, data structures, performance monitoring, and cross-platform compatibility.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Fluid Framework Common Utils

The Fluid Framework Common Utils package provides a comprehensive collection of utility functions and classes specifically designed for the Fluid Framework ecosystem. This package includes essential utilities for cross-platform development, async operations, data structures, performance monitoring, and event handling that enable consistent behavior across all Fluid Framework components.

Package Information

  • Package Name: @fluidframework/common-utils
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @fluidframework/common-utils
  • Version: 3.1.0

Core Imports

import { 
  assert, 
  delay, 
  Deferred, 
  TypedEventEmitter, 
  Timer,
  Heap,
  PromiseCache
} from "@fluidframework/common-utils";

For CommonJS:

const { 
  assert, 
  delay, 
  Deferred, 
  TypedEventEmitter, 
  Timer,
  Heap,
  PromiseCache 
} = require("@fluidframework/common-utils");

Basic Usage

import { 
  assert, 
  delay, 
  Deferred, 
  TypedEventEmitter, 
  Timer,
  Heap
} from "@fluidframework/common-utils";

// Basic assertion
assert(someCondition, "Condition must be true");

// Async delay
await delay(1000); // Wait 1 second

// Deferred promise
const deferred = new Deferred<string>();
setTimeout(() => deferred.resolve("Hello"), 100);
const result = await deferred.promise;

// Typed event emitter
class MyEmitter extends TypedEventEmitter<{
  data: (value: string) => void;
  error: (error: Error) => void;
}> {}

const emitter = new MyEmitter();
emitter.on("data", (value) => console.log(value));
emitter.emit("data", "Hello World");

// Timer with long timeout support
const timer = new Timer(5000, () => console.log("Timer fired"));
timer.start();

// Heap data structure
const heap = new Heap<number>();
heap.add(5);
heap.add(2);
heap.add(8);
console.log(heap.get()); // Gets minimum: 2

Architecture

The Fluid Framework Common Utils package is organized around several key architectural patterns:

  • Cross-Platform Compatibility: Separate implementations for Node.js and Browser environments with unified APIs
  • Type Safety: Full TypeScript support with comprehensive type definitions and generic constraints
  • Performance Optimization: Efficient data structures and performance monitoring utilities
  • Event-Driven Design: Typed event emitters and event forwarding patterns
  • Async/Await Support: Promise-based APIs with deferred execution and caching capabilities
  • Memory Management: Disposal patterns and lazy initialization for efficient resource usage

Capabilities

Assertions & Type Safety

Essential assertion utilities and type safety helpers for runtime validation and exhaustiveness checking.

function assert(condition: any, message?: string | number): asserts condition;
function unreachableCase(x: never): never;

Assertions & Type Safety

Buffer Operations

Cross-platform buffer manipulation utilities with separate optimized implementations for Node.js and Browser environments.

interface IsoBuffer extends Uint8Array {
  toString(encoding?: "utf8" | "base64"): string;
  static from(data: string | ArrayBufferLike, encoding?: "utf8" | "base64"): IsoBuffer;
}

// Node.js only - not available in browser builds
class Buffer extends Uint8Array {
  static from(data: string | ArrayBufferLike, encoding?: BufferEncoding): Buffer;
  static alloc(size: number, fill?: string | Buffer | Uint8Array | number): Buffer;
  toString(encoding?: BufferEncoding): string;
}

function Uint8ArrayToString(arr: Uint8Array, encoding: "utf8" | "base64"): string;
function stringToBuffer(str: string, encoding?: "utf8" | "base64"): ArrayBuffer;
function bufferToString(buffer: ArrayBufferLike, encoding?: "utf8" | "base64"): string;
function Uint8ArrayToArrayBuffer(array: Uint8Array): ArrayBuffer;
function isArrayBuffer(value: any): value is ArrayBuffer; // Browser only - not available in Node.js builds

Buffer Operations

Encoding & Hashing

Base64 encoding utilities and file hashing functions with platform-specific optimizations.

function fromBase64ToUtf8(str: string): string;
function fromUtf8ToBase64(str: string): string;
function toUtf8(str: string, encoding?: string): string;
function hashFile(file: ArrayBufferLike, algorithm?: "SHA-1" | "SHA-256"): Promise<string>;
function gitHashFile(file: ArrayBufferLike): Promise<string>;

Encoding & Hashing

Async Operations

Comprehensive async utilities including promises, delays, timers, and promise caching with expiration support.

function delay(timeMs: number): Promise<void>;

class Deferred<T> {
  readonly promise: Promise<T>;
  readonly isCompleted: boolean;
  resolve(value: T): void;
  reject(reason?: any): void;
}

class LazyPromise<T> implements Promise<T> {
  constructor(executor: () => Promise<T>);
}

class PromiseCache<TKey, TResult> {
  constructor(options?: PromiseCacheOptions);
  has(key: TKey): boolean;
  get(key: TKey): Promise<TResult> | undefined;
  remove(key: TKey): boolean;
  add(key: TKey, asyncWorkFn: () => Promise<TResult>): boolean;
  addOrGet(key: TKey, asyncWorkFn: () => Promise<TResult>): Promise<TResult>;
  addValue(key: TKey, value: TResult): boolean;
  addValueOrGet(key: TKey, value: TResult): Promise<TResult>;
}

function setLongTimeout(
  timeoutFn: () => void,
  timeoutMs: number,
  setTimeoutIdFn?: (timeoutId: ReturnType<typeof setTimeout>) => void
): ReturnType<typeof setTimeout>;

interface ITimer {
  readonly hasTimer: boolean;
  start(): void;
  clear(): void;
}

interface IPromiseTimerResult {
  timerResult: "timeout" | "cancel";
}

interface IPromiseTimer extends ITimer {
  start(): Promise<IPromiseTimerResult>;
}

class Timer implements ITimer {
  constructor(defaultTimeout: number, defaultHandler: () => void, getCurrentTick?: () => number);
  readonly hasTimer: boolean;
  start(ms?: number, handler?: () => void): void;
  clear(): void;
  restart(ms?: number, handler?: () => void): void;
}

class PromiseTimer implements IPromiseTimer {
  constructor(defaultTimeout: number, defaultHandler: () => void);
  readonly hasTimer: boolean;
  start(ms?: number, handler?: () => void): Promise<IPromiseTimerResult>;
  clear(): void;
}

Async Operations

Data Structures

Efficient data structures including priority heaps and range tracking utilities.

interface IComparer<T> {
  min: T;
  compare(a: T, b: T): number;
}

class Heap<T> {
  constructor(comp: IComparer<T>);
  get(): T;
  peek(): IHeapNode<T>;
  add(value: T): IHeapNode<T>;
  update(node: IHeapNode<T>): void;
  remove(node: IHeapNode<T>): void;
  count(): number;
}

class RangeTracker {
  add(primaryStart: number, primaryEnd: number, secondaryStart: number): void;
  get(primaryPosition: number, primaryEnd?: number): IRange | undefined;
}

Data Structures

Event Handling

Type-safe event emitters and event forwarding utilities for building reactive systems.

class TypedEventEmitter<TEvents> implements IEventProvider<TEvents> {
  on<K extends keyof TEvents>(event: K, listener: TEvents[K]): this;
  off<K extends keyof TEvents>(event: K, listener: TEvents[K]): this;
  emit<K extends keyof TEvents>(event: K, ...args: Parameters<TEvents[K]>): boolean;
}

class EventForwarder<TEvents> extends TypedEventEmitter<TEvents> implements IDisposable {
  constructor(from: IEventProvider<TEvents>, to?: IEventProvider<TEvents>);
  readonly disposed: boolean;
  dispose(): void;
}

Event Handling

Performance & Monitoring

Performance measurement and tracing utilities for monitoring application performance.

interface IsomorphicPerformance {
  now(): number;
  mark(name: string): void;
  measure(name: string, startMark?: string, endMark?: string): void;
  clearMarks(name?: string): void;
}

class Trace {
  static start(): Trace;
  trace(): ITraceEvent;
}

interface ITraceEvent {
  totalTimeElapsed: number;
  duration: number;
  tick: number;
}

Performance & Monitoring

Utility Functions

Collection of utility functions for common programming tasks including lazy initialization, disposal patterns, rate limiting, and safe JSON parsing.

class Lazy<T> {
  constructor(valueGenerator: () => T);
  get evaluated(): boolean;
  get value(): T;
}

function doIfNotDisposed<TDisposable extends IDisposable>(
  disposable: TDisposable
): <TArgs extends any[], TReturn>(
  fn: (this: TDisposable, ...args: TArgs) => TReturn
) => (...args: TArgs) => TReturn;

class RateLimiter {
  constructor(maxCount: number, windowSizeInMs: number);
  filter<T>(items: T[]): T[];
}

function safelyParseJSON(json: string): any;

Utility Functions

Platform-Specific Features

This package provides platform-optimized implementations:

  • Browser Environment: Uses Web APIs like crypto.subtle for hashing and requestIdleCallback for task scheduling
  • Node.js Environment: Leverages Node.js Buffer APIs and file system optimizations
  • Isomorphic APIs: Unified interfaces that work consistently across both environments

Deprecation Notice

Many APIs in this package are marked as deprecated and have been moved to more specialized packages:

  • Core utilities → @fluidframework/core-utils
  • Client utilities → @fluidframework-internal/client-utils
  • Telemetry utilities → @fluidframework/telemetry-utils

Consult the API documentation for migration guidance for specific functions.

docs

assertions.md

async-operations.md

buffer-operations.md

data-structures.md

encoding-hashing.md

event-handling.md

index.md

performance-monitoring.md

utility-functions.md

tile.json