# marko-web-p1-events — Claude Code Context

Parameter1 user-event ("p1events") tracking for Mindful Web / Marko websites. Marko
components emit events into the p1events pipeline (`events.parameter1.com`) via a global
`window.p1events(...)` command queue. This package owns the **client** side only;
ingest/classification lives in the `events` repo and reporting in `mindful-reporting`.

## ⚠️ Two library versions ship side by side

The fleet is mid-migration from the v1 library to v2. **Both paths are live in this package
and a site chooses between them in its own config** — so a `mindful-web` version bump can
never change a site's tracking behavior.

| | v1 (legacy) | v2 |
|---|---|---|
| component | `<marko-web-p1-events-init>` | `<marko-web-p1-events-init-v2>` |
| config | `p1events('init', {…})` command | the `window.__p1c` global |
| lib | `cdn.parameter1.com/p1-events/v1.6.1/` | `cdn.parameter1.com/events/v{version}/` |
| endpoint | `…/default/p1-website-events-enqueue` | `{u}/enqueue` + `{u}/orphan` |
| inline | a ~150-byte queue stub | a ~3KB **capture runtime** (see below) |
| loading | deferred script loader (`on="load"`) | `type="module" async`, no DSL |

**The opt-in is `p1events.v2`.** A site with that key renders the v2 component; a site
without it keeps v1 entirely. Its presence is also the signal the advertising components
gate on, so all three parts of a site's migration flip together (see "Migration" below).

⛔ **Never test that key by hand — there are two predicates and every consumer uses one.**

- **`utils/is-v2-site.js`** — server side, takes the `site` config (`out.global.site` /
  `req.app.locals.site`). Used by `init-v2.marko`, both ad components and `middleware.js`.
  Tests for a **non-empty object**, not truthiness: `v2: {}` is the harmful in-between state
  where the ad components suppress their libraries while `init-v2` renders nothing.
- **`browser/is-v2-runtime.js`** — browser side, reads `window.__p1c`. There is no `site`
  object in a browser entry point, and every site repo invokes the theme as a bare
  `MonoRail(Browser)`, so a config-carried flag would mean editing every repo in the fleet.
  ⚠️ **`__p1c` is the only safe marker** — `window.__p1e` and `window.p1events` both exist
  under v1 (its `init.marko` defines them before loading its own library), so testing either
  would report v2 on every legacy site.
  ⛔ It lives in `browser/` and is **ESM**, while `is-v2-site.js` is CommonJS in `utils/`.
  That split is required, not stylistic: Vite runs `@rollup/plugin-commonjs` only under
  `node_modules`, so a `module.exports` in a bundled file fails every site build with
  `"default" is not exported by …`. **Browser-imported code goes in `browser/` as ESM;
  `utils/` is Node-side CommonJS for Marko templates and express.**

### ⛔ identity-x is canonical on v2 — omeda must not overwrite it

On v2 the identity is resolved **server-side** to the reader's identity-x entity, through the
`resolveIdentity` function `init-v2.marko` serializes onto `__p1c`. It runs first in the
library's cascade and writes `__p1e_idt` at takeover.

`marko-web-theme-monorail`'s browser entry then set the identity again from
`omeda-identity-x-authenticated` / `…-rapid-identify-response`, with an **omeda** entity
string, and `applySetIdentity` overwrites unconditionally. Two consequences, both live in
production before this was guarded:

- ⚠️ **Mixed identities inside one session**, not a clean switch — the two writers race the
  beacon flush, so events before the async omeda event carried identity-x and events after
  carried omeda. The crossover moved with network timing and whether the lazily-imported
  rapid-identify chunk was warm, so the split was nondeterministic page to page.
- ⚠️ **Authenticated readers were downgraded to `known`.** The library's built-in
  `isAuthenticated` mode only grants `authenticated` to the `identity-x` / `mindful-audience`
  providers, which an omeda-provider identity can never satisfy.

The theme now guards that write with `is-v2-runtime` and registers the identity-x listener
unconditionally rather than as the omeda branch's `else`. The omeda id is not lost — it stays
joined to the identity-x user through the external id `marko-web-omeda-identity-x` writes.

⛔ **There is deliberately no v1 → v2 option mapping.** The two surfaces are not
re-encodings of each other — v1 has no `resolveIdentity` / `isAuthenticated` / `buttons`,
and v1's `mindfulPluginOptions.namespace` has nowhere to go under v2. Each site authors its
v2 config directly. `utils/build-p1c-config.js` takes the v2 shape as-is.

## Config model — `sites/<domain>/config/site.js` `p1events`

