CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-lumino--coreutils

Essential utility functions and classes for TypeScript/JavaScript applications including JSON handling, MIME data management, promise delegation, secure tokens, and cross-platform random number generation.

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

uuid-generation.mddocs/

UUID Generation

RFC 4122 compliant UUID v4 generation with cryptographically strong randomness and cross-platform support. Provides secure unique identifier generation for applications requiring globally unique identifiers.

Capabilities

UUID Namespace

Provides RFC 4122 compliant UUID v4 generation using cryptographically strong random number generation.

/**
 * The namespace for UUID related functionality.
 */
namespace UUID {
  /**
   * A function which generates UUID v4 identifiers.
   * 
   * @returns A new UUID v4 string.
   * 
   * Notes:
   * This implementation complies with RFC 4122.
   * 
   * This uses `Random.getRandomValues()` for random bytes, which in
   * turn will use the underlying `crypto` module of the platform if
   * it is available. The fallback for randomness is `Math.random`.
   */
  const uuid4: () => string;
}

UUID Factory Function

Internal factory function that creates UUID generators with custom random number sources.

/**
 * A function which creates a function that generates UUID v4 identifiers.
 * 
 * @param getRandomValues - Function to generate random bytes
 * @returns A new function that creates a UUID v4 string.
 * 
 * Notes:
 * This implementation complies with RFC 4122.
 * 
 * This uses the provided `getRandomValues` function for random bytes, which
 * allows for custom random number generators or testing with deterministic values.
 */
function uuid4Factory(
  getRandomValues: (bytes: Uint8Array) => void
): () => string;

Usage Examples:

import { UUID } from "@lumino/coreutils";

// Generate a single UUID v4
const id = UUID.uuid4();
console.log(id); // "f47ac10b-58cc-4372-a567-0e02b2c3d479"

// Generate multiple UUIDs
const userIds = Array.from({ length: 5 }, () => UUID.uuid4());
console.log(userIds);
// [
//   "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
//   "6ba7b811-9dad-11d1-80b4-00c04fd430c8",
//   "6ba7b812-9dad-11d1-80b4-00c04fd430c8",
//   "6ba7b813-9dad-11d1-80b4-00c04fd430c8",
//   "6ba7b814-9dad-11d1-80b4-00c04fd430c8"
// ]

// UUIDs are always unique
const id1 = UUID.uuid4();
const id2 = UUID.uuid4();
console.log(id1 === id2); // false

Common Use Cases

Entity Identification:

import { UUID } from "@lumino/coreutils";

interface User {
  id: string;
  name: string;
  email: string;
  createdAt: Date;
}

interface Document {
  id: string;
  title: string;
  content: string;
  authorId: string;
  version: string;
}

function createUser(name: string, email: string): User {
  return {
    id: UUID.uuid4(),
    name,
    email,
    createdAt: new Date()
  };
}

function createDocument(title: string, content: string, authorId: string): Document {
  return {
    id: UUID.uuid4(),
    title,
    content,
    authorId,
    version: UUID.uuid4() // Version ID for tracking changes
  };
}

// Usage
const user = createUser("Alice Smith", "alice@example.com");
const document = createDocument("My Document", "Document content...", user.id);

console.log("User ID:", user.id);
console.log("Document ID:", document.id);
console.log("Document Version:", document.version);

Session Management:

import { UUID } from "@lumino/coreutils";

interface Session {
  id: string;
  userId: string;
  createdAt: Date;
  expiresAt: Date;
  isActive: boolean;
}

class SessionManager {
  private sessions = new Map<string, Session>();

  createSession(userId: string, durationMs: number = 24 * 60 * 60 * 1000): Session {
    const session: Session = {
      id: UUID.uuid4(),
      userId,
      createdAt: new Date(),
      expiresAt: new Date(Date.now() + durationMs),
      isActive: true
    };

    this.sessions.set(session.id, session);
    return session;
  }

  getSession(sessionId: string): Session | undefined {
    const session = this.sessions.get(sessionId);
    if (session && session.expiresAt > new Date()) {
      return session;
    }
    
    // Clean up expired session
    if (session) {
      this.sessions.delete(sessionId);
    }
    return undefined;
  }

  invalidateSession(sessionId: string): boolean {
    const session = this.sessions.get(sessionId);
    if (session) {
      session.isActive = false;
      this.sessions.delete(sessionId);
      return true;
    }
    return false;
  }
}

// Usage
const sessionManager = new SessionManager();
const session = sessionManager.createSession("user-123", 2 * 60 * 60 * 1000); // 2 hours

console.log("Session created:", session.id);
console.log("Session expires:", session.expiresAt);

Request Tracking:

import { UUID } from "@lumino/coreutils";

interface ApiRequest {
  id: string;
  method: string;
  url: string;
  timestamp: Date;
  userId?: string;
  correlationId?: string;
}

interface ApiResponse {
  requestId: string;
  status: number;
  data?: any;
  error?: string;
  duration: number;
}

class ApiLogger {
  private requests = new Map<string, ApiRequest>();

  logRequest(method: string, url: string, userId?: string, correlationId?: string): string {
    const requestId = UUID.uuid4();
    const request: ApiRequest = {
      id: requestId,
      method,
      url,
      timestamp: new Date(),
      userId,
      correlationId: correlationId || UUID.uuid4()
    };

    this.requests.set(requestId, request);
    console.log(`[${request.correlationId}] ${method} ${url} - Request ID: ${requestId}`);
    
    return requestId;
  }

