Getting started

Install Kaji, define an action, run it, and handle the result.

Install

npm install @hiyorios/kaji zod

Kaji validates input with any Standard Schema library, including Zod, Valibot, and ArkType. This guide uses Zod.

Define

A capability is one action your app can perform, with its input, permission check, and the function that does the work.

import { capability } from "@hiyorios/kaji";
import { z } from "zod";

const refundPayment = capability({
  name: "payments.refund",
  input: z.object({
    paymentId: z.string().min(1),
    amount: z.number().positive(),
  }),
  authorize: ({ principalId }) => principalId.startsWith("user_"),
  execute: async ({ paymentId, amount }, context) => {
    // Call your payment provider here.
    return { refundId: `refund:${context.idempotencyKey}`, amount };
  },
});

Create

import { createKaji, memoryStore } from "@hiyorios/kaji";

const kaji = createKaji({ store: memoryStore() });

memoryStore() keeps records in memory for one process. Use it for development and tests. In production, use a store that saves to a database (see Stores).

Run

const outcome = await kaji.execute(refundPayment, {
  input: { paymentId: "pay_123", amount: 50 },
  principalId: "user_123",
  idempotencyKey: "refund_pay_123_v1",
});

You supply principalId (who is asking) and idempotencyKey (a unique ID for this request). Kaji does not generate either one. Retry a request with the same key. Use a new key for a new request.

If the input fails validation, kaji.execute() rejects with an InvalidInputError.

Handle

switch (outcome.status) {
  case "succeeded":
    console.log(outcome.result);
    break;
  case "denied":
  case "rejected":
  case "failed":
  case "cancelled":
    console.error(outcome.error);
    break;
  case "unknown":
    // The action started but may or may not have finished.
    // Check your payment provider before retrying.
    await checkRefundWithProvider(outcome.evidence);
    break;
}

See Outcomes for what each status means.

Approve

To require a person’s sign-off for some requests, add approval to the capability and approve to createKaji().

const refundPayment = capability({
  // name, input, authorize, and execute as above
  approval: ({ input }) => input.amount >= 1_000,
});

const kaji = createKaji({
  store: memoryStore(),
  approve: async (request) => approvalService.request(request),
});

approval returns true when a request needs approval. approve asks your approval system and returns { approved: true } to let the action run. If approval is not given, the action does not run and Kaji returns rejected. See Capabilities for details.