@xtandard/entitlements
The root entry point: the engine (createEntitlements), the pure resolver,
periods, the data model, and the storage / counter / hook contracts.
Drivers, billing providers, adapters and UI live behind their own subpaths
(e.g. @xtandard/entitlements/counters/redis); the catalog DSL is also
importable alone from @xtandard/entitlements/catalog (zero dependencies).
import { createEntitlements } from "@xtandard/entitlements";import { defineCatalog, feature } from "@xtandard/entitlements/catalog";
const catalog = defineCatalog({ features: { api_calls: feature.metered({ reset: "month" }), export_pdf: feature.boolean() }, plans: { free: { default: true, features: { api_calls: 1_000 } }, pro: { features: { api_calls: 100_000, export_pdf: true } }, },});
const ent = createEntitlements({ catalog });const decision = await ent.consume("org_42", "api_calls");// { allowed: true, reason: "within_limit", remaining: 999, resetsAt: "2026-12-01T00:00:00.000Z", … }import { … } from "@xtandard/entitlements";Also re-exports symbols of @xtandard/entitlements/catalog, documented on those pages.
Functions
Section titled “Functions”| Name | Summary |
|---|---|
addMonthsClamped |
anchor shifted by months, with the day clamped to the target month’s length. |
anchoredMonth |
The monthly window anchored on anchor that contains now. |
assertAmount |
Throws when an amount is not a finite number. |
buildLegs |
The legs for feature. A metered feature with creditCost that no plan includes is governed by its credit pools only (its own counter is record-only). |
buildOpenApiDocument |
Build the OpenAPI 3.1 document for the panel API. Every route of docs/HTTP_API.md is present; admin routes carry their authorization action as x-action. |
buildOverview |
The admin overview. Walks every stored customer (fine for admin dashboards; O(customers) state reads). |
catalogView |
The admin catalog view (every plan version, hidden plans included). |
computeApplied |
The pure decision every driver implements atomically: given the current value, how much of amount applies under options. Exported so drivers (and their tests) share one definition. |
createEntitlements |
Create the engine. |
createFetchHandler |
Build the panel fetch handler. |
createPortalToken |
Mint a portal token for customer, valid for expiresIn (default 1 hour). Call this server-side, after your own authentication — anyone holding the portal secret can mint tokens for any customer. |
currentPeriod |
The usage window for reset at now. |
denialOf |
The JSON body and status for a denied decision ({ error, ...CheckResult }). |
denialResponse |
A web Response for a denied decision (402 / 403 JSON). |
emit |
Invoke listener without awaiting it; sync throws and rejections go to onError. |
emptyCustomerState |
An empty state for a customer that has never been written (default plans only). |
evaluateGuard |
Run the guard for one request context. Never throws for a denial; errors from the customer / amount resolvers or the engine propagate. |
isBufferedCounterStore |
True when store is a BufferedCounterStore. |
isMutatingAction |
True if the action writes control-plane state. |
legState |
Compute a leg’s usage from counter values. |
newId |
A new id: prefix + _ + 22 lowercase base32 chars (sorts by creation time). now (unix ms) defaults to Date.now(); ids minted in the same millisecond (or under a clock that went backwards) still sort in creation order. |
parseInput |
Validate input against schema; return the typed output or throw an InputValidationError listing every issue. |
pgListenNotify |
A WatchSubscribe backed by Postgres LISTEN/NOTIFY. Pair with withWatch for the postgres or drizzle-over-pg adapters. Your migration owns the trigger that pg_notifys channel with the changed key as payload; this only LISTENs. |
requirePeer |
Helper for adapters whose subpath requires an optional peer dependency. Throws a clear, actionable error when the peer is missing. |
resolveEntitlements |
Resolve a customer’s entitlements at now. state may be null (an unknown customer — default plans only). |
subscriptionInactiveReason |
Why a subscription is not entitled at now, or null when it is. |
takeLegs |
Atomically take units across the legs. Modes for settling work that already happened: force records any shortfall on the allowance counter past its limit; bestEffort keeps whatever fit and reports success. |
unlockingPlans |
Plans and add-ons (current versions, not hidden, not already active; add-ons only when their requires is met by activePlans) that would allow feature — for numeric features, a total of needed units. Cheapest first (by monthly-normalized display price), then catalog order. |
verifyPortalToken |
Verify a portal token: format, signature (constant time), then claims and expiry. Returns the granted customer and scope; throws PortalTokenError otherwise. |
Classes
Section titled “Classes”| Name | Summary |
|---|---|
BillingVerificationError |
Thrown by BillingProvider.parseWebhook for bad signatures / payloads (HTTP 400). |
EntitlementDeniedError |
Thrown by require / consumeOrThrow; carries the decision. Adapters map it to 402 / 403. |
EntitlementsValidationError |
Invalid input to an engine operation (maps to HTTP 400). |
InputValidationError |
Input failed schema validation. An EntitlementsValidationError (so it maps to HTTP 400) carrying the individual issues — the API answers 400 { error, issues }. |
NotFoundError |
A referenced customer / subscription / grant / override / reservation does not exist (404). |
ReadonlyError |
Thrown by mutating operations when the engine is readonly. |
Interfaces
Section titled “Interfaces”| Name | Summary |
|---|---|
ActivePlan |
A plan currently applying to the customer. |
ActivityEntry |
A control-plane activity entry (per customer; also fed to hooks / audit). |
Actor |
Who made a control-plane change. |
ActorOptions |
Per-call actor attribution for control-plane operations. |
BillingProvider |
A billing provider adapter. |
BillingWebhook |
A verified, parsed webhook. |
Bucket |
One counter a leg may draw from. |
BufferedCounterStore |
A buffered counter store: a CounterStore plus explicit flush. |
CatalogView |
GET /api/catalog. |
CheckOptions |
Options for Entitlements.check. |
CheckoutInput |
Input to BillingProvider.createCheckout. |
CheckResult |
The answer to check / consume / reserve. |
ConsumeOptions |
Options for Entitlements.consume. |
CounterAddOptions |
Options for CounterStore.add. |
CounterAddResult |
Result of CounterStore.add. |
CounterStore |
An atomic counter backend. Missing keys read as 0. |
CreateFetchHandlerResult |
Return shape of createFetchHandler. |
CustomerClient |
A client bound to one customer. |
CustomerEntitlements |
entitlements(customer): resolved set + usage for every feature. |
CustomerState |
Everything stored for one customer (state storage, customers/{id}). |
CustomerSummary |
One row of Entitlements.listCustomers. |
Entitlements |
The engine. |
EntitlementsBilling |
The billing intake bound to an engine — what the panel’s POST /webhooks/:provider, /api/portal/checkout|manage and /api/customers/:id/reconcile routes call. |
EntitlementSet |
A customer’s resolved entitlements (ADR 0003: cached per customer). |
EntitlementsOptions |
Options for createEntitlements. |
EntitlementSource |
Where part of a feature’s entitlement came from. |
EntitlementsPanelOptions |
Options for the panel handler (shared by every framework adapter). |
EntitlementsPortalOptions |
Portal composition for the panel: verifies entpt_… bearer tokens (ADR 0010). |
FeatureUsage |
A per-feature usage snapshot (UI, portal, entitlements()). |
Grant |
A balance added to a metered / credits / capacity feature (ADR 0005). |
GrantBucket |
A one-off grant bucket, in consumption order. |
GrantInput |
Input to Entitlements.grant. |
Leg |
One feature’s share of a request. |
LegState |
Usage of one leg, from its counters. |
OpenApiOptions |
Options for buildOpenApiDocument. |
Override |
An operator exception for one feature (comp, raise a limit, disable). ADR 0009/0012. |
OverrideInput |
Input to Entitlements.override. |
Overview |
GET /api/overview. |
PanelConfig |
GET /config — the SPA bootstrap (public). |
PeriodAnchor |
Billing-period inputs for currentPeriod. |
PortalSessionInput |
Input to BillingProvider.createPortalSession. |
PortalTokenClaims |
What a verified token grants. |
PortalTokenOptions |
Options for createPortalToken. |
PortalView |
GET /api/portal/me. |
ProviderItem |
One line item of a provider subscription (a price / product / variant id). |
ProviderSubscription |
A provider subscription, normalized. |
ReconcileResult |
Result of EntitlementsBilling.reconcile. |
RequireEntitlementOptions |
Options shared by every framework’s requireEntitlement guard. |
Reservation |
A reservation from reserve (ADR 0005). |
ReserveOptions |
Options for Entitlements.reserve. |
ReserveResult |
Result of Entitlements.reserve. |
ResolvedFeature |
One feature, resolved for one customer at one instant (no usage yet). |
ResolveOptions |
Options for resolveEntitlements. |
SettleOptions |
Options for Entitlements.settle. |
SubscribeInput |
Input to Entitlements.subscribe (manual plan changes). |
Subscription |
A subscription to a plan or add-on, from any provider (or "manual"). |
SubscriptionInput |
Input to Entitlements.upsertSubscription. |
Take |
A completed counter take. |
TakeResult |
Result of takeLegs. |
ThresholdEvent |
Usage crossed threshold × limit for the current period. |
UpsertSubscriptionResult |
Result of Entitlements.upsertSubscription. |
UsageEvent |
One usage change. amount is negative for releases / refunds. |
UsagePeriod |
The current usage window of a metered / credits feature. |
UsageRecord |
A usage record to push to a provider meter (optional usage export). |
Type aliases
Section titled “Type aliases”| Name | Summary |
|---|---|
AfterEvent |
Events delivered to after hooks (committed). |
AfterEventType |
|
AuthorizationProvider |
Decides whether an action is permitted. |
AuthorizeInput |
Input passed to AuthorizationProvider.authorize. |
BeforeEvent |
Events delivered to before hooks (the mutation has not happened yet). |
BeforeEventType |
The discriminant strings of BeforeEvent / AfterEvent. |
BillingEvent |
What a verified webhook means. |
CountersOption |
Counter routing: one store, or a strict default plus a buffered store for metering: "buffered" features. |
DecisionReason |
Why a decision came out the way it did (ADR 0009). |
Denial |
payment_required = an upgrade would allow it (402). forbidden = no plan would (403). |
EntitlementsAction |
The full set of authorizable actions. |
EntitlementsHooks |
A hook: implement either side or both. |
EntitlementsHooksInput |
Accepts a single hook, an array, or nothing. |
EntitlementsResource |
The resource an action targets. customer is absent on collection-level routes (list customers, global activity, reservation sweep). |
EventErrorReporter |
Reports a listener error. |
FromContext |
A value, or a function of the framework context producing it (sync or async). |
GuardOutcome |
Outcome of evaluateGuard: the decision to attach, or the response to send. |
HookErrorReporter |
Reports an error thrown by an after hook. |
IntakeOutcome |
Outcome of one webhook delivery. |
PortalAction |
A portal action a token may grant. |
PortalTokenError |
An invalid, expired or unmintable portal token (see the PortalTokenError class). |
RouteSpec |
The documented shape of one route (consumed by the OpenAPI builder). |
RouteTag |
Route tags (OpenAPI grouping). |
SubscriptionStatus |
Provider-agnostic subscription status (ADR 0007). |
ThresholdListener |
A threshold listener. |
TypedCheckResult |
A typed decision: value is typed for value features. |
UsageListener |
A usage listener. |
Variables
Section titled “Variables”| Name | Summary |
|---|---|
ALL_ACTIONS |
Every action, in a stable order (role presets, docs, the UI). |
API_ROUTES |
The documented route table (method, path, action, schemas) — every API route. |
DEFAULT_ENTITLED_STATUSES |
Statuses that grant access unless configured otherwise. |
defaultHookErrorReporter |
Default after-hook error reporter: warn with the [@xtandard/entitlements] prefix, never throw. |
MUTATING_ACTIONS |
Control-plane actions that write state — blocked when the panel (or the roles provider) is readonly. Runtime consumption (runtime:consume) and the portal link-outs (portal:checkout, portal:manage) are not in the set: readonly freezes the control plane, metering keeps working (engine readonly has the same semantics). |
PORTAL_ACTIONS |
The actions a portal-token principal may be granted (and the default scope of a token). |
PORTAL_TOKEN_PREFIX |
Prefix of every portal token. |
PortalTokenError |
Thrown by verifyPortalToken (and createPortalToken for bad input) — malformed, bad signature, expired, or an invalid scope. Maps to HTTP 401 at the API layer. |