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

Hooks

A hook is a named platform event with a typed argument list and a typed result. The Hook enum, its payloads, registration, and the dispatchers.

A hook is a named platform event with a typed argument list and a typed result. Modules register handlers with RegisterHook, and the code that owns the event dispatches it. ExecuteHooks runs every handler and discards what they return. CollectHooks gathers their return values. GetRegisteredHooks returns the handlers themselves, for a caller that must call each one with its own arguments. HookSignatures maps each Hook member to its arguments and result, so the compiler checks a handler against the hook it registers for.

Everything on this page lives in @antelopejs/interface-dms/hooks.

Register a handler

typescript
import { Hook, RegisterHook } from "@antelopejs/interface-dms/hooks";

export function registerBillingHooks(): void {
  RegisterHook(Hook.MEMBER_ADDED, async (payload) => {
    await seedBillingProfile(payload.tenantId, payload.userId);
  });

  RegisterHook(Hook.TENANT_DELETED, async (tenantId) => {
    await dropBillingProfiles(tenantId);
  });
}

RegisterHook<H>(name: H, callback: HookHandler<H>, options?: HookRegistrationOptions) appends the callback to the hook's list. The check happens at compile time. HookHandler<H> derives the parameter and return types from HookSignatures[H], so a mismatched handler is a compile error. At runtime the call validates nothing.

A hook whose result is undefined is an event. Its dispatchers discard what the handlers return, so such a handler may return anything, including nothing, the result of a write it awaited, or a promise of it. HookHandlerResult<H> encodes that rule. It is unknown for an event hook. For a hook that has a result, such as Hook.TENANT_DATA_EXPORT, it is that result or a promise of it.

A registration belongs to the module that makes it. When that module is destroyed, because it stops for good or reloads in development, its handlers are released. A reloaded module registers its own again from its next construct(). A module therefore has nothing to unregister when it stops.

Every registration records a module id, resolved from the module that makes the call. HookRegistrationOptions.moduleId overrides it:

typescript
interface HookRegistrationOptions {
  moduleId?: string;
}

The id matters only to a dispatcher that treats handlers per module rather than as one list. The tenant data export namespaces each contributor's archive entries by it. Set it when the registration runs somewhere the runtime attributes to another module, such as a shared helper called while your module constructs. It does not change when the registration is released, which follows the module that made it.

UnregisterHook<H>(name: H, callback: HookHandler<H>) removes a registered callback by identity, for a module that stops listening while it stays loaded. When the same function is registered more than once, it removes the oldest registration. Keep a reference to the function you registered:

typescript
import {
  Hook,
  type HookHandler,
  RegisterHook,
  UnregisterHook,
} from "@antelopejs/interface-dms/hooks";

const onMemberAdded: HookHandler<Hook.MEMBER_ADDED> = async (payload) => {
  await seedBillingProfile(payload.tenantId, payload.userId);
};

RegisterHook(Hook.MEMBER_ADDED, onMemberAdded);
UnregisterHook(Hook.MEMBER_ADDED, onMemberAdded);

The Hook enum

MemberValueArgumentsResult
Hook.DATABASE_INITIALIZED"database:initialized"noneundefined
Hook.TENANT_BEING_PROVISIONED"tenant:being-provisioned"TenantProvisioningHookPayloadundefined
Hook.TENANT_DELETED"tenant:deleted"tenantId: string, context?: TenantDeletionContextundefined
Hook.TENANT_DATA_EXPORT"tenant:data-export"tenantId: string, archive: TenantExportArchive, signal: AbortSignalTenantDataExportContribution | void
Hook.INVITE_BEING_CREATED"invite:being-created"InviteHookPayloadundefined
Hook.INVITE_CREATED"invite:created"InviteCreatedHookPayloadundefined
Hook.INVITE_DELETED"invite:deleted"InviteDeletedHookPayloadundefined
Hook.MEMBER_BEING_ADDED"member:being-added"MemberHookPayloadundefined
Hook.MEMBER_BEING_CHANGED"member:being-changed"MemberChangeHookPayloadundefined
Hook.MEMBER_ADDED"member:added"MemberHookPayloadundefined
Hook.MEMBER_REMOVED"member:removed"MemberRemovedHookPayloadundefined
Hook.USER_REGISTERED"user:registered"UserRegisteredHookPayloadundefined
Hook.USER_DELETED"user:deleted"UserDeletedHookPayloadundefined

