Marketing interface
Read a tenant-scoped click heatmap, declare websites and funnels, and import historical analytics from another backend module.
@antelopejs/interface-dms-marketing exports five backend functions. GetClickHeatmap reads a click heatmap. EnsureWebsite, EnsureFunnel, EnsurePageSnapshot and ImportAnalytics ship marketing content as code, as Content from code describes. The tracker's JavaScript API and the HTTP API belong to the extending guide, not to this package.
A @antelopejs/dms-marketing release implements one minor line of this interface. The compatibility block of the module README gives that range.
An empty heatmap is a successful result
The example needs the marketing module loaded and a tenant that the calling module has already authorized.
import { GetClickHeatmap } from "@antelopejs/interface-dms-marketing";
export async function pricingHeatmap(authorizedTenantId: string, websiteId: string) {
try {
return await GetClickHeatmap({
tenantId: authorizedTenantId,
websiteId,
path: "/pricing",
});
} catch {
return null;
}
}
With no date bounds, the call reads the last seven days. A successful result with no clicks has points: [] and totalClicks: 0. In this wrapper, null means that the read failed, not that nobody clicked. A cell with weight: 8 stands for eight clicks, not eight distinct visitors. Check truncated before you present the result as the whole period.
GetClickHeatmap
interface MarketingHeatmapQuery {
tenantId: string;
path: string;
from?: string;
to?: string;
websiteId?: string;
}
interface MarketingHeatmapAnchor {
selector: string;
ox: number;
oy: number;
nth: number;
}
interface MarketingHeatmapPoint {
x: number;
y: number;
weight: number;
anchor?: MarketingHeatmapAnchor;
}
interface MarketingHeatmapPayload {
points: MarketingHeatmapPoint[];
maxWeight: number;
totalClicks: number;
truncated: boolean;
}
declare function GetClickHeatmap(
query: MarketingHeatmapQuery,
): Promise<MarketingHeatmapPayload>;
The package root exports all four interfaces. path matches the tracked path exactly, for example /pricing. Without websiteId, the query reads every website the tenant owns. An unknown website, or one of another tenant, returns an empty heatmap with points: [], zero weights and clicks, and truncated: false.
from and to are ISO 8601 instants that name the first and the last day read, not sub-day bounds. Pass the start of the first day and the end of the last day, as the dashboard's period picker does. If a bound is missing or invalid, or to is before from, the read falls back to the last seven days. The range keeps at most 90 days, and the oldest days go first. The read counts every click of the range in the database, so truncated is false.
points holds aggregated cells, not raw visitor events. weight counts the clicks in a cell, maxWeight is the highest cell weight, and totalClicks counts the usable clicks in the result. x and y are normalized document coordinates between 0 and 1. When present, anchor gives the clicked element's CSS selector, its zero-based match index nth, and the normalized offsets ox and oy inside its box. Project from the anchor when the target page can resolve it, and fall back to document coordinates otherwise. Clicks recorded before element anchoring, and clicks on the document itself, have no anchor. Past 2,000 anchored cells, the lightest ones lose their anchor and move to the document grid, with their weight kept.
Tenant and availability boundaries
The call has no HTTP authentication context. The calling module authenticates and authorizes tenantId before it passes the value, and never forwards a tenant ID taken from a request as is. A websiteId of another tenant reads nothing, so it cannot widen the authorized tenant scope. No permission check grants access to another tenant's data.
Declare the interface as an optional dependency when analytics are optional. A call made before the implementing module attaches waits for it. Past 1,000 waiting calls, a new call rejects with a ProviderQueueFullError. Storage failures reject too. Catch the rejection if your page works without a heatmap, and keep an unavailable read apart from a successful empty result. This read does not ingest events, create websites or change snapshots.
Content from code
A demo instance, a template or a migration can ship its marketing content from its own backend code, without the dashboard's HTTP routes and without writing the module's tables. The content is websites, funnels with their A/B splits, page snapshots for the heatmaps, and, as a separate call, historical analytics.
- Written once, keyed by the caller. Every call carries an id that the caller chooses. For a snapshot, the key is the page and its layout. The content is created once, never duplicated and never written again, as The declaration rule explains.
- An explicit tenant, not tenant provisioning. All four content functions require
tenantId, in TypeScript and at runtime. A missing value, a non-string, an empty or whitespace-only string, or surrounding whitespace rejects before any model access. Nothing falls back to"default", and an explicit"default"is valid. These trusted backend calls neither authorize the tenant nor prove that provisioning is complete, so the caller authorizes the tenant and makes sure its storage is ready.EnsureWebsitewrites a global row with that owner.EnsureFunnel,EnsurePageSnapshotandImportAnalyticscheck the website's owner before they touch tenant-scoped storage.GetClickHeatmapdoes not run this check. - Validated like the dashboard. The website and funnel forms' field rules apply. A refusal rejects with a
MarketingDeclarationErrorthat names the call, the id and the field, for example[dms-marketing] EnsureWebsite("shop-site"): domain: not a hostname, an IP address or localhost. - Called from the provisioning hook. Register a
Hook.TENANT_BEING_PROVISIONEDhandler in your module'sconstruct(). The DMS fires the hook once per tenant, when the tenant is created. For thedefaulttenant, it fires on the DMS start that creates the tenant, once everyHook.DATABASE_INITIALIZEDhandler has finished, so the marketing tables and settings are ready. A SaaS module fires it for each workspace it creates.start()andDATABASE_INITIALIZEDrun on every boot, so they are the wrong place.
Website ids are unique across all tenants and have at most 64 characters.
import { Hook, RegisterHook } from "@antelopejs/interface-dms/hooks";
import {
EnsureFunnel,
EnsureWebsite,
ImportAnalytics,
type MarketingImportSession,
} from "@antelopejs/interface-dms-marketing";
async function writeShopContent(tenantId: string): Promise<void> {
await EnsureWebsite({
tenantId,
id: "shop-site",
name: "Shop",
domain: "shop.example.com",
extraDomains: ["localhost"],
});
await EnsureFunnel({
tenantId,
id: "shop-quote-request",
websiteId: "shop-site",
name: "Quote request",
steps: [
{ kind: "url", value: "/pricing" },
{ kind: "custom", value: "quote_submitted" },
],
conversionWindowHours: 72,
experiment: {
key: "hero-cta",
status: "running",
startedAt: "2026-07-01T00:00:00.000Z",
variations: [
{ key: "control", weight: 1 },
{ key: "bold", weight: 1 },
],
},
});
await ImportAnalytics({
tenantId,
importId: "shop-history",
websiteId: "shop-site",
sessions: historySessions(),
});
}
export function construct(): void {
RegisterHook(Hook.TENANT_BEING_PROVISIONED, async ({ tenantId }) => {
await writeShopContent(tenantId);
});
}
declare function historySessions(): MarketingImportSession[];
EnsureWebsite
import { MarketingDeclarationResult } from "@antelopejs/interface-dms-marketing";
interface MarketingWebsiteDeclaration {
id: string;
tenantId: string;
name: string;
domain: string;
extraDomains?: string[];
trackingEnabled?: boolean;
snapshotsEnabled?: boolean;
snapshotMaskText?: boolean;
}
declare function EnsureWebsite(
declaration: MarketingWebsiteDeclaration,
): Promise<MarketingDeclarationResult>;
id is the website id itself, the data-website-id of the tag, so a site's tag can name it before the site exists. It has 1 to 64 letters, digits, - or _, and starts with a letter or a digit. It is unique across tenants, so a multi-tenant project puts the tenant in it. The fields follow the dashboard's rules. name has 1 to 100 characters. domain and at most 20 extraDomains are reduced to bare lowercase hostnames, so https://Shop.Example.com/x becomes shop.example.com. Tracking is on by default, and snapshots and text masking are off. A host that another website of the tenant already declares is refused, except for the dashboard's own website. An id that names a website of another tenant is refused too.
EnsureFunnel
import { MarketingDeclarationResult } from "@antelopejs/interface-dms-marketing";
interface MarketingFunnelStep {
kind: "url" | "custom";
value: string;
}
interface MarketingExperimentDeclaration {
key: string;
variations: { key: string; weight: number }[];
status?: "draft" | "running" | "stopped";
startedAt?: number | string;
stoppedAt?: number | string;
}
interface MarketingFunnelDeclaration {
id: string;
tenantId: string;
websiteId: string;
name: string;
steps: MarketingFunnelStep[];
conversionWindowHours?: number;
experiment?: MarketingExperimentDeclaration | null;
}
declare function EnsureFunnel(
declaration: MarketingFunnelDeclaration,
): Promise<MarketingDeclarationResult>;
id is the funnel id within its tenant, with the same shape as a website id. websiteId names a website of the same tenant. name has 1 to 100 characters. A funnel has 1 to 10 steps, and each value has at most 500 characters. A page step is stored as a path, without its query and trailing slash, and a final * makes it a prefix such as /blog/*. conversionWindowHours is between 1 and 720, and 24 by default.
The split's key is unique per website. It and each variation key are lowercase slugs (^[a-z0-9][a-z0-9_-]*$) of at most 64 characters. A split has 2 to 8 arms with distinct keys. Weights are relative, never negative, and at least one is above 0. The first arm is the control.
status is the split's state at creation, "draft" by default. "running" opens one run, and "stopped" records one closed run, a finished test shipped with its history. From then on, the dashboard moves the status. startedAt and stoppedAt date that run. Each is epoch milliseconds or ISO 8601, never in the future, and now by default. A stoppedAt before startedAt is refused. The results are counted over the runs, so a split shipped with an imported history starts when that history does.
The declaration rule
Content declared from code is written once, when the tenant is provisioned, and belongs to its owner from then on. EnsureWebsite and EnsureFunnel return { id, status }. EnsurePageSnapshot returns the same statuses with its page and layout.
| Status | When | What happens |
|---|---|---|
created | No record has this id. | The call creates the record from the declaration. |
kept | A record already has this id. It was declared before, made in the dashboard or, for a snapshot, captured. | Nothing is written. |
Nothing compares a stored record with a later declaration. A declaration that changed in code does not reach a tenant provisioned before the change. To take a record back, delete it in the dashboard, and the next declaration creates it again.
EnsurePageSnapshot
The dashboard draws a heatmap over a snapshot of its page, which the tracker captures from a sampled visit. A page that is not online, or history brought by ImportAnalytics, has clicks but no snapshot, and the dashboard then shows the counts without a backdrop. EnsurePageSnapshot declares that backdrop from code.
import { MarketingDeclarationStatus } from "@antelopejs/interface-dms-marketing";
type MarketingSnapshotLayout = "desktop" | "tablet" | "phone";
interface MarketingPageSnapshotDeclaration {
tenantId: string;
websiteId: string;
url: string;
html: string;
viewport: { width: number; height: number };
document: { width: number; height: number };
colorScheme?: "light" | "dark";
}
interface MarketingPageSnapshotResult {
url: string;
layout: MarketingSnapshotLayout;
status: MarketingDeclarationStatus;
}
declare function EnsurePageSnapshot(
declaration: MarketingPageSnapshotDeclaration,
): Promise<MarketingPageSnapshotResult>;
websiteId names a website of the tenant with snapshotsEnabled. url is absolute, has at most 500 characters, and is on a host the website accepts. html is the serialized document, at most 1,048,576 characters. The viewport sides are whole numbers from 1 to 10,000 px, and the document sides from 1 to 200,000 px. The result's url is the path the snapshot is stored under.
import { Hook, RegisterHook } from "@antelopejs/interface-dms/hooks";
import {
EnsurePageSnapshot,
EnsureWebsite,
} from "@antelopejs/interface-dms-marketing";
async function writeShopContent(tenantId: string): Promise<void> {
await EnsureWebsite({
tenantId,
id: "shop-site",
name: "Shop",
domain: "shop.example.com",
snapshotsEnabled: true,
});
await EnsurePageSnapshot({
tenantId,
websiteId: "shop-site",
url: "https://shop.example.com/pricing",
html: pricingPageHtml(),
viewport: { width: 1280, height: 800 },
document: { width: 1280, height: 2600 },
});
}
export function construct(): void {
RegisterHook(Hook.TENANT_BEING_PROVISIONED, async ({ tenantId }) => {
await writeShopContent(tenantId);
});
}
declare function pricingPageHtml(): string;
- Keyed by the page. A snapshot is stored per website, page path and layout, as a capture is. The URL keeps its path, without the query and trailing slash, like a tracked page. The viewport width picks the layout: desktop from 1024 px, tablet from 600 px, and phone below. Declare one snapshot per layout the heatmap shows. For the other layouts, the dashboard reflows the nearest one.
- The same document as a capture. The HTML is what
snapshot.jswould serialize, with styles inline or as absolute stylesheet URLs, and images by absolute URL that the dashboard can reach. The module sanitizes it like an upload. It strips scripts, frames, plugins, event handlers, script URLs and form values, and puts a content security policy in front. The capture script applies the website'ssnapshotMaskText, and this call does not, so declare an already masked document for such a site.snapshotsEnabledis the opt-in for storing page content. Turning it off, or changing text masking, in the dashboard deletes the website's snapshots, declared ones included. - The declaration rule, with captures. The result follows the declaration rule. A snapshot already stored for that page and layout, captured or declared, is
kept. A capture of the live page replaces a declared one. The tracker captures a page again once its snapshot is older than one day, so a declared backdrop gives way to the real page once the page is online and sampled. - Retention and limits. The snapshot retention prunes a declared snapshot like a capture, counted from its write. A website holds at most 1,000 snapshots, and a new page past that cap rejects.
ImportAnalytics
ImportAnalytics is separate from the declarations because it adds data, once, and only deleting the website undoes it.
type JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;
type JsonObject = { [key: string]: JsonValue };
interface MarketingImportEvent {
kind: "pageview" | "custom" | "exposure" | "click" | "scroll";
at: number | string;
url: string;
referrer?: string;
title?: string;
name?: string;
data?: JsonObject;
}
interface MarketingImportSession {
visitor: string;
userAgent?: string;
country?: string;
screen?: string;
language?: string;
events: MarketingImportEvent[];
}
interface MarketingAnalyticsImport {
importId: string;
tenantId: string;
websiteId: string;
sessions: MarketingImportSession[];
}
type MarketingImportStatus = "imported" | "in_progress" | "skipped" | "failed";
interface MarketingImportResult {
importId: string;
status: MarketingImportStatus;
sessions: number;
events: number;
dropped: number;
}
declare function ImportAnalytics(
batch: MarketingAnalyticsImport,
): Promise<MarketingImportResult>;
What it writes. The history goes through the live collection pipeline with its own timestamps. The module cuts each visitor's events into the batches the tracker would have sent. A page load starts a batch, and a batch spans at most the tracker's 5-second flush interval and 25 events, on one UTC day. Each batch is ingested on the clock of its last event. Sessions are derived again exactly as live: the 30-minute idle timeout applies, a campaign landing opens its own visit, and a visitor's first session makes them new. The raw events, the sessions and the daily marketing_website_statistics rows come out as if the tracker had sent them at the time. A caller's session groups events and does not force a visit. In the result, sessions counts the visits the replay opened, which can differ from the sessions sent.
Visitors. visitor is an opaque key from the source, at most 200 characters. Within one UTC calendar month, sessions that share it, in this import or another, are one returning visitor. The key is hashed with the same monthly salt as live visitors, never stored, and never merges with a live visitor. The module parses userAgent, at most 1,000 characters, into browser, OS and device type, then discards it. country is an ISO 3166-1 alpha-2 code and stands for what live collection derives from the IP. No IP is ever involved. screen and language have at most 16 characters. A session field past its limit rejects the whole call before anything is written.
Once per import id. importId has the same shape as a website id. The call claims it for the website before the first event is written. Every later call with that id, such as the next boot or another instance starting at the same time, writes nothing, whatever its payload, and returns the state of the first call.
status | Meaning | Counts |
|---|---|---|
"imported" | This call replayed the history. | What this call wrote. |
"in_progress" | Another call claimed the id and is still replaying it. Call again later for the final counts. | Zero, not final. |
"skipped" | An earlier call applied the import. | That call's counts. |
"failed" | An import started before imports could resume stopped part-way, and is never replayed. | Not authoritative. |
A history cannot be replaced. A corrected history takes a new import id, after you delete the website if the old history must go. An import that stops part-way is resumed by the next call with its id.
Chronology and concurrency. Split history into chronological windows for the whole website, not into separate files per visitor. Every eligible timestamp in the next call must be at least the latest eligible timestamp of the previous completed imports, and equal instants are allowed. That includes interactions on expired sessions, whose timestamp does not move the live session's idle clock. An empty or entirely filtered batch keeps the boundary where it was. A backward window rejects before it writes analytics or uses up its import id. The restriction keeps old events off a newer visit, and it does not rebuild historical sessions.
A database claim lets only one import write a website at a time, across instances. A different import id rejects while the website is busy, so retry it after the first completes. A concurrent call with the same id returns in_progress while the first replays, and never an unfinished skipped. Imported batches read durable session state, not the counters another instance cached. Other websites can import at the same time.
Failure and rollout. A replay is resumable, one UTC day at a time. The website claim carries a token its holder keeps replacing, and each day commits its counters and a ledger entry in one write to that day's row. A failed call throws and frees the claim. A process that died leaves the claim behind. A later call with that id watches the token and takes the claim over once it has stayed unchanged for 30 s, which holds wherever the holder stopped and however long a live replay takes. Either way, that call takes back the raw events and sessions on days the ledger does not name, replays those days from its own payload, and returns imported with the counts of the whole import. Days already counted are skipped, so a resumed payload need not match the first one byte for byte. Until the import completes, other import ids are refused on that website. Imports started before this protocol keep their old contract. They return failed, or in_progress from a kept claim, and need reconciliation, because their partial writes cannot be told apart. For a disposable history, deleting and recreating the website clears its analytics and claims, and also its funnels and snapshots. Completed imports from an earlier implementation, which had no chronology boundary, also need reconciliation before another import. Stop old importer instances during a rollout, because they do not take part in the claim protocol.
Dropped events. The module counts dropped events, and a dropped event never fails the call. It drops an event the collect endpoint would refuse, such as an unknown kind, a field past its limit, or a URL that is neither http(s) nor a path. It drops an event whose at is unusable, beyond the permitted client clock skew, or older than the statistics retention. It drops every event of a session whose userAgent is a bot, an interaction without a preceding session, and an exposure of a split that never left draft. An exposure of a running or stopped split is kept, and the results count only the exposures inside its runs. The collection switches, the module's and the website's, do not apply, because an import is not collection.
Limits. A call carries at most 10,000 sessions, and a session at most 1,000 events. Split a larger history into several calls with distinct import ids. The next hourly prune removes raw events older than the raw-event retention, 90 days by default, as it does live ones. The daily rows stay for the statistics retention, 395 days by default. Funnels and A/B results read raw events, and the dashboards read the daily rows.