Skip to content
View senseikatana's full-sized avatar

Block or report senseikatana

Block user

Prevent this user from interacting with your repositories and sending you notifications. Learn more about blocking users.

You must be logged in to block users.

Content in all repositories owned by your account will be closed.
Maximum 250 characters. Please don’t include any personal information such as legal names or email addresses. This note will only be visible to you.
Report abuse

Contact GitHub support about this user’s behavior. Learn more about reporting abuse.

Report abuse
senseikatana/README.md

SenseiKatana

The main repository for the SenseiKatana website, its documentation and the KatanaKit JS toolkit.

GitHub release License: MIT Astro TypeScript Bun Docs Last commit

A framework-agnostic TypeScript toolkit for the services most projects need: typed HTTP, validation, caching, reactive signals, authorization, currency conversion, and browser utilities. It ships ESM, is safe to import during SSR, and keeps every optional framework integration on its own package entry point — so a Vue app never pulls React, and a server build never pulls the DOM.

Documentation · Getting started · Tutorial · API reference · Changelog · Release history


Installation

npm install katanakit-js
# or
bun add katanakit-js
# or
pnpm add katanakit-js

Requires Node.js >= 22.18 or Bun >= 1.2. Runtime dependencies are zod, @tanstack/query-core and @js-temporal/polyfill. Prisma and Drizzle ORM are only needed for their optional subpaths — bun add @prisma/orm-postgres, or bun add drizzle-orm pg.

Framework integrations are optional peers. Install the one you need:

bun add better-auth @insforge/sdk   # only if you use those adapters
bun add express hono                 # only if you run a server

See the installation guide for CDN usage and integration requirements.


Getting started

Three steps: configure the client once, call it, branch on the result. Nothing throws for an expected failure.

import { defineApiConfig, onGet } from 'katanakit-js';

// 1. Declare the API once, at module scope.
defineApiConfig({
  pokeapi: {
    baseUri: 'https://pokeapi.co/api/v2',
    endpoints: { pokemonById: '/pokemon/:id/' },
  },
});

// 2. Call it. The path params are typed from the endpoint name.
const result = await onGet<{ name: string }>('pokeapi', 'pokemonById', {
  params: { id: 25 },
});

// 3. Branch. `result.ok` narrows the union for you.
if (result.ok) {
  console.log(result.data.name); // "pikachu"
} else {
  console.error(result.error.message);
}

Options-style config

The same literal also accepts Vue-Options-style sections when you want the whole client in one object — apis to register, data() for mutable state, onInit for one-time setup, and methods for callable requests:

import { defineApiConfig, onFetch } from 'katanakit-js';

export default defineApiConfig({
  apis: {
    pokeapi: {
      baseUri: 'https://pokeapi.co/api/v2',
      endpoints: { pokemonById: '/pokemon/:id/' },
    },
  },
  data: () => ({ calls: 0 }),
  onInit() {
    // Runs once, after registration. Synchronous on purpose.
  },
  methods: {
    async getPokemon(id: number) {
      this.data.calls += 1;
      return onFetch('pokeapi', 'pokemonById', { params: { id } });
    },
  },
});

Flat entries keep working — the sections are additive. data is plain mutable state (not reactive), and onInit runs while the module is evaluated, so async work belongs in a method. apis, data, onInit and methods are reserved names.

Safe Results

This is the convention the whole toolkit follows. A fallible operation returns a discriminated union instead of throwing, so a try/catch around a network call is never the interesting part of your code:

type SafeResult<T, E> = { data: T; error: null; ok: true } | { data: null; error: E; ok: false };

ok: false means the call failed. data: null with ok: true means it succeeded and the answer is legitimately nothing — a missing record is not an error, and the two are never collapsed into one.

The error handling guide covers the error shapes and the helpers that build them.

Validate at the boundary

Parsing an untrusted payload is the one thing worth doing every time. It turns a runtime surprise into a compile-time error:

import { onValidate } from 'katanakit-js';
import { z } from 'zod';

const Pokemon = z.object({
  id: z.number(),
  name: z.string(),
  types: z.array(z.object({ type: z.object({ name: z.string() }) })),
});

