npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@apifn/mock

v0.0.8

Published

Mock server for ApiFn

Readme

@apifn/mock

Mock server for ApiFn. Spin up a framework-free HTTP server from any OpenAPI document that returns realistic responses, optionally validating incoming requests against the spec.

Installation

npm install @apifn/mock

Features

  • Instant mock server — Serve every operation in an OpenAPI spec with no framework
  • Three response modes — Deterministic from schema, from examples, or randomized
  • Request validation — Optionally validate query/path params and JSON bodies against schemas
  • Latency simulation — Add a fixed response delay
  • CORS — Built-in CORS handling with sensible defaults or custom options
  • Safety — Configurable max request body size (default 10 MiB)

createMockServer

import { createMockServer } from "@apifn/mock";
import { parseOpenAPI } from "@apifn/core";
import { readFile } from "node:fs/promises";

const spec = parseOpenAPI(await readFile("./openapi.yml", "utf8"));

const mock = createMockServer({
  spec,
  port: 4010,
  responseMode: "schema", // "schema" | "examples" | "random"
  validateRequests: true,
  delay: 0,
  cors: true,
});

await mock.start();
console.log(`Mock server listening on http://localhost:${mock.port}`);

// later
await mock.stop();

MockServerOptions

| Option | Type | Default | Description | |--------|------|---------|-------------| | spec | OpenAPIDocument | — | The OpenAPI document to mock (required) | | port | number | 4010 | Port to bind (use 0 for a random free port) | | responseMode | "schema" \| "examples" \| "random" | "schema" | How response bodies are generated | | validateRequests | boolean | false | Validate incoming params and JSON bodies | | delay | number | 0 | Response delay in ms (simulate latency) | | maxRequestBodyBytes | number | 10485760 | Max accepted request body size (10 MiB) | | cors | boolean \| CorsOptions | — | Enable/configure CORS |

MockServer

interface MockServer {
  start(): Promise<void>;
  stop(): Promise<void>;
  server: http.Server; // underlying Node server
  port: number;        // the actually-bound port
}

Unmatched routes return 404 { error: "Not Found", path }. OPTIONS preflight requests return 204.


Response Generation

Use the generators directly when you need a mock payload without a server.

generateResponse

Pick the first 2xx response for an operation and produce a body for the given mode.

import { generateResponse } from "@apifn/mock";

const { statusCode, body } = generateResponse(operation, "schema");

generateFromSchema

Deterministic values from a JSON schema — strings become "string" (format-aware for date-time, email, uri, uuid, …), numbers 0, booleans true, arrays a single generated item, objects recurse over their properties.

import { generateFromSchema } from "@apifn/mock";

generateFromSchema({ type: "object", properties: { id: { type: "string", format: "uuid" } } });
// { id: "00000000-0000-0000-0000-000000000000" }

generateRandom

Like generateFromSchema, but produces randomized primitive values. It respects type, string enum, and a small set of formats; it does not currently enforce constraints such as minimum, maximum, minLength, maxLength, pattern, or array bounds.

import { generateRandom } from "@apifn/mock";

const value = generateRandom(schema);

Request Validation

Self-contained JSON-schema validation (no external dependencies).

validateRequestBody

import { validateRequestBody } from "@apifn/mock";

const result = validateRequestBody(body, operation);
// { valid: boolean, errors: ValidationError[] }  where ValidationError = { path, message }

Reads operation.requestBody.content["application/json"].schema; if the body is required but missing, returns an error.

validateParameters

import { validateParameters } from "@apifn/mock";

const result = validateParameters(queryParams, pathParams, operation);

Checks operation.parameters for missing required query/path params and basic numeric coercion.


Exports

export { createMockServer }
export type { MockServer }
export { generateFromSchema, generateRandom, generateResponse }
export type { ResponseMode }
export { validateRequestBody, validateParameters }
export type { ValidationError, ValidationResult }

License

MIT