CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-prisma--get-platform

Platform detection utility for Prisma's internal use that detects operating system, architecture, and Linux distribution information to determine appropriate binary targets for Prisma engines.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

test-utilities.mddocs/

Test Utilities

Comprehensive testing utilities for platform-related functionality. The main package exports Jest utilities through the public API, while additional utilities for Vitest and binary target matching are available in the source but not officially exported through the main package entry point.

Capabilities

Jest Test Context

Complete test context system for Jest-based testing with temporary directories, filesystem utilities, and process mocking.

/**
 * Jest context factory for creating isolated test environments
 */
const jestContext: {
  new(ctx?: BaseContext): ContextBuilder<BaseContext>;
};

/**
 * Base test context interface providing core testing utilities
 */
interface BaseContext {
  tmpDir: string;
  fs: FSJetpack;
  mocked: { cwd: string };
  fixture: (name: string) => void;
  cli: (...input: string[]) => ExecaChildProcess<string>;
  printDir: (dir: string, extensions: string[]) => void;
  tree: (itemPath?: string, indent?: string) => void;
}

Usage Examples:

import { jestContext } from "@prisma/get-platform";

const ctx = jestContext.new().assemble();

beforeEach(() => {
  // ctx.tmpDir is automatically created
  // ctx.fs is bound to the temporary directory
  // process.cwd() is changed to tmpDir
});

afterEach(() => {
  // Original cwd is restored
  // Temporary directory is cleaned up
});

test("platform detection in isolated environment", () => {
  // Use ctx.fs for file operations in tmpDir
  ctx.fs.write("test-file.txt", "content");
  
  // Load a test fixture
  ctx.fixture("platform-test-data");
  
  // Print directory contents
  const files = ctx.printDir(".", [".js", ".ts"]);
  console.log(files);
});

Jest Console Mocking

Console mocking utilities for capturing and testing console output in Jest.

/**
 * Console mocking context contributor for Jest
 */
const jestConsoleContext: <Ctx extends BaseContext>() => ContextContributor<Ctx, ConsoleContext>;

interface ConsoleContext {
  mocked: {
    'console.error': jest.SpyInstance;
    'console.log': jest.SpyInstance;
    'console.info': jest.SpyInstance;
    'console.warn': jest.SpyInstance;
  };
}

Usage Examples:

import { jestContext, jestConsoleContext } from "@prisma/get-platform";

const ctx = jestContext.new()
  .add(jestConsoleContext())
  .assemble();

test("console output capture", () => {
  console.warn("test warning");
  
  expect(ctx.mocked['console.warn']).toHaveBeenCalledWith("test warning");
  expect(ctx.mocked['console.error']).not.toHaveBeenCalled();
});

Jest Process Mocking

Process stdout/stderr and exit mocking for Jest testing.

/**
 * Process output mocking context contributor for Jest
 */
const jestStdoutContext: <Ctx extends BaseContext>(
  settings?: ProcessContextSettings
) => ContextContributor<Ctx, ProcessContext>;

/**
 * Process exit mocking context contributor for Jest
 */
const processExitContext: <C extends BaseContext>() => ContextContributor<C, ProcessExitContext>;

interface ProcessContext {
  mocked: {
    'process.stderr.write': jest.SpyInstance;
    'process.stdout.write': jest.SpyInstance;
  };
  normalizedCapturedStdout: () => string;
  normalizedCapturedStderr: () => string;
  clearCapturedStdout: () => void;
  clearCapturedStderr: () => void;
}

interface ProcessExitContext {
  mocked: { 'process.exit': jest.SpyInstance };
  recordedExitCode: () => number;
}

interface ProcessContextSettings {
  normalizationRules: [RegExp | string, string][];
}

Usage Examples:

import { jestContext, jestStdoutContext, processExitContext } from "@prisma/get-platform";

const ctx = jestContext.new()
  .add(jestStdoutContext({
    normalizationRules: [
      [/\/tmp\/[^/]+/g, '/tmp/normalized'],
      [/\d{4}-\d{2}-\d{2}/g, 'YYYY-MM-DD']
    ]
  }))
  .add(processExitContext())
  .assemble();

test("process output and exit", () => {
  process.stdout.write("test output");
  process.exit(42);
  
  expect(ctx.normalizedCapturedStdout()).toBe("test output");
  expect(ctx.recordedExitCode()).toBe(42);
});

Vitest Test Context

