or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-utilities.mddata-structures.mddevelopment-utilities.mddom-styling.mdfunctional-programming.mdindex.mdnetwork-fetch.mdperformance-crypto.mdtext-unicode.mduser-agent-browser.md
tile.json

performance-crypto.mddocs/

Performance & Crypto

Performance monitoring utilities and cryptographic functions including base62 encoding and CRC32 hashing.

Capabilities

Performance Monitoring

High-resolution timing utilities for performance measurement and monitoring.

const performance = require('fbjs/lib/performance');
const performanceNow = require('fbjs/lib/performanceNow');

/**
 * Performance API wrapper providing cross-browser performance measurement
 */
const performance: {
  /**
   * High-resolution timestamp from performance origin
   * @returns Timestamp in milliseconds with microsecond precision
   */
  now(): number;
  
  /**
   * Performance timing information
   */
  timing: {
    navigationStart: number;
    unloadEventStart: number;
    unloadEventEnd: number;
    redirectStart: number;
    redirectEnd: number;
    fetchStart: number;
    domainLookupStart: number;
    domainLookupEnd: number;
    connectStart: number;
    connectEnd: number;
    secureConnectionStart: number;
    requestStart: number;
    responseStart: number;
    responseEnd: number;
    domLoading: number;
    domInteractive: number;
    domContentLoadedEventStart: number;
    domContentLoadedEventEnd: number;
    domComplete: number;
    loadEventStart: number;
    loadEventEnd: number;
  };
  
  /**
   * Navigation information
   */
  navigation: {
    type: number;        // Navigation type (0=navigate, 1=reload, 2=back_forward)
    redirectCount: number; // Number of redirects
  };
  
  /**
   * Creates a performance mark
   * @param name - Name of the performance mark
   */
  mark(name: string): void;
  
  /**
   * Measures time between two marks or from navigation start
   * @param name - Name of the measure
   * @param startMark - Start mark name (optional)
   * @param endMark - End mark name (optional)
   */
  measure(name: string, startMark?: string, endMark?: string): void;
  
  /**
   * Gets performance entries by name
   * @param name - Entry name to filter by
   * @param type - Entry type to filter by
   * @returns Array of performance entries
   */
  getEntriesByName(name: string, type?: string): Array<PerformanceEntry>;
  
  /**
   * Gets performance entries by type
   * @param type - Entry type ('mark', 'measure', 'navigation', etc.)
   * @returns Array of performance entries
   */
  getEntriesByType(type: string): Array<PerformanceEntry>;
  
  /**
   * Gets all performance entries
   * @returns Array of all performance entries
   */
  getEntries(): Array<PerformanceEntry>;
  
  /**
   * Clears performance marks
   * @param name - Optional mark name to clear (clears all if not specified)
   */
  clearMarks(name?: string): void;
  
  /**
   * Clears performance measures
   * @param name - Optional measure name to clear (clears all if not specified)
   */
  clearMeasures(name?: string): void;
};

/**
 * High-resolution timestamp function
 * @returns Current timestamp in milliseconds with high precision
 */
function performanceNow(): number;

Usage Examples:

const performance = require('fbjs/lib/performance');
const performanceNow = require('fbjs/lib/performanceNow');

// Basic timing measurement
const start = performanceNow();
// ... some operation
const end = performanceNow();
console.log(`Operation took ${end - start} milliseconds`);

// Using performance marks and measures
performance.mark('operation-start');

// Simulate some work
setTimeout(() => {
  performance.mark('operation-end');
  performance.measure('total-operation', 'operation-start', 'operation-end');
  
  const measures = performance.getEntriesByType('measure');
  measures.forEach(measure => {
    console.log(`${measure.name}: ${measure.duration}ms`);
  });
}, 100);

// Function timing utility
function timeFunction(fn, name = 'function') {
  const start = performanceNow();
  const result = fn();
  const end = performanceNow();
  
  console.log(`${name} execution time: ${end - start}ms`);
  return result;
}

// Usage example
const result = timeFunction(() => {
  // Some computational work
  let sum = 0;
  for (let i = 0; i < 1000000; i++) {
    sum += i;
  }
  return sum;
}, 'sum-calculation');

// Benchmark comparison
function benchmark(operations) {
  const results = {};
  
  operations.forEach(({ name, fn }) => {
    performance.mark(`${name}-start`);
    fn();
    performance.mark(`${name}-end`);
    performance.measure(name, `${name}-start`, `${name}-end`);
    
    const measure = performance.getEntriesByName(name, 'measure')[0];
    results[name] = measure.duration;
  });
  
  return results;
}