Every component reads config with `site.getAsObject("p1events")`. Shape:

```js
p1events: {
  enabled: true,            // master gate — nothing tracks unless true
  tenant: 'abmedia',        // required alongside `enabled` for v1 init to run
  cookieDomain: '…',        // prod cookie domain for the v1 lib (dropped in v2)
  engagement: {             // optional; engagement is default-ON (see below)
    enabled: false,         // set false to OPT OUT of engagement on this site
    floorPx: 500,           // override engagement scroll thresholds (rare)
    viewportFraction: 0.75,
    enableTextSelect: false,
  },
  v2: {                     // PRESENCE = this site is on v2. Omit for legacy.
    slug: 'abmedia',        // required; v1's `tenant`, renamed to the wire field
    isAuthenticated: 'mindful-audience',
    mindfulNativeAds: true,
    mindfulBannerAds: { origin: '…', tenant: 'ironmarkets' },
  },
}
```

`types.js` types the `v2` object — import `P1EventsV2Config` from a site repo for editor
autocompletion. ⚠️ It only checks with `maxNodeModuleJsDepth: 1` in the site's
`jsconfig.json`, and only when annotating a **hoisted const** rather than the export; see
the file's own header for both measurements.

There is **no shared/base p1events config** — each site declares its own inline `p1events`
literal. (This is why engagement was made default-ON rather than adding it per-site — see
mindful-web #275.)

## Initialization

- **`init.marko`** (`<marko-web-p1-events-init>`) — **v1**. Gates on `enabled && tenant`,
  loads the p1events lib (`cdn.parameter1.com/p1-events/...`), and calls `p1events('init',
  { tenant, realm, env, uri, cookieDomain, … })` via `utils/build-init-config.js`. Optional
  GAM / Mindful ad-server plugins (`enableGamPlugin` / `enableMindfulPlugin`) and deferred
  loading via `on`. ⛔ Knows nothing about v2 — when every site has migrated this file and
  its builder delete with no callers left.
- **`init-v2.marko`** (`<marko-web-p1-events-init-v2>`) — **v2**. Gates on `enabled && v2`
  and renders **three tags whose order is load-bearing**:
  1. `window.__p1c = {…}` (built by `utils/build-p1c-config.js`)
  2. `<marko-web-p1-events-inline-snippet>` — the capture runtime, **synchronous**
  3. the library, `<script type="module" async>`

  Takes **flat** v2 inputs; the site's `p1events.v2` object is spread onto it by the
  document. ⛔ Config must never be pre-set on `window.__p1e` — the library's double-include
  guard reads that global's mere presence as "already ran" and would attach **no listeners
  at all**.

  ⛔ **Every `input` read and the `buildP1cConfig` call sit behind the `renders` flag, and
  must stay there.** A document renders this tag as `...site.get('p1events.v2')`, so on an
  unmigrated site the spread contributes no attributes and Marko passes `input` as
  **`undefined`, not `{}`**. 📏 Measured on three ascend sites sharing a package with
  migrated ones: a bare `input.scriptSrc` threw `Cannot read property 'scriptSrc' of
  undefined` and 500'd **every page**. ⚠️ Normalizing `input` alone is **not** a fix —
  `buildP1cConfig` then throws "`slug` is required" from the same place, which is the same
  500 wearing a different message. The guard reads the **site** config (`isV2Site`), never
  `input`, so an opted-in site still builds eagerly and still fails loudly on a bad value.
  `test/components/init-v2.spec.js` pins all of this.
- **`inline-snippet.marko`** + **`utils/inline-snippet.min.js`** — the v2 inline capture
  runtime, a **verbatim copy** built in `mindful-reporting/packages/p1-events/lib` by
  `yarn build:inline`. ⚠️ **Not a queue stub.** It anchors the page load and captures
  gestures, visibility/focus attention, active time, max scroll depth, bfcache restores and
  the orphan-load beacon — none of which the library can reconstruct, and `start()` **throws**
  if it never ran. To update: rebuild there, copy the file across, and bump
  `P1_EVENTS_INLINE_VERSION` (which also drives the library's CDN version, keeping the two
  halves of a release in step).
- **`middleware.js`** — `p1EventsVisitorCookie()` sets the `__p1e_vis` visitor cookie
  server-side (2-year, non-httpOnly). Important for the Mindful ad server, which reads it
  when requesting ads. ⚠️ Not v2-specific, and **coupled**: `marko-web-mindful-ads`'
  `load-ad-data.js` throws if this middleware has not run, so it cannot be removed on its
  own (see "Migration").

### Why v2 does not use the deferred script loader

`type="module"` is already deferred, so `async` never blocks parsing or rendering — the DSL
would only delay the *fetch* to `ready`/`load`, while itself costing an extra CDN request
and a competing `modulepreload`. ⚠️ That delay is not free here: until the library
initializes it cannot set `__p1e.owned`, and every abandonment before that point sends an
**orphan** beacon instead of a real page-load event — worst on exactly the slow connections
where abandonment is likeliest.

## Event model

All tracking goes through `window.p1events('track', { category, action, entity, label?,
ctx?, props? })`. `entity = { id, ns, name?, props?, refs? }`. Namespaces come from
`utils/create-namespace.js` → `base.{TENANT_KEY}.{type}` (native/mindful trackers use
`mindful.{namespace}.*` instead). `p1events('setIdentity', entity)` associates the session
with an app-user entity (used by conversion events so the session de-anonymizes at submit).

## View trackers (one `View` event per page-type)

Each gates on `config.enabled`, emits `action: 'View'`, and — except native-story — mounts
`<marko-web-p1-events-track-engagement>` passing its own `category` + `entity` as props.

| Component | category | entity ns (`base.{tenant}.`…) | notes |
|---|---|---|---|
| `track-content` | `Content` | `content-{type}` | refs: primarySection, company, authors, createdBy; `label: 'Sponsored'` when sponsored |
| `track-website-section` | `Website Section` | `website-section` | |
| `track-static-route-view` | `Static Route` | `static-route` | |
| `track-user-route-view` | `User Route` | `user-route` | |
| `track-search` | `Search` | `search` | `label` = search term, lowercased |
| `track-native-story` | `Advertising Post` / `Content` | `mindful.{ns}.advertising-post` / nativeX ns | mindful-ads vs nativeX branch; **does not** mount engagement |

## Engagement tracking — `Engaged View`

> ⚠️ **DEPRECATED on v2 sites — but deliberately kept.** The v2 library captures engagement
> itself, from the inline runtime: `engTime` / `focusTime` / `activeTime` / `scrollMax`, plus
> `ver` / `gest` derived from the same trusted-gesture signal this component triggers on,
> flushed onto the page-load document. So on a v2 site this is **redundant in the pipeline**.
>
> ⛔ It is **not** redundant in the **reports** — upstream consumers still read the
> `Engaged View` event, so removing it breaks them. It stays mounted on v2 sites until those
> reports move to the v2 load-document engagement data. Only then do
> `track-engagement.marko`, `browser/track-engagement.vue` and the mounts in the View
> trackers come out.

**Why:** a positive "humanity" signal to counter bot-inflated page views. Cloudflare `bmsc`
already gates p1events, but the 30–99 score band passes through as human, so AI crawlers /
headless leak in. Engagement is orthogonal (positive humanity vs. negative bot score) and
lets reporting surface **"Engaged Page Views."**

**Wrapper — `track-engagement.marko`** (`<marko-web-p1-events-track-engagement>`):
- Gates on `config.enabled && engagement.enabled !== false` → **default-ON (opt-out) since
  v1.76.4** (mindful-web #275). A site opts out with `p1events.engagement.enabled: false`.
- Reads `floorPx` / `viewportFraction` / `enableTextSelect` thresholds from config and
  passes `category` + `entity` (from the mounting View tracker) as props.

**Browser component — `browser/track-engagement.vue`:** fires exactly **one** `Engaged View`
on the first genuine human interaction, then unbinds all listeners. One View tracker per
page → exactly one engagement event, attributed to that page's entity.

- **Triggers (OR):** scroll past `max(floorPx=500, viewportFraction=0.75 × innerHeight)`;
  link/button click; menu-open (classified via `MENU_SELECTOR`); form-field focus
  (`focusin`); media `play`; text-selection (opt-in, off by default).
- **Guards on every trigger** (added after the Oct 2026 "Close Newsletter Menu" bot, which
  made 32–35% of Athletic Business's Engaged Views by clicking the auto-opened pushdown's
  close button in an unfocused window):
  - **Trusted input only.** Gesture, key, pointer and click events with `isTrusted ===
    false` are ignored. ⚠️ This stops `element.click()` / `dispatchEvent`, **not**
    automation that drives the browser (CDP input is trusted).
  - **Scroll needs a recent scroll gesture.** A `scroll` counts only within
    `GESTURE_WINDOW_MS` (3s) of a trusted wheel / touchmove / reading key (`READING_KEYS`,
    mirroring the v2 library). `scrollY` also moves on layout shift (scroll anchoring when
    content above the viewport collapses or loads), anchor jumps, scroll restoration and
    scripted scrolls; none of those are the reader. Enter/Escape never arm it.
  - **Dismiss controls never count** — `DISMISS_SELECTOR`: `[data-p1-no-engage]` plus the
    newsletter pushdown/modal close, sticky and prestitial ad close, and the GTM-injected
    cookieconsent notice. ⛔ Give any new auto-shown overlay's close control
    `data-p1-no-engage`. A press on one does not arm the other triggers either.
  - **Focus / media / selection need prior real input** (`sawInput`), since the browser
    raises those events for autofocus, autoplay and scripted selection too.
  - **Attention.** Nothing fires in a hidden tab; click-type triggers also need
    `document.hasFocus()`. A rejected trigger does not consume the single shot.
- **Event shape:** `action: 'Engaged View'`; `category` + `entity` mirror the View;
  `label: 'Sponsored'` on sponsored content (so reporting splits editorial vs. sponsored
  engagement the same way it splits Views); `props.eventName` = the trigger type
  (`scroll | link-click | menu-open | form-input | media-play | text-select`).
- **Ad clicks are NOT a trigger.** GAM and Mindful creatives render in cross-origin
  (safe)frames, so their clicks never bubble to the page — and they are already tracked and
  bot-filtered by the ad servers. Same-origin ad containers (`[data-unit-form]`,
  `[id^="mfads-req-"]`) are explicitly ignored.
- **Deliberately separate from scroll-depth.** Engagement is single-shot humanity; the
  scroll-depth trackers are gated-content-aware and multi-threshold. Do not merge them.
- **GTM/GA4 mirror.** `fire()` also pushes a `verified-view` event to `window.dataLayer`
  (in addition to the p1event) so GA4 can report the same signal. Shape follows the fleet
  convention (`identity-x`): a top-level `event: 'verified-view'` for the GTM Custom Event
  trigger, plus a nested `'p1-events'` namespace object (`category`, `action: 'Engaged
  View'`, `label?`, `eventName`, `entityId`/`entityNs`/`entityName`) that GTM Data Layer
  Variables read. Pushed independently of `window.p1events`, so GA4 still gets it if the
  p1events lib is blocked. Gated only on `dataLayer` presence — no extra config. GTM side:
  Custom Event trigger on `verified-view` → GA4 event tag mapping the `p1-events.*` DLVs.

**Accepted limitations** (deliberately biased toward *under*-counting — the safe direction
for an advertiser-facing "engaged" number):
- **Ad-only clickers uncredited per-post.** A human whose only interaction is an
  above-the-fold ad click isn't counted engaged — the tracker can't see cross-origin ad
  clicks, and the bot-filtered ad-click p1event carries the ad-creative entity, not the
  content entity. Tiny population and the most bot-adversarial signal; measure the gap from
  ad-click events rather than blending it in.
- **Forward-only.** `engagedViews` exists from client-ship forward; historical days show 0.
  Communicate this to analytics consumers.
- **Score-filter residual.** Catches the cheap-bot majority (`bmsc` 30–99 leaking into
  `events-by-hour`), not synthetic-interaction adversaries. A sub-second time-to-interaction
  floor was deferred (instrument first) — add only if a near-zero synthetic cluster appears.
  The trigger guards above remove the scripted and unfocused cases; a bot that drives a
  focused browser and clicks a real link or wheel-scrolls still counts.

## Scroll-depth trackers — `track-scroll-depth/`

Separate family (`track-content-scroll-depth`, `-website-section-`, `-native-story-`) that
emit `Scroll` events at `targetScrollDepths` (default `[0.25, 0.5, 0.75, 0.9]`) via the
`P1EventsTrackScrollDepth` browser component. Content/section entities mirror the View
trackers'. Each needs `content` (builds the entity) and a CSS `selector` for the scroll
container. **Gated-content-aware and multi-threshold — deliberately NOT merged with
engagement** (see above).

**Gating principle (critical).** Scroll depth must fire ONLY when the full body is actually
on the page — never on an anonymous/gated preview (a "Scroll 90%" on a 2-paragraph preview
is a false read). This is enforced by **placement/selector, not a runtime auth check**: the
full body renders through `theme-body-with-injection` (or a site's local
`content-body-with-injection`) into `#content-body-${content.id}`, while gated previews
render a truncated `marko-web-content-body` with **no** id — so the tracker only ever
attaches to the full render. Access (`canAccess`) is resolved server-side
(`marko-web-identity-x/components/access.marko`), so the SSR HTML already differs.

**The seam.** `theme-body-with-injection` takes an opt-in `track-scroll-depth` attribute
(+ optional `target-scroll-depths`); when set it renders
`<marko-web-p1-events-track-content-scroll-depth content=content selector=\`#${selector}\`>`
after the body. Site content layouts flip `track-scroll-depth=true` on the **primary-body**
(`content=content`) calls. Bare-`marko-web-content-body` layouts (product/company/whitepaper/
webinar/document/media-gallery) instead get the tracker added at the call site, targeting the
body's `#content-body-${id}` id (or its `.${blockName}__content-body` class, e.g. company =
`.leaders-more-info__content-body`).

**Rules when extending (new content type / new site):**
- Enable ONLY on the full, id'd `obj=content` render. NEVER on `obj={ body }` /
  `getContentPreview(...)` previews, nor hidden `modifiers=["ld-json"]` / `display:none` SEO
  copies.
- NEVER on the transcript render (`content={ body: content.transcript }`) —
  `theme-body-with-injection` is reused for transcripts, so a second tracker double-counts.
- Do NOT add tracking to the base `marko-web-content-body` component — it's a generic field
  renderer (feeds/teasers/inline/print), not a valid seam.
- **Pitfall:** older sites had an *ungated* `track-content-scroll-depth` in content
  `wrapper.marko` `<@page>` (selector `.…page-contents__content-body`) that fired on previews
  and double-counted the gated tracker. Removed fleet-wide — do not reintroduce a
  wrapper-level scroll tracker.

## Conversion & integration events — `browser/index.js`

Bridges identity-x / form EventBus events to `p1events('track', …)`:
- Newsletter form action → `category/action/label` from the payload.
- Identity conversions: `Submit` (Content Access, Content Download, Profile), `Sent`
  (Login Link), `Click` (Login Link); Subscription `Subscribe`. Events in the
  `identifyOnSubmit` set call `setIdentity` **before** tracking so the session
  de-anonymizes at submit time (identity is otherwise baked at page render).
- Submission trackers: `track-inquiry-submission` / `track-download-submission`
  (`eventName` prop), `track-content-body-links` (`category` / `action` props).

## Migration — v1 → v2 (in progress)

**Per site, three things MUST land in one change**, which setting `p1events.v2` does
automatically since all three gate on it:

1. the `__p1c` config swap (`init-v2.marko` instead of `init.marko`),
2. fortnight-js / native-x killed,
3. `tracking.js` dropped **and** the banner-ad plugin enabled via `mindfulBannerAds`.

Every partial combination is wrong in a measurable way:

| partial state | result |
|---|---|
| v2 config + fortnight-js still loading | **double-counts** native ads |
| fortnight-js killed, still on v1 config | **loses** native ads entirely |
| `tracking.js` loading + `mindfulBannerAds` on | **double-counts** banner view/activeview |
| `tracking.js` dropped, no `mindfulBannerAds` | **loses** banner tracking entirely |

⛔ **`mindfulBannerAds.tenant` is the AD SERVER tenant key, not `slug`.** The mapping is
many-to-one (`fusable` and `randall-reilly` both → `randallreilly`), so it **cannot be
derived** — copy the value from `<marko-web-mindful-ads-init tenant="…">`.

### Open risks

- 🔴 **Link tracking may double-count.** v2 defaults `links` ON and **document-wide**, while
  `browser/track-content-body-links.vue` still scopes to the article body. In-body external
  clicks may be counted twice on a v2 site. **Measure on the first migrated site**; if
  confirmed, set `links: false` in that site's `p1events.v2`.
- ⚠️ v2's link category defaults to `External Link`, not v1's `In-Body Content Link`, and
  nav/footer/promo clicks now count. Expected, but it changes report totals.

### Teardown — LAST, and gated on all eight ad tenants

⛔ Not per-site. The `__p1e_vis` cookie removal is a **chain**, not a deletion: drop
`visitorId` from `marko-web-mindful-ads`' `load-ad-data.js` (which **throws** without the
middleware), then from the `/data` + `/preview` schemas and the `mindful-reporting` nonce,
and only then remove `p1EventsVisitorCookie()`. ⚠️ Doing any of it before a tenant is on v2
yields events with **neither** page context nor `vis` — strictly worse than v1.

## Downstream (pointers — not the source of truth here)

- **Reporting:** `Engaged View` events roll up to `metrics.engagedViews` and are exposed as
  `engagedViews` / `engagedPageViews` — see `mindful-reporting` (graphql/reporting
  `resolvers/analytics/content-performance.ts` + the content-post sync).
- **CMS:** surfaced in the Content Performance analytics view in `mindful-cms`.
