Skip to main content
Home

Built and signed on GitHub Actions

Works with
This package works with Node.js, Deno, BunIt is unknown whether this package works with Cloudflare Workers
It is unknown whether this package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
This package works with Bun
JSR Score100%
Published7 months ago (0.1.2)

Type-safe dynamic runtime state API

Type-safe dynamic runtime state API.

  1. Declare a key for a specific runtime type
  2. Provide the typed data in an async closure
  3. Retrieve data directly in user modules

Examples

End-to-end declare, provide & use summary

import { Context } from "@classic/context";
import { assert } from "@std/assert";

type User = {
  id: bigint;
  name: string;
};

// Shared code - export this key to provider and consumers
export const $user = Context.for<User>("user");

// Provider code
const john = {
  id: 42n,
  name: "John",
};

$user.provide(john, () => {
  // Consumer code - `user` is correctly typed as `User`
  assert($user.use() === john);
});

Use functions: expect context transparently in custom logic

import { Context } from "@classic/context";
import { assert } from "@std/assert";

type User = {
  id: bigint;
  name: string;
};

export const $user = Context.for<User>("user");
export const getUserId = () => $user.use().id;

// Provider code
$user.provide({ id: 42n, name: "John" }, () => {
  // Looks the same, but only exposes read access
  assert(getUserId() === 42n);
});

Safe or optional context access

import { Context } from "@classic/context";
import { assert, assertThrows } from "@std/assert";

export const $sessionId = Context.for<string>("sessionId");

assertThrows(() => $sessionId.use());
assert($sessionId.get() === undefined);
Built and signed on
GitHub Actions

Report package

Please provide a reason for reporting this package. We will review your report and take appropriate action.

Please review the JSR usage policy before submitting a report.