[data-reveal]{opacity:1!important;transform:none!important}
AntelopeJS DMS
DocumentationLifecycle and usage

Lifecycle and usage

Registration extras, durable tenant lifecycle consumers, idempotent invoice usage providers and billing e-mail enrichers.

These contracts are exported from the direct subpaths below, and from the root's invoiceLineItems, tenantLifecycle, planChanges and billingEmails namespaces. Consumers and providers are registered from the owning module's lifecycle, not from a request handler. A registration is held until SaaS attaches, replayed when SaaS reloads, and dropped when its owner unloads.

Integration points by task

TaskIntegrationExample result
Save onboarding answersProvisioning hookA referral code is stored before signup completes
Create paid product resourcescreated lifecycle consumerA workspace gets its resources after payment is committed
Pause or resume resourcesLifecycle consumerSaaS access waits for the required reactivation receipts
Add measured usage to a billInvoice line-item provider120 compute minutes produce one priced line
Add lines to a billing e-mailBilling e-mail enricherA suspension e-mail also lists the apps put to sleep

In the last row, amountCents: 600 and quantity: 120 mean a line total of €6.00 on an EUR invoice, not 120 × €6.00. The resolver calculates the total, and SaaS does not multiply it by the quantity. The working provider example implements the contract below.

Invoice line items

These names are exported from /invoice-line-items. RegisterInvoiceLineItemsProvider(provider: InvoiceLineItemsProvider): void registers { id: string, resolve: InvoiceLineItemsResolver, onUsageGap?: (gap: InvoiceUsageGap) => void }. UnregisterInvoiceLineItemsProvider(providerId: string): void removes it and ignores unknown IDs. A module registers its provider during construct() and unregisters it during stop().

InvoiceLineItemsResolution is the union of two exported interfaces, InvoiceLineItemsReady and InvoiceLineItemsNotReady.

Contract ts
interface InvoiceLineItemsContext {
  tenantId: string;
  invoiceId: string;
  currency: string;
  periodStart: Date;
  periodEnd: Date;
  isPreview?: boolean;
}

interface InvoiceLineItem {
  key: string;
  description: string;
  amountCents: number;
  quantity?: number;
  unit?: string;
  metadata?: Record<string, string>;
}

type InvoiceLineItemsResolution =
  | { status: "ready"; lines: InvoiceLineItem[] }
  | { status: "not_ready"; reason: string };

interface InvoiceUsageGap {
  tenantId: string;
  invoiceId: string;
  periodStart: Date;
  periodEnd: Date;
  reasons: string[];
}

type InvoiceLineItemsResolver = (
  context: InvoiceLineItemsContext,
) =>
  | Promise<InvoiceLineItem[] | InvoiceLineItemsResolution>
  | InvoiceLineItem[]
  | InvoiceLineItemsResolution;

The runtime asks providers for subscription_cycle renewal invoices, not for initial or one-off invoices. The dates cover the cycle that just closed, clipped to the subscription's paid usage period. Complimentary and grace usage is excluded, and no provider runs for an empty covered window. The resolver runs inside the webhook request or the recovery worker, so it reads tenant-scoped, pre-aggregated usage and returns the same lines every time for a closed window.

amountCents is the line total in the invoice currency, as a safe integer. A negative amount is a credit. quantity and unit are audit metadata, never factors of the total. Zero amounts are dropped. A line is invalid when its key or description is empty, its amount is not a safe integer, its key contains :, or its provider-prefixed key is longer than 150 characters. A provider ID must not contain :, and registration throws if it does. Provider IDs are unique across modules. A second registration with the same ID replaces the first provider, and a clash that happens before SaaS attaches leaves no trace, because the buffer is keyed by ID.

A line key stays stable from cycle to cycle. The runtime injects at most one line per invoice, provider and key across webhook replays and concurrent workers. A returned line is not proof that Stripe accepted the invoice item.

On a closing invoice the runtime first suspends the draft (auto_advance=false) and hands the injection to a durable task. The invoice is always finalized, either once every provider's lines are on it, or 48 hours after the task was registered (INVOICE_LINE_DEADLINE_MS) with the lines available. The resolver's answer decides what happens:

Resolver answerEffect
An array, or { status: "ready", lines }The lines are injected. An empty array states an empty bill.
{ status: "not_ready", reason }, or a thrown errorThe draft stays suspended and the provider is asked again later. Past the deadline, the invoice is finalized without its lines.
Any other valueRead as not_ready with the reason invalid_resolution (INVALID_RESOLUTION_REASON).

