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

Extending

Plug your modules into the SaaS module through its interface, replace the public screens, capture sign-up data, bill usage, preview invoices and add workspace pages.

The SaaS module exposes its extension points through the separately published @antelopejs/interface-dms-saas package. Pages you add stay backend-declared trees of DMS blocks. Make a custom component only for the block the DMS lacks, and give it .meta({ name, description, icon }) so the role editor can show it.

Choose an integration

You want toStart hereExpected result
Save a referral code at signupRegistration extrasYour module stores the answers before registration completes
Bill compute or storage usageInvoice line itemsUsage appears beside the subscription on renewal invoices
Show an estimated billUpcoming invoice previewA priced estimate, or an explicit absent or unavailable state
Add your lines to the billing e-mailsBilling e-mail enrichersA suspension e-mail also says which apps were put to sleep
Add a billing blockWorkspace settings pagesYour block appears beside the existing billing content
Provision a resource after paymentTenant lifecycleA durable notification your module deduplicates before creating resources

Start with the example for your task. The interface reference holds the complete types and failure contracts. The sections below show how to use them in a product.

Consuming this module

A module that extends the SaaS module lists the separately published interface package ("@antelopejs/interface-dms-saas") in its dependencies and imports the extension points from it. Load the SaaS module (@antelopejs/dms-saas) separately in the project, because importing its package root boots the registration graph. The consumer reference maps the supported subpaths and defines signatures, results, failures and lifecycle contracts.

invoiceLineItems and tenantLifecycle come off the root entry as namespaces, because each carries an internal proxy namespace of its own. db is reachable only through its subpath, since importing it registers the SaaS tables.

After a seed or import writes subscription records directly, await RecomputeTenantBillingState for each affected tenant. It refreshes the derived billing and workspace directory state. It does not replace the runtime's Stripe or lifecycle work. The module's crons go on acting on the rows written, so their dates must stay relative to the time of writing. See Demos, tests and seeded data.

@antelopejs/dms-saas depends on the interface package through the range >=<interface version> <0.<minor + 1>.0. The module implements the interface, so the range stops below the next minor, and a breaking interface minor never reaches a SaaS module version that does not implement it. During workspace development pnpm resolves that range to the sibling package. To release, publish the interface package first, then @antelopejs/dms-saas, and then update consumers to the published interface version.

Tenant owner permissions

The dms-saas.plan-intersection permissions resolver runs at order 100. For a member whose isTenantOwner is true in the requested tenant, it grants every explicit permission of that tenant's resolved plan, inherited permissions included, whatever roles the member holds. Permissions outside the plan are removed even when a role grants them. Other members keep only the intersection of their incoming permissions and the resolved plan.

A plan grants exactly the ids it lists, and nothing nested under them. The plan editor's permission tree adds a node's descendants and ancestors when you tick it, so plans built from the UI list every component id. Plans seeded by code must list them too.

