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

@open-apiary/core

v0.0.8

Published

The runtime. `makeApiary` makes the engine of an API over the bundle that `apiary build` wrote. `invoke` calls one endpoint, and the engine runs it for each call. Neither does HTTP. The public [`open-apiary`](../open-apiary) package re-exports both.

Readme

@open-apiary/core

The runtime. makeApiary makes the engine of an API over the bundle that apiary build wrote. invoke calls one endpoint, and the engine runs it for each call. Neither does HTTP. The public open-apiary package re-exports both.

Install

pnpm add open-apiary zod

The engine

import bundle from "@acme/api";
import document from "@acme/api/openapi.json" with { type: "json" };
import { makeApiary } from "open-apiary";

const apiary = makeApiary(bundle, { document });

| Member | Description | | --------------------------- | --------------------------------------------------------------------------------------------- | | endpoints | The data of each endpoint: id, method, route, status, scopes, tags. A read loads no endpoint. | | endpoint(id) | The data of one endpoint. | | load(id) | Loads one endpoint. The first call imports its route module. A failed load runs again. | | invoke(id, raw, caller) | Loads the endpoint and runs invoke on it. The body is typed from the bundle. | | respond(id, raw, caller) | As invoke, but every error becomes a status and a problem details object. See below. | | document | The OpenAPI document of the options, for the integration to serve. | | check() | Throws UnfilledContractsError when a contract of the bundle has no class. | | register(contract, Class) | Puts a class under a contract, in place of the one of the bundle. For a test. | | dispose() | Disposes the singletons that the calls built. A server calls it when it shuts down. |

The options are authorize, the authorization function of every call, document, container, which replaces the container that the engine makes, onError, which takes each error that respond answers with a 500 for, and challenge, the WWW-Authenticate of a 401, such as Bearer. An id that the bundle lacks is an UnknownEndpointError. A route module whose default export is not an endpoint is an InvalidRouteModuleError.

A framework integration is a wrapper around the engine. It registers one route for each entry of endpoints, turns a request into a raw input and a caller, calls respond, and sends the status, the headers, and the body.

respond answers as HTTP does, and throws for nothing but an id that the bundle lacks:

  • An exception that the endpoint may answer with is its status and its problem details object, as RFC 9457 defines it, with the header content-type: application/problem+json. These are the classes of withExceptions, InvalidInputException for an endpoint with a validator, UnauthorizedException for one that requires a caller, and ForbiddenException for one with scopes. A 401 has the challenge of the options as its www-authenticate header, when the options have one. The class that the endpoint declares sets the status, the title, and the type, so the answer is what the document says. The headers that the class declares go with it, such as the retry-after of a 429.
  • Any other error is a 500 whose problem says nothing of the cause: an error that is no ApiaryException, an ApiaryException that the endpoint does not declare, extensions that the class of the exception rejects, an output that fails its validator, or a route module that fails to load.

onError(error, { id, caller }) takes each error of the second kind. An undeclared ApiaryException comes inside an UndeclaredExceptionError, and rejected extensions inside an InvalidExtensionsError, rejected headers inside an InvalidHeadersError, each with the exception of the handler as its cause. The default writes the error to the log of the API, as an errors.unhandled entry. See The log.

const apiary = makeApiary(bundle, {
  onError: (error, { id }) => logger.error({ err: error, endpoint: id }),
});

One endpoint

import getUser from "@acme/api/routes/getUsersById";
import { invoke, isApiaryException } from "open-apiary";

try {
  const { status, body } = await invoke(
    getUser,
    { path: { id: "42" }, query: {}, headers: {} },
    { scopes: ["users:read"] },
    {
      authorize: (caller, scopes) =>
        scopes.every((s) => caller.scopes.includes(s)),
    },
  );
} catch (error) {
  if (isApiaryException(error)) {
    // error.status, error.code, error.detail, error.extensions
  }
}