normalizeInvoiceLineItemsResolution(value: InvoiceLineItem[] | InvoiceLineItemsResolution): InvoiceLineItemsResolution applies the table. It returns { status: "ready", lines } for an array or a well-formed ready resolution, and { status: "not_ready", reason } for a not_ready one. Any other runtime value, such as a malformed object from an untyped resolver, becomes not_ready with INVALID_RESOLUTION_REASON. An empty bill is stated, never inferred from a malformed answer.

An invoice can be finalized without some of its lines. The causes include a provider still not ready at the deadline, invalid lines, Stripe refusing a line, and a draft changed outside @antelopejs/dms-saas. The missing usage is never billed, so the gap favours the customer. The runtime logs the gap at error level (invoice finalized with missing usage) and calls onUsageGap on every provider the invoice was registered with, so the provider can raise an alert and its owner can fix the cause. Each reason starts with a stable code, such as provider_not_ready, managed_lines_unexpected_or_changed or before_finalize. Most codes are followed by : and a detail.

periodStart is inclusive and periodEnd exclusive, so two adjacent cycle invoices cover disjoint windows.

A provider that may still be loading when an invoice is created is listed in the runtime's invoiceLineRequiredProviders option, so the invoice waits for it. The runtime configuration describes the option.

Preview calls set isPreview: true, use a synthetic upcoming_<subscription id> invoice ID, and end at the request time. A preview quotes the open cycle's usage without invoicing it. It is a quote of the next invoice, not an addition to it. A resolver never changes usage accounting, because a preview can call it at any time. A failed resolver or an invalid line makes the preview unavailable.

Line helpers

LINE_KEY_SEPARATOR is ":". buildInvoiceLineKey(providerId: string, key: string): string joins the two fragments and does not validate them.

selectInvoiceLineItemsToCreate(providerId: string, items: readonly InvoiceLineItem[], alreadyInjectedKeys: ReadonlySet<string>): InvoiceLineItemSelection is synchronous and has no Stripe side effects. It returns accepted: PreparedInvoiceLineItem[] ({ lineKey, item }, with trimmed item keys) and skipped: SkippedInvoiceLineItem[] ({ lineKey, reason }). SkippedLineItemReason is already_invoiced, duplicate_key, zero_amount, or invalid. alreadyInjectedKeys holds full provider-prefixed keys. The helper alone gives no transactional idempotency.

Plan changes

These names are exported from /plan-changes. A module that owns tenant inventory (applications, environments, the seats it counts) registers the policy that SaaS consults before a paid-to-Free downgrade lands:

Contract ts
import type {
  PlanChangeFinding,
  PlanChangeValidationRequest,
} from "@antelopejs/interface-dms-saas/plan-changes";

interface PlanChangePolicy {
  name: string;
  validatePlanChange(
    request: PlanChangeValidationRequest,
  ): Promise<PlanChangeFinding[]>;
}

PlanChangeValidationRequest has tenantId: string, currentPlan: Plan | null, targetPlan: Plan, operationId: string, phase: "preview" | "schedule" | "effective" and effectiveAt: Date | null. PlanChangeFinding is PlanChangeIncompatibility | PlanChangeNotice. Both have code: string, message: string, an optional params: PlanChangeMessageParams (Record<string, string | number>) and an optional resource: string. They differ by severity: a notice has "notice", an incompatibility has "blocking" or no severity.

The plan-change confirmation shows each entry in the reader's language when it can. code is also an i18n key: when the application registered it in its locale files, the confirmation shows that message filled with params; otherwise it shows message as it is. message stays required: it is that fallback, and what an API client reads. SaaS's own seat refusal, seat_limit, carries { limit, occupied } and is translated by SaaS itself. A policy that returns a database's name in params and registers myapp.plan_change.database_restarts in en-GB and fr-FR shows that line in each reader's language:

Translated notice ts
import type { PlanChangeNotice } from "@antelopejs/interface-dms-saas/plan-changes";

const notice: PlanChangeNotice = {
  severity: "notice",
  code: "myapp.plan_change.database_restarts",
  params: { database: "orders" },
  message: "orders restarts and is unavailable for about a minute",
  resource: "database:orders",
};

Only a notice leaves the change allowed. Every other entry refuses it, an entry with a severity the interface does not define included. The owner reads the notices in the plan-change confirmation, such as "2 databases will restart", and can still confirm. SaaS shows them from the preview phase only and ignores the notices a policy returns for schedule and effective. It never stores a notice: TenantPlanConstraints.incompatibilities holds only PlanChangeIncompatibility entries.

