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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@archtx/procedures

v5.0.0

Published

Procedure generator for @archtx

Readme

@archtx/procedures

A TypeScript library for generating type-safe Procedure Calls with built-in schema validation using Suretype or TypeBox.

Features

  • Create type-safe Procedures
  • Built-in schema validation using Suretype/TypeBox
  • Runtime validation of arguments
  • Generated JSON-Schema for Procedures

Installation

npm install @archtx/procedures

Usage

Basic Example

import { Procedures } from '@archtx/procedures'
import { v } from 'suretype'

const { Create } = Procedures()

// Register a query Procedure
const { getUserInfo, getUserInfoSchema } = Create(
  'getUserInfo',
  {
    schema: {
      args: v.object({ userId: v.string().required() }),
      data: v.object({
        name: v.string().required(),
        email: v.string(),
      }),
    },
  },
  async (ctx, args) => {
    // Handle the Procedure call
    return {
      name: 'John Doe',
      email: '[email protected]',
    }
  },
)

// Call the Procedure
const userInfo = await getUserInfo({ userId: '123' })

// view the JSON-schema for the Procedure
console.log(getUserInfoSchema.args, getUserInfoSchema.data)

With Custom Context

You can pass a type to the Procedures<Type>() invokation to require custom context in all procedure calls. The hook function allows you to add local context to the Procedure call. This is useful for adding additional context to the Procedure call, such as authentication tokens or user information.

The context type will be typed in the Procedure handler first argument ctx.

When your procedure has a hook the return value of the hook function will be passed to the Procedure handler by extending the ctx object. This allows you to pass additional context to the Procedure handler.

interface CustomContext {
  authToken: string
}

const { Create } = Procedures<CustomContext>({
  // Procedure handler registration callback
  onCreate: ({ handler, name }) => {
    httpRouter.post(`/Procedure/${name}`, async (req) => {
      return handler({ authToken: req.headers.authorization }, req.body)
    })
  },
})

const { CheckIsAuthenticated } = Create(
  'CheckIsAuthenticated',
  {
    hook: async (ctx, args) => {
      if (validateAuthToken(ctx.authToken)) {
        const user = await getUserFromToken(ctx.authToken)

        return { user }
      }

      throw new Error('Invalid auth token')
    },

    schema: {
      data: v.string(),
    },
  },
  async (ctx, args) => {
    // Access context in handler with type-safety
    console.log(ctx.user)
    return 'User authentication is valid'
  },
)

// Call the Procedure
CheckIsAuthenticated({ authToken: 'valid-token' }, {}) // Returns 'User authentication is valid'
CheckIsAuthenticated({ authToken: 'no-token' }, {}) // Throws 'ProcedureContextError: Invalid auth token'

Retrieving Registered Procedures

const { Create, getProcedures } = Procedures()

// Later in your code
const registeredProcedures = getProcedures()
const userInfoProcedure = registeredProcedures.get('getUserInfo')

Generated JSON-Schema

const { Create, getProcedures } = Procedures()

const { getUserInfo, getUserInfoSchema } = Create(
  'getUserInfo',
  {
    schema: {
      args: v.object({ userId: v.string().required() }),
      data: v.object({
        name: v.string().required(),
        email: v.string(),
      }),
    },
  },
  async (ctx, args) => {
    // Handle the Procedure call
    return {
      name: 'John Doe',
      email: '',
    }
  },
)

console.log(getUserInfoSchema) // { args: JSON-schema; data: JSON-schema }
// or
console.log(getProcedures().get('getUserInfo').config.schema) // { args: JSON-schema; data: JSON-schema }

Procedure Errors

The context provided to each procedure has a built-in error method that can be used to throw errors with a specific error code and message. This is useful for handling errors in a consistent way across all procedures.

import { Procedures, ProcedureCodes } from '@archtx/procedures'

const { Create } = Procedures()

const { getUserInfo } = Create(
  'getUserInfo',
  {
    //...
  },
  async (ctx, args) => {
    if (!isSomeConditionPassing(args)) {
      throw ctx.error(
        ProcedureCodes.PRECONDITION_FAILED,
        'Some condition failed',
        {
          // extra (optional) meta data for the error
        },
      )
    }
    return {
      name: 'John Doe',
      email: '',
    }
  },
)

The lib exports a ProcedureError that can be used:

import { ProcedureError } from '@archtx/procedures'
import { processError } from '@vitest/utils/error'

const procedureError = new ProcedureError(500, 'Internal server error', {
  // this 3rd argument is optional
  extraInfo: '...',
})

processError.procedureName // string
processError.code // number
processError.message // string
processError.meta // object
/**
 * A list of common codes borrowed from HTTP status codes.
 */
enum ProcedureCodes {
  OK = 200,
  CREATED = 201,
  ACCEPTED = 202,
  NO_CONTENT = 204,
  RESET_CONTENT = 205,
  PARTIAL_CONTENT = 206,
  BAD_REQUEST = 400,
  UNAUTHORIZED = 401,
  FORBIDDEN = 403,
  NOT_FOUND = 404,
  NOT_ACCEPTABLE = 406,
  PROXY_AUTHENTICATION_REQUIRED = 407,
  TIMEOUT = 408,
  CONFLICT = 409,
  PRECONDITION_FAILED = 412,
  VALIDATION_ERROR = 422,
  TOO_MANY_REQUESTS = 429,
  INTERNAL_ERROR = 500,
  HANDLER_ERROR = 500,
  NOT_IMPLEMENTED = 501,
  SERVICE_UNAVAILABLE = 503,
}

API Reference

Procedures(options?)

Creates a new Procedure generator instance.

Options

  • onCreate: Callback function called when a new Procedure is registered
    • handler: The Procedure handler function
    • config: Configuration object containing schema and local Procedure context handler
    • name: Name of the Procedure procedure

Create

Object containing methods to register new Procedures.

Methods

  • query(name, options, handler): Register a query Procedure
  • mutation(name, options, handler): Register a mutation Procedure

Note: query and mutation methods are identical, except for the type of Procedure registered. These Procedure "type"'s are used in client implementation to differentiate between query and mutation Procedures. This helps clients support caching calls appropriately if using a cache layer. For example, you can cache
query Procedures but should not cache mutation Procedures.

Options

  • schema:
    • args: Suretype/TypeBox validation schema for arguments
    • data: Suretype/TypeBox validation schema for return data
  • context: Function that returns additional context local to the Procedure call

Error Handling

The library includes built-in validation error handling through the ProcedureValidationError class.

If the Procedure config.args schema exists, the args are validated before the Procedure handler is called. If the validation fails, an ProcedureValidationError is thrown with the validation error message.

Acknowledgements

  • typebox - For providing a great library for generating JSON schema with TypeScript.
  • @suretype/suretype - For providing a great library for runtime type validation.
  • @typeschema - For providing inspiration for the Procedure schema resolver between Suretype or TypeBox.

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.