const parsed = onValidate(Pokemon, await result.data);

if (parsed.ok) {
  parsed.data.types[0]?.type.name; // fully typed
} else {
  console.error(parsed.error.message);
}

What it includes

Currency conversion — ECB reference rates

Convert an amount between two currencies in one call. Rates come from Frankfurter (ECB daily reference rates, no API key), every call returns a Safe Result and never throws, and the rate source is a port — swap in a live-market provider when you need one:

import { onConvertCurrency, onFormatCurrency } from 'katanakit-js';

const result = await onConvertCurrency({ amount: 100, from: 'USD', to: 'EUR' });
if (result.ok) {
  result.data.converted; // 88.87 — money: exactly 2 decimals (symmetric rounding)
  result.data.rate; // 0.88865 — full precision from the source
  result.data.date; // the day the ECB rate belongs to

  // Conversion and formatting are separate concerns — compose them:
  onFormatCurrency({ amount: result.data.converted, currency: 'EUR', locale: 'es', digits: 2 });
  // "88,87 €"
}

These are reference rates, not intraday forex quotes: published around 14:15 CET on working days, with no bid/ask spread. 33 currencies typecheck — all the majors (USD, EUR, GBP, JPY, CHF, CAD, AUD, NZD) and the usual traded set. ARS, COP and CLP format fine but are not covered by the default source, so those pairs return an explicit error instead of a wrong number. Pairs are resolved by dividing through a pivot currency, so a small quote never loses precision and both directions are exactly reciprocal. Subscribe to rate updates with onSubscribeRates(), or implement ICurrencyRateProvider and inject it for live quotes.

→ Currency conversion guide

Authorization — roles, capabilities and resource grants

A role says what class of thing a person may ever do. A grant says whether they may do it to this one thing. Both are needed the moment you share a document with one person and not with everybody else.

import { onCan, onRegisterRole } from 'katanakit-js';

// The built-in ladder is owner > admin > editor > author > member > guest,
// and each role inherits everything below it.
onCan({ id: 1, roles: ['editor'] }, 'content:publish'); // true
onCan({ id: 2, roles: ['author'] }, 'content:edit:any'); // false

// Register a role for your own domain. Roles and capabilities are open
// strings, not a closed enum — `nomina:aprobar` is a legal capability.
onRegisterRole({
  slug: 'rrhh',
  label: 'RRHH',
  rank: 4,
  capabilities: ['nomina:aprobar'],
});

Then resolve against a specific resource. Global roles are checked first, then grants scoped to that resource:

import { onGrantAwareCan } from 'katanakit-js';

const decision = onGrantAwareCan({
  subject, // from onResolveSubject()
  resource: { type: 'expediente', id: 42 },
  capability: 'expediente:read',
  onGrants: ({ subject, resource }) => listShares(subject.id, resource),
});

decision.allowed; // boolean
decision.source; // "role" | "grant" | "none" — why, for your audit log

Storage is injected, never assumed: the kit ships the contract, your table holds the rows. Expired grants are evaluated by the core, so revoking access means deleting one record.

Pair it with a directory that refuses to lock you out:

import { DirectoryService } from 'katanakit-js';

const directory = new DirectoryService({ repository });
const result = await directory.suspend(actor, id, 'contract ended');

if (!result.ok) {
  // "last_owner", "self_suspension", "privilege_escalation", ...
  console.error(result.error.code, result.error.message);
}

The last active holder of a role cannot lose it, nobody can suspend or demote themselves, and owner is never assigned through these paths.

→ Access control guide

Authentication — one port, any provider

Identity, credential and authorization are three different things. The kit normalizes the first two into a single Principal so the third never has to know which provider produced it:

import { AuthService, onResolveSubject } from 'katanakit-js';
import { onBetterAuthProvider } from 'katanakit-js/adapters/better-auth';

AuthService.getInstance().register(onBetterAuthProvider(auth));

