@aglyn/aglyn 1.0.0-beta.222 → 1.0.0-beta.224
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +11 -11
- package/src/lib/app-utils/crm-email-templates.js +6 -4
- package/src/lib/app-utils/crm-email-templates.js.map +1 -1
- package/src/lib/app-utils/crm.d.ts +1 -1
- package/src/lib/app-utils/crm.js.map +1 -1
- package/src/lib/app-utils/docs-help.generated.d.ts +3 -3
- package/src/lib/app-utils/docs-help.generated.js +6 -0
- package/src/lib/app-utils/docs-help.generated.js.map +1 -1
- package/src/lib/app-utils/docs-index.generated.js +17 -10
- package/src/lib/app-utils/docs-index.generated.js.map +1 -1
- package/src/lib/app-utils/functions.d.ts +10 -0
- package/src/lib/app-utils/functions.js +78 -0
- package/src/lib/app-utils/functions.js.map +1 -1
- package/src/lib/app-utils/health-report.js +12 -0
- package/src/lib/app-utils/health-report.js.map +1 -1
- package/src/lib/app-utils/host-events.d.ts +14 -0
- package/src/lib/app-utils/host-events.js +8 -0
- package/src/lib/app-utils/host-events.js.map +1 -1
- package/src/lib/app-utils/operator-alerts.js +52 -0
- package/src/lib/app-utils/operator-alerts.js.map +1 -1
- package/src/lib/app-utils/plugin-host-events.generated.js +14 -5
- package/src/lib/app-utils/plugin-host-events.generated.js.map +1 -1
- package/src/lib/app-utils/realm-host-surface.generated.js +1 -0
- package/src/lib/app-utils/realm-host-surface.generated.js.map +1 -1
- package/src/lib/app-utils/screen-route.d.ts +11 -0
- package/src/lib/app-utils/screen-route.js +16 -0
- package/src/lib/app-utils/screen-route.js.map +1 -1
- package/src/lib/app-utils/server.d.ts +0 -2
- package/src/lib/app-utils/server.js +0 -5
- package/src/lib/app-utils/server.js.map +1 -1
- package/src/lib/app-utils/site-interactions.d.ts +23 -0
- package/src/lib/app-utils/site-interactions.js +39 -2
- package/src/lib/app-utils/site-interactions.js.map +1 -1
- package/src/lib/app-utils/utm-touch.d.ts +109 -4
- package/src/lib/app-utils/utm-touch.js +364 -33
- package/src/lib/app-utils/utm-touch.js.map +1 -1
- package/src/lib/canvas-manager/canvas-manager.js +3 -1
- package/src/lib/canvas-manager/canvas-manager.js.map +1 -1
- package/src/lib/plugin-manager/first-party-plugins.generated.js +5 -1
- package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
- package/src/lib/plugin-manager/interaction-recipes.d.ts +7 -1
- package/src/lib/plugin-manager/interaction-recipes.js.map +1 -1
- package/src/lib/plugin-manager/plugin-conversion-credit.d.ts +51 -0
- package/src/lib/plugin-manager/plugin-conversion-credit.js +39 -0
- package/src/lib/plugin-manager/plugin-conversion-credit.js.map +1 -1
- package/src/lib/plugin-manager/plugin-record-pages.d.ts +15 -1
- package/src/lib/plugin-manager/plugin-record-pages.js +14 -2
- package/src/lib/plugin-manager/plugin-record-pages.js.map +1 -1
- package/src/lib/plugin-manager/plugin-record-timeline.d.ts +31 -0
- package/src/lib/plugin-manager/plugin-record-timeline.js +14 -0
- package/src/lib/plugin-manager/plugin-record-timeline.js.map +1 -1
- package/src/lib/plugin-manager/realm-host-aglyn.generated.js +1 -0
- package/src/lib/plugin-manager/realm-host-aglyn.generated.js.map +1 -1
- package/src/lib/app-utils/crm-next-activity.d.ts +0 -107
- package/src/lib/app-utils/crm-next-activity.js +0 -140
- package/src/lib/app-utils/crm-next-activity.js.map +0 -1
- package/src/lib/app-utils/crm-task-reminders.d.ts +0 -152
- package/src/lib/app-utils/crm-task-reminders.js +0 -161
- package/src/lib/app-utils/crm-task-reminders.js.map +0 -1
|
@@ -17,6 +17,7 @@ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_wi
|
|
|
17
17
|
* limitations under the License.
|
|
18
18
|
*/ import { resolveAuthoredEventName, sanitizeEventParams } from "./analytics-events.js";
|
|
19
19
|
import { sanitizeAuthorHtml } from "./author-html.js";
|
|
20
|
+
import { expressionSyntaxError } from "./functions.js";
|
|
20
21
|
import { PLUGIN_INTERACTION_STEPS_DECLARED } from "../plugin-manager/first-party-plugins.generated.js";
|
|
21
22
|
import { isKnownInteractionRecipe } from "../plugin-manager/interaction-recipes.js";
|
|
22
23
|
/**
|
|
@@ -95,6 +96,39 @@ export function isSiteEventType(event) {
|
|
|
95
96
|
}
|
|
96
97
|
return false;
|
|
97
98
|
}
|
|
99
|
+
/*
|
|
100
|
+
* A comparison or a logical operator, outside a quoted string: `==`, `!=`,
|
|
101
|
+
* `=`, `<`, `>`, `&&`, `||`, `!`. The filter's evaluator is the no-code
|
|
102
|
+
* functions' arithmetic (`functions.ts`), which has none of them, so a filter
|
|
103
|
+
* written with one throws on every event and the automation never fires.
|
|
104
|
+
*/ const FILTER_COMPARISON = /[=!<>]|&&|\|\|/;
|
|
105
|
+
function withoutStrings(text) {
|
|
106
|
+
return text.replace(/"[^"]*"|'[^']*'/g, '""');
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Why a trigger's free-text `filter` can never run, or `null` (AGL-3458).
|
|
110
|
+
*
|
|
111
|
+
* The filter is evaluated by the arithmetic expression evaluator — names,
|
|
112
|
+
* numbers, quoted text, `+ - * /`, parentheses and the built-in functions —
|
|
113
|
+
* and runs the automation when the result is truthy. It has no comparison,
|
|
114
|
+
* so `source == "form"` parses on no event: the evaluator throws, the
|
|
115
|
+
* dispatcher treats a throwing filter as "do not run", and the automation
|
|
116
|
+
* saves fine and never fires. The comparison the author meant is a
|
|
117
|
+
* CONDITION, which the editor offers right beside the filter, so the refusal
|
|
118
|
+
* names it.
|
|
119
|
+
*
|
|
120
|
+
* Only the text is judged. A name the event may not carry is the event's
|
|
121
|
+
* business: `subscribe` is a filter that runs when the field is filled in.
|
|
122
|
+
*/ export function triggerFilterProblem(filter, options = {}) {
|
|
123
|
+
const text = String(filter != null ? filter : '').trim();
|
|
124
|
+
if (!text) return null;
|
|
125
|
+
const remedy = options.remedy === 'action' ? 'start the workflow from an action with a condition (for example: source equals form) instead' : 'use a condition instead (for example: source equals form)';
|
|
126
|
+
if (FILTER_COMPARISON.test(withoutStrings(text))) {
|
|
127
|
+
return `A filter can’t compare values (no ==, !=, <, >, && or ||) — ${remedy}, and clear the filter`;
|
|
128
|
+
}
|
|
129
|
+
const syntax = expressionSyntaxError(text);
|
|
130
|
+
return syntax ? `The filter can’t be read (${syntax}) — ${remedy}, and clear the filter` : null;
|
|
131
|
+
}
|
|
98
132
|
/** How chained trigger conditions combine (AGL-565). */ export const TRIGGER_COMBINATORS = [
|
|
99
133
|
'and',
|
|
100
134
|
'or'
|
|
@@ -389,7 +423,7 @@ export function isClientActionStep(step) {
|
|
|
389
423
|
* does not know is left to its owner, through `validateStep`.
|
|
390
424
|
*/ export function validateInteraction(interaction, options = {}) {
|
|
391
425
|
var _ref, _interaction_steps;
|
|
392
|
-
var _interaction_name, _interaction_trigger_event, _interaction_trigger, _interaction_trigger_selector, _interaction_trigger1, _interaction_trigger2, _interaction_trigger3, _interaction_trigger4;
|
|
426
|
+
var _interaction_name, _interaction_trigger_event, _interaction_trigger, _interaction_trigger_selector, _interaction_trigger1, _interaction_trigger2, _interaction_trigger3, _interaction_trigger4, _interaction_trigger5;
|
|
393
427
|
if (!((_interaction_name = interaction.name) == null ? void 0 : _interaction_name.trim())) return 'Name the action';
|
|
394
428
|
// A stamp is provenance, and provenance naming a recipe that does not
|
|
395
429
|
// exist is a document nothing can read back; `null` and absent both pass.
|
|
@@ -417,8 +451,11 @@ export function isClientActionStep(step) {
|
|
|
417
451
|
if (((_interaction_trigger3 = interaction.trigger) == null ? void 0 : _interaction_trigger3.cooldownMinutes) != null && !(Number(interaction.trigger.cooldownMinutes) >= 1)) {
|
|
418
452
|
return 'Cooldown must be at least 1 minute';
|
|
419
453
|
}
|
|
454
|
+
// A filter the evaluator can never run saves fine and never fires (AGL-3458).
|
|
455
|
+
const filterProblem = triggerFilterProblem((_interaction_trigger4 = interaction.trigger) == null ? void 0 : _interaction_trigger4.filter);
|
|
456
|
+
if (filterProblem) return filterProblem;
|
|
420
457
|
// Structured payload conditions (AGL-557; chained AGL-565).
|
|
421
|
-
const combinator = (
|
|
458
|
+
const combinator = (_interaction_trigger5 = interaction.trigger) == null ? void 0 : _interaction_trigger5.combinator;
|
|
422
459
|
if (combinator != null && !TRIGGER_COMBINATORS.includes(combinator)) {
|
|
423
460
|
return 'Combine conditions with AND or OR';
|
|
424
461
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/site-interactions.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { resolveAuthoredEventName, sanitizeEventParams } from './analytics-events'\nimport { type AuthorHtmlRemoval, sanitizeAuthorHtml } from './author-html'\nimport { PLUGIN_INTERACTION_STEPS_DECLARED } from '../plugin-manager/first-party-plugins.generated'\nimport { isKnownInteractionRecipe } from '../plugin-manager/interaction-recipes'\n\n/**\n * SITE INTERACTIONS: what a published page does when a visitor does something.\n *\n * An interaction is a trigger and an ordered step list. The trigger names an\n * event — a SITE event the page runtime watches for itself (a click, a hover,\n * an element scrolled into view, exit intent), or an event raised on the\n * server — narrowed by payload conditions and capped in how often it fires.\n * The steps the platform knows are the ones a page carries out in the\n * visitor's own browser: showing and hiding elements, opening menus and\n * drawers, classes and ARIA attributes, scrolling, playing a video, an alert,\n * a redirect, an analytics event, author HTML and script.\n *\n * An interaction is stored on the element that carries it\n * (`node-interactions.ts`) or as a row of `hosts/{hostId}/actions`, and the\n * same shape holds more than the platform's own steps. A plugin adds steps of\n * its own — the workflows plugin's server steps, which a page hands to\n * `/api/events/dispatch` for the host-event listener that owns them. The\n * platform types only its own steps ({@link ClientInteractionStep}), knows any\n * other step only by its `type`, and treats every step that is not one of its\n * client steps as the server's to run. A plugin that wants one of its steps\n * offered in the interaction builder DECLARES it, under `interactionSteps` in\n * `plugins.config.json` ({@link InteractionStepDeclaration}); nothing here\n * names a plugin.\n */\n\n/**\n * Client-side site events (AGL-256) the tenant page runtime emits:\n * element interactions, scroll behavior, dwell time, and exit intent.\n * Trigger config (selector/threshold/path) rides the interaction's trigger.\n */\nexport const SITE_EVENT_TYPES = [\n 'scrollDepth',\n 'scrollToElement',\n 'elementClick',\n 'elementVisible',\n // Hover choreography (AGL-562): delegated enter/leave on the trigger\n // selector — the nav-menu/drawer show-hide building blocks.\n 'elementHoverEnter',\n 'elementHoverLeave',\n 'exitIntent',\n 'timeOnPage',\n 'pageVisit',\n] as const\n\n/** Site events that watch a specific element and need a selector. */\nexport const ELEMENT_SCOPED_SITE_EVENTS = [\n 'scrollToElement',\n 'elementClick',\n 'elementVisible',\n 'elementHoverEnter',\n 'elementHoverLeave',\n] as const\n\nexport type SiteEventType = (typeof SITE_EVENT_TYPES)[number]\n\nexport function isSiteEventType(event: string): event is SiteEventType {\n return SITE_EVENT_TYPES.includes(event as SiteEventType)\n}\n\n/** Structured condition operators (AGL-557). */\nexport const TRIGGER_CONDITION_OPS = [\n 'equals',\n 'contains',\n 'notEmpty',\n] as const\n\nexport type TriggerConditionOp = (typeof TRIGGER_CONDITION_OPS)[number]\n\n/**\n * Structured per-interaction condition over the event payload (AGL-557): the\n * no-code sibling of the free-text `filter` expression, e.g. \"only run\n * when the `subscribe` field is not empty\". Evaluated against the same\n * scope as the filter (event name + payload fields); the interaction is\n * skipped when unmet.\n */\nexport interface InteractionCondition {\n /** Payload field the condition reads (a submitted form field name). */\n field: string\n op: TriggerConditionOp\n /** Comparison value for `equals`/`contains`; unused by `notEmpty`. */\n value?: string\n}\n\n/**\n * Evaluates a structured trigger condition (AGL-557). String-coerces the\n * payload value; `equals`/`contains` compare trimmed + case-insensitive\n * so checkbox values like \"Yes\" match an author-typed \"yes\". A missing\n * field never matches (and is \"empty\" for `notEmpty`); an absent or\n * field-less condition always passes, mirroring the filter's default.\n */\nexport function evaluateTriggerCondition(\n condition: InteractionCondition | undefined | null,\n payload: Record<string, unknown>,\n): boolean {\n const field = condition?.field?.trim()\n if (!condition || !field) return true\n const raw = (payload ?? {})[field]\n const actual = (raw == null ? '' : String(raw)).trim().toLowerCase()\n if (condition.op === 'notEmpty') return actual.length > 0\n const expected = String(condition.value ?? '')\n .trim()\n .toLowerCase()\n if (condition.op === 'equals') return actual === expected\n if (condition.op === 'contains') {\n return expected.length > 0 && actual.includes(expected)\n }\n return false\n}\n\n/** How chained trigger conditions combine (AGL-565). */\nexport const TRIGGER_COMBINATORS = ['and', 'or'] as const\n\nexport type TriggerCombinator = (typeof TRIGGER_COMBINATORS)[number]\n\n/** Cap on chained conditions per trigger (AGL-565). */\nexport const ACTION_MAX_CONDITIONS = 5\n\n/**\n * Normalizes a trigger's condition clauses to a list (AGL-565): the\n * `conditions` array wins when present; a legacy single `condition`\n * (AGL-557) becomes a one-element list. Read-time only — persisted docs\n * are never migrated, so pre-565 single-condition docs keep working\n * unchanged.\n */\nexport function normalizeTriggerConditions(\n trigger:\n | Pick<InteractionTrigger, 'condition' | 'conditions'>\n | undefined\n | null,\n): InteractionCondition[] {\n const conditions = trigger?.conditions\n if (Array.isArray(conditions)) return conditions.filter(Boolean)\n return trigger?.condition ? [trigger.condition] : []\n}\n\n/**\n * Evaluates a trigger's condition list with its combinator (AGL-565):\n * `and` (the default) requires every condition to pass, `or` any one.\n * Per-condition semantics are unchanged from AGL-557\n * (`evaluateTriggerCondition`), and an empty list always passes — which\n * covers every pre-565 doc without conditions.\n */\nexport function evaluateTriggerConditions(\n trigger:\n | Pick<InteractionTrigger, 'condition' | 'conditions' | 'combinator'>\n | undefined\n | null,\n payload: Record<string, unknown>,\n): boolean {\n const conditions = normalizeTriggerConditions(trigger)\n if (!conditions.length) return true\n return trigger?.combinator === 'or'\n ? conditions.some((condition) =>\n evaluateTriggerCondition(condition, payload),\n )\n : conditions.every((condition) =>\n evaluateTriggerCondition(condition, payload),\n )\n}\n\nexport interface InteractionTrigger {\n /**\n * Event the interaction listens for: a HOST_EVENT_TYPE (server-emitted), a\n * SITE_EVENT_TYPE (client-emitted, AGL-256), or a custom name fired by\n * another automation's `customEvent` step.\n */\n event: string\n /** Optional expression over the payload; runs only when truthy. */\n filter?: string\n /** Optional structured payload condition (AGL-557); null clears it. */\n condition?: InteractionCondition | null\n /**\n * Chained payload conditions (AGL-565), combined with `combinator`.\n * When present this list wins over the legacy single `condition`\n * (see `normalizeTriggerConditions`); null clears it.\n */\n conditions?: InteractionCondition[] | null\n /** How the chained conditions combine (AGL-565); default `and`. */\n combinator?: TriggerCombinator | null\n /** CSS selector for element-scoped site events (click/visible/scroll-to). */\n selector?: string\n /** Percent 0-100 (scrollDepth) or seconds (timeOnPage). */\n threshold?: number\n /** Path pattern the site event listens on (overlay glob rules); empty = all. */\n pathPattern?: string\n /**\n * Fire at most once per visitor (AGL-266, localStorage-keyed) instead\n * of once per pageview. Site events only.\n */\n oncePerVisitor?: boolean\n /**\n * Fire at most once per browser session (AGL-274,\n * sessionStorage-keyed). Site events only.\n */\n oncePerSession?: boolean\n /**\n * Minimum minutes between fires for the same visitor (AGL-274,\n * localStorage timestamp). Site events only; ignored when\n * `oncePerVisitor` is set.\n */\n cooldownMinutes?: number\n /**\n * Fire on EVERY occurrence instead of once per pageview (AGL-562) —\n * required for repeatable UI choreography (menu toggles, drawer\n * open/close, hover show/hide). Site events only; the explicit\n * per-session/visitor/cooldown caps above still win when set.\n */\n everyTime?: boolean\n}\n\n/**\n * A per-STEP condition, and the difference between an automation and a flow.\n *\n * `InteractionTrigger.conditions` gates the whole interaction: every step runs or\n * none does. That is enough for \"when a form is submitted, do these three\n * things\" and not enough for anything with a shape — \"wait three days, then,\n * only if they have not ordered, send the reminder\" needs the condition to\n * belong to the step rather than to the run.\n *\n * Same clause type and the same combinator as the trigger's, evaluated\n * against the same scope, so an author learns one condition editor and the\n * two can never disagree about what `contains` means.\n */\nexport interface InteractionStepGuard {\n conditions: InteractionCondition[]\n /** How the clauses combine; default `and`, as on the trigger. */\n combinator?: TriggerCombinator | null\n}\n\n/**\n * Evaluates a step's own guard, with the trigger's semantics.\n *\n * An absent or clause-less guard passes, exactly as an absent trigger\n * condition does — so every step written before guards existed keeps running.\n */\nexport function evaluateStepGuard(\n guard: InteractionStepGuard | undefined | null,\n scope: Record<string, unknown>,\n): boolean {\n const conditions = (guard?.conditions ?? []).filter(Boolean)\n if (!conditions.length) return true\n return guard?.combinator === 'or'\n ? conditions.some((condition) => evaluateTriggerCondition(condition, scope))\n : conditions.every((condition) => evaluateTriggerCondition(condition, scope))\n}\n\n/**\n * The steps the platform itself carries out, in the visitor's browser (AGL-257).\n *\n * Every other step an interaction may hold is a plugin's, known here only as\n * {@link InteractionStepBase}.\n */\nexport type ClientInteractionStep = (\n | {\n type: 'siteAlert'\n message: string\n severity?: 'info' | 'success' | 'warning' | 'error'\n }\n // Client-side UI steps (AGL-257): run in the visitor's page by the\n // tenant automations engine; the server executor skips them.\n | { type: 'showOverlay'; overlayId?: string; overlayName?: string }\n | { type: 'stickyNav'; selector?: string }\n // Selectors accept CSS or a node id via [data-node-id=\"…\"] — the\n // besigner element picker emits the latter (AGL-314/319).\n | { type: 'addClass'; selector: string; className: string }\n | { type: 'removeClass'; selector: string; className: string }\n | { type: 'toggleClass'; selector: string; className: string }\n // Element show/hide choreography (AGL-562): sugar over the shared\n // hidden class (see element-ui.ts) so authors never type class names.\n // The besigner target picker emits the node's stable data-aglyn\n // selector; any CSS selector works.\n // Element visibility (AGL-562) with menu-grade choreography (AGL-589):\n // `delayMs` defers the change and a later visibility step on the same\n // selector cancels the pending one (the hover grace period), and\n // `dismissOn` self-dismisses a shown element on Escape / outside click.\n | {\n type: 'showElement'\n selector: string\n delayMs?: number\n dismissOn?: ElementDismissOption[]\n }\n | { type: 'hideElement'; selector: string; delayMs?: number }\n | {\n type: 'toggleElement'\n selector: string\n delayMs?: number\n dismissOn?: ElementDismissOption[]\n }\n // Drawer commands (AGL-562): delivered to muiDrawer instances over the\n // window event bus keyed by node id; an empty target addresses the\n // page's first drawer.\n // Attribute steps (AGL-2546): the semantics half of a hand-built\n // disclosure. `showElement` opens the panel; these are what let it say so.\n //\n // `selector`, deliberately, and NOT a new targeting field. Two mechanisms\n // key off that exact name: `regraftStepSelectors` rewrites it to the\n // grafted `cmp__{instance}__{id}` when an interaction is authored inside a\n // reusable component, and the runtime wraps it in `expandLeafSelector`.\n // The menu steps took `menuNodeId` instead, get neither, and compensate at\n // run time — one concept should not have three targeting models.\n //\n // Two verbs rather than one with an empty value: `\"\"` does not mean\n // \"absent\" uniformly. `hidden=\"\"` is true, `aria-expanded=\"\"` is invalid\n // and discarded, `data-x=\"\"` is a real value an attribute selector still\n // matches. Overloading it would make the step's meaning depend on which\n // attribute the author picked.\n | { type: 'setAttribute'; selector: string; name: string; value: string }\n | { type: 'removeAttribute'; selector: string; name: string }\n // Steps that act on ONE element (AGL-2867): the first rendered match of\n // `selector`, which is spelled `selector` for the reason the attribute\n // steps give above. `scrollTo` rather than `scrollToElement`, because that\n // name is already a TRIGGER — \"the visitor scrolled to the element\" — and\n // one word meaning both directions would be read wrong by every reader of a\n // stored document.\n | {\n type: 'scrollTo'\n selector: string\n /** Absent means `smooth`. A visitor who asks for reduced motion is always scrolled instantly. */\n behavior?: ScrollToBehavior\n /** Pixels left above the target, so a sticky header does not cover it. Absent means 0. */\n offsetPx?: number\n }\n // Presses a Video element's poster from outside it: the same press, so\n // the lightbox opens and plays, or the film plays in place of the poster.\n | { type: 'playVideo'; selector: string }\n | { type: 'openDrawer'; drawerNodeId?: string }\n | { type: 'closeDrawer'; drawerNodeId?: string }\n | { type: 'toggleDrawer'; drawerNodeId?: string }\n // Menu commands (AGL-568): the drawer pattern for Dropdown/Mega Menu\n // elements — delivered over their own window event bus keyed by node\n // id; an empty target addresses the page's first menu. Hover-triggered\n // opens carry a hover flag so the menu closes on pointer leave.\n | { type: 'openMenu'; menuNodeId?: string }\n | { type: 'closeMenu'; menuNodeId?: string }\n | { type: 'toggleMenu'; menuNodeId?: string }\n | { type: 'showHtml'; html: string }\n | { type: 'runJs'; code: string }\n // Screen targets are rename-safe (AGL-339): the tenant resolves the\n // screen id against the host routing map at run time; `url` is the\n // external/manual fallback.\n | { type: 'redirect'; url?: string; screenId?: string }\n | {\n type: 'trackGaEvent'\n eventName: string\n params?: Record<string, string>\n }\n) & {\n /** See {@link InteractionStepGuard}. Absent means the step always runs. */\n when?: InteractionStepGuard | null\n}\n\nexport type ClientInteractionStepType = ClientInteractionStep['type']\n\n/**\n * Any step, as the platform holds it: a type, the guard every step may carry,\n * and fields the platform does not read. A plugin's own step types its other\n * fields itself.\n */\nexport interface InteractionStepBase {\n type: string\n when?: InteractionStepGuard | null\n [field: string]: unknown\n}\n\n/**\n * An interaction, as `hosts/{hostId}/actions/{id}` and an element's own\n * `interactions` hold it.\n *\n * `Step` is the platform's client vocabulary unless a reader names more: the\n * workflows plugin reads the same documents with its server steps added, and\n * a step from a plugin this reader does not know is still carried, untyped,\n * in the list.\n */\nexport interface SiteInteraction<Step extends InteractionStepBase = ClientInteractionStep> {\n name: string\n trigger: InteractionTrigger\n steps: Step[]\n /** A disabled interaction never runs; a new one defaults enabled. */\n enabled?: boolean\n /**\n * The recipe this interaction was installed from or begun as (AGL-2639) —\n * one a plugin offers through `plugin-manager/interaction-recipes` — or\n * `null` for one begun blank. Absent on a document from before the stamp\n * existed: read it through `interactionRecipeStamp`, which keeps the three\n * cases apart.\n */\n recipe?: string | null\n}\n\n/** Steps the tenant page runtime executes client-side (AGL-257). */\nexport const CLIENT_ACTION_STEP_TYPES: ReadonlySet<string> =\n new Set<ClientInteractionStepType>([\n 'showOverlay',\n 'stickyNav',\n 'addClass',\n 'removeClass',\n 'toggleClass',\n 'showElement',\n 'hideElement',\n 'toggleElement',\n 'openDrawer',\n 'closeDrawer',\n 'toggleDrawer',\n 'openMenu',\n 'closeMenu',\n 'toggleMenu',\n 'setAttribute',\n 'removeAttribute',\n 'scrollTo',\n 'playVideo',\n 'showHtml',\n 'runJs',\n 'redirect',\n 'trackGaEvent',\n 'siteAlert',\n ] as const)\n\nexport function isClientActionStep(step: InteractionStepBase): step is ClientInteractionStep {\n return CLIENT_ACTION_STEP_TYPES.has(step.type)\n}\n\n/**\n * How an editor, a run history and a drafter name each of the platform's\n * client steps. Every other step is named by the plugin that declares it\n * ({@link interactionStepLabel}).\n */\nexport const CLIENT_INTERACTION_STEP_LABELS: Readonly<Record<ClientInteractionStepType, string>> = {\n siteAlert: 'Show a site alert',\n showOverlay: 'Show a popup or bar',\n stickyNav: 'Make navigation sticky',\n addClass: 'Add a CSS class',\n toggleClass: 'Toggle a CSS class',\n removeClass: 'Remove a CSS class',\n showElement: 'Show an element',\n hideElement: 'Hide an element',\n toggleElement: 'Show/hide an element',\n openDrawer: 'Open a drawer',\n closeDrawer: 'Close a drawer',\n toggleDrawer: 'Open/close a drawer',\n openMenu: 'Open a menu',\n closeMenu: 'Close a menu',\n toggleMenu: 'Open/close a menu',\n setAttribute: 'Set an ARIA or data attribute',\n removeAttribute: 'Remove an ARIA or data attribute',\n scrollTo: 'Scroll to element',\n playVideo: 'Play a video',\n showHtml: 'Show custom HTML',\n runJs: 'Run custom JS (Business)',\n redirect: 'Redirect the visitor',\n trackGaEvent: 'Track an analytics event',\n}\n\n/**\n * The client steps' fields a person types words into, and what a sentence\n * calls each: where a drafted interaction may leave a placeholder\n * (`draft-placeholders.ts`). A client step absent here holds none — a\n * selector, a class name, HTML or a script uses brackets as syntax.\n */\nconst CLIENT_INTERACTION_STEP_TYPED_FIELDS: Readonly<\n Partial<Record<ClientInteractionStepType, readonly InteractionStepTypedField[]>>\n> = {\n showOverlay: [{ key: 'overlayName', names: 'the popup or bar' }],\n siteAlert: [{ key: 'message', names: 'the message' }],\n}\n\n/**\n * Basic presentational interactions (AGL-577): the subset of client steps\n * that are pure DOM choreography — menu/drawer open-close, element\n * show/hide, class toggles, sticky nav, navigation, and client-only\n * alerts. They carry NO server cost and touch NO data, so they run on\n * every plan (the `interactions` feature, on by default everywhere).\n *\n * The powerful client steps stay behind the `actions` entitlement:\n * `showOverlay` (marketing overlays), `showHtml` (arbitrary HTML\n * injection), and `trackGaEvent` (analytics). `runJs` keeps its own\n * higher `webhooks` (Business) gate. A step that is not a client step is\n * the server's, and is re-checked against `actions` where it runs.\n */\nexport const BASIC_CLIENT_ACTION_STEP_TYPES: ReadonlySet<string> =\n new Set<ClientInteractionStepType>([\n 'stickyNav',\n 'addClass',\n 'removeClass',\n 'toggleClass',\n 'showElement',\n 'hideElement',\n 'toggleElement',\n 'openDrawer',\n 'closeDrawer',\n 'toggleDrawer',\n 'openMenu',\n 'closeMenu',\n 'toggleMenu',\n 'setAttribute',\n 'removeAttribute',\n // Moving the page and pressing a player the author placed: no data, no\n // server, and nothing a Video element's own poster does not already do\n // on every plan.\n 'scrollTo',\n 'playVideo',\n 'redirect',\n 'siteAlert',\n ] as const)\n\n/** A client step available on all plans (no `actions` entitlement). */\nexport function isBasicClientActionStep(step: InteractionStepBase): boolean {\n return BASIC_CLIENT_ACTION_STEP_TYPES.has(step.type)\n}\n\n/**\n * Whether a client step may run for the given entitlement tier (AGL-577).\n * This is the single source of truth the page enricher uses to trim the\n * client-automation payload per plan:\n *\n * - Basic presentational steps → always (every plan).\n * - `runJs` → `allowJs` (Business `webhooks` tier).\n * - Remaining advanced client steps (overlay / showHtml / analytics) →\n * `actionsEntitled` (`actions` tier).\n *\n * Server steps are not client steps and always return false here; they\n * are dispatched and re-authorized server-side.\n */\nexport function isClientStepEntitled(\n step: InteractionStepBase,\n entitlements: { actionsEntitled: boolean; allowJs: boolean },\n): boolean {\n if (!isClientActionStep(step)) return false\n if (isBasicClientActionStep(step)) return true\n if (step.type === 'runJs') return entitlements.allowJs\n return entitlements.actionsEntitled\n}\n\n/** The longest step list an interaction may hold. */\nexport const ACTION_MAX_STEPS = 10\n\n/**\n * Cap on the parameters one `trackGaEvent` step may carry (AGL-1587).\n *\n * Not a storage concern. These pairs are the least trustworthy analytics\n * input on the platform — both halves are typed by a site author and land in\n * that site's own GA4 property — and a bounded list is one an author can read\n * back in full before publishing, which is the only review a parameter ever\n * gets. GA4 caps custom parameters per event as well and drops the overflow\n * without saying so, so an unbounded editor would let an author configure\n * parameters that are never delivered and never explained. Ten, the same\n * ceiling {@link ACTION_MAX_STEPS} puts on the step list itself.\n */\nexport const ACTION_MAX_EVENT_PARAMS = 10\n\n/**\n * Longest analytics parameter NAME GA4 accepts; it drops a longer one on\n * arrival, so a name over this is silence rather than a truncated dimension.\n * The value half is capped by `ANALYTICS_PARAM_MAX_LENGTH`, which truncates\n * instead of dropping.\n */\nexport const ACTION_EVENT_PARAM_NAME_MAX_LENGTH = 40\n\n/** Self-dismiss triggers for shown elements (AGL-589). */\nexport const ELEMENT_DISMISS_OPTIONS = ['escape', 'outsideClick'] as const\nexport type ElementDismissOption = (typeof ELEMENT_DISMISS_OPTIONS)[number]\n/** Visibility grace-delay ceiling — enough for hover travel, no dead UIs. */\nexport const ELEMENT_VISIBILITY_MAX_DELAY_MS = 5000\n\n/**\n * How a `scrollTo` step moves the page. Stored in documents; never rename a\n * value. `instant` rather than the DOM's `auto`, because `auto` defers to the\n * site's CSS `scroll-behavior` — a site that sets `smooth` there would animate\n * a scroll the author asked to be instant.\n */\nexport const SCROLL_TO_BEHAVIORS = ['smooth', 'instant'] as const\nexport type ScrollToBehavior = (typeof SCROLL_TO_BEHAVIORS)[number]\n\n/**\n * The largest offset a `scrollTo` step may leave above its target.\n *\n * The offset exists to clear a sticky header, which is tens of pixels and\n * rarely more than a few hundred with an announcement bar stacked on it. A\n * thousand leaves room for any header while still refusing the extra digit\n * that would park the target off the bottom of the screen.\n */\nexport const SCROLL_TO_MAX_OFFSET_PX = 1000\n\n/** Custom event names: short, no collision with built-ins. */\nexport const CUSTOM_EVENT_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]{1,39}$/\n\n/**\n * The attribute names an interaction may write (AGL-2546).\n *\n * An unrestricted attribute setter is a self-XSS vector authored through the\n * interactions UI: it reaches `href`, `src`, `onclick`, `formaction` and\n * `style`, and on a site with collaborators the author and the victim need\n * not be the same person. `aria-*` and `data-*` carry the entire\n * accessibility use case and none of that exposure.\n *\n * Deliberately NOT solved by an entitlement gate. `runJs` is Business-gated\n * because it is dangerous at any tier; this has to work on every plan,\n * because a screen-reader user's access to a menu is not a paid feature.\n */\nexport const INTERACTION_ATTRIBUTE_NAME_PATTERN = /^(?:aria|data)-[a-z][a-z0-9-]*$/\n\n/**\n * Whether an interaction is allowed to write this attribute name.\n *\n * Case-insensitive because HTML attribute names are, and a rejected name is\n * a no-op rather than an error: a step that cannot run must not break the\n * steps after it in the same interaction.\n */\nexport function isInteractionAttributeAllowed(name: unknown): boolean {\n return (\n typeof name === 'string' &&\n INTERACTION_ATTRIBUTE_NAME_PATTERN.test(name.trim().toLowerCase())\n )\n}\n\n/**\n * An interaction step a plugin declares under `interactionSteps` in\n * `plugins.config.json`, compiled into the first-party catalog, so the\n * interaction builder can offer it and every validator can check it without\n * the plugin loaded.\n *\n * A step may be the plugin's own (a server step the plugin runs) or a\n * platform client step whose target is a record the plugin keeps. Either way\n * the declaration says how the builder names it and, for a step that PICKS a\n * record, where the builder lists the records from and which of the step's\n * fields hold the pick.\n */\nexport interface InteractionStepDeclaration {\n /** The plugin that declared it. */\n pluginId: string\n /** The stored step `type`. */\n type: string\n /** How the builder's step picker names it: \"Run a workflow\". */\n label: string\n /** The record this step acts on, picked in the builder. */\n picks?: {\n /** The site collection the records are listed from — one the plugin declares it owns. */\n collection: string\n /** How many records the builder lists. */\n limit: number\n /** The step field holding the picked record's id (rename-safe). */\n idField: string\n /** The step field holding its name at the time it was picked (display only). */\n nameField: string\n /** The picker's label: \"Workflow\". */\n label: string\n /** What a step with no pick is told, after its `Step N:` prefix. */\n missing: string\n }\n /**\n * `false` for a step only an automation holds — one that acts on the server\n * after the page that started it has gone, such as an email or a wait — so\n * the besigner's interaction builder does not offer it. Absent means offered.\n */\n offered?: false\n /** For a step that SUSPENDS the run that reaches it: see {@link InteractionStepHolds}. */\n holds?: InteractionStepHolds\n /** The step's fields a person types words into, in the order a sentence lists them. */\n typedFields?: readonly InteractionStepTypedField[]\n}\n\n/**\n * A step that suspends the run reaching it, to be continued later from a\n * beat: the whole minutes it may hold, and — where a hold can end on the\n * clock rather than on what it waits for — the scope field the continued run\n * carries to say it ran out of time. A visitor's page never runs a step past\n * one ({@link interactionStepsForClient}): everything after it belongs to a\n * run that has not happened yet.\n */\nexport interface InteractionStepHolds {\n minMinutes: number\n maxMinutes: number\n timeoutField?: string\n}\n\n/** One field of a step a person types words into, and what a sentence calls it: \"the list\". */\nexport interface InteractionStepTypedField {\n key: string\n names: string\n}\n\n/** Every step the first-party plugins declare, in `plugins.config.json` order. */\nexport function declaredInteractionSteps(): readonly InteractionStepDeclaration[] {\n return PLUGIN_INTERACTION_STEPS_DECLARED\n}\n\n/** The declared step of this type, or `null` for one no plugin declares. */\nexport function declaredInteractionStep(\n type: string,\n declarations: readonly InteractionStepDeclaration[] = PLUGIN_INTERACTION_STEPS_DECLARED,\n): InteractionStepDeclaration | null {\n return declarations.find((declaration) => declaration.type === type) ?? null\n}\n\n/**\n * How a step type reads in an editor, a run history and a drafter's words:\n * the platform's own label for a client step, else the label the declaring\n * plugin gave it; `null` for a type nobody declares.\n */\nexport function interactionStepLabel(\n type: string,\n declarations: readonly InteractionStepDeclaration[] = PLUGIN_INTERACTION_STEPS_DECLARED,\n): string | null {\n return (\n CLIENT_INTERACTION_STEP_LABELS[type as ClientInteractionStepType] ??\n declaredInteractionStep(type, declarations)?.label ??\n null\n )\n}\n\n/** The hold a step type declares, or `null` for one that never suspends a run. */\nexport function interactionStepHolds(\n type: string,\n declarations: readonly InteractionStepDeclaration[] = PLUGIN_INTERACTION_STEPS_DECLARED,\n): InteractionStepHolds | null {\n return declaredInteractionStep(type, declarations)?.holds ?? null\n}\n\n/** The fields of a step type a person types words into: the platform's, else the declaring plugin's. */\nexport function interactionStepTypedFields(\n type: string,\n declarations: readonly InteractionStepDeclaration[] = PLUGIN_INTERACTION_STEPS_DECLARED,\n): readonly InteractionStepTypedField[] {\n return (\n CLIENT_INTERACTION_STEP_TYPED_FIELDS[type as ClientInteractionStepType] ??\n declaredInteractionStep(type, declarations)?.typedFields ??\n []\n )\n}\n\n/**\n * The step list as the visitor's browser may see it: cut at the first step\n * that suspends the run.\n *\n * A client step AFTER a hold must never reach the page. The page runs its\n * slice of the list the moment the trigger fires, so shipping the whole list\n * would make \"wait three days, then show the popup\" show the popup at once —\n * the delay would appear to work on the server, be ignored in the browser,\n * and the two halves of one authored flow would disagree about when it\n * happened.\n *\n * Truncating rather than filtering: everything past the first hold belongs to\n * a run that has not happened yet, whichever side would have executed it.\n */\nexport function interactionStepsForClient<Step extends InteractionStepBase>(\n steps: readonly Step[] | undefined | null,\n declarations: readonly InteractionStepDeclaration[] = PLUGIN_INTERACTION_STEPS_DECLARED,\n): Step[] {\n const list = steps ?? []\n const holdAt = list.findIndex((step) => interactionStepHolds(step.type, declarations) !== null)\n return [...(holdAt < 0 ? list : list.slice(0, holdAt))]\n}\n\nexport interface ValidateInteractionOptions {\n /**\n * One step's checks that belong to its owner — a plugin's own step types.\n * Runs after the step's guard is checked; its answer, when not `null`, is\n * the interaction's.\n */\n validateStep?: (step: InteractionStepBase, label: string) => string | null\n /** The declared steps; the compiled first-party catalog unless a spec says otherwise. */\n declarations?: readonly InteractionStepDeclaration[]\n}\n\n/**\n * Validates an interaction's shape; returns a human-readable error or null.\n * Every surface that writes one shares this, so a bad step never persists or\n * runs.\n *\n * The platform checks what is its own: the name, the recipe stamp, the\n * trigger and its conditions, the step count, each step's guard, its client\n * steps, and the pick of every declared step that picks a record. A step it\n * does not know is left to its owner, through `validateStep`.\n */\nexport function validateInteraction(\n interaction: SiteInteraction<InteractionStepBase>,\n options: ValidateInteractionOptions = {},\n): string | null {\n if (!interaction.name?.trim()) return 'Name the action'\n // A stamp is provenance, and provenance naming a recipe that does not\n // exist is a document nothing can read back; `null` and absent both pass.\n if (interaction.recipe != null && !isKnownInteractionRecipe(interaction.recipe)) {\n return 'Unknown recipe'\n }\n const event = interaction.trigger?.event?.trim() ?? ''\n if (!event) return 'Pick a trigger event'\n // A server event or a custom one fired by another step is, like a site\n // event, a name; every built-in server event fits the custom pattern.\n if (!isSiteEventType(event) && !CUSTOM_EVENT_PATTERN.test(event)) {\n return 'Custom event names are 2–40 letters, digits, dashes'\n }\n // Site-event trigger config (AGL-256; hover events AGL-562).\n if (\n (ELEMENT_SCOPED_SITE_EVENTS as readonly string[]).includes(event) &&\n !interaction.trigger?.selector?.trim()\n ) {\n return 'This trigger needs a CSS selector'\n }\n if (\n ['scrollDepth', 'timeOnPage'].includes(event) &&\n !(Number(interaction.trigger?.threshold) > 0)\n ) {\n return event === 'scrollDepth'\n ? 'Set the scroll percentage (1–100)'\n : 'Set the seconds on page'\n }\n // Frequency caps (AGL-274).\n if (\n interaction.trigger?.cooldownMinutes != null &&\n !(Number(interaction.trigger.cooldownMinutes) >= 1)\n ) {\n return 'Cooldown must be at least 1 minute'\n }\n // Structured payload conditions (AGL-557; chained AGL-565).\n const combinator = interaction.trigger?.combinator\n if (combinator != null && !TRIGGER_COMBINATORS.includes(combinator)) {\n return 'Combine conditions with AND or OR'\n }\n const conditions = normalizeTriggerConditions(interaction.trigger)\n if (conditions.length > ACTION_MAX_CONDITIONS) {\n return `Conditions are capped at ${ACTION_MAX_CONDITIONS}`\n }\n for (const [index, condition] of conditions.entries()) {\n // Single-condition messages stay exactly as AGL-557 shipped them;\n // the row marker only appears once there are rows to tell apart.\n const where = conditions.length > 1 ? ` (condition ${index + 1})` : ''\n if (!TRIGGER_CONDITION_OPS.includes(condition.op)) {\n return `Pick a condition operator${where}`\n }\n if (!condition.field?.trim()) {\n return `Name the field the condition checks${where}`\n }\n if (condition.op !== 'notEmpty' && !condition.value?.trim()) {\n return `Enter the value the condition compares against${where}`\n }\n }\n const steps = interaction.steps ?? []\n if (!steps.length) return 'Add at least one step'\n if (steps.length > ACTION_MAX_STEPS) {\n return `Actions are capped at ${ACTION_MAX_STEPS} steps`\n }\n for (const [index, step] of steps.entries()) {\n const label = `Step ${index + 1}`\n // A step's own guard, checked with the same messages the trigger's\n // clauses get — one condition editor, one set of complaints about it.\n const guardClauses = (step.when?.conditions ?? []).filter(Boolean)\n if (guardClauses.length > ACTION_MAX_CONDITIONS) {\n return `${label}: conditions are capped at ${ACTION_MAX_CONDITIONS}`\n }\n if (\n step.when?.combinator != null &&\n !TRIGGER_COMBINATORS.includes(step.when.combinator)\n ) {\n return `${label}: combine conditions with AND or OR`\n }\n for (const clause of guardClauses) {\n if (!TRIGGER_CONDITION_OPS.includes(clause.op)) {\n return `${label}: pick a condition operator`\n }\n if (!clause.field?.trim()) {\n return `${label}: name the field the condition checks`\n }\n if (clause.op !== 'notEmpty' && !clause.value?.trim()) {\n return `${label}: enter the value the condition compares against`\n }\n }\n const owned = options.validateStep?.(step, label)\n if (owned) return owned\n const declared = declaredInteractionStep(step.type, options.declarations)\n if (declared?.picks) {\n const id = step[declared.picks.idField]\n const name = step[declared.picks.nameField]\n if (\n !(typeof id === 'string' && id.trim()) &&\n !(typeof name === 'string' && name.trim())\n ) {\n return `${label}: ${declared.picks.missing}`\n }\n }\n if (isClientActionStep(step)) {\n const problem = clientStepProblem(step, label)\n if (problem) return problem\n }\n }\n return null\n}\n\n/** A client step's own complaint, or null. The step's guard is checked by the caller. */\nfunction clientStepProblem(step: ClientInteractionStep, label: string): string | null {\n if (step.type === 'siteAlert' && !step.message?.trim()) {\n return `${label}: enter the alert message`\n }\n if (\n step.type === 'addClass' ||\n step.type === 'removeClass' ||\n step.type === 'toggleClass'\n ) {\n if (!step.selector?.trim()) return `${label}: enter a CSS selector`\n if (!step.className?.trim()) return `${label}: enter the class name`\n }\n // Element show/hide steps (AGL-562) always target a selector; drawer\n // (AGL-562) and menu (AGL-568) commands may omit the target (the\n // page's first drawer/menu answers).\n if (\n (step.type === 'showElement' ||\n step.type === 'hideElement' ||\n step.type === 'toggleElement') &&\n !step.selector?.trim()\n ) {\n return `${label}: pick the element to show or hide`\n }\n if (\n step.type === 'showElement' ||\n step.type === 'hideElement' ||\n step.type === 'toggleElement'\n ) {\n // Choreography options (AGL-589).\n const delay = (step as { delayMs?: unknown }).delayMs\n if (\n delay != null &&\n !(\n Number.isInteger(delay) &&\n (delay as number) >= 0 &&\n (delay as number) <= ELEMENT_VISIBILITY_MAX_DELAY_MS\n )\n ) {\n return `${label}: delay must be 0–${ELEMENT_VISIBILITY_MAX_DELAY_MS}ms`\n }\n const dismiss = (step as { dismissOn?: unknown }).dismissOn\n if (\n dismiss != null &&\n !(\n Array.isArray(dismiss) &&\n dismiss.every((option) =>\n (ELEMENT_DISMISS_OPTIONS as readonly string[]).includes(\n option as string,\n ),\n )\n )\n ) {\n return `${label}: dismiss options are escape and outsideClick`\n }\n }\n // One-target steps (AGL-2867). The runtime does nothing for a target it\n // cannot find, so a missing one is refused here, where it can be fixed.\n if (step.type === 'scrollTo') {\n if (!step.selector?.trim()) {\n return `${label}: pick the element to scroll to`\n }\n const behavior = (step as { behavior?: unknown }).behavior\n if (\n behavior != null &&\n !(SCROLL_TO_BEHAVIORS as readonly unknown[]).includes(behavior)\n ) {\n return `${label}: scroll smoothly or instantly`\n }\n const offset = (step as { offsetPx?: unknown }).offsetPx\n if (\n offset != null &&\n !(\n Number.isInteger(offset) &&\n (offset as number) >= 0 &&\n (offset as number) <= SCROLL_TO_MAX_OFFSET_PX\n )\n ) {\n return `${label}: the offset must be 0–${SCROLL_TO_MAX_OFFSET_PX}px`\n }\n }\n if (step.type === 'playVideo' && !step.selector?.trim()) {\n return `${label}: pick the video to play`\n }\n if (step.type === 'showHtml') {\n if (!step.html?.trim()) return `${label}: enter the HTML`\n // AGL-2486: the author-facing half of the runtime sanitizer, exactly as\n // the reserved analytics name below is the author-facing half of the\n // runtime refusal. `site-runtime.tsx` runs this HTML through\n // `sanitizeAuthorHtml` for a VISITOR, where the only thing it can do\n // with markup it refuses is drop it and say nothing — so an author who\n // pastes an embed snippet gets a step that runs, reports success, and\n // shows nothing. The refusal is reported HERE, where the person who\n // can fix it is looking, and it is the SAME function that will run at\n // render rather than a second description of its rules.\n const removals: AuthorHtmlRemoval[] = []\n const safe = sanitizeAuthorHtml(step.html, removals)\n if (!safe.trim()) {\n return `${label}: none of this HTML can be shown on a published page — ${removals[0]?.message ?? 'it is removed by the sanitizer.'}`\n }\n if (removals.length) {\n return `${label}: ${removals[0].message}${removals.length > 1 ? ` (+${removals.length - 1} more)` : ''}`\n }\n }\n if (step.type === 'runJs' && !step.code?.trim()) {\n return `${label}: enter the JavaScript`\n }\n if (step.type === 'redirect' && !step.url?.trim() && !step.screenId) {\n return `${label}: pick a page or enter the destination URL`\n }\n if (step.type === 'trackGaEvent') {\n if (!step.eventName?.trim()) {\n return `${label}: name the analytics event`\n }\n // AGL-1587: the author-facing half of the runtime refusal. The runtime\n // can only drop a bad name silently — it is executing for a VISITOR —\n // so the name is checked HERE, where the person who can fix it is.\n const resolved = resolveAuthoredEventName(step.eventName)\n if (resolved.reason === 'reserved') {\n return `${label}: \"${step.eventName.trim()}\" is a reserved analytics event name — pick another`\n }\n if (!resolved.name) {\n return `${label}: the analytics event name must start with a letter`\n }\n const params = Object.entries(step.params ?? {})\n if (params.length > ACTION_MAX_EVENT_PARAMS) {\n return `${label}: analytics parameters are capped at ${ACTION_MAX_EVENT_PARAMS}`\n }\n for (const [key, value] of params) {\n if (!key.trim()) return `${label}: name every analytics parameter`\n if (key.trim().length > ACTION_EVENT_PARAM_NAME_MAX_LENGTH) {\n return `${label}: the \"${key.trim().slice(0, 16)}…\" parameter name is over ${ACTION_EVENT_PARAM_NAME_MAX_LENGTH} characters, which GA4 drops`\n }\n if (!String(value ?? '').trim()) {\n return `${label}: enter a value for the \"${key.trim()}\" parameter`\n }\n }\n // The author-facing half of the runtime sanitizer, the same shape the\n // reserved name above and the `showHtml` check take. `trackAuthoredEvent`\n // strips a parameter that can carry personal data and says nothing about\n // it, because it is executing for a VISITOR — so an author who binds a\n // form field into a parameter gets a step that runs, reports success,\n // and delivers an event missing the dimension it was created for. The\n // strip is reported HERE, by running the REAL `sanitizeEventParams`\n // rather than a second description of its rules, so the two can never\n // disagree about which parameter survives.\n const kept = sanitizeEventParams(step.params ?? undefined)\n const stripped = params.find(([key]) => !(key in kept))\n if (stripped) {\n return `${label}: the \"${stripped[0]}\" parameter is never sent — an analytics parameter must not carry a visitor's own details`\n }\n }\n return null\n}\n\n/**\n * An interaction as the document at `hosts/{hostId}/actions/{id}` holds it.\n *\n * Every optional trigger key is written OUT — a boolean cap as `false`, a\n * cleared list as `null` — because the editors save with a merge-set, and a\n * merge keeps whatever key the payload omits: a frequency cap switched off,\n * left out of the payload, would stay on. The legacy single `condition` is\n * always nulled; `conditions` has been canonical since the list shape arrived\n * and a document that carried both would have the reader pick. Everything\n * else is the interaction, unchanged.\n *\n * `recipe` rides along only when the interaction SAYS something about it: an\n * id or `null`. One that carries no stamp (an older document, edited and\n * saved again) keeps carrying none — see `interactionRecipeStamp` for why an\n * absent stamp must not become a `null` one.\n */\nexport type SiteInteractionDocument<Step extends InteractionStepBase = InteractionStepBase> =\n SiteInteraction<Step> & {\n trigger: InteractionTrigger & {\n oncePerVisitor: boolean\n oncePerSession: boolean\n cooldownMinutes: number | null\n everyTime: boolean\n condition: null\n conditions: InteractionCondition[] | null\n combinator: TriggerCombinator | null\n }\n enabled: boolean\n }\n\n/** The stored shape of an interaction: what every writer of `hosts/{hostId}/actions` saves. */\nexport function siteInteractionDocument<Step extends InteractionStepBase>(\n interaction: SiteInteraction<Step>,\n): SiteInteractionDocument<Step> {\n const { recipe, ...rest } = interaction\n const trigger = interaction.trigger\n return {\n ...rest,\n trigger: {\n ...trigger,\n oncePerVisitor: trigger.oncePerVisitor === true,\n oncePerSession: trigger.oncePerSession === true,\n cooldownMinutes:\n Number(trigger.cooldownMinutes) >= 1 ? Number(trigger.cooldownMinutes) : null,\n everyTime: trigger.everyTime === true,\n condition: null,\n conditions: trigger.conditions ?? null,\n combinator: trigger.combinator ?? null,\n },\n enabled: interaction.enabled !== false,\n ...(recipe !== undefined ? { recipe } : {}),\n }\n}\n\n/** Alert produced by a `siteAlert` step, surfaced to the emitting client. */\nexport interface SiteAlert {\n message: string\n severity: 'info' | 'success' | 'warning' | 'error'\n}\n\n/**\n * How many LIVE action documents one host may hold (AGL-2266).\n *\n * `hosts/{hostId}/actions` was in NO exclusion list in\n * `cloud/firebase-firestore.rules`, so the host catch-all's `allow create`\n * granted it to any editor, client-direct, on any plan — and the import\n * route's own table said so in as many words: *\"no `RESOURCES` entry and no\n * quota key anywhere; all three creators write the document client-direct.\"*\n * A free org could therefore mint unbounded Firestore documents from the\n * browser against a $0 subscription. Unbounded infrastructure, not a bypass of\n * anything we sell, which is `WEBHOOK_MAX_PER_HOST`'s (AGL-1360) and\n * `NON_PAGE_SCREEN_MAX_PER_HOST`'s (AGL-1399) shape exactly: a flat PLATFORM\n * cap with no `OrgEntitlements` key, no variation by plan, and nothing on the\n * price list to explain.\n *\n * ## Not gated on the `actions` entitlement, deliberately\n *\n * `actions` is a Pro feature and `interactions` is free, and BOTH write this\n * collection — the interaction builder and the besigner's preset wiring create\n * the same document type the Pro actions card does. Gating creation on the\n * paid flag would take element interactions away from every free and starter\n * site, which is a pricing change wearing a cap's clothes. The runtime already\n * checks the entitlement where it decides what may RUN\n * (`run-event-actions.ts`), which is the right place for it.\n *\n * ## Why 500\n *\n * Sized to the busiest plausible site rather than to today's data. An action\n * is authored per interactive element, so a heavy marketing site with dropdown\n * choreography on every section reaches tens; presets wire a handful at a\n * time. 500 is far past anything authoring produces and well short of what a\n * script in a loop wants, which is the only property a flat cap needs. Live\n * documents only — the interactions provider soft-deletes with `deletedAt`, so\n * counting tombstones would be AGL-1173's bug one collection over, where\n * removing an interaction never frees its slot.\n */\nexport const ACTIONS_MAX_PER_HOST = 500\n"],"names":["resolveAuthoredEventName","sanitizeEventParams","sanitizeAuthorHtml","PLUGIN_INTERACTION_STEPS_DECLARED","isKnownInteractionRecipe","SITE_EVENT_TYPES","ELEMENT_SCOPED_SITE_EVENTS","isSiteEventType","event","includes","TRIGGER_CONDITION_OPS","evaluateTriggerCondition","condition","payload","field","trim","raw","actual","String","toLowerCase","op","length","expected","value","TRIGGER_COMBINATORS","ACTION_MAX_CONDITIONS","normalizeTriggerConditions","trigger","conditions","Array","isArray","filter","Boolean","evaluateTriggerConditions","combinator","some","every","evaluateStepGuard","guard","scope","CLIENT_ACTION_STEP_TYPES","Set","isClientActionStep","step","has","type","CLIENT_INTERACTION_STEP_LABELS","siteAlert","showOverlay","stickyNav","addClass","toggleClass","removeClass","showElement","hideElement","toggleElement","openDrawer","closeDrawer","toggleDrawer","openMenu","closeMenu","toggleMenu","setAttribute","removeAttribute","scrollTo","playVideo","showHtml","runJs","redirect","trackGaEvent","CLIENT_INTERACTION_STEP_TYPED_FIELDS","key","names","BASIC_CLIENT_ACTION_STEP_TYPES","isBasicClientActionStep","isClientStepEntitled","entitlements","allowJs","actionsEntitled","ACTION_MAX_STEPS","ACTION_MAX_EVENT_PARAMS","ACTION_EVENT_PARAM_NAME_MAX_LENGTH","ELEMENT_DISMISS_OPTIONS","ELEMENT_VISIBILITY_MAX_DELAY_MS","SCROLL_TO_BEHAVIORS","SCROLL_TO_MAX_OFFSET_PX","CUSTOM_EVENT_PATTERN","INTERACTION_ATTRIBUTE_NAME_PATTERN","isInteractionAttributeAllowed","name","test","declaredInteractionSteps","declaredInteractionStep","declarations","find","declaration","interactionStepLabel","label","interactionStepHolds","holds","interactionStepTypedFields","typedFields","interactionStepsForClient","steps","list","holdAt","findIndex","slice","validateInteraction","interaction","options","recipe","selector","Number","threshold","cooldownMinutes","index","entries","where","guardClauses","when","clause","owned","validateStep","declared","picks","id","idField","nameField","missing","problem","clientStepProblem","message","className","delay","delayMs","isInteger","dismiss","dismissOn","option","behavior","offset","offsetPx","html","removals","safe","code","url","screenId","eventName","resolved","reason","params","Object","kept","undefined","stripped","siteInteractionDocument","rest","oncePerVisitor","oncePerSession","everyTime","enabled","ACTIONS_MAX_PER_HOST"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,wBAAwB,EAAEC,mBAAmB,QAAQ,wBAAoB;AAClF,SAAiCC,kBAAkB,QAAQ,mBAAe;AAC1E,SAASC,iCAAiC,QAAQ,qDAAiD;AACnG,SAASC,wBAAwB,QAAQ,2CAAuC;AAEhF;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED;;;;CAIC,GACD,OAAO,MAAMC,mBAAmB;IAC9B;IACA;IACA;IACA;IACA,qEAAqE;IACrE,4DAA4D;IAC5D;IACA;IACA;IACA;IACA;CACD,CAAS;AAEV,mEAAmE,GACnE,OAAO,MAAMC,6BAA6B;IACxC;IACA;IACA;IACA;IACA;CACD,CAAS;AAIV,OAAO,SAASC,gBAAgBC,KAAa;IAC3C,OAAOH,iBAAiBI,QAAQ,CAACD;AACnC;AAEA,8CAA8C,GAC9C,OAAO,MAAME,wBAAwB;IACnC;IACA;IACA;CACD,CAAS;AAmBV;;;;;;CAMC,GACD,OAAO,SAASC,yBACdC,SAAkD,EAClDC,OAAgC;QAORD;QALVA;IAAd,MAAME,QAAQF,8BAAAA,mBAAAA,UAAWE,KAAK,qBAAhBF,iBAAkBG,IAAI;IACpC,IAAI,CAACH,aAAa,CAACE,OAAO,OAAO;IACjC,MAAME,MAAM,CAACH,kBAAAA,UAAW,CAAC,EAAE,CAACC,MAAM;IAClC,MAAMG,SAAS,AAACD,CAAAA,OAAO,OAAO,KAAKE,OAAOF,IAAG,EAAGD,IAAI,GAAGI,WAAW;IAClE,IAAIP,UAAUQ,EAAE,KAAK,YAAY,OAAOH,OAAOI,MAAM,GAAG;IACxD,MAAMC,WAAWJ,Q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,OAAOtF,QAAQwF,eAAe,IAAI;YAC3E8C,WAAWtI,QAAQsI,SAAS,KAAK;YACjCrJ,WAAW;YACXgB,UAAU,GAAED,sBAAAA,QAAQC,UAAU,YAAlBD,sBAAsB;YAClCO,UAAU,GAAEP,sBAAAA,QAAQO,UAAU,YAAlBP,sBAAsB;;QAEpCuI,SAASrD,YAAYqD,OAAO,KAAK;OAC7BnD,WAAW4C,YAAY;QAAE5C;IAAO,IAAI,CAAC;AAE7C;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCC,GACD,OAAO,MAAMoD,uBAAuB,IAAG"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/site-interactions.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { resolveAuthoredEventName, sanitizeEventParams } from './analytics-events'\nimport { type AuthorHtmlRemoval, sanitizeAuthorHtml } from './author-html'\nimport { expressionSyntaxError } from './functions'\nimport { PLUGIN_INTERACTION_STEPS_DECLARED } from '../plugin-manager/first-party-plugins.generated'\nimport { isKnownInteractionRecipe } from '../plugin-manager/interaction-recipes'\n\n/**\n * SITE INTERACTIONS: what a published page does when a visitor does something.\n *\n * An interaction is a trigger and an ordered step list. The trigger names an\n * event — a SITE event the page runtime watches for itself (a click, a hover,\n * an element scrolled into view, exit intent), or an event raised on the\n * server — narrowed by payload conditions and capped in how often it fires.\n * The steps the platform knows are the ones a page carries out in the\n * visitor's own browser: showing and hiding elements, opening menus and\n * drawers, classes and ARIA attributes, scrolling, playing a video, an alert,\n * a redirect, an analytics event, author HTML and script.\n *\n * An interaction is stored on the element that carries it\n * (`node-interactions.ts`) or as a row of `hosts/{hostId}/actions`, and the\n * same shape holds more than the platform's own steps. A plugin adds steps of\n * its own — the workflows plugin's server steps, which a page hands to\n * `/api/events/dispatch` for the host-event listener that owns them. The\n * platform types only its own steps ({@link ClientInteractionStep}), knows any\n * other step only by its `type`, and treats every step that is not one of its\n * client steps as the server's to run. A plugin that wants one of its steps\n * offered in the interaction builder DECLARES it, under `interactionSteps` in\n * `plugins.config.json` ({@link InteractionStepDeclaration}); nothing here\n * names a plugin.\n */\n\n/**\n * Client-side site events (AGL-256) the tenant page runtime emits:\n * element interactions, scroll behavior, dwell time, and exit intent.\n * Trigger config (selector/threshold/path) rides the interaction's trigger.\n */\nexport const SITE_EVENT_TYPES = [\n 'scrollDepth',\n 'scrollToElement',\n 'elementClick',\n 'elementVisible',\n // Hover choreography (AGL-562): delegated enter/leave on the trigger\n // selector — the nav-menu/drawer show-hide building blocks.\n 'elementHoverEnter',\n 'elementHoverLeave',\n 'exitIntent',\n 'timeOnPage',\n 'pageVisit',\n] as const\n\n/** Site events that watch a specific element and need a selector. */\nexport const ELEMENT_SCOPED_SITE_EVENTS = [\n 'scrollToElement',\n 'elementClick',\n 'elementVisible',\n 'elementHoverEnter',\n 'elementHoverLeave',\n] as const\n\nexport type SiteEventType = (typeof SITE_EVENT_TYPES)[number]\n\nexport function isSiteEventType(event: string): event is SiteEventType {\n return SITE_EVENT_TYPES.includes(event as SiteEventType)\n}\n\n/** Structured condition operators (AGL-557). */\nexport const TRIGGER_CONDITION_OPS = [\n 'equals',\n 'contains',\n 'notEmpty',\n] as const\n\nexport type TriggerConditionOp = (typeof TRIGGER_CONDITION_OPS)[number]\n\n/**\n * Structured per-interaction condition over the event payload (AGL-557): the\n * no-code sibling of the free-text `filter` expression, e.g. \"only run\n * when the `subscribe` field is not empty\". Evaluated against the same\n * scope as the filter (event name + payload fields); the interaction is\n * skipped when unmet.\n */\nexport interface InteractionCondition {\n /** Payload field the condition reads (a submitted form field name). */\n field: string\n op: TriggerConditionOp\n /** Comparison value for `equals`/`contains`; unused by `notEmpty`. */\n value?: string\n}\n\n/**\n * Evaluates a structured trigger condition (AGL-557). String-coerces the\n * payload value; `equals`/`contains` compare trimmed + case-insensitive\n * so checkbox values like \"Yes\" match an author-typed \"yes\". A missing\n * field never matches (and is \"empty\" for `notEmpty`); an absent or\n * field-less condition always passes, mirroring the filter's default.\n */\nexport function evaluateTriggerCondition(\n condition: InteractionCondition | undefined | null,\n payload: Record<string, unknown>,\n): boolean {\n const field = condition?.field?.trim()\n if (!condition || !field) return true\n const raw = (payload ?? {})[field]\n const actual = (raw == null ? '' : String(raw)).trim().toLowerCase()\n if (condition.op === 'notEmpty') return actual.length > 0\n const expected = String(condition.value ?? '')\n .trim()\n .toLowerCase()\n if (condition.op === 'equals') return actual === expected\n if (condition.op === 'contains') {\n return expected.length > 0 && actual.includes(expected)\n }\n return false\n}\n\n/*\n * A comparison or a logical operator, outside a quoted string: `==`, `!=`,\n * `=`, `<`, `>`, `&&`, `||`, `!`. The filter's evaluator is the no-code\n * functions' arithmetic (`functions.ts`), which has none of them, so a filter\n * written with one throws on every event and the automation never fires.\n */\nconst FILTER_COMPARISON = /[=!<>]|&&|\\|\\|/\n\nfunction withoutStrings(text: string): string {\n return text.replace(/\"[^\"]*\"|'[^']*'/g, '\"\"')\n}\n\n/**\n * Why a trigger's free-text `filter` can never run, or `null` (AGL-3458).\n *\n * The filter is evaluated by the arithmetic expression evaluator — names,\n * numbers, quoted text, `+ - * /`, parentheses and the built-in functions —\n * and runs the automation when the result is truthy. It has no comparison,\n * so `source == \"form\"` parses on no event: the evaluator throws, the\n * dispatcher treats a throwing filter as \"do not run\", and the automation\n * saves fine and never fires. The comparison the author meant is a\n * CONDITION, which the editor offers right beside the filter, so the refusal\n * names it.\n *\n * Only the text is judged. A name the event may not carry is the event's\n * business: `subscribe` is a filter that runs when the field is filled in.\n */\nexport function triggerFilterProblem(\n filter: string | null | undefined,\n options: {\n /**\n * Where the comparison the author meant belongs. An action's trigger has\n * conditions beside the filter; a workflow's has none, so it is pointed\n * at an action with a condition that runs the workflow.\n */\n remedy?: 'conditions' | 'action'\n } = {},\n): string | null {\n const text = String(filter ?? '').trim()\n if (!text) return null\n const remedy =\n options.remedy === 'action'\n ? 'start the workflow from an action with a condition (for example: source equals form) instead'\n : 'use a condition instead (for example: source equals form)'\n if (FILTER_COMPARISON.test(withoutStrings(text))) {\n return `A filter can’t compare values (no ==, !=, <, >, && or ||) — ${remedy}, and clear the filter`\n }\n const syntax = expressionSyntaxError(text)\n return syntax ? `The filter can’t be read (${syntax}) — ${remedy}, and clear the filter` : null\n}\n\n/** How chained trigger conditions combine (AGL-565). */\nexport const TRIGGER_COMBINATORS = ['and', 'or'] as const\n\nexport type TriggerCombinator = (typeof TRIGGER_COMBINATORS)[number]\n\n/** Cap on chained conditions per trigger (AGL-565). */\nexport const ACTION_MAX_CONDITIONS = 5\n\n/**\n * Normalizes a trigger's condition clauses to a list (AGL-565): the\n * `conditions` array wins when present; a legacy single `condition`\n * (AGL-557) becomes a one-element list. Read-time only — persisted docs\n * are never migrated, so pre-565 single-condition docs keep working\n * unchanged.\n */\nexport function normalizeTriggerConditions(\n trigger:\n | Pick<InteractionTrigger, 'condition' | 'conditions'>\n | undefined\n | null,\n): InteractionCondition[] {\n const conditions = trigger?.conditions\n if (Array.isArray(conditions)) return conditions.filter(Boolean)\n return trigger?.condition ? [trigger.condition] : []\n}\n\n/**\n * Evaluates a trigger's condition list with its combinator (AGL-565):\n * `and` (the default) requires every condition to pass, `or` any one.\n * Per-condition semantics are unchanged from AGL-557\n * (`evaluateTriggerCondition`), and an empty list always passes — which\n * covers every pre-565 doc without conditions.\n */\nexport function evaluateTriggerConditions(\n trigger:\n | Pick<InteractionTrigger, 'condition' | 'conditions' | 'combinator'>\n | undefined\n | null,\n payload: Record<string, unknown>,\n): boolean {\n const conditions = normalizeTriggerConditions(trigger)\n if (!conditions.length) return true\n return trigger?.combinator === 'or'\n ? conditions.some((condition) =>\n evaluateTriggerCondition(condition, payload),\n )\n : conditions.every((condition) =>\n evaluateTriggerCondition(condition, payload),\n )\n}\n\nexport interface InteractionTrigger {\n /**\n * Event the interaction listens for: a HOST_EVENT_TYPE (server-emitted), a\n * SITE_EVENT_TYPE (client-emitted, AGL-256), or a custom name fired by\n * another automation's `customEvent` step.\n */\n event: string\n /** Optional expression over the payload; runs only when truthy. */\n filter?: string\n /** Optional structured payload condition (AGL-557); null clears it. */\n condition?: InteractionCondition | null\n /**\n * Chained payload conditions (AGL-565), combined with `combinator`.\n * When present this list wins over the legacy single `condition`\n * (see `normalizeTriggerConditions`); null clears it.\n */\n conditions?: InteractionCondition[] | null\n /** How the chained conditions combine (AGL-565); default `and`. */\n combinator?: TriggerCombinator | null\n /** CSS selector for element-scoped site events (click/visible/scroll-to). */\n selector?: string\n /** Percent 0-100 (scrollDepth) or seconds (timeOnPage). */\n threshold?: number\n /** Path pattern the site event listens on (overlay glob rules); empty = all. */\n pathPattern?: string\n /**\n * Fire at most once per visitor (AGL-266, localStorage-keyed) instead\n * of once per pageview. Site events only.\n */\n oncePerVisitor?: boolean\n /**\n * Fire at most once per browser session (AGL-274,\n * sessionStorage-keyed). Site events only.\n */\n oncePerSession?: boolean\n /**\n * Minimum minutes between fires for the same visitor (AGL-274,\n * localStorage timestamp). Site events only; ignored when\n * `oncePerVisitor` is set.\n */\n cooldownMinutes?: number\n /**\n * Fire on EVERY occurrence instead of once per pageview (AGL-562) —\n * required for repeatable UI choreography (menu toggles, drawer\n * open/close, hover show/hide). Site events only; the explicit\n * per-session/visitor/cooldown caps above still win when set.\n */\n everyTime?: boolean\n}\n\n/**\n * A per-STEP condition, and the difference between an automation and a flow.\n *\n * `InteractionTrigger.conditions` gates the whole interaction: every step runs or\n * none does. That is enough for \"when a form is submitted, do these three\n * things\" and not enough for anything with a shape — \"wait three days, then,\n * only if they have not ordered, send the reminder\" needs the condition to\n * belong to the step rather than to the run.\n *\n * Same clause type and the same combinator as the trigger's, evaluated\n * against the same scope, so an author learns one condition editor and the\n * two can never disagree about what `contains` means.\n */\nexport interface InteractionStepGuard {\n conditions: InteractionCondition[]\n /** How the clauses combine; default `and`, as on the trigger. */\n combinator?: TriggerCombinator | null\n}\n\n/**\n * Evaluates a step's own guard, with the trigger's semantics.\n *\n * An absent or clause-less guard passes, exactly as an absent trigger\n * condition does — so every step written before guards existed keeps running.\n */\nexport function evaluateStepGuard(\n guard: InteractionStepGuard | undefined | null,\n scope: Record<string, unknown>,\n): boolean {\n const conditions = (guard?.conditions ?? []).filter(Boolean)\n if (!conditions.length) return true\n return guard?.combinator === 'or'\n ? conditions.some((condition) => evaluateTriggerCondition(condition, scope))\n : conditions.every((condition) => evaluateTriggerCondition(condition, scope))\n}\n\n/**\n * The steps the platform itself carries out, in the visitor's browser (AGL-257).\n *\n * Every other step an interaction may hold is a plugin's, known here only as\n * {@link InteractionStepBase}.\n */\nexport type ClientInteractionStep = (\n | {\n type: 'siteAlert'\n message: string\n severity?: 'info' | 'success' | 'warning' | 'error'\n }\n // Client-side UI steps (AGL-257): run in the visitor's page by the\n // tenant automations engine; the server executor skips them.\n | { type: 'showOverlay'; overlayId?: string; overlayName?: string }\n | { type: 'stickyNav'; selector?: string }\n // Selectors accept CSS or a node id via [data-node-id=\"…\"] — the\n // besigner element picker emits the latter (AGL-314/319).\n | { type: 'addClass'; selector: string; className: string }\n | { type: 'removeClass'; selector: string; className: string }\n | { type: 'toggleClass'; selector: string; className: string }\n // Element show/hide choreography (AGL-562): sugar over the shared\n // hidden class (see element-ui.ts) so authors never type class names.\n // The besigner target picker emits the node's stable data-aglyn\n // selector; any CSS selector works.\n // Element visibility (AGL-562) with menu-grade choreography (AGL-589):\n // `delayMs` defers the change and a later visibility step on the same\n // selector cancels the pending one (the hover grace period), and\n // `dismissOn` self-dismisses a shown element on Escape / outside click.\n | {\n type: 'showElement'\n selector: string\n delayMs?: number\n dismissOn?: ElementDismissOption[]\n }\n | { type: 'hideElement'; selector: string; delayMs?: number }\n | {\n type: 'toggleElement'\n selector: string\n delayMs?: number\n dismissOn?: ElementDismissOption[]\n }\n // Drawer commands (AGL-562): delivered to muiDrawer instances over the\n // window event bus keyed by node id; an empty target addresses the\n // page's first drawer.\n // Attribute steps (AGL-2546): the semantics half of a hand-built\n // disclosure. `showElement` opens the panel; these are what let it say so.\n //\n // `selector`, deliberately, and NOT a new targeting field. Two mechanisms\n // key off that exact name: `regraftStepSelectors` rewrites it to the\n // grafted `cmp__{instance}__{id}` when an interaction is authored inside a\n // reusable component, and the runtime wraps it in `expandLeafSelector`.\n // The menu steps took `menuNodeId` instead, get neither, and compensate at\n // run time — one concept should not have three targeting models.\n //\n // Two verbs rather than one with an empty value: `\"\"` does not mean\n // \"absent\" uniformly. `hidden=\"\"` is true, `aria-expanded=\"\"` is invalid\n // and discarded, `data-x=\"\"` is a real value an attribute selector still\n // matches. Overloading it would make the step's meaning depend on which\n // attribute the author picked.\n | { type: 'setAttribute'; selector: string; name: string; value: string }\n | { type: 'removeAttribute'; selector: string; name: string }\n // Steps that act on ONE element (AGL-2867): the first rendered match of\n // `selector`, which is spelled `selector` for the reason the attribute\n // steps give above. `scrollTo` rather than `scrollToElement`, because that\n // name is already a TRIGGER — \"the visitor scrolled to the element\" — and\n // one word meaning both directions would be read wrong by every reader of a\n // stored document.\n | {\n type: 'scrollTo'\n selector: string\n /** Absent means `smooth`. A visitor who asks for reduced motion is always scrolled instantly. */\n behavior?: ScrollToBehavior\n /** Pixels left above the target, so a sticky header does not cover it. Absent means 0. */\n offsetPx?: number\n }\n // Presses a Video element's poster from outside it: the same press, so\n // the lightbox opens and plays, or the film plays in place of the poster.\n | { type: 'playVideo'; selector: string }\n | { type: 'openDrawer'; drawerNodeId?: string }\n | { type: 'closeDrawer'; drawerNodeId?: string }\n | { type: 'toggleDrawer'; drawerNodeId?: string }\n // Menu commands (AGL-568): the drawer pattern for Dropdown/Mega Menu\n // elements — delivered over their own window event bus keyed by node\n // id; an empty target addresses the page's first menu. Hover-triggered\n // opens carry a hover flag so the menu closes on pointer leave.\n | { type: 'openMenu'; menuNodeId?: string }\n | { type: 'closeMenu'; menuNodeId?: string }\n | { type: 'toggleMenu'; menuNodeId?: string }\n | { type: 'showHtml'; html: string }\n | { type: 'runJs'; code: string }\n // Screen targets are rename-safe (AGL-339): the tenant resolves the\n // screen id against the host routing map at run time; `url` is the\n // external/manual fallback.\n | { type: 'redirect'; url?: string; screenId?: string }\n | {\n type: 'trackGaEvent'\n eventName: string\n params?: Record<string, string>\n }\n) & {\n /** See {@link InteractionStepGuard}. Absent means the step always runs. */\n when?: InteractionStepGuard | null\n}\n\nexport type ClientInteractionStepType = ClientInteractionStep['type']\n\n/**\n * Any step, as the platform holds it: a type, the guard every step may carry,\n * and fields the platform does not read. A plugin's own step types its other\n * fields itself.\n */\nexport interface InteractionStepBase {\n type: string\n when?: InteractionStepGuard | null\n [field: string]: unknown\n}\n\n/**\n * An interaction, as `hosts/{hostId}/actions/{id}` and an element's own\n * `interactions` hold it.\n *\n * `Step` is the platform's client vocabulary unless a reader names more: the\n * workflows plugin reads the same documents with its server steps added, and\n * a step from a plugin this reader does not know is still carried, untyped,\n * in the list.\n */\nexport interface SiteInteraction<Step extends InteractionStepBase = ClientInteractionStep> {\n name: string\n trigger: InteractionTrigger\n steps: Step[]\n /** A disabled interaction never runs; a new one defaults enabled. */\n enabled?: boolean\n /**\n * The recipe this interaction was installed from or begun as (AGL-2639) —\n * one a plugin offers through `plugin-manager/interaction-recipes` — or\n * `null` for one begun blank. Absent on a document from before the stamp\n * existed: read it through `interactionRecipeStamp`, which keeps the three\n * cases apart.\n */\n recipe?: string | null\n}\n\n/** Steps the tenant page runtime executes client-side (AGL-257). */\nexport const CLIENT_ACTION_STEP_TYPES: ReadonlySet<string> =\n new Set<ClientInteractionStepType>([\n 'showOverlay',\n 'stickyNav',\n 'addClass',\n 'removeClass',\n 'toggleClass',\n 'showElement',\n 'hideElement',\n 'toggleElement',\n 'openDrawer',\n 'closeDrawer',\n 'toggleDrawer',\n 'openMenu',\n 'closeMenu',\n 'toggleMenu',\n 'setAttribute',\n 'removeAttribute',\n 'scrollTo',\n 'playVideo',\n 'showHtml',\n 'runJs',\n 'redirect',\n 'trackGaEvent',\n 'siteAlert',\n ] as const)\n\nexport function isClientActionStep(step: InteractionStepBase): step is ClientInteractionStep {\n return CLIENT_ACTION_STEP_TYPES.has(step.type)\n}\n\n/**\n * How an editor, a run history and a drafter name each of the platform's\n * client steps. Every other step is named by the plugin that declares it\n * ({@link interactionStepLabel}).\n */\nexport const CLIENT_INTERACTION_STEP_LABELS: Readonly<Record<ClientInteractionStepType, string>> = {\n siteAlert: 'Show a site alert',\n showOverlay: 'Show a popup or bar',\n stickyNav: 'Make navigation sticky',\n addClass: 'Add a CSS class',\n toggleClass: 'Toggle a CSS class',\n removeClass: 'Remove a CSS class',\n showElement: 'Show an element',\n hideElement: 'Hide an element',\n toggleElement: 'Show/hide an element',\n openDrawer: 'Open a drawer',\n closeDrawer: 'Close a drawer',\n toggleDrawer: 'Open/close a drawer',\n openMenu: 'Open a menu',\n closeMenu: 'Close a menu',\n toggleMenu: 'Open/close a menu',\n setAttribute: 'Set an ARIA or data attribute',\n removeAttribute: 'Remove an ARIA or data attribute',\n scrollTo: 'Scroll to element',\n playVideo: 'Play a video',\n showHtml: 'Show custom HTML',\n runJs: 'Run custom JS (Business)',\n redirect: 'Redirect the visitor',\n trackGaEvent: 'Track an analytics event',\n}\n\n/**\n * The client steps' fields a person types words into, and what a sentence\n * calls each: where a drafted interaction may leave a placeholder\n * (`draft-placeholders.ts`). A client step absent here holds none — a\n * selector, a class name, HTML or a script uses brackets as syntax.\n */\nconst CLIENT_INTERACTION_STEP_TYPED_FIELDS: Readonly<\n Partial<Record<ClientInteractionStepType, readonly InteractionStepTypedField[]>>\n> = {\n showOverlay: [{ key: 'overlayName', names: 'the popup or bar' }],\n siteAlert: [{ key: 'message', names: 'the message' }],\n}\n\n/**\n * Basic presentational interactions (AGL-577): the subset of client steps\n * that are pure DOM choreography — menu/drawer open-close, element\n * show/hide, class toggles, sticky nav, navigation, and client-only\n * alerts. They carry NO server cost and touch NO data, so they run on\n * every plan (the `interactions` feature, on by default everywhere).\n *\n * The powerful client steps stay behind the `actions` entitlement:\n * `showOverlay` (marketing overlays), `showHtml` (arbitrary HTML\n * injection), and `trackGaEvent` (analytics). `runJs` keeps its own\n * higher `webhooks` (Business) gate. A step that is not a client step is\n * the server's, and is re-checked against `actions` where it runs.\n */\nexport const BASIC_CLIENT_ACTION_STEP_TYPES: ReadonlySet<string> =\n new Set<ClientInteractionStepType>([\n 'stickyNav',\n 'addClass',\n 'removeClass',\n 'toggleClass',\n 'showElement',\n 'hideElement',\n 'toggleElement',\n 'openDrawer',\n 'closeDrawer',\n 'toggleDrawer',\n 'openMenu',\n 'closeMenu',\n 'toggleMenu',\n 'setAttribute',\n 'removeAttribute',\n // Moving the page and pressing a player the author placed: no data, no\n // server, and nothing a Video element's own poster does not already do\n // on every plan.\n 'scrollTo',\n 'playVideo',\n 'redirect',\n 'siteAlert',\n ] as const)\n\n/** A client step available on all plans (no `actions` entitlement). */\nexport function isBasicClientActionStep(step: InteractionStepBase): boolean {\n return BASIC_CLIENT_ACTION_STEP_TYPES.has(step.type)\n}\n\n/**\n * Whether a client step may run for the given entitlement tier (AGL-577).\n * This is the single source of truth the page enricher uses to trim the\n * client-automation payload per plan:\n *\n * - Basic presentational steps → always (every plan).\n * - `runJs` → `allowJs` (Business `webhooks` tier).\n * - Remaining advanced client steps (overlay / showHtml / analytics) →\n * `actionsEntitled` (`actions` tier).\n *\n * Server steps are not client steps and always return false here; they\n * are dispatched and re-authorized server-side.\n */\nexport function isClientStepEntitled(\n step: InteractionStepBase,\n entitlements: { actionsEntitled: boolean; allowJs: boolean },\n): boolean {\n if (!isClientActionStep(step)) return false\n if (isBasicClientActionStep(step)) return true\n if (step.type === 'runJs') return entitlements.allowJs\n return entitlements.actionsEntitled\n}\n\n/** The longest step list an interaction may hold. */\nexport const ACTION_MAX_STEPS = 10\n\n/**\n * Cap on the parameters one `trackGaEvent` step may carry (AGL-1587).\n *\n * Not a storage concern. These pairs are the least trustworthy analytics\n * input on the platform — both halves are typed by a site author and land in\n * that site's own GA4 property — and a bounded list is one an author can read\n * back in full before publishing, which is the only review a parameter ever\n * gets. GA4 caps custom parameters per event as well and drops the overflow\n * without saying so, so an unbounded editor would let an author configure\n * parameters that are never delivered and never explained. Ten, the same\n * ceiling {@link ACTION_MAX_STEPS} puts on the step list itself.\n */\nexport const ACTION_MAX_EVENT_PARAMS = 10\n\n/**\n * Longest analytics parameter NAME GA4 accepts; it drops a longer one on\n * arrival, so a name over this is silence rather than a truncated dimension.\n * The value half is capped by `ANALYTICS_PARAM_MAX_LENGTH`, which truncates\n * instead of dropping.\n */\nexport const ACTION_EVENT_PARAM_NAME_MAX_LENGTH = 40\n\n/** Self-dismiss triggers for shown elements (AGL-589). */\nexport const ELEMENT_DISMISS_OPTIONS = ['escape', 'outsideClick'] as const\nexport type ElementDismissOption = (typeof ELEMENT_DISMISS_OPTIONS)[number]\n/** Visibility grace-delay ceiling — enough for hover travel, no dead UIs. */\nexport const ELEMENT_VISIBILITY_MAX_DELAY_MS = 5000\n\n/**\n * How a `scrollTo` step moves the page. Stored in documents; never rename a\n * value. `instant` rather than the DOM's `auto`, because `auto` defers to the\n * site's CSS `scroll-behavior` — a site that sets `smooth` there would animate\n * a scroll the author asked to be instant.\n */\nexport const SCROLL_TO_BEHAVIORS = ['smooth', 'instant'] as const\nexport type ScrollToBehavior = (typeof SCROLL_TO_BEHAVIORS)[number]\n\n/**\n * The largest offset a `scrollTo` step may leave above its target.\n *\n * The offset exists to clear a sticky header, which is tens of pixels and\n * rarely more than a few hundred with an announcement bar stacked on it. A\n * thousand leaves room for any header while still refusing the extra digit\n * that would park the target off the bottom of the screen.\n */\nexport const SCROLL_TO_MAX_OFFSET_PX = 1000\n\n/** Custom event names: short, no collision with built-ins. */\nexport const CUSTOM_EVENT_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]{1,39}$/\n\n/**\n * The attribute names an interaction may write (AGL-2546).\n *\n * An unrestricted attribute setter is a self-XSS vector authored through the\n * interactions UI: it reaches `href`, `src`, `onclick`, `formaction` and\n * `style`, and on a site with collaborators the author and the victim need\n * not be the same person. `aria-*` and `data-*` carry the entire\n * accessibility use case and none of that exposure.\n *\n * Deliberately NOT solved by an entitlement gate. `runJs` is Business-gated\n * because it is dangerous at any tier; this has to work on every plan,\n * because a screen-reader user's access to a menu is not a paid feature.\n */\nexport const INTERACTION_ATTRIBUTE_NAME_PATTERN = /^(?:aria|data)-[a-z][a-z0-9-]*$/\n\n/**\n * Whether an interaction is allowed to write this attribute name.\n *\n * Case-insensitive because HTML attribute names are, and a rejected name is\n * a no-op rather than an error: a step that cannot run must not break the\n * steps after it in the same interaction.\n */\nexport function isInteractionAttributeAllowed(name: unknown): boolean {\n return (\n typeof name === 'string' &&\n INTERACTION_ATTRIBUTE_NAME_PATTERN.test(name.trim().toLowerCase())\n )\n}\n\n/**\n * An interaction step a plugin declares under `interactionSteps` in\n * `plugins.config.json`, compiled into the first-party catalog, so the\n * interaction builder can offer it and every validator can check it without\n * the plugin loaded.\n *\n * A step may be the plugin's own (a server step the plugin runs) or a\n * platform client step whose target is a record the plugin keeps. Either way\n * the declaration says how the builder names it and, for a step that PICKS a\n * record, where the builder lists the records from and which of the step's\n * fields hold the pick.\n */\nexport interface InteractionStepDeclaration {\n /** The plugin that declared it. */\n pluginId: string\n /** The stored step `type`. */\n type: string\n /** How the builder's step picker names it: \"Run a workflow\". */\n label: string\n /** The record this step acts on, picked in the builder. */\n picks?: {\n /** The site collection the records are listed from — one the plugin declares it owns. */\n collection: string\n /** How many records the builder lists. */\n limit: number\n /** The step field holding the picked record's id (rename-safe). */\n idField: string\n /** The step field holding its name at the time it was picked (display only). */\n nameField: string\n /** The picker's label: \"Workflow\". */\n label: string\n /** What a step with no pick is told, after its `Step N:` prefix. */\n missing: string\n }\n /**\n * `false` for a step only an automation holds — one that acts on the server\n * after the page that started it has gone, such as an email or a wait — so\n * the besigner's interaction builder does not offer it. Absent means offered.\n */\n offered?: false\n /** For a step that SUSPENDS the run that reaches it: see {@link InteractionStepHolds}. */\n holds?: InteractionStepHolds\n /** The step's fields a person types words into, in the order a sentence lists them. */\n typedFields?: readonly InteractionStepTypedField[]\n}\n\n/**\n * A step that suspends the run reaching it, to be continued later from a\n * beat: the whole minutes it may hold, and — where a hold can end on the\n * clock rather than on what it waits for — the scope field the continued run\n * carries to say it ran out of time. A visitor's page never runs a step past\n * one ({@link interactionStepsForClient}): everything after it belongs to a\n * run that has not happened yet.\n */\nexport interface InteractionStepHolds {\n minMinutes: number\n maxMinutes: number\n timeoutField?: string\n}\n\n/** One field of a step a person types words into, and what a sentence calls it: \"the list\". */\nexport interface InteractionStepTypedField {\n key: string\n names: string\n}\n\n/** Every step the first-party plugins declare, in `plugins.config.json` order. */\nexport function declaredInteractionSteps(): readonly InteractionStepDeclaration[] {\n return PLUGIN_INTERACTION_STEPS_DECLARED\n}\n\n/** The declared step of this type, or `null` for one no plugin declares. */\nexport function declaredInteractionStep(\n type: string,\n declarations: readonly InteractionStepDeclaration[] = PLUGIN_INTERACTION_STEPS_DECLARED,\n): InteractionStepDeclaration | null {\n return declarations.find((declaration) => declaration.type === type) ?? null\n}\n\n/**\n * How a step type reads in an editor, a run history and a drafter's words:\n * the platform's own label for a client step, else the label the declaring\n * plugin gave it; `null` for a type nobody declares.\n */\nexport function interactionStepLabel(\n type: string,\n declarations: readonly InteractionStepDeclaration[] = PLUGIN_INTERACTION_STEPS_DECLARED,\n): string | null {\n return (\n CLIENT_INTERACTION_STEP_LABELS[type as ClientInteractionStepType] ??\n declaredInteractionStep(type, declarations)?.label ??\n null\n )\n}\n\n/** The hold a step type declares, or `null` for one that never suspends a run. */\nexport function interactionStepHolds(\n type: string,\n declarations: readonly InteractionStepDeclaration[] = PLUGIN_INTERACTION_STEPS_DECLARED,\n): InteractionStepHolds | null {\n return declaredInteractionStep(type, declarations)?.holds ?? null\n}\n\n/** The fields of a step type a person types words into: the platform's, else the declaring plugin's. */\nexport function interactionStepTypedFields(\n type: string,\n declarations: readonly InteractionStepDeclaration[] = PLUGIN_INTERACTION_STEPS_DECLARED,\n): readonly InteractionStepTypedField[] {\n return (\n CLIENT_INTERACTION_STEP_TYPED_FIELDS[type as ClientInteractionStepType] ??\n declaredInteractionStep(type, declarations)?.typedFields ??\n []\n )\n}\n\n/**\n * The step list as the visitor's browser may see it: cut at the first step\n * that suspends the run.\n *\n * A client step AFTER a hold must never reach the page. The page runs its\n * slice of the list the moment the trigger fires, so shipping the whole list\n * would make \"wait three days, then show the popup\" show the popup at once —\n * the delay would appear to work on the server, be ignored in the browser,\n * and the two halves of one authored flow would disagree about when it\n * happened.\n *\n * Truncating rather than filtering: everything past the first hold belongs to\n * a run that has not happened yet, whichever side would have executed it.\n */\nexport function interactionStepsForClient<Step extends InteractionStepBase>(\n steps: readonly Step[] | undefined | null,\n declarations: readonly InteractionStepDeclaration[] = PLUGIN_INTERACTION_STEPS_DECLARED,\n): Step[] {\n const list = steps ?? []\n const holdAt = list.findIndex((step) => interactionStepHolds(step.type, declarations) !== null)\n return [...(holdAt < 0 ? list : list.slice(0, holdAt))]\n}\n\nexport interface ValidateInteractionOptions {\n /**\n * One step's checks that belong to its owner — a plugin's own step types.\n * Runs after the step's guard is checked; its answer, when not `null`, is\n * the interaction's.\n */\n validateStep?: (step: InteractionStepBase, label: string) => string | null\n /** The declared steps; the compiled first-party catalog unless a spec says otherwise. */\n declarations?: readonly InteractionStepDeclaration[]\n}\n\n/**\n * Validates an interaction's shape; returns a human-readable error or null.\n * Every surface that writes one shares this, so a bad step never persists or\n * runs.\n *\n * The platform checks what is its own: the name, the recipe stamp, the\n * trigger and its conditions, the step count, each step's guard, its client\n * steps, and the pick of every declared step that picks a record. A step it\n * does not know is left to its owner, through `validateStep`.\n */\nexport function validateInteraction(\n interaction: SiteInteraction<InteractionStepBase>,\n options: ValidateInteractionOptions = {},\n): string | null {\n if (!interaction.name?.trim()) return 'Name the action'\n // A stamp is provenance, and provenance naming a recipe that does not\n // exist is a document nothing can read back; `null` and absent both pass.\n if (interaction.recipe != null && !isKnownInteractionRecipe(interaction.recipe)) {\n return 'Unknown recipe'\n }\n const event = interaction.trigger?.event?.trim() ?? ''\n if (!event) return 'Pick a trigger event'\n // A server event or a custom one fired by another step is, like a site\n // event, a name; every built-in server event fits the custom pattern.\n if (!isSiteEventType(event) && !CUSTOM_EVENT_PATTERN.test(event)) {\n return 'Custom event names are 2–40 letters, digits, dashes'\n }\n // Site-event trigger config (AGL-256; hover events AGL-562).\n if (\n (ELEMENT_SCOPED_SITE_EVENTS as readonly string[]).includes(event) &&\n !interaction.trigger?.selector?.trim()\n ) {\n return 'This trigger needs a CSS selector'\n }\n if (\n ['scrollDepth', 'timeOnPage'].includes(event) &&\n !(Number(interaction.trigger?.threshold) > 0)\n ) {\n return event === 'scrollDepth'\n ? 'Set the scroll percentage (1–100)'\n : 'Set the seconds on page'\n }\n // Frequency caps (AGL-274).\n if (\n interaction.trigger?.cooldownMinutes != null &&\n !(Number(interaction.trigger.cooldownMinutes) >= 1)\n ) {\n return 'Cooldown must be at least 1 minute'\n }\n // A filter the evaluator can never run saves fine and never fires (AGL-3458).\n const filterProblem = triggerFilterProblem(interaction.trigger?.filter)\n if (filterProblem) return filterProblem\n // Structured payload conditions (AGL-557; chained AGL-565).\n const combinator = interaction.trigger?.combinator\n if (combinator != null && !TRIGGER_COMBINATORS.includes(combinator)) {\n return 'Combine conditions with AND or OR'\n }\n const conditions = normalizeTriggerConditions(interaction.trigger)\n if (conditions.length > ACTION_MAX_CONDITIONS) {\n return `Conditions are capped at ${ACTION_MAX_CONDITIONS}`\n }\n for (const [index, condition] of conditions.entries()) {\n // Single-condition messages stay exactly as AGL-557 shipped them;\n // the row marker only appears once there are rows to tell apart.\n const where = conditions.length > 1 ? ` (condition ${index + 1})` : ''\n if (!TRIGGER_CONDITION_OPS.includes(condition.op)) {\n return `Pick a condition operator${where}`\n }\n if (!condition.field?.trim()) {\n return `Name the field the condition checks${where}`\n }\n if (condition.op !== 'notEmpty' && !condition.value?.trim()) {\n return `Enter the value the condition compares against${where}`\n }\n }\n const steps = interaction.steps ?? []\n if (!steps.length) return 'Add at least one step'\n if (steps.length > ACTION_MAX_STEPS) {\n return `Actions are capped at ${ACTION_MAX_STEPS} steps`\n }\n for (const [index, step] of steps.entries()) {\n const label = `Step ${index + 1}`\n // A step's own guard, checked with the same messages the trigger's\n // clauses get — one condition editor, one set of complaints about it.\n const guardClauses = (step.when?.conditions ?? []).filter(Boolean)\n if (guardClauses.length > ACTION_MAX_CONDITIONS) {\n return `${label}: conditions are capped at ${ACTION_MAX_CONDITIONS}`\n }\n if (\n step.when?.combinator != null &&\n !TRIGGER_COMBINATORS.includes(step.when.combinator)\n ) {\n return `${label}: combine conditions with AND or OR`\n }\n for (const clause of guardClauses) {\n if (!TRIGGER_CONDITION_OPS.includes(clause.op)) {\n return `${label}: pick a condition operator`\n }\n if (!clause.field?.trim()) {\n return `${label}: name the field the condition checks`\n }\n if (clause.op !== 'notEmpty' && !clause.value?.trim()) {\n return `${label}: enter the value the condition compares against`\n }\n }\n const owned = options.validateStep?.(step, label)\n if (owned) return owned\n const declared = declaredInteractionStep(step.type, options.declarations)\n if (declared?.picks) {\n const id = step[declared.picks.idField]\n const name = step[declared.picks.nameField]\n if (\n !(typeof id === 'string' && id.trim()) &&\n !(typeof name === 'string' && name.trim())\n ) {\n return `${label}: ${declared.picks.missing}`\n }\n }\n if (isClientActionStep(step)) {\n const problem = clientStepProblem(step, label)\n if (problem) return problem\n }\n }\n return null\n}\n\n/** A client step's own complaint, or null. The step's guard is checked by the caller. */\nfunction clientStepProblem(step: ClientInteractionStep, label: string): string | null {\n if (step.type === 'siteAlert' && !step.message?.trim()) {\n return `${label}: enter the alert message`\n }\n if (\n step.type === 'addClass' ||\n step.type === 'removeClass' ||\n step.type === 'toggleClass'\n ) {\n if (!step.selector?.trim()) return `${label}: enter a CSS selector`\n if (!step.className?.trim()) return `${label}: enter the class name`\n }\n // Element show/hide steps (AGL-562) always target a selector; drawer\n // (AGL-562) and menu (AGL-568) commands may omit the target (the\n // page's first drawer/menu answers).\n if (\n (step.type === 'showElement' ||\n step.type === 'hideElement' ||\n step.type === 'toggleElement') &&\n !step.selector?.trim()\n ) {\n return `${label}: pick the element to show or hide`\n }\n if (\n step.type === 'showElement' ||\n step.type === 'hideElement' ||\n step.type === 'toggleElement'\n ) {\n // Choreography options (AGL-589).\n const delay = (step as { delayMs?: unknown }).delayMs\n if (\n delay != null &&\n !(\n Number.isInteger(delay) &&\n (delay as number) >= 0 &&\n (delay as number) <= ELEMENT_VISIBILITY_MAX_DELAY_MS\n )\n ) {\n return `${label}: delay must be 0–${ELEMENT_VISIBILITY_MAX_DELAY_MS}ms`\n }\n const dismiss = (step as { dismissOn?: unknown }).dismissOn\n if (\n dismiss != null &&\n !(\n Array.isArray(dismiss) &&\n dismiss.every((option) =>\n (ELEMENT_DISMISS_OPTIONS as readonly string[]).includes(\n option as string,\n ),\n )\n )\n ) {\n return `${label}: dismiss options are escape and outsideClick`\n }\n }\n // One-target steps (AGL-2867). The runtime does nothing for a target it\n // cannot find, so a missing one is refused here, where it can be fixed.\n if (step.type === 'scrollTo') {\n if (!step.selector?.trim()) {\n return `${label}: pick the element to scroll to`\n }\n const behavior = (step as { behavior?: unknown }).behavior\n if (\n behavior != null &&\n !(SCROLL_TO_BEHAVIORS as readonly unknown[]).includes(behavior)\n ) {\n return `${label}: scroll smoothly or instantly`\n }\n const offset = (step as { offsetPx?: unknown }).offsetPx\n if (\n offset != null &&\n !(\n Number.isInteger(offset) &&\n (offset as number) >= 0 &&\n (offset as number) <= SCROLL_TO_MAX_OFFSET_PX\n )\n ) {\n return `${label}: the offset must be 0–${SCROLL_TO_MAX_OFFSET_PX}px`\n }\n }\n if (step.type === 'playVideo' && !step.selector?.trim()) {\n return `${label}: pick the video to play`\n }\n if (step.type === 'showHtml') {\n if (!step.html?.trim()) return `${label}: enter the HTML`\n // AGL-2486: the author-facing half of the runtime sanitizer, exactly as\n // the reserved analytics name below is the author-facing half of the\n // runtime refusal. `site-runtime.tsx` runs this HTML through\n // `sanitizeAuthorHtml` for a VISITOR, where the only thing it can do\n // with markup it refuses is drop it and say nothing — so an author who\n // pastes an embed snippet gets a step that runs, reports success, and\n // shows nothing. The refusal is reported HERE, where the person who\n // can fix it is looking, and it is the SAME function that will run at\n // render rather than a second description of its rules.\n const removals: AuthorHtmlRemoval[] = []\n const safe = sanitizeAuthorHtml(step.html, removals)\n if (!safe.trim()) {\n return `${label}: none of this HTML can be shown on a published page — ${removals[0]?.message ?? 'it is removed by the sanitizer.'}`\n }\n if (removals.length) {\n return `${label}: ${removals[0].message}${removals.length > 1 ? ` (+${removals.length - 1} more)` : ''}`\n }\n }\n if (step.type === 'runJs' && !step.code?.trim()) {\n return `${label}: enter the JavaScript`\n }\n if (step.type === 'redirect' && !step.url?.trim() && !step.screenId) {\n return `${label}: pick a page or enter the destination URL`\n }\n if (step.type === 'trackGaEvent') {\n if (!step.eventName?.trim()) {\n return `${label}: name the analytics event`\n }\n // AGL-1587: the author-facing half of the runtime refusal. The runtime\n // can only drop a bad name silently — it is executing for a VISITOR —\n // so the name is checked HERE, where the person who can fix it is.\n const resolved = resolveAuthoredEventName(step.eventName)\n if (resolved.reason === 'reserved') {\n return `${label}: \"${step.eventName.trim()}\" is a reserved analytics event name — pick another`\n }\n if (!resolved.name) {\n return `${label}: the analytics event name must start with a letter`\n }\n const params = Object.entries(step.params ?? {})\n if (params.length > ACTION_MAX_EVENT_PARAMS) {\n return `${label}: analytics parameters are capped at ${ACTION_MAX_EVENT_PARAMS}`\n }\n for (const [key, value] of params) {\n if (!key.trim()) return `${label}: name every analytics parameter`\n if (key.trim().length > ACTION_EVENT_PARAM_NAME_MAX_LENGTH) {\n return `${label}: the \"${key.trim().slice(0, 16)}…\" parameter name is over ${ACTION_EVENT_PARAM_NAME_MAX_LENGTH} characters, which GA4 drops`\n }\n if (!String(value ?? '').trim()) {\n return `${label}: enter a value for the \"${key.trim()}\" parameter`\n }\n }\n // The author-facing half of the runtime sanitizer, the same shape the\n // reserved name above and the `showHtml` check take. `trackAuthoredEvent`\n // strips a parameter that can carry personal data and says nothing about\n // it, because it is executing for a VISITOR — so an author who binds a\n // form field into a parameter gets a step that runs, reports success,\n // and delivers an event missing the dimension it was created for. The\n // strip is reported HERE, by running the REAL `sanitizeEventParams`\n // rather than a second description of its rules, so the two can never\n // disagree about which parameter survives.\n const kept = sanitizeEventParams(step.params ?? undefined)\n const stripped = params.find(([key]) => !(key in kept))\n if (stripped) {\n return `${label}: the \"${stripped[0]}\" parameter is never sent — an analytics parameter must not carry a visitor's own details`\n }\n }\n return null\n}\n\n/**\n * An interaction as the document at `hosts/{hostId}/actions/{id}` holds it.\n *\n * Every optional trigger key is written OUT — a boolean cap as `false`, a\n * cleared list as `null` — because the editors save with a merge-set, and a\n * merge keeps whatever key the payload omits: a frequency cap switched off,\n * left out of the payload, would stay on. The legacy single `condition` is\n * always nulled; `conditions` has been canonical since the list shape arrived\n * and a document that carried both would have the reader pick. Everything\n * else is the interaction, unchanged.\n *\n * `recipe` rides along only when the interaction SAYS something about it: an\n * id or `null`. One that carries no stamp (an older document, edited and\n * saved again) keeps carrying none — see `interactionRecipeStamp` for why an\n * absent stamp must not become a `null` one.\n */\nexport type SiteInteractionDocument<Step extends InteractionStepBase = InteractionStepBase> =\n SiteInteraction<Step> & {\n trigger: InteractionTrigger & {\n oncePerVisitor: boolean\n oncePerSession: boolean\n cooldownMinutes: number | null\n everyTime: boolean\n condition: null\n conditions: InteractionCondition[] | null\n combinator: TriggerCombinator | null\n }\n enabled: boolean\n }\n\n/** The stored shape of an interaction: what every writer of `hosts/{hostId}/actions` saves. */\nexport function siteInteractionDocument<Step extends InteractionStepBase>(\n interaction: SiteInteraction<Step>,\n): SiteInteractionDocument<Step> {\n const { recipe, ...rest } = interaction\n const trigger = interaction.trigger\n return {\n ...rest,\n trigger: {\n ...trigger,\n oncePerVisitor: trigger.oncePerVisitor === true,\n oncePerSession: trigger.oncePerSession === true,\n cooldownMinutes:\n Number(trigger.cooldownMinutes) >= 1 ? Number(trigger.cooldownMinutes) : null,\n everyTime: trigger.everyTime === true,\n condition: null,\n conditions: trigger.conditions ?? null,\n combinator: trigger.combinator ?? null,\n },\n enabled: interaction.enabled !== false,\n ...(recipe !== undefined ? { recipe } : {}),\n }\n}\n\n/** Alert produced by a `siteAlert` step, surfaced to the emitting client. */\nexport interface SiteAlert {\n message: string\n severity: 'info' | 'success' | 'warning' | 'error'\n}\n\n/**\n * How many LIVE action documents one host may hold (AGL-2266).\n *\n * `hosts/{hostId}/actions` was in NO exclusion list in\n * `cloud/firebase-firestore.rules`, so the host catch-all's `allow create`\n * granted it to any editor, client-direct, on any plan — and the import\n * route's own table said so in as many words: *\"no `RESOURCES` entry and no\n * quota key anywhere; all three creators write the document client-direct.\"*\n * A free org could therefore mint unbounded Firestore documents from the\n * browser against a $0 subscription. Unbounded infrastructure, not a bypass of\n * anything we sell, which is `WEBHOOK_MAX_PER_HOST`'s (AGL-1360) and\n * `NON_PAGE_SCREEN_MAX_PER_HOST`'s (AGL-1399) shape exactly: a flat PLATFORM\n * cap with no `OrgEntitlements` key, no variation by plan, and nothing on the\n * price list to explain.\n *\n * ## Not gated on the `actions` entitlement, deliberately\n *\n * `actions` is a Pro feature and `interactions` is free, and BOTH write this\n * collection — the interaction builder and the besigner's preset wiring create\n * the same document type the Pro actions card does. Gating creation on the\n * paid flag would take element interactions away from every free and starter\n * site, which is a pricing change wearing a cap's clothes. The runtime already\n * checks the entitlement where it decides what may RUN\n * (`run-event-actions.ts`), which is the right place for it.\n *\n * ## Why 500\n *\n * Sized to the busiest plausible site rather than to today's data. An action\n * is authored per interactive element, so a heavy marketing site with dropdown\n * choreography on every section reaches tens; presets wire a handful at a\n * time. 500 is far past anything authoring produces and well short of what a\n * script in a loop wants, which is the only property a flat cap needs. Live\n * documents only — the interactions provider soft-deletes with `deletedAt`, so\n * counting tombstones would be AGL-1173's bug one collection over, where\n * removing an interaction never frees its slot.\n */\nexport const ACTIONS_MAX_PER_HOST = 500\n"],"names":["resolveAuthoredEventName","sanitizeEventParams","sanitizeAuthorHtml","expressionSyntaxError","PLUGIN_INTERACTION_STEPS_DECLARED","isKnownInteractionRecipe","SITE_EVENT_TYPES","ELEMENT_SCOPED_SITE_EVENTS","isSiteEventType","event","includes","TRIGGER_CONDITION_OPS","evaluateTriggerCondition","condition","payload","field","trim","raw","actual","String","toLowerCase","op","length","expected","value","FILTER_COMPARISON","withoutStrings","text","replace","triggerFilterProblem","filter","options","remedy","test","syntax","TRIGGER_COMBINATORS","ACTION_MAX_CONDITIONS","normalizeTriggerConditions","trigger","conditions","Array","isArray","Boolean","evaluateTriggerConditions","combinator","some","every","evaluateStepGuard","guard","scope","CLIENT_ACTION_STEP_TYPES","Set","isClientActionStep","step","has","type","CLIENT_INTERACTION_STEP_LABELS","siteAlert","showOverlay","stickyNav","addClass","toggleClass","removeClass","showElement","hideElement","toggleElement","openDrawer","closeDrawer","toggleDrawer","openMenu","closeMenu","toggleMenu","setAttribute","removeAttribute","scrollTo","playVideo","showHtml","runJs","redirect","trackGaEvent","CLIENT_INTERACTION_STEP_TYPED_FIELDS","key","names","BASIC_CLIENT_ACTION_STEP_TYPES","isBasicClientActionStep","isClientStepEntitled","entitlements","allowJs","actionsEntitled","ACTION_MAX_STEPS","ACTION_MAX_EVENT_PARAMS","ACTION_EVENT_PARAM_NAME_MAX_LENGTH","ELEMENT_DISMISS_OPTIONS","ELEMENT_VISIBILITY_MAX_DELAY_MS","SCROLL_TO_BEHAVIORS","SCROLL_TO_MAX_OFFSET_PX","CUSTOM_EVENT_PATTERN","INTERACTION_ATTRIBUTE_NAME_PATTERN","isInteractionAttributeAllowed","name","declaredInteractionSteps","declaredInteractionStep","declarations","find","declaration","interactionStepLabel","label","interactionStepHolds","holds","interactionStepTypedFields","typedFields","interactionStepsForClient","steps","list","holdAt","findIndex","slice","validateInteraction","interaction","recipe","selector","Number","threshold","cooldownMinutes","filterProblem","index","entries","where","guardClauses","when","clause","owned","validateStep","declared","picks","id","idField","nameField","missing","problem","clientStepProblem","message","className","delay","delayMs","isInteger","dismiss","dismissOn","option","behavior","offset","offsetPx","html","removals","safe","code","url","screenId","eventName","resolved","reason","params","Object","kept","undefined","stripped","siteInteractionDocument","rest","oncePerVisitor","oncePerSession","everyTime","enabled","ACTIONS_MAX_PER_HOST"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,wBAAwB,EAAEC,mBAAmB,QAAQ,wBAAoB;AAClF,SAAiCC,kBAAkB,QAAQ,mBAAe;AAC1E,SAASC,qBAAqB,QAAQ,iBAAa;AACnD,SAASC,iCAAiC,QAAQ,qDAAiD;AACnG,SAASC,wBAAwB,QAAQ,2CAAuC;AAEhF;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED;;;;CAIC,GACD,OAAO,MAAMC,mBAAmB;IAC9B;IACA;IACA;IACA;IACA,qEAAqE;IACrE,4DAA4D;IAC5D;IACA;IACA;IACA;IACA;CACD,CAAS;AAEV,mEAAmE,GACnE,OAAO,MAAMC,6BAA6B;IACxC;IACA;IACA;IACA;IACA;CACD,CAAS;AAIV,OAAO,SAASC,gBAAgBC,KAAa;IAC3C,OAAOH,iBAAiBI,QAAQ,CAACD;AACnC;AAEA,8CAA8C,GAC9C,OAAO,MAAME,wBAAwB;IACnC;IACA;IACA;CACD,CAAS;AAmBV;;;;;;CAMC,GACD,OAAO,SAASC,yBACdC,SAAkD,EAClDC,OAAgC;QAORD;QALVA;IAAd,MAAME,QAAQF,8BAAAA,mBAAAA,UAAWE,KAAK,qBAAhBF,iBAAkBG,IAAI;IACpC,IAAI,CAACH,aAAa,CAACE,OAAO,OAAO;IACjC,MAAME,MAAM,CAACH,kB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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCC,GACD,OAAO,MAAMqD,uBAAuB,IAAG"}
|
|
@@ -64,6 +64,13 @@
|
|
|
64
64
|
* entry is DELETED on the read that finds it, rather than ignored, so a
|
|
65
65
|
* device never holds a campaign it can no longer be credited with.
|
|
66
66
|
*
|
|
67
|
+
* One entry, {@link UTM_TOUCH_STORAGE_KEY}, holds everything this module
|
|
68
|
+
* remembers: the labels below and the page touch further down, side by side
|
|
69
|
+
* in the wire form a door sends. Their keys do not overlap, so each half is
|
|
70
|
+
* read by its own parser, an entry written before the page touch existed
|
|
71
|
+
* still reads, and a half past the window is dropped without touching the
|
|
72
|
+
* other. Withdrawing consent removes the one entry.
|
|
73
|
+
*
|
|
67
74
|
* ## Last touch, not first
|
|
68
75
|
*
|
|
69
76
|
* The revenue join credits the LAST click, and a product where a lead and an
|
|
@@ -110,8 +117,9 @@
|
|
|
110
117
|
*
|
|
111
118
|
* Only the three allowlisted `utm_` labels, scrubbed by
|
|
112
119
|
* {@link parseUtmAttribution} — which refuses an email-shaped value
|
|
113
|
-
* outright
|
|
114
|
-
*
|
|
120
|
+
* outright — and, for the page touch below, the ids of the campaigns and the
|
|
121
|
+
* screen a page is filed under with its path. No address, no person's
|
|
122
|
+
* identifier, no click id, nothing that names the visitor. A campaign link is exactly where putting a recipient in
|
|
115
123
|
* a query string would be tempting, and the parser is what makes it
|
|
116
124
|
* impossible rather than merely discouraged: the stored string is re-parsed
|
|
117
125
|
* through the same allowlist that wrote it, so a hand-edited `localStorage`
|
|
@@ -131,8 +139,12 @@ export declare const ATTRIBUTION_WINDOW_DAYS = 7;
|
|
|
131
139
|
/** The same window in milliseconds. */
|
|
132
140
|
export declare const ATTRIBUTION_WINDOW_MS: number;
|
|
133
141
|
/**
|
|
134
|
-
* Where the
|
|
135
|
-
* spelled as visitors' devices already hold it.
|
|
142
|
+
* Where the touches are held. Namespaced like every other key this app sets,
|
|
143
|
+
* and spelled as visitors' devices already hold it.
|
|
144
|
+
*
|
|
145
|
+
* The only key this module writes. The labels and the page touch share it in
|
|
146
|
+
* the wire form {@link utmTouchField} sends, so remembering a page adds no
|
|
147
|
+
* second thing to the visitor's device.
|
|
136
148
|
*/
|
|
137
149
|
export declare const UTM_TOUCH_STORAGE_KEY = "aglyn:campaign-touch";
|
|
138
150
|
/**
|
|
@@ -149,6 +161,18 @@ export interface UtmTouch extends UtmAttribution {
|
|
|
149
161
|
/** When the visitor followed the campaign link, epoch ms. */
|
|
150
162
|
atMs: number;
|
|
151
163
|
}
|
|
164
|
+
/**
|
|
165
|
+
* Run `callback` once the visitor's storage consent is settled — at once when
|
|
166
|
+
* it already is, else on the first {@link setUtmTouchConsent} that settles it.
|
|
167
|
+
*
|
|
168
|
+
* For a caller whose answer depends on whether the device may remember
|
|
169
|
+
* anything ({@link claimFirstCampaignTouch}, AGL-3461): asked too early, an
|
|
170
|
+
* unresolved state would read as "may not", and the visit would go uncounted
|
|
171
|
+
* for no reason but timing.
|
|
172
|
+
*
|
|
173
|
+
* @returns a function that withdraws the callback if it has not run.
|
|
174
|
+
*/
|
|
175
|
+
export declare function whenUtmTouchConsentSettles(callback: (allowed: boolean) => void): () => void;
|
|
152
176
|
/**
|
|
153
177
|
* The canonical stored form of a touch — the ONLY place it is written, so it
|
|
154
178
|
* cannot drift from what {@link parseUtmTouch} reads back.
|
|
@@ -208,7 +232,88 @@ export declare function readUtmTouch(nowMs?: number): UtmTouch | null;
|
|
|
208
232
|
* that produced none. Empty when there is no touch — never a placeholder,
|
|
209
233
|
* never `campaignTouch: undefined`, so that "arrived from nowhere" and "this
|
|
210
234
|
* door does not report" stay distinguishable on the wire.
|
|
235
|
+
*
|
|
236
|
+
* Both touches ride the one field (AGL-3461): the labels the visitor arrived
|
|
237
|
+
* with and the page filed under a campaign they last viewed. Their keys do
|
|
238
|
+
* not overlap, so each parser reads its own half of the same string and
|
|
239
|
+
* ignores the other's — which is also why every door carries the page touch
|
|
240
|
+
* without a change of its own.
|
|
211
241
|
*/
|
|
212
242
|
export declare function utmTouchField(nowMs?: number): {
|
|
213
243
|
campaignTouch?: string;
|
|
214
244
|
};
|
|
245
|
+
/**
|
|
246
|
+
* How many of a page's campaigns a touch carries. A page is rarely filed
|
|
247
|
+
* under more than one; the cap is on the bytes a wire field may carry.
|
|
248
|
+
*/
|
|
249
|
+
export declare const PAGE_TOUCH_MAX_CAMPAIGNS = 5;
|
|
250
|
+
/** A page filed under one or more campaigns, and when it was viewed. */
|
|
251
|
+
export interface PageTouch {
|
|
252
|
+
/** The campaign ids the page was filed under, in the screen's order. */
|
|
253
|
+
containerIds: string[];
|
|
254
|
+
/** The screen the page renders. */
|
|
255
|
+
screenId: string;
|
|
256
|
+
/** The page's path, `/`-led. */
|
|
257
|
+
path: string;
|
|
258
|
+
/** When the visitor viewed it, epoch ms. */
|
|
259
|
+
atMs: number;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* The canonical wire form of a page touch — the ONLY place it is written, so
|
|
263
|
+
* it cannot drift from what {@link parsePageTouch} reads back.
|
|
264
|
+
*/
|
|
265
|
+
export declare function pageTouchWire(touch: PageTouch | null | undefined): string;
|
|
266
|
+
/**
|
|
267
|
+
* Read a stored or transmitted page touch back, or `null`.
|
|
268
|
+
*
|
|
269
|
+
* The window is enforced here for the reason {@link parseUtmTouch} gives:
|
|
270
|
+
* every reader agrees that an expired touch is nothing. The ids are shape-
|
|
271
|
+
* checked only — whether the page is still filed under them is the server's
|
|
272
|
+
* question, asked at the moment of credit.
|
|
273
|
+
*/
|
|
274
|
+
export declare function parsePageTouch(wire: unknown, nowMs?: number): PageTouch | null;
|
|
275
|
+
/**
|
|
276
|
+
* Tell this module which campaigns the page being viewed is filed under.
|
|
277
|
+
*
|
|
278
|
+
* Called by the plugin that keeps campaigns, on every pageview, with what its
|
|
279
|
+
* server half read off the screen — or with `null` for a page filed under
|
|
280
|
+
* none, which clears the LIVE page and leaves the remembered one alone: a
|
|
281
|
+
* visitor who reads a campaign's landing page and then the site's pricing
|
|
282
|
+
* page has still been touched by the campaign.
|
|
283
|
+
*
|
|
284
|
+
* Overwrites the remembered page touch, because the model is last touch.
|
|
285
|
+
*
|
|
286
|
+
* @returns the touch now live, or `null`.
|
|
287
|
+
*/
|
|
288
|
+
export declare function notePageCampaigns(page: {
|
|
289
|
+
screenId?: string | null;
|
|
290
|
+
containerIds?: readonly string[] | null;
|
|
291
|
+
path?: string | null;
|
|
292
|
+
} | null, nowMs?: number): PageTouch | null;
|
|
293
|
+
/**
|
|
294
|
+
* The page touch to credit a conversion happening right now, or `null`.
|
|
295
|
+
*
|
|
296
|
+
* The page the visitor is on wins, with the instant they viewed it; only on a
|
|
297
|
+
* page filed under nothing does this fall back to what was remembered. An
|
|
298
|
+
* expired entry is deleted on the read that finds it, as the labels' is.
|
|
299
|
+
*/
|
|
300
|
+
export declare function readPageTouch(nowMs?: number): PageTouch | null;
|
|
301
|
+
/**
|
|
302
|
+
* Whether this pageview is the device's FIRST campaign touch in the window —
|
|
303
|
+
* answered with `keys` when it is, and `[]` otherwise.
|
|
304
|
+
*
|
|
305
|
+
* `keys` are the caller's own words for what touched the visitor on this
|
|
306
|
+
* page: a campaign id, or a label the server will look up. They are answered
|
|
307
|
+
* together or not at all, because they are one touch. Once per page load: the
|
|
308
|
+
* first claim spends it, and a later page in the same visit has been preceded
|
|
309
|
+
* by this one.
|
|
310
|
+
*
|
|
311
|
+
* A first touch is only claimed when the device now REMEMBERS one — the
|
|
312
|
+
* page's or the address's labels are written before the answer — so the next
|
|
313
|
+
* page load reads it and answers `[]`. A device that refuses the write claims
|
|
314
|
+
* nothing, and the figure stays a floor rather than counting one visitor on
|
|
315
|
+
* every page.
|
|
316
|
+
*
|
|
317
|
+
* Answers `[]` without the storage grant — see the section note.
|
|
318
|
+
*/
|
|
319
|
+
export declare function claimFirstCampaignTouch(keys: readonly string[], nowMs?: number): string[];
|