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/collections

v0.0.8

Published

OpenCollection YAML read/write/run for ApiFn

Readme

@apifn/collections

OpenCollection YAML read/write/run for ApiFn. Read and write portable API request collections, generate them from OpenAPI specs or routers, and run them as a test suite with assertions, scripting, and pluggable reporters.

Installation

npm install @apifn/collections

Features

  • Read / Write — Load and persist an OpenCollection directory (opencollection.yml + per-request YAML + environments)
  • Generate — Produce a collection from an OpenAPI document or a @superfunctions/http router
  • Run — Execute a collection with sequential or parallel scheduling, retries, timeouts, and bail-on-failure
  • Assertions — Chai-like expect/test runtime with JSON Schema and JSONPath support
  • Scripting — Sandboxed pre-request and test scripts (Node vm, no process/require/fetch)
  • Reporters — Console, JSON, JUnit XML, and silent reporters
  • Safety — Secret redaction in captured request/response data, path-traversal-safe writes

Reading & Writing

readCollection

Reads an OpenCollection directory. Expects opencollection.yml at the root; files under environments/ become environments; any YAML with both info and http keys is a request. Items are assembled into a nested folder tree.

import { readCollection } from "@apifn/collections";

const collection = await readCollection("./.apifn/collection");
// { info, environments, items, rootDir }

writeCollection

Persists a Collection back to its rootDir (writes opencollection.yml, environments/*.yml, and each request/folder). Paths are validated against traversal.

import { writeCollection } from "@apifn/collections";

await writeCollection(collection);

validateCollection

Returns ValidationError[] describing structural problems (missing info.name, malformed environments, requests missing http.method, etc.).

import { validateCollection } from "@apifn/collections";

const errors = validateCollection(collection);

Generating Collections

openAPIToCollection

Build a collection from an OpenAPI document. Operations are grouped by tag (default) or first path segment.

import { openAPIToCollection } from "@apifn/collections";

const collection = openAPIToCollection(openApiDoc, {
  baseUrl: "https://api.example.com",
  environmentName: "development",
  groupBy: "tag", // or "path"
  includeExamples: true,
});

routerToCollection

Introspect a @superfunctions/http router and produce a collection in one step.

import { routerToCollection } from "@apifn/collections";

const collection = routerToCollection(router, {
  baseUrl: "https://api.example.com",
  info: { title: "My API", version: "1.0.0" },
});

Path params {id} become {{id}} template variables and URLs are prefixed with {{baseUrl}}.


Running Collections

runCollection

Execute a collection against an environment. Returns a RunReport.

import { readCollection, runCollection, createConsoleReporter } from "@apifn/collections";

const collection = await readCollection("./.apifn/collection");
const report = await runCollection(collection, {
  environment: "development",
  reporter: createConsoleReporter(),
  parallel: false,
  bail: false,
  retries: 1,
  timeout: 30_000,
});

console.log(report.summary);
// { total, passed, failed, skipped, errors, duration }

RunOptions

| Option | Type | Description | |--------|------|-------------| | environment | string \| Environment | Environment name or object (required) | | include / exclude | string[] | Glob-ish patterns matched against path/name/"METHOD url" | | includePaths | string[] | Exact collection-relative request paths to run | | parallel | boolean | Run requests concurrently (default: sequential) | | concurrency | number | Max concurrent requests in parallel mode (default: 4) | | timeout | number | Per-request timeout in ms (default: 30000) | | bail | boolean | Stop on first failure | | retries | number | Retry network errors and HTTP 5xx responses (default: 0) | | delay | number | Delay between sequential requests in ms | | httpClient | HttpClient | Custom client (default: built-in fetch-based) | | cookieJar | CookieJar | Shared cookie jar | | reporter | RunReporter | Progress/result reporter | | overrides | Record<string, string> | Variable overrides (highest precedence) | | processEnv | NodeJS.ProcessEnv | Explicit values for {{process.env.NAME}} (default: empty) | | allowScripts | boolean | Execute scripts from a trusted collection (default: false) | | redactHeaders | string[] | Extra headers to redact in captured data |

A request passes when its status matches the expected status (default < 400, or settings.expectedStatus) and no assertion fails.

Redaction: authorization, cookie, set-cookie, x-api-key, and x-auth-token headers are redacted by default (plus any redactHeaders), and common secret-bearing body keys (token, password, apiKey, otp, …) are recursively masked.


Reporters

| Reporter | Factory | Output | |----------|---------|--------| | Console | createConsoleReporter({ color?, write? }) | Colored per-request badges + summary | | JSON | createJsonReporter({ write?, indent? }) | Full RunReport as JSON | | JUnit | createJUnitReporter({ write? }) | JUnit XML (reportToJUnitXml(report) for a string) | | Silent | createSilentReporter() | No output |

import { runCollection, createJsonReporter } from "@apifn/collections";

await runCollection(collection, {
  environment: "development",
  reporter: createJsonReporter({ indent: 2 }),
});

Assertions

createAssertionRuntime() returns a Chai-like expect/test API used inside test scripts.

import { createAssertionRuntime } from "@apifn/collections";

const { expect, test, getResults } = createAssertionRuntime();
const response = {
  status: 200,
  body: { id: "usr_123", roles: ["admin"], profile: { email: "[email protected]" } },
  responseTime: 120,
};

test("returns the user", () => {
  expect(response.status).to.equal(200);
  expect(response.body).to.have.property("id");
  expect(response.body.roles).to.include("admin");
  expect(response.body).to.have.jsonPath("$.profile.email");
  expect(response.responseTime).to.be.below(500);
});

const results = getResults(); // AssertionResult[]

Supported matchers: .equal, .include, .matchSchema, .have.property, .have.length / .have.length.above, .have.jsonPath, .be.below.


Scripting

The runner rejects selected requests that contain scripts before sending any HTTP requests. Set allowScripts: true only when you trust the scripts as fully as local code. The Node vm context exposes host objects, and its 10-second synchronous execution limit cannot bound asynchronous work.

import { executePreRequestScript, executeTestScript } from "@apifn/collections";

Use these helpers directly only with trusted script code.

  • executePreRequestScript({ code, env, req, cookies?, timeoutMs? }) — mutate req, set env variables before sending
  • executeTestScript({ code, env, req, res, cookies?, assertionResults, timeoutMs? }) — assert against res with expect/test

Environments & Variables

import {
  readEnvironments,
  selectEnvironment,
  interpolateVariables,
  resolveVariableContext,
  loadDotEnvFile,
} from "@apifn/collections";

const envs = await readEnvironments("./.apifn/collection/environments");
const env = selectEnvironment(envs, "development");

const context = resolveVariableContext({
  collection: {},
  environment: env.variables, // collection < environment < overrides
  overrides: loadDotEnvFile(".env"),
});

const { value, warnings } = interpolateVariables(
  "{{baseUrl}}/users?token={{process.env.API_TOKEN}}",
  context,
  { processEnv: { API_TOKEN: process.env.API_TOKEN } },
);

{{var}} tokens are replaced from the context. Unknown context tokens are left intact and reported in warnings. {{process.env.X}} requires an explicit value for X in the processEnv option and throws if the value is missing.


HTTP Client & Cookies

import { createFetchHttpClient, createCookieJar } from "@apifn/collections";

const jar = createCookieJar();
const client = createFetchHttpClient({ cookieJar: jar, followRedirects: true, maxRedirects: 10 });

The built-in fetch client handles redirects manually, strips sensitive headers on cross-origin redirects, downgrades 303 to GET, and injects/stores cookies via the jar.

License

MIT