The *_BEING_* members fire before the write they precede. The past-tense members fire after it. TENANT_BEING_PROVISIONED has no past-tense counterpart. See Enrich a workspace being provisioned.

Some members have timing of their own:

  • DATABASE_INITIALIZED fires on every DMS start, and a handler registered later runs at once. See Initialise against the database.
  • MEMBER_BEING_CHANGED is fired by changeTenantMembers, under tenant lifecycle admission, before every membership write. It fires once per change, with kind set to added, removed, roles or ownership. A handler that throws refuses the write.
  • USER_DELETED fires after every user deletion the DMS performs, once the user's rows are gone. Today the only such deletion is a user deleting their own account. The DMS catches and logs a failing handler, and the account stays deleted.
  • USER_REGISTERED fires after the account is created. The DMS catches and logs a failing handler, so a subscriber cannot strand a user whose account already exists.
  • TENANT_DELETED may fire more than once for one deletion. A handler deduplicates effects that are not idempotent by context.operationId.

Payload interfaces

typescript
import type { InviteExtensionPayloads } from "@antelopejs/interface-dms/invite-extension-payloads";

interface TenantProvisioningHookPayload {
  tenantId: string;
  /** Absent for the `default` tenant. */
  userId?: string;
  extras: Record<string, unknown>;
}

interface TenantDeletionContext {
  operationId: string;
}

interface InviteHookPayload {
  tenantId: string;
  email: string;
  asTenantOwner: boolean;
  roleIds: string[];
  deliveryId?: string;
}

interface InviteCreatedHookPayload extends InviteHookPayload {
  inviteId: string;
}

type InviteDeletedReason =
  | "accepted"
  | "cancelled"
  | "replaced"
  | "expired"
  | "resent";

interface InviteDeletedHookPayload {
  tenantId: string;
  inviteId: string;
  email: string;
  reason: InviteDeletedReason;
  deliveryId?: string;
  extensions?: InviteExtensionPayloads | null;
}

interface MemberHookPayload {
  tenantId: string;
  userId: string;
  isTenantOwner: boolean;
  deliveryId?: string;
}

interface MemberRemovedHookPayload {
  tenantId: string;
  userIds: string[];
}

interface UserRegisteredHookPayload {
  tenantId: string;
  userId: string;
  email: string;
  name: string;
}

type UserDeletionReason = "self";

interface UserDeletedHookPayload {
  userId: string;
  email: string;
  tenantIds: string[];
  reason: UserDeletionReason;
}

The shapes differ on purpose. MEMBER_BEING_ADDED and MEMBER_ADDED describe one member with userId. MEMBER_REMOVED carries userIds, because one removal can cover several members. The handler's inferred parameter type shows which shape a hook passes.

deliveryId is a stable identity for an invitation decision. It is set when the event comes from a durable invitation step, which can replay after a failure. A handler uses it to recognise a replay of an event it already handled.

InviteDeletedHookPayload.reason says why the invitation row went away. Two reasons delete the row without ending the invitation. accepted means the invitee joined and the invitation was consumed. resent means the same invitation was reissued under a new token. extensions holds the payloads the invitation carried, for a handler that must undo its own work. Invites covers how an invitation is resolved and replaced.

MemberChangeHookPayload is MemberChange & { tenantId: string }, where MemberChange is a union discriminated by kind:

typescript
type MemberChange =
  | { kind: "added"; userId: string; isTenantOwner: boolean; roleIds: string[]; deliveryId?: string }
  | { kind: "removed"; userId: string; isTenantOwner: boolean }
  | { kind: "roles"; userId: string; roleIds: string[]; previousRoleIds: string[] }
  | { kind: "ownership"; userId: string; isTenantOwner: boolean; previousIsTenantOwner: boolean };