invoke runs these steps:

  1. It checks that an endpoint that requires a caller has one: the caller is undefined for a request with none. A failure is UnauthorizedException, status 401. Then it checks the scopes of the endpoint against the caller with authorize. A failure is ForbiddenException, status 403. The default requires every scope of the endpoint in the scopes of the caller.
  2. It parses path, query, headers, and body or form with the validators of the endpoint. A missing path, query, or headers is an empty object. The form of the input is a FormData, or an object with one member for each field. An endpoint with a form validator and an input with no form is UnsupportedMediaTypeException, status 415. A failure is InvalidInputException, status 400. Its errors extension lists the issues of every part: where the value is (in), its JSON Pointer (pointer), and what is wrong with it (detail).
  3. It opens a lifetime of the container and runs the handler with a context: caller, endpoint, and resolve.
  4. It disposes the lifetime, and with it each per-lifetime provider that the handler resolved, whether the handler returned or threw.
  5. It parses the value with the output validator. A failure is InvalidOutputError, which is no ApiaryException: the fault is in the API.

The result is { status, body }. The body is typed from the output validator of the endpoint. invoke checks no exception against withExceptions: an ApiaryException from the handler propagates as it is, and so does any other error. respond is what turns them into answers.

Providers

A handler imports the code that it runs the same way everywhere. What it gets by name is a provider: a contract names it, a class fills the contract, and the handler resolves it.

// src/contracts/users.ts
export const UsersContract = apiary.contract<Users>("users");

// src/providers/users.ts
export default class MemoryUsers implements Users {
  static readonly contract = UsersContract;

  find(id: string) { … }
}

// src/endpoints/users/get.ts
export default apiary
  .GET("/users/{id}", { path: Id }, User)
  .handle((ctx, input) => ctx.resolve(UsersContract).find(input.path.id));

The build writes the classes of the API and of its presets to the bundle, in the order of the layers, and makeApiary provides each one to the container. A later class takes the contract of an earlier one. A server registers nothing:

const engine = makeApiary(bundle);

The bundle also lists the key of each contract. check() throws UnfilledContractsError, with every key that no class fills. An integration calls it when it mounts the engine, and each invoke and respond runs it until it passes, so an open contract is an error at startup and not at the first resolve of it.

register puts a class under a contract in place of the one of the bundle. It is for a test, which sets a fake where the provider was:

const engine = makeApiary(bundle).register(UsersContract, FakeUsers);

A class is a singleton unless it has static readonly perLifetime = true. A singleton is built at the first resolve and kept until dispose(). A per-lifetime provider is built once for each call that resolves it, takes the context of the call in its constructor, and is disposed when the handler ends. A provider that holds a resource has a dispose method. The lifetimes, the errors, and the container itself are in @open-apiary/container.

The log

Every API has a class under LogContract, with no code of its own: makeApiary provides StdoutLog, which writes one line of JSON on the standard output for each entry, with its level, its time, its message, and the members of its data.

A provider that extends Provider has the log as this.log:

import { NotFoundException, Provider } from "open-apiary";

export default class MemoryUsers extends Provider implements Users {
  static readonly contract = UsersContract;

  get(id: string): User {
    const user = this.users.get(id);
    if (user === undefined) {
      this.log.warn("users.missing", { id });
      throw new NotFoundException(`no user with id ${id}`);
    }
    return user;
  }
}

A handler has it on its context, as ctx.log:

.handle((ctx, input) => {
  ctx.log.info("users.read", { id: input.path.id });
  return ctx.resolve(UsersContract).get(input.path.id);
})

Provider is optional: any class with a static contract is a provider. A per-lifetime provider extends Provider<Context> and reads the call from this.ctx. A subclass with a constructor passes the context on with super(ctx).

StdoutLog writes no entry under info. A subclass sets another level with protected override readonly level = "debug".

An API replaces the log as it fills any contract: a class under providers/ whose static contract is LogContract. The log is a singleton, so that a singleton can hold it: a per-lifetime class under the contract is a CaptiveProviderError.

invoke on one endpoint takes the container as an option: invoke(endpoint, raw, caller, { container }). Without one, no contract resolves but the log, which invoke provides to any container that lacks one.