// The seam between authentication and authorization. The role lookup is
// yours, so the core stays free of I/O.
const subject = await onResolveSubject('better-auth', request, (principal) =>
  directory.rolesFor(principal.subject),
);

if (!subject.ok) return response.status(500).end(); // the provider is broken
if (!subject.data) return response.status(401).end(); // anonymous
// subject.data is now an AccessSubject with roles

Swap the provider, keep the rest of the app. InsForge, Better Auth, or your own national-identity integration — they all implement the same IAuthProvider.

An anonymous visitor is { ok: true, data: null }, not an error. Only a real failure is ok: false. Flattening those two turns a broken provider into a publicly readable route.

→ Better Auth guide · InsForge guide

katanakitAI — API keys, MCP and agent config

One encrypted vault for AI provider keys, MCP server registration and per-agent configuration. Local-first: scrypt + AES-256-GCM at rest, masked secrets everywhere except an explicit reveal, and encrypted backups you can store anywhere. Run it as kai (installed) or without installing via npx katanakit-js / bunx katanakit-js.

kai keys add openai --label ci            # secret via --secret or stdin
kai mcp add context7 --url https://mcp.context7.com/mcp
kai agents config opencode --key <id>     # auto config + manual connection
kai keys export --out ~/backups/keys.enc.json

See katanakitAI for the full guide.

Reactive signals

Framework-free reactivity with automatically tracked dependencies. No build step, no decorators, no runtime dependency:

import { onCreateEffect, onCreateMemo, onCreateSignal } from 'katanakit-js';

const [count, setCount] = onCreateSignal(0);
const doubled = onCreateMemo(() => count() * 2);

onCreateEffect(() => {
  console.log('now', doubled()); // re-runs only when `count` actually changes
});

// setCount((n) => n + 1);

Works identically in Node and in the browser — the effect simply does not run where there is no DOM to update.

→ Reactive guide

Framework adapters

One import path per runtime, so a bundle only ever contains what it uses:

import { onQuery } from 'katanakit-js/adapters/vue';
import { onRequireCapability } from 'katanakit-js/adapters/express';
import { onAuthClient } from 'katanakit-js/adapters/better-auth';

Available entry points: express, hono, bun, nestjs, nuxt, vue, astro, next, react, solid, svelte, angular, vanilla, better-auth, insforge, drizzle, assistant, notion, wordpress, photoswipe, plus /schemas, /prisma and /styles.css.

→ Framework adapters

Typed HTTP, dates, arrays and more

import { DatesService, onDateAdd, onDateBetween, onDateOrder } from 'katanakit-js';

DatesService.getInstance().format('2026-03-01', 'es', { dateStyle: 'long' }); // "1 de marzo de 2026"
onDateAdd('2026-03-01', 30, 'days'); // "2026-03-31"
onDateBetween('2026-03-01', '2026-04-01', 'days'); // 31
onDateBetween('2026-03-01', '2026-04-01', 'months'); // 1
onDateOrder('2026-04-01', '2026-03-01'); // "after"

onDateBetween() is signed and never fractional, and its units are the ones Notion uses in its formula editor — years, quarters, months, weeks, days, hours, minutes.

→ All services

Native forms, validated with Zod

import { Form, Field, Input, Submit } from 'katanakit-js/adapters/react';

<Form schema={SignUpSchema} onSubmit={(values) => signUp(values)}>
  <Field name="email" label="Email" hint="Only used for receipts.">
    <Input type="email" autoComplete="email" required />
  </Field>
  <Submit pendingLabel="Creating account…">Create account</Submit>
</Form>;

Fields stay uncontrolled — typing re-renders nothing — and the schema you already write decides the messages. Errors render inside each field with aria-invalid + aria-describedby, the first invalid field takes focus, and the submit button reports aria-busy until an async onSubmit settles. No react-hook-form, no resolvers: FormData in, typed values out.

→ Forms guide

One service shape