Read kind first and return early for the kinds your policy does not limit. An invitation acceptance is an added change that carries its deliveryId. The veto runs before the acceptance is stored, on a replay too, so a deliveryId does not exempt a change from policy. See changeTenantMembers for which writes announce which kind.

UserDeletedHookPayload.tenantIds lists the workspaces the user was a member of. The user left all of them before the deletion. A module deletes the per-user rows it keeps in them. reason is "self" today, a user deleting their own account.

InviteCreatedHookPayload carries no token. An invitation stores only the digest of its token, and a creation replayed after a failure has nothing else to hand out.

TenantProvisioningHookPayload.extras is opaque. The DMS reads no key of it, validates nothing and stores nothing. See Enrich a workspace being provisioned.

TENANT_DATA_EXPORT is the one hook whose handler returns a result. Its argument and result types live in @antelopejs/interface-dms/tenant-export, and this module re-exports them. Tenant data export covers them.

Dispatch with ExecuteHooks or CollectHooks

Both take the hook and its arguments, and await each handler in registration order. They differ in what they do with the outcome.

typescript
async function ExecuteHooks<H extends Hook>(
  name: H,
  ...args: HookSignatures[H]["args"]
): Promise<void>;

async function CollectHooks<H extends Hook>(
  name: H,
  ...args: HookSignatures[H]["args"]
): Promise<Awaited<HookHandlerResult<H>>[]>;
ExecuteHooksCollectHooks
Return valuePromise<void>. Handler results are discarded.Promise<Result[]>, one entry per handler that did not throw. Result is the hook's declared result, and unknown for an event hook, whose handlers may return anything.
A handler that throwsThe rejection reaches the caller, and the remaining handlers do not run.The error is logged and the handler adds no entry. The remaining handlers still run.
Use forAnnouncing that something happenedAsking every handler to contribute something

Use ExecuteHooks for the notification hooks, where a failing handler fails the operation that fired it. Use CollectHooks where one broken module must not stop the others. On an event hook, CollectHooks still runs every handler and returns whatever each one returned, typed unknown.

typescript
import {
  CollectHooks,
  ExecuteHooks,
  Hook,
} from "@antelopejs/interface-dms/hooks";

await ExecuteHooks(Hook.TENANT_DELETED, tenantId);

const results = await CollectHooks(Hook.MEMBER_ADDED, {
  tenantId,
  userId,
  isTenantOwner: false,
});

A caller that a subscriber must not break wraps ExecuteHooks in its own try/catch. The DMS does so for USER_REGISTERED and USER_DELETED.

Dispatch handler by handler with GetRegisteredHooks

Both dispatchers pass the same arguments to every handler. When each handler needs arguments of its own, take the list instead:

typescript
function GetRegisteredHooks<H extends Hook>(name: H): RegisteredHook<H>[];

interface RegisteredHook<H extends Hook> {
  moduleId?: string;
  handler: HookHandler<H>;
}

moduleId is the id the registration recorded. It is the HookRegistrationOptions.moduleId passed, or else the module the runtime attributed the call to, and undefined when neither resolved. The caller handles failures, because nothing wraps the handler.

The tenant data export runs this way. Each contributor needs an archive namespaced under its own module id, which no shared argument list can express.

Initialise against the database

DATABASE_INITIALIZED behaves like a promise that has already resolved. The DMS fires it from its start(), once the database schemas are registered, and the hook stays settled until the DMS stops:

  • A handler registered before the DMS starts runs when it starts, in series with the others, as ExecuteHooks runs them. A handler that throws fails the DMS start.
  • A handler registered while the hook is settled runs at once, in the background. This covers a module loaded after the DMS started, and a module reloaded in development. The registration does not wait for the handler. A failure is logged with the hook and module name, and is not thrown into the registering module's construct() or start().
  • A handler registered while the DMS is stopped waits for its next start.