RegisterPlanChangePolicy(policy: PlanChangePolicy): void registers the sole policy, and throws when name is blank. UnregisterPlanChangePolicy(name: string): void removes it, but does not lift the restrictions on changes already persisted. Registering a policy opts deferred changes into the guarded paid-to-Free flow. Guarded paid-to-paid changes are not supported. validatePlanChange runs for the preview, schedule and effective phases. The effective call runs after DMS tenant admission is paused and earlier membership writers have drained. The callback does not mutate inventory or call Stripe. When the runtime's requiredPlanChangePolicy option names a policy that is not registered, plan changes fail closed. A second policy competing with the first also fails closed.

FunctionUse
GetTenantPlanConstraints(tenantId: string): Promise<TenantPlanConstraints>currentPlan, pendingPlan, effectiveAt, planChangeOperationId, blocked, admissionBlocked and incompatibilities. Inventory writers read it after entering their own admission. It is a read-only snapshot, not a reservation.
CountOccupiedSeats(tenantId: string): Promise<number>Occupied seats, including unexpired invitations and excluding platform support. Not a billing cache and not an atomic quota reservation.
GetPlanChangeActivation(tenantId: string): Promise<PlanChangeActivation | null>{ planChangeOperationId, operationId, gateId } of the only downgrade hold an activation consumer may release, or null. The consumer matches both operation IDs on the lifecycle message, evaluates every DMS access gate (EvaluateTenantAccess) and keeps every other denial. A null result or an error never authorizes a guarded delivery. The snapshot is not a reservation, so the consumer reads it again under its own sleep lock.

TenantLifecycleMessage.planChangeOperationId (optional) marks a lifecycle delivery produced by a guarded downgrade. A consumer that cannot authorize such a delivery never treats it as an ordinary resume.

Tenant lifecycle

These names are exported from /tenant-lifecycle. TENANT_LIFECYCLE_TRANSITIONS contains created, suspended and reactivation_requested, and TenantLifecycleTransition is their union.

The package has no workspace-named lifecycle API and no alias for one. RegisterWorkspaceLifecycleConsumer, UnregisterWorkspaceLifecycleConsumer, the WorkspaceLifecycle* types, WORKSPACE_LIFECYCLE_TRANSITIONS, IsWorkspaceProvisioningCommitted, the /workspace-lifecycle subpath and the root workspaceLifecycle namespace do not exist. The tenant-named API below and the root tenantLifecycle namespace replace them, so this package and @antelopejs/dms-saas are upgraded together. Persisted consumer IDs, transition values and operation IDs are the same under both names, so existing consumer names and deduplication keys stay valid.

Contract ts
import type { TenantLifecycleTransition } from "@antelopejs/interface-dms-saas/tenant-lifecycle";

interface TenantLifecycleMessage {
  tenantId: string;
  operationId: string;
  transition: TenantLifecycleTransition;
  requestedAt: Date;
  planChangeOperationId?: string;
}
interface TenantLifecycleReceipt {
  receiptId: string;
  effectiveAt?: Date;
}
interface TenantLifecycleConsumer {
  name: string;
  transitions: readonly TenantLifecycleTransition[];
  consume(message: TenantLifecycleMessage): Promise<TenantLifecycleReceipt>;
}
interface TenantLifecycleConsumerRegistration { unregister(): void; }

declare function RegisterTenantLifecycleConsumer(
  consumer: TenantLifecycleConsumer,
): TenantLifecycleConsumerRegistration;
declare function UnregisterTenantLifecycleConsumer(name: string): void;
declare function IsTenantProvisioningCommitted(tenantId: string): Promise<boolean>;

A consumer name matches /^[a-z][a-z0-9._-]{2,63}$/, and an invalid name throws synchronously. The name is stable and unique, and transitions lists every transition the consumer opts into. The module unregisters the consumer through the returned handle, or by name, when it stops.

Delivery is at least once. A consumer deduplicates by operationId, durably links the resources it provisions, then returns a durable receipt. A rejection is not an acknowledgement. Suspension closes SaaS access before delivery. Reactivation keeps access closed until every registered required consumer returns a receipt. created arrives after the ownership, billing records and pre-provisioning hooks succeed and the first invoice is paid, or when no payment is required.