Tenant ownership never grants *, even if a plan contains it. An incoming * (the DMS platform owner's wildcard, for example) keeps the existing behaviour. The wildcard survives, and the other incoming permissions are intersected with the plan. Without a subscription, a planId, or an existing plan, the resolver keeps the incoming permissions and grants nothing new. A tenant with missing billing data therefore keeps its access.

A role preview (Settings › Workspace › Roles › Preview as role) shapes the set of an ordinary member who holds only the previewed role, whoever the viewer is. The resolver reads the DMS resolver context (context.preview). Under a preview it never grants the owner's plan permissions, keeps the role's permissions that the plan grants, keeps * only when the previewed role itself holds it, and returns the role unchanged when no plan resolves. The dms-saas.owner-only-surfaces resolver (order 110) withholds the owner-only screens (the danger zone and the data export) from the previewed role, as it does for every member except the owner. A set that holds * passes through it unchanged. If you write a resolver keyed on the user, read the context the same way.

Applications define their business permissions. A later resolver can map the capabilities that survive the plan to resource-specific actions, with no separate tenant-owner grant list. Subscription access gates stay independent and unchanged. This resolver does not constrain defaultGranted permissions, or guards that do not consult effective permissions.

Public screens

The SaaS module ships a working registration screen, so a fresh project can sell from day one. Treat it as a reference implementation, not a design. The module owns the money and the compliance of the flow, and the consuming SaaS owns the conversion.

To replace the screen, first turn the bundled page off in the module config. Page registration is keyed by slug, so a second page on register races the bundled one instead of overriding it.

json
{
  "modules": {
    "dms-saas": {
      "config": {
        "publicScreens": { "register": false }
      }
    }
  }
}

Then register your own page on the register slug and build it on the useSaasRegistration() composable, which the Vue adapter auto-imports. The composable holds the whole flow and renders nothing, so a re-themed screen keeps the same steps. The flow covers the card policy, the Stripe setup intent and card confirmation, the order in which the requirements are validated, the provisioning call and the landing route.

vue
<script setup lang="ts">
const {
  form, // name, email, password, hasAcceptedLegal, skipsPaymentMethod
  paymentElementId,
  canSkipPaymentMethod, // computed: true under the `optional` policy the server applies
  isPaymentStepVisible, // bind with v-show so the Stripe element stays mounted
  passwordStrength, // { strength, score, color } for <DmsPasswordStrength>
  isRegistrationClosed, // render the invitation-only state instead of the form
  errorMessage,
  isSubmitting,
  submit,
} = useSaasRegistration({ redirectTo: "/welcome" });
</script>

Nothing the composable returns throws. A failure appears as a translated errorMessage, and submit() resolves to the new tenant id or null. A password outside the DMS policy stops submit() before the card is confirmed. The workspace name is the localised saas.register.default_workspace_name. Every screen stays enabled by default, so an existing project needs no configuration change.

Registration extras and the provisioning hook

To capture your own fields at signup, such as a referral source or a team size, send them as extras on the registration payload and write them from a TENANT_BEING_PROVISIONED listener. The SaaS module forwards the object verbatim. It never reads, stores or returns it, so the data and its schema stay yours.

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

RegisterHook(
  Hook.TENANT_BEING_PROVISIONED,
  async ({ tenantId, userId, extras }: TenantBeingProvisionedPayload) => {
    // The DMS `default` tenant is provisioned at startup, with no signup.
    if (!userId) return undefined;
    await storeOnboardingAnswers(tenantId, userId, extras);
    return undefined;
  },
);

storeOnboardingAnswers is your module's persistence function. Keep the explicit undefined return, because this hook's handler contract is Promise<undefined>, not Promise<void>.

The provisioning contract defines the capture limits, the rollback and the per-card lock. Keep the hook to bounded persistence work, because a failure cancels the registration. To create external resources after payment, use the durable tenant lifecycle instead.

In the browser, useSaasRegistration() takes the capture as an option and sends it with the rest of the form:

vue
<script setup lang="ts">
const answers = reactive({ referral: "", teamSize: "" });
const { form, submit } = useSaasRegistration({ extras: () => answers });
</script>

Invoice line items

RegisterInvoiceLineItemsProvider lets a module bill its own metered usage on the workspace's subscription invoice. When Stripe opens the renewal invoice of a billing cycle, the SaaS module asks every registered provider for the lines it wants. It adds them as Stripe invoice items while the invoice is still a draft, so Stripe charges them when it finalizes the invoice.

The SaaS module never interprets a line. The provider decides what a metric is, how it is measured and how it is priced.

typescript
import {
  RegisterInvoiceLineItemsProvider,
  UnregisterInvoiceLineItemsProvider,
} from "@antelopejs/interface-dms-saas/invoice-line-items";

const PROVIDER_ID = "cloud";

export async function construct(): Promise<void> {
  RegisterInvoiceLineItemsProvider({
    id: PROVIDER_ID,
    resolve: async ({ tenantId, periodStart, periodEnd, currency }) => {
      const usage = await aggregateUsage(tenantId, periodStart, periodEnd);
      return [
        {
          key: "vcpu-minutes",
          description: "vCPU minutes",
          amountCents: usage.vcpuCents,
          quantity: usage.vcpuMinutes,
          unit: "minute",
        },
        {
          key: "included-credit",
          description: "Included usage credit",
          amountCents: -usage.includedCreditCents,
        },
      ];
    },
  });
}

export async function stop(): Promise<void> {
  UnregisterInvoiceLineItemsProvider(PROVIDER_ID);
}

Use a unique provider ID, stable line keys and pre-aggregated usage. Follow the invoice line-item contract for paid-period boundaries, amounts, idempotency, error handling and preview calls. A resolver also prices previews, so reading usage must not consume it.

Upcoming invoice preview

GetUpcomingInvoicePreview returns what Stripe will bill the current workspace next, tax included, so a page can show the exact VAT and total before the invoice exists. Stripe computes every figure with Stripe Tax (country, VAT number, reverse charge), and the SaaS module copies them without recomputing any.

typescript
import { GetUpcomingInvoicePreview } from "@antelopejs/interface-dms-saas/billing";

const preview = await GetUpcomingInvoicePreview({ tenantId, userId });
if (preview.status === "available") {
  const { taxMinorUnits, totalMinorUnits, currency } = preview;
  render({ tax: taxMinorUnits, total: totalMinorUnits, currency });
}

Take the scope from trusted authentication and handle all three states, available, absent and unavailable. The billing reference defines their fields, reason codes, authorization failures and monetary units.

The preview quotes usage up to the time of the request, with the same providers, paid coverage window and line validation as the renewal invoice. Its tax therefore covers plan and usage together. It estimates a cycle that is still running, and the renewal invoice bills the whole cycle.

The SaaS module caches previews per workspace for an hour, in the database, so every instance shares them. Set upcomingInvoicePreviewCacheTtlSeconds to change that lifetime, or set it to 0 to price every request. The SaaS module drops a cached preview as soon as the workspace's subscription (plan change, status) or billing identity (address, VAT number) changes locally. It also drops it on the Stripe events invoice.created, invoice.finalized, invoice.paid, invoice.voided, customer.subscription.updated, customer.subscription.deleted and customer.updated. It never caches an unavailable result. Display computedAt so the reader knows how current the figures are.

The Stripe reads a page renders (this preview, the billing status and the VAT check) give up after stripe.readTimeoutMs, 4000 ms by default. They are not retried unless you set stripe.readMaxNetworkRetries, so a slow Stripe makes the preview unavailable instead of holding the page. Writes keep the Stripe SDK's own timeout and retries.

Billing e-mail enrichers

When billing e-mails are on, the module e-mails each billing event once to the owners of the workspace and to its billing contact. RegisterBillingEmailEnricher lets a module add its own lines to that e-mail, so a recipient gets one e-mail per event, with every module's lines in it.

typescript
import {
  RegisterBillingEmailEnricher,
  UnregisterBillingEmailEnricher,
} from "@antelopejs/interface-dms-saas/billing-emails";

const ENRICHER_NAME = "cloud.environments";

export async function construct(): Promise<void> {
  RegisterBillingEmailEnricher({
    name: ENRICHER_NAME,
    subjects: ["saas.workspace_suspended", "saas.subscription_cancelled"],
    enrich: async ({ tenantId, locale }) => {
      const asleep = await countSleepingApps(tenantId);
      if (asleep === 0) return null;
      return {
        paragraphs: [
          locale === "fr"
            ? `Vos ${asleep} applications sont endormies.`
            : `Your ${asleep} apps are asleep.`,
        ],
      };
    },
  });
}

export async function stop(): Promise<void> {
  UnregisterBillingEmailEnricher(ENRICHER_NAME);
}

The enricher is asked once per language of the recipients, with the workspace, the subject, the event id and the notification's params. It writes its text in the language it is given. The e-mail escapes the text, so a block holds no HTML.

The e-mail does not depend on the enricher:

  • An enricher that throws, or that has not answered within billingEmails.enricherTimeoutMs (2 seconds by default), is left out, and the e-mail goes out without its block.
  • Blocks appear in the order of the enricher names.
  • A later registration under the same name replaces the earlier one.

The billing e-mails reference has the complete contract.

Workspace settings pages

To add a page to workspace settings, take workspaceSettingsCategory from @antelopejs/interface-dms/page instead of rebuilding its hierarchy. The SaaS interface exports neither this category nor a category getter.

typescript
import { PageController, RegisterPage, workspaceSettingsCategory } from "@antelopejs/interface-dms/page";

@RegisterPage()
export class WorkspaceRegistriesController extends PageController("registries", {
  displayName: "$cloud.workspace.registries.title",
  category: workspaceSettingsCategory,
  icon: "i-ph-package",
  order: 10,
}) {}

To extend the existing tenant billing page, use its stable identifiers instead of importing its controller. Use an anchor such as tenantBillingPage.components.planCard. The page extension reference defines placement and registration lifetime.

typescript
import { CustomComponent } from "@antelopejs/interface-dms/base/custom";
import {
  RegisterTenantBillingPageExtension,
  tenantBillingPage,
  type TenantBillingPageExtensionRegistration,
} from "@antelopejs/interface-dms-saas/pages";

let billingBlocks: TenantBillingPageExtensionRegistration | undefined;

export function construct(): void {
  billingBlocks = RegisterTenantBillingPageExtension({
    name: "CloudBillingBlocks",
    components: [
      {
        key: "inProgressInvoice",
        component: CustomComponent("CloudInProgressInvoice").meta({
          name: "$cloud.billing.in_progress_invoice",
          description: "$cloud.billing.in_progress_invoice_description",
          icon: "i-ph-receipt",
        }),
        side: "after",
        anchorKey: tenantBillingPage.components.planCard,
      },
    ],
  });
}

export function stop(): void {
  billingBlocks?.unregister();
  billingBlocks = undefined;
}

A platform module can extend the SaaS platform-owner workspace detail without importing its controller or the private saasModule instance. Use platformSaasModule, platformWorkspaceDetailPage and RegisterPlatformWorkspaceDetailPageExtension from the same public pages entry point. platformSaasModule is a synchronous descriptor. Runtime code that needs the registered module root can await GetPlatformSaasModule().

A platform data controller that must hide a tenant routing field can import HiddenStringFilter from @antelopejs/interface-dms-saas/data-api. The SaaS data controllers themselves stay private. The canonical database models come from /db. Read the import and direct-write warnings before you use them.

Plan feature labels and values

A feature's displayName and tooltip are localized fields (@Localized, falling back to en). The row stores one value per locale, and every reader gets the text in the viewer's language, taken from the x-content-language header the DMS frontend sends. The tenant plan pages and the plan admin pages show the text as written. The features table in the platform admin edits it one language at a time.

A module that declares features writes every locale at once through localize("*", FEATURE_LOCALIZED_FIELDS), never i18n keys:

typescript
import { GetModel } from "@antelopejs/interface-database-decorators";
import {
  FEATURE_FALLBACK_LOCALE,
  FEATURE_LOCALIZED_FIELDS,
  FeatureModel,
} from "@antelopejs/interface-dms-saas/db";

const row = FeatureModel.fromPlainData({
  _id: "cloud.plan.egress",
  // ...
}).localize("*", FEATURE_LOCALIZED_FIELDS);
row.displayName = { en: "Included egress", fr: "Trafic sortant inclus" };
row.tooltip = { en: "Outbound traffic", fr: "Trafic sortant" };
await GetModel(FeatureModel).insert(row.localize(FEATURE_FALLBACK_LOCALE));

That view is a FeatureInAllLocales: each localized field takes one value per locale, so the wording needs no cast. Read back from the database, a field may also hold a plain text or nothing, and the type says so. localize(locale) gives back the row type insert and update take, with every locale still stored.

Read a row with localizeFeature(feature, locale) from @antelopejs/interface-dms-saas/plans. A row with no value in the viewer's locale or in en has no tooltip.

The plan pages format values from the feature's valueType and unit. -1 reads as unlimited, booleans read as ✓ or —, and numbers are grouped in the viewer's locale. A per <unit> unit makes the value a price in the plan's currency, and currency units makes it an amount of that currency. Known units are scaled to something a person reads at a glance. Any other unit is shown verbatim after the grouped number. A text value follows the same convention as labels. A $<key> value is translated in the declaring module's locales, and any other value is shown as stored.

Stored unitQuantity reads asper <unit> price reads as
byte(s)bytes, KB, MB, GB or TB (powers of 1000)per GB
minute(s)minutesper minute

If your module declares features in its own units, teach the plan pages how they read with registerPlanFeatureUnit, which is auto-imported like the other SaaS module composables. Call it from a frontend plugin that runs on the server and in the browser, so server-rendered and hydrated values agree. Each scale says how many stored units it holds. A quantity takes the largest scale it fills, and a per <unit> price reads per priceScale. Labels are full i18n keys that the module ships in its own locales. Each label is a node that holds a quantity message ({value}, pluralised on the scaled value) and a price message ({price}).

typescript
// frontend-vue/app/plugins/plan-feature-units.ts
const MINUTES_PER_HOUR = 60;
const vcpuHour = { label: "cloud.plan.units.vcpu_hour", size: MINUTES_PER_HOUR };

export default defineDmsPlugin(() => {
  registerPlanFeatureUnit(["vCPU-minute", "vCPU-minutes"], {
    scales: [vcpuHour],
    priceScale: vcpuHour,
  });
});
json
{
  "cloud": {
    "plan": {
      "units": {
        "vcpu_hour": {
          "quantity": "{value} vCPU-hour | {value} vCPU-hours",
          "price": "{price} / vCPU-hour"
        }
      }
    }
  }
}

Units match case-insensitively, and a registered unit takes precedence over a built-in unit of the same name.