Every core service is a Singleton facade class — getInstance() plus descriptive methods — with thin module-level on* helpers in the same module for the common calls. Both styles reach the same instance, so the call shape does not change between FormatterService, UnitConverterService and CurrencyConverterService. Pure class methods keep plain names (filter, get, can); side-effecting helpers use on<Name> (onFetch, onLogger, onInitTheme). The pattern vocabulary is small and fixed: Singleton, Facade, Observer, Strategy and Dependency Injection (create() builds an isolated instance with injected collaborators).

import { AccessService, ArrayService, FetchApiManager } from 'katanakit-js';

ArrayService.getInstance().filter(products, (product) => product.inStock);
AccessService.getInstance().can(subject, 'content:publish');
await FetchApiManager.getInstance().get('pokeapi', 'pokemonById', { params: { id: 25 } });

→ Service architecture


Examples

These patterns take more than a single call. Each example is embedded here, so it stays next to the API it documents.

Query cache with React
import { onGet, defineApiConfig } from 'katanakit-js';
import { onQuery, onSafeQueryFn } from 'katanakit-js/adapters/react';

defineApiConfig({
  pokeapi: {
    baseUri: 'https://pokeapi.co/api/v2',
    endpoints: { pokemonById: '/pokemon/:id/' },
  },
});

function PokemonCard({ id }: { id: number }) {
  const { data, isPending, isFetching, isError, error } = onQuery({
    queryKey: ['pokemon', id],
    queryFn: onSafeQueryFn(() =>
      onGet<{ name: string }>('pokeapi', 'pokemonById', { params: { id } }),
    ),
    staleTime: 60_000,
  });

  if (isPending) return <p>Loading…</p>;
  if (isError) return <p role="alert">{error.message}</p>;

  return (
    <article>
      <h2>{data?.name}</h2>
      {isFetching && <small>refreshing…</small>}
    </article>
  );
}

The other adapters expose the same onQuery / onSafeQueryFn pair with their own reactivity bridge: vue, solid, svelte, angular and vanilla.

Assistant endpoint with tools
import { mkdir, readFile, appendFile } from 'node:fs/promises';
import { dirname, join, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';

import { onInitAssistant, type AiTool } from 'katanakit-js';
import { onStartAssistant } from 'katanakit-js/adapters/assistant';

const dataDir = join(dirname(fileURLToPath(import.meta.url)), 'data');
await mkdir(dataDir, { recursive: true });

function confine(requested: string): string | null {
  const candidate = resolve(dataDir, requested);
  return candidate === dataDir || candidate.startsWith(dataDir + sep) ? candidate : null;
}

const tools: AiTool[] = [
  {
    name: 'readFile',
    description: 'Reads a document from the local knowledge base.',
    parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },
    execute: async (input) => {
      const path = confine((input as { path: string }).path);
      return path ? readFile(path, 'utf8') : { error: 'Path outside the knowledge base.' };
    },
  },
  {
    name: 'saveNote',
    description: 'Appends a note for a human follow-up.',
    parameters: { type: 'object', properties: { note: { type: 'string' } }, required: ['note'] },
    execute: async (input) => {
      const note = (input as { note: string }).note;
      await appendFile(join(dataDir, 'notes.jsonl'), `${JSON.stringify({ note })}\n`);
      return { saved: true };
    },
  },
];

onInitAssistant({ tools, maxSteps: 6 });
onStartAssistant(Number(process.env.PORT ?? 3000));
// POST /assistant/chat { "message": "What are your hours?" }

onStartAssistant() mounts the router and starts Express. Use onCreateAssistantRouter() when the app already owns the server. See the katanakitAI guide.

Deterministic seed data
import {
  onFakeDate,
  onFakeEmail,
  onFakeFullName,
  onFakeList,
  onFakeSeed,
  onFakeSetDefaultRefDate,
  onFakeUuid,
  onEnsureDir,
  onGetDirname,
  onJoinPath,
  onWriteJsonFile,
} from 'katanakit-js';

await onFakeSeed(42);
await onFakeSetDefaultRefDate('2026-01-01');

const users = await onFakeList(
  async () => ({
    id: await onFakeUuid(),
    fullName: await onFakeFullName(),
    email: await onFakeEmail(),
    createdAt: (await onFakeDate('2024-01-01')).toISOString(),
  }),
  5,
);