  logResponse(requestId: string, status: number, data?: any, error?: string): void {
    const request = this.requests.get(requestId);
    if (!request) {
      console.warn(`Request ${requestId} not found`);
      return;
    }

    const duration = Date.now() - request.timestamp.getTime();
    const response: ApiResponse = {
      requestId,
      status,
      data,
      error,
      duration
    };

    console.log(`[${request.correlationId}] ${request.method} ${request.url} - ${status} (${duration}ms)`);
    
    // Clean up after logging
    this.requests.delete(requestId);
  }
}

// Usage
const logger = new ApiLogger();

// Log API request
const requestId = logger.logRequest("POST", "/api/users", "user-123");

// Simulate API processing time
setTimeout(() => {
  logger.logResponse(requestId, 201, { id: "user-456", name: "New User" });
}, 150);

File and Resource Management:

import { UUID } from "@lumino/coreutils";

interface FileUpload {
  id: string;
  originalName: string;
  storedName: string;
  mimeType: string;
  size: number;
  uploadedAt: Date;
  uploadedBy: string;
}

interface TemporaryResource {
  id: string;
  type: string;
  data: any;
  expiresAt: Date;
  accessCount: number;
}

class FileManager {
  private uploads = new Map<string, FileUpload>();

  uploadFile(file: File, userId: string): Promise<FileUpload> {
    return new Promise((resolve) => {
      const fileId = UUID.uuid4();
      const storedName = `${fileId}-${file.name}`;
      
      const upload: FileUpload = {
        id: fileId,
        originalName: file.name,
        storedName,
        mimeType: file.type,
        size: file.size,
        uploadedAt: new Date(),
        uploadedBy: userId
      };

      this.uploads.set(fileId, upload);
      
      // Simulate file storage
      setTimeout(() => {
        console.log(`File uploaded: ${file.name} -> ${storedName}`);
        resolve(upload);
      }, 100);
    });
  }

  getFile(fileId: string): FileUpload | undefined {
    return this.uploads.get(fileId);
  }
}

class TemporaryResourceManager {
  private resources = new Map<string, TemporaryResource>();

  createResource(type: string, data: any, ttlMs: number = 60000): string {
    const resourceId = UUID.uuid4();
    const resource: TemporaryResource = {
      id: resourceId,
      type,
      data,
      expiresAt: new Date(Date.now() + ttlMs),
      accessCount: 0
    };

    this.resources.set(resourceId, resource);
    
    // Auto-cleanup after expiration
    setTimeout(() => {
      this.resources.delete(resourceId);
    }, ttlMs);

    return resourceId;
  }

  getResource(resourceId: string): any | undefined {
    const resource = this.resources.get(resourceId);
    if (resource && resource.expiresAt > new Date()) {
      resource.accessCount++;
      return resource.data;
    }
    return undefined;
  }
}

// Usage
const fileManager = new FileManager();
const tempManager = new TemporaryResourceManager();

// File upload simulation
const mockFile = new File(["content"], "document.txt", { type: "text/plain" });
fileManager.uploadFile(mockFile, "user-123").then(upload => {
  console.log("File uploaded with ID:", upload.id);
});

// Temporary resource
const tempId = tempManager.createResource("cache", { result: "computed data" }, 30000);
console.log("Temporary resource created:", tempId);

Testing with Custom UUID Generation:

import { uuid4Factory } from "@lumino/coreutils";

// Create deterministic UUID generator for testing
function createTestUuidGenerator(): () => string {
  let counter = 0;
  
  const deterministicRandom = (buffer: Uint8Array): void => {
    for (let i = 0; i < buffer.length; i++) {
      buffer[i] = (counter + i) % 256;
    }
    counter++;
  };

  return uuid4Factory(deterministicRandom);
}

// Usage in tests
const testUuid = createTestUuidGenerator();

console.log("Test UUID 1:", testUuid()); // Predictable output
console.log("Test UUID 2:", testUuid()); // Different but predictable output

// Create mock UUID generator that returns specific values
function createMockUuidGenerator(values: string[]): () => string {
  let index = 0;
  return () => {
    if (index >= values.length) {
      throw new Error("No more mock UUIDs available");
    }
    return values[index++];
  };
}

const mockUuid = createMockUuidGenerator([
  "00000000-0000-4000-8000-000000000001",
  "00000000-0000-4000-8000-000000000002",
  "00000000-0000-4000-8000-000000000003"
]);

console.log("Mock UUID 1:", mockUuid());
console.log("Mock UUID 2:", mockUuid());
console.log("Mock UUID 3:", mockUuid());

UUID Format

UUID v4 identifiers generated by this library follow the RFC 4122 specification:

  • Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  • Length: 36 characters (32 hex digits + 4 hyphens)
  • Version: 4 (indicated by the 4 in the 13th position)
  • Variant: RFC 4122 (indicated by 8, 9, A, or B in the 17th position)
  • Randomness: 122 bits of randomness (6 bits are fixed for version and variant)

Example: f47ac10b-58cc-4372-a567-0e02b2c3d479

Platform Support

UUID generation uses the same cross-platform random number generation as the Random module:

Browser Support

  • Modern browsers: Uses window.crypto.getRandomValues()
  • Internet Explorer 11: Uses window.msCrypto.getRandomValues()
  • Fallback: Uses Math.random() if crypto APIs unavailable

Node.js Support

  • Node.js 7+: Uses crypto.randomFillSync()
  • Node.js 0.10+: Uses crypto.randomBytes()
  • Fallback: Uses Math.random() if crypto module unavailable

Security Considerations

  • UUIDs generated with crypto APIs provide cryptographically strong uniqueness
  • Fallback Math.random() implementation is not cryptographically secure
  • For security-critical applications, ensure crypto APIs are available
  • The probability of generating duplicate UUIDs is astronomically low with proper random sources

docs

index.md

json-utilities.md

mime-data.md

promise-delegation.md

random-generation.md

token-system.md

uuid-generation.md

tile.json