A handler therefore runs once per DMS start, and once per registration made while the DMS runs. Over the life of a process that adds up to several runs. A DMS reload replays every handler, and a reloaded module registers its handler again, which runs it again. Write the handler so it is safe to replay against a live database. Create what is missing, never insert unconditionally, and never send a message or charge from it without a record that it already happened.

SettleHook and UnsettleHook manage the settled state. They accept only the hooks typed StickyHook, and DATABASE_INITIALIZED is the only one. The DMS is the only caller.

Enrich a workspace being provisioned

A SaaS signup provisions a workspace, and the product often collects more at that moment than the DMS models, such as an acquisition source, a team size or a referral code. A module writes those to its own tables in a TENANT_BEING_PROVISIONED handler, while the provisioning is not yet final.

typescript
import {
  Hook,
  RegisterHook,
} from "@antelopejs/interface-dms/hooks";

RegisterHook(Hook.TENANT_BEING_PROVISIONED, async ({ tenantId, userId, extras }) => {
  await recordAcquisition(tenantId, userId, {
    source: extras.acquisitionSource,
    referral: extras.referralCode,
  });
});

The hook is dispatched with ExecuteHooks, so handlers run in series, each awaited. A handler that throws aborts the provisioning. The rejection reaches the emitter, later handlers do not run, and the emitter removes the workspace it was creating. A workspace therefore never ends up provisioned while an enrichment a consumer needed failed to be written. The hook fires before the commit to give that guarantee.

The reverse does not hold, because there is no shared transaction. A handler that already returned has committed its own rows. A later handler that throws, or an emitter that fails afterwards, does not take them back. Two habits make that safe:

  • Key the write on tenantId, so it can be cleaned up with the workspace. A TENANT_DELETED handler covers the normal deletion path.
  • Make the write idempotent, so a retried signup does not write it twice.

A handler that throws for its own reasons fails someone's signup. Keep its work to what must not be lost.

extras is opaque. The DMS reads no key of it, validates nothing, and stores nothing. It carries the object from the caller of the provisioning flow to the handlers, and each handler writes the keys it recognises. The shape is a contract between that caller and that handler, and the DMS is not part of it. A product can therefore collect a new field without a DMS release.

The hook fires once per tenant, when the tenant is created, and never again on a later start once it has succeeded. The DMS fires it for the default tenant once every module has started, so the tables and settings that modules registered are ready. That payload has no userId, because the default tenant has no owner until onboarding. Replicas that share a new database elect one holder through a lease on the tenant's row, and the others serve meanwhile. A holder that stops renewing for provisioningLease.staleAfterMs is taken over, even if its handlers are still running. If that attempt fails, or its process dies, the next start or another replica runs every handler again, so a handler skips what it already wrote. Stopping the DMS does not wait for the handlers. An attempt still running then stops renewing its lease and is taken over the same way, even if its handlers are still running. A SaaS module such as dms-saas fires the hook for each workspace its signup flow creates.

A module writes the default data a tenant starts with in this hook, such as templates, folders, a sender or a demo history. Once written, that data belongs to the tenant. The module does not write it again on a later start, does not compare it with what members changed since, and does not wait for the tenant from start() or DATABASE_INITIALIZED.

typescript
RegisterHook(Hook.TENANT_BEING_PROVISIONED, async ({ tenantId }) => {
  await writeDefaultFolders(tenantId);
});

An emitter fires the hook through ProvisionTenant from @antelopejs/interface-dms/tenant-provisioning, never with a bare ExecuteHooks. ProvisionTenant registers the tenant as an instance of the dms-tenant schema first, then runs the handlers. No handler runs before the instance exists, whatever order the modules registered in.

Contribute to a tenant data export

TENANT_DATA_EXPORT asks every module for its part of one tenant's data, assembled into a single ZIP archive. Register a contributor with RegisterTenantDataExportContributor. Tenant data export covers the handler, the archive it writes into, and the manifest.

Next steps

Realtime covers pushing an event to an open page, as opposed to reacting to a platform event.