const outDir = await onJoinPath(await onGetDirname(import.meta.url), 'out');
await onEnsureDir(outDir);
const written = await onWriteJsonFile(await onJoinPath(outDir, 'users.json'), users);
if (!written.ok) throw new Error(`[${written.error.code}] ${written.error.message}`);

Same seed + same reference date + same call order = byte-identical files. onFakeList receives the zero-based index, which is what makes relations (users[index % users.length]) reproducible.

Dashboard shell from the UI kit
import { onAlert, onBadge, onCard, onTabs, toast } from '@katanakit/ui';
import { onAppend, onGetElementById, onSetHtml } from 'katanakit-js';

const mount = (id: string, ...nodes: HTMLElement[]) => {
  const host = onGetElementById(id);
  if (!host) throw new Error(`Missing #${id}`);
  onSetHtml(host, '');
  for (const node of nodes) onAppend(host, node);
};

const stats = [
  { label: 'Revenue', value: '$48,290', delta: '+12.4%', variant: 'success' as const },
  { label: 'Orders', value: '1,284', delta: '+3.1%', variant: 'info' as const },
];

mount(
  'stats',
  ...stats.map((stat) =>
    onCard({
      elevated: true,
      children: [
        `${stat.label}: ${stat.value}`,
        onBadge({ label: stat.delta, variant: stat.variant }),
      ],
    }),
  ),
);

mount('alert', onAlert({ variant: 'info', message: 'Figures are mocked.', dismissible: true }));

const tabs = onTabs({
  label: 'Overview',
  tabs: [
    { id: 'revenue', label: 'Revenue', content: '…' },
    { id: 'activity', label: 'Activity', content: '…' },
  ],
  onChange: (id) => toast.info(`Showing ${id}.`),
});
mount('tabs', tabs.root);

The component factories own markup, focus handling and ARIA state; the services own DOM, theme, timing and observer wiring.


Boilerplates and gists

Copy-paste starting points, kept in sync with this repository. Each one is a complete file set with a README, and each was verified by building it against the version it names.

Boilerplates

Ready-to-run project scaffolds using katanakit-js where it removes boilerplate.

Gist What it scaffolds
Nuxt 4 nuxt.config.ts, runtimeConfig vs app.config, route rules, error page, API routes with onEventResponse / onUnwrap
Astro 7 Content collections, getStaticPaths with pathsFrom, pagination, tag pages, RSS endpoint
React 19 + Vite 8 createRoot, error boundary, onQuery + onSafeQueryFn, mutations, typed env
VS Code snippets 36 whole-file scaffolds — type nuxt-config, astro-static-paths, react-main, …

Standalone source

Single-file extracts of the services, for reading and adapting without installing anything. Useful when you want the source in front of you; prefer the package otherwise.

Gist Covers
DOM SSR-safe element helpers, sanitised attribute writes
Dates Temporal calendar arithmetic
API Manager Named endpoints, interceptors, Safe Results
Reactive Core Signals, effects, memos, batching
Safe Result Errors as values
Query Adapters TanStack Query bindings for React, Vue, Svelte, Solid, Angular

The same links live in the docs sidebar under Boilerplates.


Documentation

The site follows Diátaxis: one page, one kind.

Kind Where Read it when
Tutorial first-api-client You are learning the toolkit end to end
How-to guides You know the goal and need the steps
Reference API reference You need exact signatures
Explanation why KatanaKit · decisions You want the reasoning behind a choice

Architecture decisions are recorded as ADRs and are never rewritten — see the decisions index.


Contributing

git clone https://github.com/senseikatana/katanakit-js.git
cd katanakit-js
git checkout dev
bun install
bun run check   # ESLint, typechecks, tests

Keep changes focused, add or update tests, and update the relevant docs with any public API change. Read CONTRIBUTING.md for the architecture rules, coding conventions and release workflow. To report a vulnerability, see SECURITY.md.

License

MIT

Pinned Loading

  1. senseikatana senseikatana Public

    My Personal Github Repository to show everything whatever I'm doing right now

    Astro 1