// Navigation timing analysis
function analyzePageLoad() {
  const timing = performance.timing;
  
  const metrics = {
    'DNS Lookup': timing.domainLookupEnd - timing.domainLookupStart,
    'TCP Connect': timing.connectEnd - timing.connectStart,
    'Request': timing.responseStart - timing.requestStart,
    'Response': timing.responseEnd - timing.responseStart,
    'DOM Processing': timing.domComplete - timing.domLoading,
    'Total Load Time': timing.loadEventEnd - timing.navigationStart
  };
  
  Object.entries(metrics).forEach(([name, time]) => {
    console.log(`${name}: ${time}ms`);
  });
  
  return metrics;
}

Cryptographic Utilities

Encoding and hashing functions for data integrity and compact representation.

const base62 = require('fbjs/lib/base62');
const crc32 = require('fbjs/lib/crc32');

/**
 * Converts number to base62 string representation
 * Uses alphabet: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
 * @param number - Number to convert (must be non-negative integer)
 * @returns Base62 encoded string
 */
function base62(number: number): string;

/**
 * Computes CRC32 hash of input string
 * @param input - String to hash
 * @returns CRC32 hash as signed 32-bit integer
 */
function crc32(input: string): number;

Usage Examples:

const base62 = require('fbjs/lib/base62');
const crc32 = require('fbjs/lib/crc32');

// Base62 encoding for compact IDs
const userId = 123456789;
const shortId = base62(userId); // "8M0kX"
console.log(`User ID ${userId} encoded as: ${shortId}`);

// Generate short URLs
function generateShortUrl(longUrl) {
  const hash = Math.abs(crc32(longUrl));
  const shortCode = base62(hash);
  return `https://short.ly/${shortCode}`;
}

const longUrl = 'https://example.com/very/long/path/to/resource?param=value';
const shortUrl = generateShortUrl(longUrl);
console.log(`Short URL: ${shortUrl}`);

// Create compact session IDs
function generateSessionId() {
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 1000000);
  const combined = parseInt(`${timestamp}${random}`);
  return base62(combined);
}

const sessionId = generateSessionId();
console.log(`Session ID: ${sessionId}`);

// Data integrity checking with CRC32
function addChecksum(data) {
  const dataString = JSON.stringify(data);
  const checksum = crc32(dataString);
  return {
    data: data,
    checksum: checksum
  };
}

function verifyChecksum(package) {
  const dataString = JSON.stringify(package.data);
  const computedChecksum = crc32(dataString);
  return computedChecksum === package.checksum;
}

// Usage example
const originalData = { message: 'Hello, World!', timestamp: Date.now() };
const packageWithChecksum = addChecksum(originalData);

console.log('Package:', packageWithChecksum);
console.log('Valid:', verifyChecksum(packageWithChecksum)); // true

// File content hashing
function hashContent(content) {
  const hash = crc32(content);
  const hashString = base62(Math.abs(hash));
  return hashString;
}

const fileContent = 'This is the content of a file...';
const contentHash = hashContent(fileContent);
console.log(`Content hash: ${contentHash}`);

// Cache key generation
function generateCacheKey(url, params = {}) {
  const keyString = url + JSON.stringify(params);
  const hash = Math.abs(crc32(keyString));
  return `cache_${base62(hash)}`;
}

const cacheKey = generateCacheKey('/api/users', { page: 1, limit: 10 });
console.log(`Cache key: ${cacheKey}`);

// Collision detection
function detectCollisions(strings) {
  const hashes = new Map();
  const collisions = [];
  
  strings.forEach(str => {
    const hash = crc32(str);
    if (hashes.has(hash)) {
      collisions.push({
        hash: hash,
        strings: [hashes.get(hash), str]
      });
    } else {
      hashes.set(hash, str);
    }
  });
  
  return collisions;
}

// Version fingerprinting
function createVersionFingerprint(files) {
  const combined = files
    .map(file => `${file.name}:${file.content}`)
    .sort()
    .join('|');
  
  const hash = Math.abs(crc32(combined));
  return base62(hash);
}

const projectFiles = [
  { name: 'index.js', content: 'console.log("Hello");' },
  { name: 'style.css', content: 'body { margin: 0; }' },
  { name: 'config.json', content: '{"version": "1.0.0"}' }
];

const versionFingerprint = createVersionFingerprint(projectFiles);
console.log(`Version fingerprint: ${versionFingerprint}`);

Animation Frame Utilities