Note: Vitest utilities are available in the source code but not exported through the main package entry point. They would need to be imported from individual source files if used.

Complete test context system for Vitest-based testing, mirroring Jest functionality.

/**
 * Vitest context factory for creating isolated test environments
 */
const vitestContext: {
  new(ctx?: BaseContext): ContextBuilder<BaseContext>;
};

/**
 * Console mocking context contributor for Vitest
 */
const vitestConsoleContext: <Ctx extends BaseContext>() => ContextContributor<Ctx, ConsoleContext>;

/**
 * Process output mocking context contributor for Vitest
 */
const vitestStdoutContext: <Ctx extends BaseContext>(
  settings?: ProcessContextSettings
) => ContextContributor<Ctx, ProcessContext>;

/**
 * Process exit mocking context contributor for Vitest
 */
const vitestProcessExitContext: <C extends BaseContext>() => ContextContributor<C, ProcessExitContext>;

Usage Examples:

import { vitestContext, vitestConsoleContext } from "@prisma/get-platform";
import { beforeEach, afterEach, test, expect } from "vitest";

const ctx = vitestContext.new()
  .add(vitestConsoleContext())
  .assemble();

test("vitest platform testing", () => {
  // Same API as Jest context
  ctx.fs.write("config.json", JSON.stringify({ platform: "test" }));
  
  console.log("test message");
  expect(ctx.mocked['console.log']).toHaveBeenCalledWith("test message");
});

Binary Target Regex

Note: Binary target regex is available in the source code but not exported through the main package entry point.

Regular expression for matching binary target names in strings, useful for testing and string processing.

/**
 * Regular expression that matches all supported binary target names
 * Platform names are sorted by length (descending) to ensure longest match
 */
const binaryTargetRegex: RegExp;

Usage Examples:

import { binaryTargetRegex } from "@prisma/get-platform";

// Extract binary targets from strings
const logMessage = "Downloading engines for darwin-arm64 and linux-musl-openssl-3.0.x";
const matches = logMessage.match(binaryTargetRegex);
console.log(matches);
// ["darwin-arm64", "linux-musl-openssl-3.0.x"]

// Replace binary targets in text
const normalized = logMessage.replace(binaryTargetRegex, "[BINARY_TARGET]");
console.log(normalized);
// "Downloading engines for [BINARY_TARGET] and [BINARY_TARGET]"

// Validate if string contains valid binary targets
function containsValidTargets(text: string): boolean {
  return binaryTargetRegex.test(text);
}

Link Utility

Terminal-friendly link formatting utility for creating clickable links with fallback support.

/**
 * Creates terminal-friendly links with fallback to underlined text
 * @param url - URL to create link for
 * @returns Formatted link string
 */
function link(url: any): string;

Usage Examples:

import { link } from "@prisma/get-platform";

// Create terminal link
const helpLink = link("https://prisma.io/docs");
console.log(helpLink);
// In terminals with link support: clickable link
// In terminals without link support: underlined URL

// Use in error messages
function showError(message: string) {
  console.error(`${message}\nFor help, visit: ${link("https://github.com/prisma/prisma/issues")}`);
}

Context Builder Pattern

The test utilities use a builder pattern for composing test contexts:

interface ContextBuilder<Context> {
  add<NewContext>(contributor: ContextContributor<Context, NewContext>): ContextBuilder<Context & NewContext>;
  assemble(): Context;
}

type ContextContributor<Context, NewContext> = (ctx: Context) => Context & NewContext;

Usage Examples:

// Build complex test context
const ctx = jestContext.new()
  .add(jestConsoleContext())
  .add(jestStdoutContext({ 
    normalizationRules: [[/\d+/g, 'NUMBER']] 
  }))
  .add(processExitContext())
  .assemble();

// Now ctx has all capabilities:
// - Base context (tmpDir, fs, etc.)
// - Console mocking
// - Process output capture with normalization
// - Process exit capture

Testing Best Practices

Isolation: Each test gets a fresh temporary directory and clean mocks

Cleanup: All mocks are automatically restored after each test

Fixtures: Use ctx.fixture() to load predefined test data

Normalization: Use normalization rules to make output predictable across environments

Cross-framework: Same API works for both Jest and Vitest with appropriate imports

Install with Tessl CLI

npx tessl i tessl/npm-prisma--get-platform

docs

binary-targets.md

index.md

node-api-support.md

platform-detection.md

test-utilities.md

tile.json