IsTenantProvisioningCommitted returns false for preparing, unpaid or cancelled self-service workspaces. It returns true for committed creations, and for legacy or bootstrap tenants without a marker. It is not an existence, membership or access check. Storage and missing-implementation errors propagate, and a caller fails closed instead of reading an unavailable check as eligibility.

Billing e-mails

These names are exported from /billing-emails. BILLING_EMAIL_SUBJECTS lists the notification subjects the SaaS module e-mails when its billingEmails option is on: saas.trial_ending_soon, saas.trial_ended_blocked, saas.free_workspace_ending_soon, saas.free_workspace_expired, saas.payment_failed, saas.workspace_suspended, saas.workspace_reactivated, saas.subscription_cancelled and saas.plan_migrated. BillingEmailSubject is their union, and isBillingEmailSubject(value) narrows a string to it.

Contract ts
import type { BillingEmailSubject } from "@antelopejs/interface-dms-saas/billing-emails";

type BillingEmailLocale = "en" | "fr";
interface BillingEmailContext {
  tenantId: string;
  subject: BillingEmailSubject;
  eventId: string;
  locale: BillingEmailLocale;
  params: Readonly<Record<string, string | number>>;
}
interface BillingEmailBlock {
  title?: string;
  paragraphs: string[];
}
interface BillingEmailEnricher {
  name: string;
  subjects: readonly BillingEmailSubject[];
  enrich(
    context: BillingEmailContext,
  ): Promise<BillingEmailBlock | null> | BillingEmailBlock | null;
}
interface BillingEmailEnricherRegistration { unregister(): void; }

declare function RegisterBillingEmailEnricher(
  enricher: BillingEmailEnricher,
): BillingEmailEnricherRegistration;
declare function UnregisterBillingEmailEnricher(name: string): void;

An enricher name matches /^[a-z][a-z0-9._-]{2,63}$/, and an invalid name throws synchronously. A later registration under the same name replaces the earlier one, and an unknown name passed to UnregisterBillingEmailEnricher is ignored.

For each e-mailed event, the module asks every enricher that lists the subject once per language of the recipients:

  • eventId is the same on every delivery of the event: the Stripe event id, an operation id or a job intent.
  • params are the values the in-app notification interpolates.
  • The enricher answers a block in locale, or null to add nothing.

The block is plain text, escaped in the e-mail. Empty paragraphs are dropped. A block keeps at most 10 paragraphs of at most 1,000 characters each. Blocks appear in the order of the enricher names. An enricher that throws, or that has not answered within the module's billingEmails.enricherTimeoutMs, is left out of that e-mail, which goes out without its block. The e-mail is sent once per event and address, so an enricher that reads live state reads it when the e-mail is written, not on later deliveries of the event. An e-mail whose send failed is written again when the module retries it, so its enrichers are asked again then.

Registration and provisioning

TenantBeingProvisionedPayload from /provisioning has tenantId: string, an optional userId: string, and an optional extras: JsonObject. /json exports JsonObject and JsonValue. The payload goes with the DMS Hook.TENANT_BEING_PROVISIONED hook, whose handler returns Promise<undefined>, not Promise<void>. The runtime fires the hook through the DMS ProvisionTenant, which registers the workspace's tenant-schema instance before any listener runs. DMS also fires the hook once for its default tenant, at its creation, without userId and with empty extras. A tenant's default data is written in this hook, never in start() or DATABASE_INITIALIZED.

Listeners run in series inside provisioning, after the workspace records exist and before the first payment is settled or registration returns. When a signed-in user creates another workspace, the runtime also holds that workspace's card for the whole creation. A throwing listener cancels the registration. The runtime then rolls back its own tenant, subscription and Stripe customer, and deletes the account a password registration created. When the rollback itself fails, the runtime logs it and keeps the attempt for reconciliation. External side effects of the listener are not rolled back. A listener does bounded persistence work, not network provisioning, and post-payment resources go through the durable created delivery.

The runtime passes extras to listeners as the registration captured them, from both the password and the OAuth completion paths. When nothing was captured, listeners receive an empty object. The extras belong to the consumer, and the runtime neither persists nor returns them. /registration exports RegistrationExtrasLimits and REGISTRATION_EXTRAS_LIMITS, which are maxSerialisedBytes: 4096, maxKeys: 64 and maxDepth: 4. Public registration also rejects the keys __proto__, constructor and prototype. Rejected extras produce HTTP 400 errors (saas.errors.registration.extras_invalid, extras_too_large or extras_too_complex) before any listener runs.