Cross-browser animation frame utilities for smooth animations.

const requestAnimationFrame = require('fbjs/lib/requestAnimationFrame');
const requestAnimationFramePolyfill = require('fbjs/lib/requestAnimationFramePolyfill');
const cancelAnimationFramePolyfill = require('fbjs/lib/cancelAnimationFramePolyfill');
const nativeRequestAnimationFrame = require('fbjs/lib/nativeRequestAnimationFrame');

/**
 * Cross-browser requestAnimationFrame implementation
 * @param callback - Function to call before next repaint
 * @returns Request ID that can be used to cancel the request
 */
function requestAnimationFrame(callback: (timestamp: number) => void): number;

/**
 * Polyfill implementation of requestAnimationFrame
 * Falls back to setTimeout with 16ms delay for 60fps
 * @param callback - Function to call before next repaint
 * @returns Request ID
 */
function requestAnimationFramePolyfill(callback: (timestamp: number) => void): number;

/**
 * Cancels animation frame request
 * @param id - Request ID returned by requestAnimationFrame
 */
function cancelAnimationFramePolyfill(id: number): void;

/**
 * Reference to native requestAnimationFrame if available
 */
const nativeRequestAnimationFrame: ?(callback: (timestamp: number) => void) => number;

Usage Examples:

const requestAnimationFrame = require('fbjs/lib/requestAnimationFrame');
const cancelAnimationFramePolyfill = require('fbjs/lib/cancelAnimationFramePolyfill');

// Simple animation loop
function animateElement(element, duration = 1000) {
  const startTime = performance.now();
  const startPosition = 0;
  const endPosition = 300;
  
  function animate(currentTime) {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);
    
    // Easing function (ease-out)
    const easeOut = 1 - Math.pow(1 - progress, 3);
    
    const currentPosition = startPosition + (endPosition - startPosition) * easeOut;
    element.style.transform = `translateX(${currentPosition}px)`;
    
    if (progress < 1) {
      requestAnimationFrame(animate);
    }
  }
  
  requestAnimationFrame(animate);
}

// Smooth counter animation
function animateCounter(element, start, end, duration = 2000) {
  const startTime = performance.now();
  
  function updateCounter(currentTime) {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);
    
    const current = Math.floor(start + (end - start) * progress);
    element.textContent = current.toLocaleString();
    
    if (progress < 1) {
      requestAnimationFrame(updateCounter);
    }
  }
  
  requestAnimationFrame(updateCounter);
}

// Cancelable animation
class Animation {
  constructor() {
    this.requestId = null;
    this.isRunning = false;
  }
  
  start(callback) {
    if (this.isRunning) return;
    
    this.isRunning = true;
    const animate = (timestamp) => {
      if (!this.isRunning) return;
      
      callback(timestamp);
      this.requestId = requestAnimationFrame(animate);
    };
    
    this.requestId = requestAnimationFrame(animate);
  }
  
  stop() {
    if (this.requestId) {
      cancelAnimationFramePolyfill(this.requestId);
      this.requestId = null;
    }
    this.isRunning = false;
  }
}

// Usage example
const animation = new Animation();
const element = document.getElementById('animated-element');

animation.start((timestamp) => {
  const rotation = (timestamp * 0.1) % 360;
  element.style.transform = `rotate(${rotation}deg)`;
});

// Stop animation after 5 seconds
setTimeout(() => {
  animation.stop();
}, 5000);

// FPS counter
function createFPSCounter() {
  let frames = 0;
  let lastTime = performance.now();
  let fps = 0;
  
  function countFrame(currentTime) {
    frames++;
    
    if (currentTime - lastTime >= 1000) {
      fps = Math.round((frames * 1000) / (currentTime - lastTime));
      frames = 0;
      lastTime = currentTime;
      
      console.log(`FPS: ${fps}`);
    }
    
    requestAnimationFrame(countFrame);
  }
  
  requestAnimationFrame(countFrame);
  
  return {
    getFPS: () => fps
  };
}

// Smooth scrolling
function smoothScrollTo(element, targetScrollTop, duration = 800) {
  const startScrollTop = element.scrollTop;
  const distance = targetScrollTop - startScrollTop;
  const startTime = performance.now();
  
  function scroll(currentTime) {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);
    
    // Smooth easing
    const ease = 0.5 - Math.cos(progress * Math.PI) / 2;
    
    element.scrollTop = startScrollTop + distance * ease;
    
    if (progress < 1) {
      requestAnimationFrame(scroll);
    }
  }
  
  requestAnimationFrame(scroll);
}