@mrrocket/sdk 0.24.0 → 0.26.0

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.tsx"],"sourcesContent":["\"use client\";\n\nimport { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { usePathname } from \"next/navigation\";\nimport { Ctx, type CockpitContext, type CockpitUser, useCtx } from \"./context\";\nimport { Survey, forgetStoredDismissals } from \"./survey\";\nimport { RageDetector, clickInfo, seenDepth } from \"./capture\";\nimport type { ReplayHandle } from \"./replay\";\nimport { type ErrorCapture, startErrorCapture } from \"./errors\";\nimport {\n type AttributionMode,\n DEFAULT_REFERRAL_DAYS,\n captureReferral,\n carriesReferral,\n forgetStoredReferral,\n getReferral,\n resetReferral,\n storeReferral,\n} from \"./referral\";\nimport {\n type CockpitConfig,\n type CockpitEvent,\n type ConsentChoice,\n type ConsentMode,\n EMBED_PARAM,\n EXPOSURE_PARAM,\n ID_COOKIE,\n PREVIEW_PARAM,\n SDK_VERSION,\n SESSION_COOKIE,\n type VariantId,\n envKey,\n experimentsOfText,\n exposureFrom,\n flagExposure,\n flagFor,\n parsePreview,\n redirectFor,\n resolveHost,\n resolveVariant,\n textChanges,\n warnOverlaps,\n CONSENT_OFF_EVENT,\n} from \"./core\";\nimport type { PushResult, WebPushOptions } from \"./push-web\";\nimport { bodies } from \"./batch\";\nimport { YEAR_S, deleteCookie, enterPage, kept, page, privacySignal, touchSession, visitorId, writeCookie } from \"./web-state\";\nimport { type CancelFlowOptions, type CancelFlowResult, type FlowsController, type OnboardingFlow, createFlows } from \"./flows\";\nimport type { OnboardingReport, OnboardingReportOptions } from \"./onboarding-report\";\nimport { type UseOnboarding, useOnboardingItem, useReportWith } from \"./onboarding-state\";\nimport { startPicker } from \"./pick\";\nimport type { FlowsTheme } from \"./flows-ui\";\nimport { forgetFlowsStorage, webFlowsEnv } from \"./flows-web\";\nimport { type PaywallHost, type PaywallOptions, type PaywallResult, createPaywallHost } from \"./paywall\";\nimport { type IdentifyOptions, type Signed, hashFor, nextSigned, warnUnsigned } from \"./identity\";\nimport { currentLocale, langParam, onLocale, onWords, setLocale, setWords } from \"./i18n\";\n\n/** Tells the developer once, in the browser console, why the SDK is not reaching MRRocket (a wrong host or key is the usual cause). */\nconst warned = new Set<string>();\nconst warnOnce = (message: string) => {\n if (warned.has(message)) return;\n warned.add(message);\n console.warn(`[MRRocket] ${message}`);\n};\n\nexport interface CockpitProviderProps {\n /** The product's public key from Cockpit › Settings › SDK. Safe in the browser. Default: `NEXT_PUBLIC_MRROCKET_KEY`. */\n apiKey?: string;\n /** Where MRRocket runs, like `https://app.example.com`. Default: `NEXT_PUBLIC_MRROCKET_HOST`, else the page's own origin. */\n host?: string;\n preview?: Record<string, VariantId>;\n embedded?: boolean;\n /** Config fetched on the server, to render the right variant on the first paint. */\n config?: CockpitConfig;\n /**\n * 0.21.0: the language of the SDK's words and of what the server answers, like \"de-AT\", for an app with its own\n * language switch. Default: the browser's. `setLocale` does the same from anywhere.\n */\n locale?: string;\n /** Your own id for this visitor, for example a signed-in user id. Keeps variants stable without cookies. */\n distinctId?: string;\n /**\n * The identity hash of `distinctId` (0.16.0): `await userHash(user.id)` from `@mrrocket/sdk/next/server`, made in\n * the server layout that knows the user. Sent with every request for that id, so MRRocket knows it is really them\n * (needed with MRRocket › Settings › Products › Sign-in › \"Only signed users\"). In the browser pass it to\n * `identify(id, props, { hash })` instead.\n */\n userHash?: string;\n /**\n * \"cookieless\" (default) stores nothing in the browser, \"cookies\" keeps a visitor cookie for a year, \"off\" sends\n * nothing. The SDK does not remember the choice: set it on every page load, from the prop or setConsent().\n */\n consent?: ConsentMode;\n /** Send nothing when the browser asks not to be tracked (Do Not Track or Global Privacy Control). */\n respectDnt?: boolean;\n /**\n * The visitor's consent to session recordings, separate from analytics (default false). Recording also needs the\n * product to record (Cockpit › Sessions) and analytics not \"off\". Without it nothing is recorded or buffered.\n * Change it later with `setConsent({ replay })`.\n */\n replay?: boolean;\n /**\n * Clicks and scroll depth for Heatmaps (default true): where a click landed, a short selector and a link's or\n * button's label, never typed text. Sent under the normal analytics consent as `$click`, `$rageclick` and `$scroll`.\n */\n heatmaps?: boolean;\n /** Ask visitors the surveys you run in Cockpit. Set false to switch them off. */\n surveys?: boolean;\n /**\n * Error tracking for Build › Errors (default true): uncaught errors and unhandled promise rejections, with the page\n * and the last pages and clicks, under the normal analytics consent. Report errors you catch with\n * `useCockpit().captureError(error)`.\n */\n errors?: boolean;\n /** Your release (a version or a commit), so MRRocket can tell which release an error came with. */\n release?: string;\n /**\n * Affiliate referrals (`?ref=` links and MRRocket's tracked links). \"consent\" (default): stored in the first-party\n * `mrr_ref` cookie only while consent is \"cookies\", in memory otherwise. \"always\": stored whatever the consent (only\n * where your legal basis allows it). \"off\": referrals are ignored.\n */\n attribution?: AttributionMode;\n /** The query parameter of direct partner links, default `ref` (`https://your.site/?ref=maya`). */\n referralParam?: string;\n /**\n * Onboarding flows start on their own when the visitor does their trigger (default true). False: only\n * `useCockpit().startOnboarding()` starts one. In-app messages and `openCancelFlow` work either way.\n */\n onboarding?: boolean;\n /**\n * The look of the cancel flow, onboarding and message dialogs: `{ theme: \"dark\", accent: \"#0f766e\", className }`.\n * Without an accent the onboarding dialogs take the product's brand color from MRRocket (0.18.0).\n */\n appearance?: FlowsTheme;\n /**\n * 0.18.0: opens what a checklist task's \"Opens: page or screen\" names, with your router (`(target) => router.push(target)`).\n * Without it a path or an http(s) address opens as a normal page load.\n */\n onNavigate?: (target: string) => void;\n /** 0.18.0: a checklist task set to \"Opens: your code\" was tapped: `(taskId, item) => …`. */\n onTask?: (taskId: string, item: OnboardingFlow) => void;\n /**\n * Form leads (0.12.0): a submitted form marked `data-mrrocket-form` becomes a contact in MRRocket (default true).\n * \"auto\" also captures any form with an email field (never one with a password field); false captures none. Only\n * the email, the name and the other fields a person typed go out, never passwords, card or hidden fields (forms.ts).\n */\n forms?: boolean | \"auto\";\n children: ReactNode;\n}\n\n/**\n * Put it once around your app, in `app/layout.tsx`. It loads your experiments, keeps each visitor in one variant,\n * records page views and sends your events to Cockpit in small batches.\n *\n * `preview` forces variants for this render, for example from the `ck_preview` search param on the server,\n * so a Cockpit preview never flickers. Without it the provider reads the param itself after the first render.\n */\nexport const CockpitProvider = ({\n apiKey: apiKeyProp,\n host: hostProp,\n preview: forced,\n embedded: embeddedProp,\n config: bootstrapConfig,\n locale,\n distinctId: bootstrapId,\n userHash: bootstrapHash,\n consent: consentProp = \"cookieless\",\n respectDnt = false,\n replay: replayProp = false,\n heatmaps = true,\n surveys = true,\n errors = true,\n release,\n attribution = \"consent\",\n referralParam = \"ref\",\n onboarding = true,\n appearance,\n onNavigate,\n onTask,\n forms = true,\n children,\n}: CockpitProviderProps) => {\n const pathname = usePathname();\n const apiKey = apiKeyProp ?? envKey() ?? \"\";\n const host = resolveHost(hostProp);\n const [config, setConfig] = useState<CockpitConfig | null>(bootstrapConfig ?? null);\n // The app's language before any child asks the server for words. Only in the browser: this module's state is shared\n // by all requests on a server.\n useState(() => {\n if (locale && typeof window !== \"undefined\") setLocale(locale);\n });\n const [localeTick, setLocaleTick] = useState(0);\n const [wordsTick, setWordsTick] = useState(0);\n const [consent, setConsentState] = useState<ConsentMode>(consentProp);\n const [replayConsent, setReplayConsent] = useState(replayProp);\n const [mounted, setMounted] = useState(false);\n const [dnt, setDnt] = useState(false);\n // The visitor id and the consent mode it was made for; null until the browser has been read.\n const [visitor, setVisitor] = useState<{ mode: ConsentMode; id: string } | null>(null);\n const [identified, setIdentified] = useState<string | undefined>();\n const [urlPreview, setUrlPreview] = useState<Record<string, VariantId>>({});\n const [urlEmbedded, setUrlEmbedded] = useState(false);\n const [user, setUser] = useState<CockpitUser | undefined>();\n const [ready, setReady] = useState(!!bootstrapConfig);\n // The id identify() signed and its hash (identity.ts); the ref answers callbacks at once, the state re-renders.\n const [signed, setSigned] = useState<Signed | null>(null);\n const signedRef = useRef<Signed | null>(null);\n const queue = useRef<CockpitEvent[]>([]);\n // Calls from before the visitor was known (a child's effect runs before ours); replayed once it is.\n const early = useRef<(() => void)[]>([]);\n const exposed = useRef(new Set<string>());\n const lastPage = useRef<string | null>(null);\n\n const bootstrap = bootstrapId && bootstrapId !== \"anonymous\" ? bootstrapId : undefined;\n // The `distinctId` prop signed by the server layout (`userHash` prop).\n const bootSigned = useMemo(() => (bootstrap && bootstrapHash ? nextSigned(null, bootstrap, bootstrapHash) : null), [bootstrap, bootstrapHash]);\n const bootSignedRef = useRef(bootSigned);\n bootSignedRef.current = bootSigned;\n /** The identity hash for `id`, only when the SDK holds one for exactly that id. */\n const hashOf = useCallback((id: string | undefined) => hashFor(signedRef.current, id) ?? hashFor(bootSignedRef.current, id), []);\n const preview = useMemo(() => ({ ...urlPreview, ...forced }), [urlPreview, forced]);\n const embedded = embeddedProp ?? urlEmbedded;\n const effectiveConsent: ConsentMode = respectDnt && dnt ? \"off\" : consent;\n const distinctId = identified ?? bootstrap ?? visitor?.id ?? \"anonymous\";\n const tracking = !embedded && effectiveConsent !== \"off\" && visitor?.mode === effectiveConsent;\n // Without cookies, events carry an id only after identify(); the server counts everyone else by its daily hash,\n // which the config hands over as `unit` (0.24.0) so the events carry the id the tests assigned by.\n const sendId = effectiveConsent === \"cookies\" ? distinctId : identified;\n const unit = config?.unit;\n // A config from the server without a unit (its server could not ask for the visitor's) is read again in the browser\n // for one; until then running tests show control and record nothing, so nobody switches version twice.\n const [unitWait, setUnitWait] = useState(() => !!bootstrapConfig && !bootstrapConfig.unit && !bootstrap && consentProp === \"cookieless\" && !!apiKey);\n /**\n * The id tests and flags assign by (0.24.0): a signed-in id or the `ck_id` cookie, else the config's `unit` (the\n * same all day, also in the server render), else this page load's id (an older MRRocket). Null while the unit is on\n * its way.\n */\n const assignId: string | null = identified ?? bootstrap ?? (visitor?.mode === \"cookies\" ? visitor.id : undefined) ?? unit ?? (unitWait ? null : (visitor?.id ?? \"anonymous\"));\n const assignRef = useRef(assignId);\n assignRef.current = assignId;\n const wantUnit = useRef(false);\n wantUnit.current = !bootstrap && effectiveConsent === \"cookieless\";\n const userHash = hashFor(signed, distinctId) ?? hashFor(bootSigned, distinctId);\n\n // Preview flags and the browser's privacy signal, once, in the browser.\n useEffect(() => {\n const params = new URLSearchParams(window.location.search);\n setUrlPreview(parsePreview(params.get(PREVIEW_PARAM)));\n setUrlEmbedded(params.get(EMBED_PARAM) === \"1\");\n setDnt(privacySignal());\n setMounted(true);\n // Opened by MRRocket's onboarding editor to pick an element for a tour step (./pick.ts); only then, only in a frame.\n return params.get(EMBED_PARAM) === \"1\" ? (startPicker() ?? undefined) : undefined;\n }, []);\n\n /** Sends these events now, past the queue; a beacon outlives the page. */\n const sendNow = useCallback(\n (events: CockpitEvent[], beacon: boolean, hash: string | undefined) => {\n if (!apiKey) return;\n const url = `${host}/api/sdk/events`;\n for (const body of bodies(apiKey, events, { v: SDK_VERSION, errors }, hash)) {\n const sent = beacon && typeof navigator !== \"undefined\" && \"sendBeacon\" in navigator && navigator.sendBeacon(url, body);\n if (!sent)\n fetch(url, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body, keepalive: true })\n .then((r) => {\n if (r.status === 401) warnUnsigned(401);\n else if (!r.ok) warnOnce(`Events were rejected with ${r.status}. Check the public key (Settings › SDK) and NEXT_PUBLIC_MRROCKET_HOST.`);\n })\n .catch(() => warnOnce(`Could not reach ${host || \"this origin\"} to send events. Check NEXT_PUBLIC_MRROCKET_HOST.`));\n }\n },\n [apiKey, host, errors],\n );\n\n const setConsent = useCallback(\n (choice: ConsentChoice) => {\n const { analytics: mode, replay } = typeof choice === \"string\" ? { analytics: choice, replay: undefined } : choice;\n if (mode === \"off\") {\n queue.current.length = 0;\n // The one thing that still goes out: the signed-in person withdrew, so lists stop sorting them by what they do.\n // Sent here, not queued: the effect below empties the queue when consent turns off. Only a change made here\n // says it: a browser's privacy signal or a page that starts off never tracked anyone.\n const now = live.current;\n const who = now.identified ? now.sendId : bootstrap;\n if (now.tracking && who) {\n live.current = { ...now, tracking: false };\n sendNow([{ event: CONSENT_OFF_EVENT, distinctId: who, ts: Date.now() }], true, hashOf(who));\n }\n }\n if (mode) setConsentState(mode);\n if (typeof replay === \"boolean\") setReplayConsent(replay);\n },\n [bootstrap, hashOf, sendNow],\n );\n\n // Follow the `consent` and `replay` props when they change; setConsent() calls in between stay until they do.\n const lastProp = useRef(consentProp);\n useEffect(() => {\n if (lastProp.current === consentProp) return;\n lastProp.current = consentProp;\n setConsent(consentProp);\n }, [consentProp, setConsent]);\n const lastReplayProp = useRef(replayProp);\n useEffect(() => {\n if (lastReplayProp.current === replayProp) return;\n lastReplayProp.current = replayProp;\n setConsent({ replay: replayProp });\n }, [replayProp, setConsent]);\n\n // Storage follows consent. Leaving \"cookies\" deletes what the SDK stored; this page keeps its id in memory.\n const storedFor = useRef<ConsentMode | null>(null);\n useEffect(() => {\n if (!mounted) return;\n const before = storedFor.current;\n storedFor.current = effectiveConsent;\n if (before === \"cookies\" && effectiveConsent !== \"cookies\") {\n deleteCookie(ID_COOKIE);\n deleteCookie(SESSION_COOKIE);\n forgetStoredDismissals();\n forgetFlowsStorage();\n }\n if (effectiveConsent === \"off\") {\n queue.current.length = 0;\n page.session = undefined;\n }\n setVisitor({ mode: effectiveConsent, id: visitorId(effectiveConsent, !bootstrap) });\n }, [mounted, effectiveConsent, bootstrap]);\n\n useEffect(() => {\n if (locale) setLocale(locale);\n }, [locale]);\n useEffect(() => onLocale(() => setLocaleTick((n) => n + 1)), []);\n // New words: every widget under the provider draws again (the context changes with them).\n useEffect(() => onWords(() => setWordsTick((n) => n + 1)), []);\n\n // Experiments for this key. Without a key or when MRRocket is unreachable the page keeps control and carries on.\n useEffect(() => {\n if (!apiKey) warnOnce(\"No public key. Pass apiKey or set NEXT_PUBLIC_MRROCKET_KEY; nothing is tracked until then.\");\n // A config from the server stays unless the visitor reads another language than the one it brought. In an\n // effect, not in render: the first paint must match the server's, which has no visitor language.\n if (bootstrapConfig) setWords(bootstrapConfig.words, bootstrapConfig.lang);\n const reads = currentLocale()?.split(\"-\")[0].toLowerCase();\n // 0.24.0: a server config without the visitor's unit is read again here for it (cookieless, no id of the app's).\n const lacksUnit = !!bootstrapConfig && !bootstrapConfig.unit && wantUnit.current;\n if (!apiKey || (bootstrapConfig && (!reads || reads === (bootstrapConfig.lang ?? \"en\")) && !lacksUnit)) {\n setReady(true);\n setUnitWait(false);\n return;\n }\n let live = true;\n fetch(`${host}/api/sdk/config?key=${encodeURIComponent(apiKey)}${langParam()}`)\n .then((r) => {\n if (!r.ok) warnOnce(`Config request to ${host || \"this origin\"} answered ${r.status}. Check the public key and NEXT_PUBLIC_MRROCKET_HOST.`);\n return r.ok ? r.json() : null;\n })\n .then((c: CockpitConfig | null) => {\n if (!live) return;\n if (c && Array.isArray(c.experiments)) {\n setWords(c.words, c.lang);\n // The server render's unit stays: it chose the versions this page shows.\n setConfig(bootstrapConfig?.unit ? { ...c, unit: bootstrapConfig.unit } : c);\n }\n setReady(true);\n setUnitWait(false);\n })\n .catch(() => {\n warnOnce(`Could not reach ${host || \"this origin\"}. Check NEXT_PUBLIC_MRROCKET_HOST. The page keeps working with control variants.`);\n if (live) {\n setReady(true);\n setUnitWait(false);\n }\n });\n return () => {\n live = false;\n };\n }, [apiKey, host, bootstrapConfig, localeTick]);\n\n const flush = useCallback(\n (beacon = false) => {\n if (!queue.current.length) return;\n if (!apiKey) {\n queue.current.length = 0;\n return;\n }\n sendNow(queue.current.splice(0), beacon, hashOf(live.current.sendId));\n },\n [apiKey, hashOf, sendNow],\n );\n\n useEffect(() => {\n const timer = window.setInterval(() => flush(), 2000);\n const leave = () => flush(true);\n window.addEventListener(\"pagehide\", leave);\n return () => {\n window.clearInterval(timer);\n window.removeEventListener(\"pagehide\", leave);\n flush(true);\n };\n }, [flush]);\n\n // The latest values for callbacks that must not change identity, so effects that use them run once.\n const live = useRef({ resolved: false, tracking, distinctId, sendId, unit, persist: false, identified: false });\n live.current = { resolved: visitor !== null, tracking, distinctId, sendId, unit, persist: visitor?.mode === \"cookies\", identified: !!identified };\n\n const record = useCallback((event: string, props: Record<string, unknown> | undefined, ts = Date.now(), url?: string) => {\n const now = live.current;\n if (!now.resolved) {\n early.current.push(() => record(event, props, ts, url));\n return;\n }\n // Previews in Cockpit never count, and nothing is sent without consent.\n if (!now.tracking) return;\n const referral = carriesReferral(event) ? getReferral() : null;\n queue.current.push({\n event,\n props: referral ? { ...props, $referral: { code: referral.code, clickId: referral.clickId } } : props,\n // Without an id of its own a cookieless event carries the unit: MRRocket's own daily hash, the id tests\n // assigned by, so a version shown and the events after it count for the same visitor (0.24.0).\n distinctId: now.sendId ?? now.unit,\n sessionId: touchSession(now.persist),\n ts,\n url: url ?? window.location.href,\n referrer: page.referrer,\n ...page.utm,\n screen: { w: window.screen.width, h: window.screen.height },\n });\n }, []);\n\n // The running recorder, if this visit records (see the recording effect below).\n const replayer = useRef<ReplayHandle | null>(null);\n // Error tracking, while `errors` is on (see the effect below).\n const errorer = useRef<ErrorCapture | null>(null);\n\n // The cancel flow, onboarding and in-app messages (flows.ts): one controller for the provider's lifetime.\n const flowsRef = useRef<FlowsController | null>(null);\n // The latest handlers, read when a task is tapped.\n const handlers = useRef({ onNavigate, onTask });\n handlers.current = { onNavigate, onTask };\n // 0.24.0: an onboarding item with a running test records its exposure as it shows (set below, once `expose` exists).\n const exposeTest = useRef<(key: string) => void>(() => undefined);\n const flows = (flowsRef.current ??= createFlows({\n ...webFlowsEnv({\n host,\n apiKey,\n track: (event, props) => record(event, props),\n personId: () => (live.current.tracking && live.current.identified ? live.current.distinctId : undefined),\n userHash: hashOf,\n canStore: () => live.current.persist,\n auto: onboarding,\n onNavigate: () => handlers.current.onNavigate,\n onTask: () => handlers.current.onTask,\n }),\n expose: (key) => exposeTest.current(key),\n }));\n\n // Paywalls (paywall.ts): one controller too; its dialog loads with the first `open` (a dynamic import).\n const configNow = useRef(config);\n configNow.current = config;\n const paywallRef = useRef<{ host: PaywallHost; mounted?: Promise<unknown> } | null>(null);\n const paywall = (paywallRef.current ??= {\n host: createPaywallHost({ config: () => configNow.current, distinctId: () => assignRef.current, track: (event, props) => record(event, props), kept: kept() }),\n });\n\n const track = useCallback(\n (event: string, props?: Record<string, unknown>) => {\n record(event, props);\n if (live.current.tracking) replayer.current?.event(event);\n flows.onEvent(event);\n },\n [record, flows],\n );\n\n const identify = useCallback(\n (id: string, props?: Record<string, unknown>, options?: IdentifyOptions) => {\n const now = live.current;\n if (!now.resolved) {\n early.current.push(() => identify(id, props, options));\n return;\n }\n const previous = now.sendId;\n // The hash belongs to this id; another id without one drops it (identity.ts).\n signedRef.current = nextSigned(signedRef.current ?? bootSignedRef.current, id, options?.hash);\n setSigned(signedRef.current);\n // From here on events carry this id in every mode; only \"cookies\" keeps it for the next visit.\n live.current = { ...now, distinctId: id, sendId: id, identified: true };\n record(\"$identify\", { ...props, id, ...(previous && previous !== id ? { previousId: previous } : {}) });\n replayer.current?.identify(id, hashOf(id));\n if (now.persist) writeCookie(ID_COOKIE, id, YEAR_S);\n setIdentified(id);\n setUser({ id, ...(props as Omit<CockpitUser, \"id\">) });\n },\n [record, hashOf],\n );\n\n // Form leads (forms.ts, a dynamic import): one submit listener on the document while `forms` is on.\n const identifyRef = useRef(identify);\n identifyRef.current = identify;\n useEffect(() => {\n if (!forms || !apiKey || embedded || typeof window === \"undefined\") return;\n let off: (() => void) | undefined;\n let gone = false;\n void import(\"./forms\")\n .then((m) => {\n if (gone) return;\n off = m.watchForms({\n host,\n apiKey,\n auto: forms === \"auto\",\n distinctId: () => (live.current.tracking ? live.current.sendId : undefined),\n userHash: hashOf,\n identified: () => live.current.identified,\n identify: (id, props) => identifyRef.current(id, props),\n tracking: () => live.current.tracking,\n referrer: () => page.referrer,\n utm: () => page.utm,\n });\n })\n .catch(() => undefined);\n return () => {\n gone = true;\n off?.();\n };\n }, [forms, apiKey, host, embedded, hashOf]);\n\n // Replay what came in before the visitor was known: sent when tracking is on, dropped when it is not.\n useEffect(() => {\n if (!visitor) return;\n for (const run of early.current.splice(0)) run();\n }, [visitor]);\n\n // Affiliate referrals: read once the consent is known and the program's cookie days have loaded.\n const referralDays = config?.referral?.cookieDays ?? DEFAULT_REFERRAL_DAYS;\n const storeReferrals = attribution === \"always\" ? effectiveConsent !== \"off\" : attribution === \"consent\" && effectiveConsent === \"cookies\";\n const captured = useRef<string | null>(null);\n const storedReferral = useRef(false);\n useEffect(() => {\n if (!visitor || !ready || embedded) return;\n if (attribution === \"off\" || effectiveConsent === \"off\") {\n resetReferral();\n if (attribution === \"off\" || storedReferral.current) forgetStoredReferral();\n return;\n }\n const href = window.location.href;\n if (captured.current === href) return;\n captured.current = href;\n void captureReferral({\n search: window.location.search,\n param: referralParam,\n store: storeReferrals,\n days: referralDays,\n beacon: apiKey\n ? ({ code, clickId }) =>\n fetch(`${host}/api/sdk/affiliate/click`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ key: apiKey, code, clickId, url: href, referrer: document.referrer || undefined }),\n keepalive: true,\n })\n .then((r) => (r.ok ? (r.json() as Promise<{ clickId?: string | null }>) : null))\n .then((b) => b?.clickId ?? null)\n : undefined,\n });\n }, [visitor, ready, embedded, attribution, effectiveConsent, pathname, referralParam, storeReferrals, referralDays, apiKey, host]);\n\n // Consent given later keeps this page load's referral; consent withdrawn deletes what was stored.\n useEffect(() => {\n if (!mounted) return;\n const r = getReferral();\n if (storeReferrals && r) storeReferral(r, referralDays);\n else if (!storeReferrals && storedReferral.current) forgetStoredReferral();\n storedReferral.current = storeReferrals;\n }, [mounted, storeReferrals, referralDays]);\n\n // `tracking` is a dependency so that variants seen before consent are recorded once tracking starts.\n const expose = useCallback(\n (key: string, variant: VariantId) => {\n if (!tracking) return;\n const mark = `${pathname}|${key}`;\n if (exposed.current.has(mark)) return;\n exposed.current.add(mark);\n track(\"$exposure\", { experiment: key, variant });\n },\n [pathname, track, tracking],\n );\n // A test's exposure with this visitor's version, for callers that only know the test (onboarding items).\n exposeTest.current = (key) => {\n if (assignId === null && !preview[key]) return;\n expose(key, resolveVariant(key, config, assignId, preview, kept()));\n };\n\n // Redirects, once per page: a page redirect or a redirect test's variant sends the visitor on as soon as the config is\n // known (`experimentRedirect` in proxy.ts does it before the page renders, without a flash). A redirect test's\n // control stays and is recorded here; the page a variant lands on records it from `ck_x`, then drops the parameter.\n const decided = useRef<{ path: string; r: ReturnType<typeof redirectFor> } | null>(null);\n const arrived = useRef<string | null | undefined>(undefined);\n useEffect(() => {\n // A cookieless page waiting for its unit decides once it has it, so a redirect test sends the right visitors.\n if (!ready || !visitor || assignId === null) return;\n if (decided.current?.path !== pathname) {\n const r = redirectFor(config, window.location.href, assignId, preview, kept());\n decided.current = { path: pathname, r };\n if (r?.to) {\n flush(true);\n window.location.replace(r.to);\n return;\n }\n }\n if (arrived.current === undefined) {\n const params = new URLSearchParams(window.location.search);\n arrived.current = params.get(EXPOSURE_PARAM);\n if (arrived.current !== null) {\n params.delete(EXPOSURE_PARAM);\n const q = params.toString();\n window.history.replaceState(window.history.state, \"\", `${window.location.pathname}${q ? `?${q}` : \"\"}${window.location.hash}`);\n }\n }\n if (!tracking) return;\n const r = decided.current.r;\n if (r?.experiment && !r.to) expose(r.experiment, r.variant!);\n const x = exposureFrom(config, arrived.current);\n if (x) expose(x.experiment, x.variant);\n arrived.current = null;\n }, [ready, visitor, pathname, config, assignId, preview, tracking, expose, flush]);\n\n // The referrer and campaign of each page; before the page view below, so it already carries them.\n useEffect(() => {\n enterPage();\n replayer.current?.page(pathname);\n errorer.current?.crumb(\"navigation\", pathname);\n }, [pathname]);\n\n // Errors of the page for Build › Errors; sent only while tracking (consent, not a preview), like events.\n useEffect(() => {\n if (!errors || !apiKey || embedded) return;\n const capture = startErrorCapture({\n host,\n apiKey,\n release,\n context: () => ({ send: live.current.tracking, distinctId: live.current.sendId, sessionId: page.session?.id, userHash: hashOf(live.current.sendId) }),\n warn: warnOnce,\n });\n errorer.current = capture;\n capture.crumb(\"navigation\", window.location.pathname);\n return () => {\n capture.stop();\n if (errorer.current === capture) errorer.current = null;\n };\n }, [errors, apiKey, host, release, embedded, hashOf]);\n\n const captureError = useCallback((error: unknown) => errorer.current?.capture(error, \"manual\"), []);\n\n // One page view per route change while tracking, so a later setConsent() records the current page right away\n // (a ref keeps React's dev double-run from counting twice).\n useEffect(() => {\n if (!tracking || lastPage.current === pathname) return;\n lastPage.current = pathname;\n // Exposures are remembered per path (\"/pricing|test\"), so nothing needs clearing here.\n track(\"$pageview\", { path: pathname });\n }, [pathname, tracking, track]);\n\n // Clicks on anything marked `data-ck-goal=\"signup_started\"` count as that goal. Every click also feeds Heatmaps\n // (`$click`, `$rageclick` on the third quick click on one spot) and, when this visit records, the recording.\n const rage = useRef(new RageDetector());\n useEffect(() => {\n const onClick = (e: MouseEvent) => {\n const el = (e.target as HTMLElement | null)?.closest<HTMLElement>(\"[data-ck-goal]\");\n if (el?.dataset.ckGoal) track(el.dataset.ckGoal, { text: el.textContent?.trim().slice(0, 80) });\n if (!live.current.tracking) return;\n const c = clickInfo(e);\n if (!c) return;\n const raged = rage.current.push(c.x, c.y, Date.now());\n if (c.label || c.selector) errorer.current?.crumb(\"click\", c.label || c.selector);\n replayer.current?.click(c, raged);\n if (!heatmaps) return;\n const props = { x: c.x, y: c.y, vw: c.vw, vh: c.vh, docH: c.docH, selector: c.selector, label: c.label, dead: !c.interactive };\n record(\"$click\", props);\n if (raged) record(\"$rageclick\", props);\n };\n document.addEventListener(\"click\", onClick);\n return () => document.removeEventListener(\"click\", onClick);\n }, [track, record, heatmaps]);\n\n // Scroll depth for Heatmaps: the deepest point seen on each page, sent when the page changes or hides.\n const depth = useRef<{ url: string; max: number; docH: number } | null>(null);\n useEffect(() => {\n if (!heatmaps || !tracking || embedded) return;\n const send = () => {\n const d = depth.current;\n if (d && d.max > 0) record(\"$scroll\", { depth: d.max, docH: d.docH, vw: window.innerWidth, vh: window.innerHeight }, Date.now(), d.url);\n depth.current = null;\n };\n const measure = () => {\n const doc = document.documentElement;\n const docH = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);\n const max = seenDepth();\n const href = window.location.href;\n if (depth.current?.url !== href) depth.current = { url: href, max, docH };\n else if (max > depth.current.max) depth.current = { url: href, max, docH };\n };\n measure();\n let frame = 0;\n const onScroll = () => {\n if (frame) return;\n frame = window.requestAnimationFrame(() => {\n frame = 0;\n measure();\n });\n };\n const onHide = () => {\n send();\n flush(true);\n };\n window.addEventListener(\"scroll\", onScroll, { passive: true });\n window.addEventListener(\"pagehide\", onHide);\n return () => {\n window.removeEventListener(\"scroll\", onScroll);\n window.removeEventListener(\"pagehide\", onHide);\n window.cancelAnimationFrame(frame);\n send();\n };\n }, [heatmaps, tracking, embedded, pathname, record, flush]);\n\n // Session recording: only with the visitor's replay consent, while tracking, and when the product records. The\n // recorder and rrweb are loaded here, lazily; withdrawing consent stops it and drops what was not sent.\n const replayConfig = config?.replay;\n const recording = tracking && replayConsent && !!replayConfig && !!apiKey;\n useEffect(() => {\n if (!recording || !replayConfig) return;\n let active = true;\n let handle: ReplayHandle | null = null;\n // `typeof window` is a build-time constant in Next.js: on the server this folds to null and the import (with\n // rrweb) never enters the server bundle.\n void (typeof window === \"undefined\" ? Promise.resolve(null) : import(\"./replay\"))\n .then((m) =>\n m?.startReplay({\n host,\n apiKey,\n sessionId: touchSession(live.current.persist),\n distinctId: live.current.sendId,\n identified: live.current.identified,\n userHash: hashOf(live.current.sendId),\n sampleRate: replayConfig.sampleRate,\n warn: warnOnce,\n }),\n )\n .then((h) => {\n if (!active) h?.stop(true);\n else replayer.current = handle = h ?? null;\n })\n .catch(() => warnOnce(\"Session recording could not start (the recorder did not load).\"));\n return () => {\n active = false;\n handle?.stop(true);\n if (replayer.current === handle) replayer.current = null;\n };\n }, [recording, replayConfig, host, apiKey, hashOf]);\n\n // The flows follow the config and the person: their messages and onboarding progress load once both are known.\n useEffect(() => {\n if (!ready || !visitor || embedded) return;\n flows.setConfig(config);\n void flows.refresh();\n }, [flows, ready, visitor, embedded, config, identified, tracking, effectiveConsent]);\n\n // The dialogs load the first time something is about to show (a dynamic import), and stay mounted after.\n const look = useRef(appearance);\n look.current = appearance;\n useEffect(() => {\n if (embedded) return;\n let unmount: (() => void) | null = null;\n let loading = false;\n let gone = false;\n const show = () => {\n if (unmount || loading || !flows.view()) return;\n loading = true;\n void (typeof window === \"undefined\" ? Promise.resolve(null) : import(\"./flows-ui\"))\n .then((m) => {\n if (!m || gone) return;\n unmount = m.mountFlows(flows, look.current);\n })\n .catch(() => warnOnce(\"The cancel flow and onboarding dialogs did not load.\"))\n .finally(() => {\n loading = false;\n });\n };\n const off = flows.subscribe(show);\n show();\n return () => {\n gone = true;\n off();\n unmount?.();\n };\n }, [flows, embedded]);\n\n const openCancelFlow = useCallback((options?: CancelFlowOptions) => flows.openCancelFlow(options), [flows]);\n const startOnboarding = useCallback((id?: string) => flows.startOnboarding(id), [flows]);\n const openPaywall = useCallback(\n (placement: string, options?: PaywallOptions): Promise<PaywallResult> => {\n if (typeof window === \"undefined\") return Promise.resolve({ outcome: \"closed\", index: 0 });\n paywall.mounted ??= import(\"./flows-ui\").then((m) => m.mountPaywall(paywall.host, look.current));\n return paywall.mounted.then(() => paywall.host.open(placement, options));\n },\n [paywall],\n );\n\n // Web push (push-web.ts, a dynamic import on the first call). The permission is asked here, synchronously inside the\n // click that called it: Safari refuses one asked after an await.\n const subscribeToPush = useCallback(\n (options?: WebPushOptions): Promise<PushResult> => {\n if (typeof window === \"undefined\") return Promise.resolve({ status: \"unsupported\" });\n const now = live.current;\n const distinctId = now.tracking && now.identified ? now.distinctId : undefined;\n if (!distinctId) return Promise.resolve({ status: \"not-signed-in\" });\n const N = window.Notification;\n const permission = Promise.resolve(N && N.permission === \"default\" && options?.ask !== false ? N.requestPermission() : N?.permission);\n return import(\"./push-web\").then((m) => m.subscribeWebPush({ host, apiKey, distinctId, userHash: hashOf(distinctId), permission }, options));\n },\n [host, apiKey, hashOf],\n );\n const unsubscribeFromPush = useCallback(\n () => {\n if (typeof window === \"undefined\") return Promise.resolve(false);\n const distinctId = live.current.identified ? live.current.distinctId : undefined;\n return import(\"./push-web\").then((m) => m.unsubscribeWebPush({ host, apiKey, distinctId, userHash: hashOf(distinctId) }));\n },\n [host, apiKey, hashOf],\n );\n\n const texts = useMemo(() => textChanges(config, assignId, preview, kept()), [config, assignId, preview]);\n // Two running tests on one text (0.24.0): the first wins; a development build names both in the console once.\n useEffect(() => {\n if (process.env.NODE_ENV !== \"production\") warnOverlaps(config);\n }, [config]);\n\n const value = useMemo<CockpitContext>(\n () => ({\n apiKey,\n host,\n user,\n ready,\n distinctId,\n assignId,\n userHash,\n config,\n preview,\n embedded,\n consent,\n effectiveConsent,\n replayConsent,\n setConsent,\n texts,\n track,\n identify,\n expose,\n captureError,\n openCancelFlow,\n startOnboarding,\n flows,\n openPaywall,\n subscribeToPush,\n unsubscribeFromPush,\n }),\n [\n wordsTick,\n flows,\n apiKey,\n host,\n user,\n ready,\n distinctId,\n assignId,\n userHash,\n config,\n preview,\n embedded,\n consent,\n effectiveConsent,\n replayConsent,\n setConsent,\n texts,\n track,\n identify,\n expose,\n captureError,\n openCancelFlow,\n startOnboarding,\n openPaywall,\n subscribeToPush,\n unsubscribeFromPush,\n ],\n );\n return (\n <Ctx.Provider value={value}>\n {children}\n {surveys ? <Survey /> : null}\n </Ctx.Provider>\n );\n};\n\n/**\n * `track`, `identify`, `captureError`, the consent mode, the replay consent and their setter, the visitor id and whether\n * the experiments and flags have loaded. `setConsent(\"cookies\")` sets the mode, `setConsent({ replay: true })` the\n * replay consent.\n */\nexport const useCockpit = () => {\n const { track, identify, captureError, distinctId, ready, embedded, consent, replayConsent, setConsent, openCancelFlow, startOnboarding } = useCtx();\n return { track, identify, captureError, distinctId, ready, embedded, consent, replay: replayConsent, setConsent, openCancelFlow, startOnboarding };\n};\n\n/**\n * Push notifications from your Lifecycle journeys for the signed-in person (`identify` first). Call `subscribe()` from\n * a click: it asks the browser's permission and signs this browser up (your site hosts `/mrrocket-sw.js`). Call\n * `unsubscribe()` on sign-out. Resolves with `{ status: \"subscribed\" | \"denied\" | \"not-asked\" | \"unsupported\" |\n * \"not-signed-in\" | \"error\" }`.\n *\n * const push = usePush();\n * <button onClick={() => push.subscribe()}>Turn on notifications</button>\n */\nexport const usePush = (): { subscribe: (options?: WebPushOptions) => Promise<PushResult>; unsubscribe: () => Promise<boolean> } => {\n const { subscribeToPush, unsubscribeFromPush } = useCtx();\n return useMemo(() => ({ subscribe: subscribeToPush, unsubscribe: unsubscribeFromPush }), [subscribeToPush, unsubscribeFromPush]);\n};\n\n/**\n * A feature flag from MRRocket › Build › Feature flags: true while it is on for this visitor (its audience and rollout\n * in Production), false while it is off, unknown, or the flags have not loaded yet (`useCockpit().ready`). The person's\n * properties from `identify(id, props)` feed the audience conditions (\"Email\", \"Plan\" …).\n *\n * const newCheckout = useFlag(\"new-checkout\");\n */\nexport const useFlag = (key: string): boolean => useFlagValue(key) !== false;\n\n/** The variant of a multivariate flag for this visitor (\"control\", \"test\" …), or null while the flag is off. */\nexport const useFlagVariant = (key: string): string | null => {\n const v = useFlagValue(key);\n return typeof v === \"string\" ? v : null;\n};\n\n/** A flag's value; one that measures a running test also records its exposure, once per page view (0.24.0). */\nconst useFlagValue = (key: string) => {\n const { config, assignId, user, expose } = useCtx();\n const id = assignId ?? \"anonymous\";\n const value = useMemo(() => flagFor(key, config, id, { ...user }), [key, config, id, user]);\n const x = useMemo(() => (assignId === null ? null : flagExposure(key, config, assignId, { ...user })), [key, config, assignId, user]);\n useEffect(() => {\n if (x) expose(x.experiment, x.variant);\n }, [x?.experiment, x?.variant, expose]);\n return value;\n};\n\n/** The variant this visitor sees, for example `\"control\"` or `\"a\"`. Records the exposure. */\nexport const useVariant = (key: string): VariantId => {\n const { config, assignId, preview, expose } = useCtx();\n const variant = resolveVariant(key, config, assignId, preview, kept());\n useEffect(() => {\n if ((config && assignId !== null) || preview[key]) expose(key, variant);\n }, [config, assignId, preview, key, variant, expose]);\n return variant;\n};\n\n/** Renders the element for the visitor's variant; control when the variant has no element. */\nexport const Experiment = ({ name, variants }: { name: string; variants: Record<VariantId, ReactNode> & { control: ReactNode } }) => {\n const variant = useVariant(name);\n return <>{variants[variant] ?? variants.control}</>;\n};\n\n/**\n * A text that experiments may change without a deploy: Cockpit sends the new copy for `id` and this renders it.\n * Write your default as the children.\n */\nexport const Text = ({ id, children }: { id: string; children: string }) => {\n const { texts, config, assignId, preview, expose } = useCtx();\n // Showing a text a running test changes is an exposure to that test, whichever variant the visitor has.\n useEffect(() => {\n for (const key of experimentsOfText(config, id)) if (assignId !== null || preview[key]) expose(key, resolveVariant(key, config, assignId, preview, kept()));\n }, [config, id, assignId, preview, expose]);\n return <>{texts[id] ?? children}</>;\n};\n\n/**\n * The cancel flow you built in MRRocket › Churn › Cancel flow. Call `open` from your Cancel button: it shows the flow\n * and resolves with what the customer did. MRRocket never changes the subscription; your `onCancel` and `onSave` do.\n *\n * const cancelFlow = useCancelFlow();\n * <button onClick={() => cancelFlow.open({ customer: \"business\", onCancel: cancelSubscription, onSave: applyOffer })}>\n */\nexport const useCancelFlow = (): { open: (options?: CancelFlowOptions) => Promise<CancelFlowResult> } => {\n const { openCancelFlow } = useCtx();\n return useMemo(() => ({ open: openCancelFlow }), [openCancelFlow]);\n};\n\n/**\n * 0.18.0: an onboarding item you draw yourself (\"Shown by: your code\" in MRRocket): its content, the person's progress\n * and the calls that report what they did; MRRocket still counts it and keeps the answers on the contact.\n *\n * const { item, steps, done, complete, dismiss } = useOnboarding(\"flow_123\");\n * if (!item || done) return null;\n * return <MyChecklist title={item.name} tasks={steps} onTick={complete} onClose={dismiss} />;\n */\nexport const useOnboarding = (id?: string): UseOnboarding => {\n const { flows, startOnboarding } = useCtx();\n return useOnboardingItem(flows, id, startOnboarding);\n};\n\n/**\n * 0.22.0: for an onboarding that lives in your own code. Nothing to set up in MRRocket: the first report makes the item\n * under Onboarding, and MRRocket shows who saw each step and what they answered. It follows the visitor's consent.\n *\n * const report = useOnboardingReport(\"Welcome questions\", { order: [\"goal\", \"role\"] });\n * report.saw(\"goal\", \"What brings you here?\");\n * report.answered(\"goal\", \"dream\", \"Dream game\");\n * report.closed(\"goal\");\n */\nexport const useOnboardingReport = (name: string, options?: OnboardingReportOptions): OnboardingReport => useReportWith(useCtx().track, name, options);\n\n/**\n * The paywalls you built in MRRocket › Paywalls, with their pages (benefits, social proof, plans). `open` shows the\n * placement's paywall page by page; on its last page the button hands the chosen plan to `onPurchase`, where your code\n * buys it (Stripe Checkout). MRRocket never takes a payment. A running test gives each visitor their variant's pages.\n *\n * const paywall = usePaywall();\n * <button onClick={() => paywall.open(\"feature_gate\", { onPurchase: (plan) => startCheckout(plan.id) })}>\n */\nexport const usePaywall = (): { open: (placement: string, options?: PaywallOptions) => Promise<PaywallResult> } => {\n const { openPaywall } = useCtx();\n return useMemo(() => ({ open: openPaywall }), [openPaywall]);\n};\n"],"mappings":";;;AAEA,SAAyB,aAAa,WAAW,SAAS,QAAQ,gBAAgB;AAClF,SAAS,mBAAmB;AAC5B,SAAS,KAA4C,cAAc;AACnE,SAAS,QAAQ,8BAA8B;AAC/C,SAAS,cAAc,WAAW,iBAAiB;AAEnD,SAA4B,yBAAyB;AACrD;AAAA,EAEI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP;AAAA,EAKI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAEP,SAAS,cAAc;AACvB,SAAS,QAAQ,cAAc,WAAW,MAAM,MAAM,eAAe,cAAc,WAAW,mBAAmB;AACjH,SAAmG,mBAAmB;AAEtH,SAA6B,mBAAmB,qBAAqB;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,SAAO,QAAQ,OAAO,EAAE,MAAM,YAAY,IAAI,CAAC,WAAW,CAAC;AAC/D;","names":["live","r","distinctId"]}
1
+ {"version":3,"sources":["../src/client.tsx"],"sourcesContent":["\"use client\";\n\nimport { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { usePathname } from \"next/navigation\";\nimport { Ctx, type CockpitContext, type CockpitUser, useCtx } from \"./context\";\nimport { Survey, forgetStoredDismissals } from \"./survey\";\nimport { RageDetector, clickInfo, seenDepth } from \"./capture\";\nimport type { ReplayHandle } from \"./replay\";\nimport { type ErrorCapture, startErrorCapture } from \"./errors\";\nimport {\n type AttributionMode,\n DEFAULT_REFERRAL_DAYS,\n captureReferral,\n carriesReferral,\n forgetStoredReferral,\n getReferral,\n resetReferral,\n storeReferral,\n} from \"./referral\";\nimport {\n type CockpitConfig,\n type CockpitEvent,\n type ConsentChoice,\n type ConsentMode,\n EMBED_PARAM,\n EXPOSURE_PARAM,\n ID_COOKIE,\n PREVIEW_ATTR,\n PREVIEW_EDIT_PARAM,\n PREVIEW_PARAM,\n PREVIEW_TOKEN_PARAM,\n type PreviewPayload,\n withPreview,\n SDK_VERSION,\n SESSION_COOKIE,\n type VariantId,\n envKey,\n experimentsOfText,\n exposureFrom,\n flagExposure,\n flagFor,\n parsePreview,\n redirectFor,\n resolveHost,\n resolveVariant,\n textChanges,\n warnOverlaps,\n CONSENT_OFF_EVENT,\n} from \"./core\";\nimport type { PushResult, WebPushOptions } from \"./push-web\";\nimport { bodies } from \"./batch\";\nimport { YEAR_S, deleteCookie, enterPage, kept, page, privacySignal, touchSession, visitorId, writeCookie } from \"./web-state\";\nimport { type CancelFlowOptions, type CancelFlowResult, type FlowsController, type OnboardingFlow, createFlows } from \"./flows\";\nimport type { OnboardingReport, OnboardingReportOptions } from \"./onboarding-report\";\nimport { type UseOnboarding, useOnboardingItem, useReportWith } from \"./onboarding-state\";\nimport { startPicker } from \"./pick\";\nimport type { FlowsTheme } from \"./flows-ui\";\nimport { forgetFlowsStorage, webFlowsEnv } from \"./flows-web\";\nimport { type PaywallHost, type PaywallOptions, type PaywallResult, createPaywallHost } from \"./paywall\";\nimport { type IdentifyOptions, type Signed, hashFor, nextSigned, warnUnsigned } from \"./identity\";\nimport { currentLocale, langParam, onLocale, onWords, setLocale, setWords } from \"./i18n\";\n\n/** Tells the developer once, in the browser console, why the SDK is not reaching MRRocket (a wrong host or key is the usual cause). */\nconst warned = new Set<string>();\nconst warnOnce = (message: string) => {\n if (warned.has(message)) return;\n warned.add(message);\n console.warn(`[MRRocket] ${message}`);\n};\n\nexport interface CockpitProviderProps {\n /** The product's public key from Cockpit › Settings › SDK. Safe in the browser. Default: `NEXT_PUBLIC_MRROCKET_KEY`. */\n apiKey?: string;\n /** Where MRRocket runs, like `https://app.example.com`. Default: `NEXT_PUBLIC_MRROCKET_HOST`, else the page's own origin. */\n host?: string;\n preview?: Record<string, VariantId>;\n embedded?: boolean;\n /** Config fetched on the server, to render the right variant on the first paint. */\n config?: CockpitConfig;\n /**\n * 0.21.0: the language of the SDK's words and of what the server answers, like \"de-AT\", for an app with its own\n * language switch. Default: the browser's. `setLocale` does the same from anywhere.\n */\n locale?: string;\n /** Your own id for this visitor, for example a signed-in user id. Keeps variants stable without cookies. */\n distinctId?: string;\n /**\n * The identity hash of `distinctId` (0.16.0): `await userHash(user.id)` from `@mrrocket/sdk/next/server`, made in\n * the server layout that knows the user. Sent with every request for that id, so MRRocket knows it is really them\n * (needed with MRRocket › Settings › Products › Sign-in › \"Only signed users\"). In the browser pass it to\n * `identify(id, props, { hash })` instead.\n */\n userHash?: string;\n /**\n * \"cookieless\" (default) stores nothing in the browser, \"cookies\" keeps a visitor cookie for a year, \"off\" sends\n * nothing. The SDK does not remember the choice: set it on every page load, from the prop or setConsent().\n */\n consent?: ConsentMode;\n /** Send nothing when the browser asks not to be tracked (Do Not Track or Global Privacy Control). */\n respectDnt?: boolean;\n /**\n * The visitor's consent to session recordings, separate from analytics (default false). Recording also needs the\n * product to record (Cockpit › Sessions) and analytics not \"off\". Without it nothing is recorded or buffered.\n * Change it later with `setConsent({ replay })`.\n */\n replay?: boolean;\n /**\n * Clicks and scroll depth for Heatmaps (default true): where a click landed, a short selector and a link's or\n * button's label, never typed text. Sent under the normal analytics consent as `$click`, `$rageclick` and `$scroll`.\n */\n heatmaps?: boolean;\n /** Ask visitors the surveys you run in Cockpit. Set false to switch them off. */\n surveys?: boolean;\n /**\n * Error tracking for Build › Errors (default true): uncaught errors and unhandled promise rejections, with the page\n * and the last pages and clicks, under the normal analytics consent. Report errors you catch with\n * `useCockpit().captureError(error)`.\n */\n errors?: boolean;\n /** Your release (a version or a commit), so MRRocket can tell which release an error came with. */\n release?: string;\n /**\n * Affiliate referrals (`?ref=` links and MRRocket's tracked links). \"consent\" (default): stored in the first-party\n * `mrr_ref` cookie only while consent is \"cookies\", in memory otherwise. \"always\": stored whatever the consent (only\n * where your legal basis allows it). \"off\": referrals are ignored.\n */\n attribution?: AttributionMode;\n /** The query parameter of direct partner links, default `ref` (`https://your.site/?ref=maya`). */\n referralParam?: string;\n /**\n * Onboarding flows start on their own when the visitor does their trigger (default true). False: only\n * `useCockpit().startOnboarding()` starts one. In-app messages and `openCancelFlow` work either way.\n */\n onboarding?: boolean;\n /**\n * The look of the cancel flow, onboarding and message dialogs: `{ theme: \"dark\", accent: \"#0f766e\", className }`.\n * Without an accent the onboarding dialogs take the product's brand color from MRRocket (0.18.0).\n */\n appearance?: FlowsTheme;\n /**\n * 0.18.0: opens what a checklist task's \"Opens: page or screen\" names, with your router (`(target) => router.push(target)`).\n * Without it a path or an http(s) address opens as a normal page load.\n */\n onNavigate?: (target: string) => void;\n /** 0.18.0: a checklist task set to \"Opens: your code\" was tapped: `(taskId, item) => …`. */\n onTask?: (taskId: string, item: OnboardingFlow) => void;\n /**\n * Form leads (0.12.0): a submitted form marked `data-mrrocket-form` becomes a contact in MRRocket (default true).\n * \"auto\" also captures any form with an email field (never one with a password field); false captures none. Only\n * the email, the name and the other fields a person typed go out, never passwords, card or hidden fields (forms.ts).\n */\n forms?: boolean | \"auto\";\n children: ReactNode;\n}\n\n/**\n * Put it once around your app, in `app/layout.tsx`. It loads your experiments, keeps each visitor in one variant,\n * records page views and sends your events to Cockpit in small batches.\n *\n * `preview` forces variants for this render, for example from the `ck_preview` search param on the server,\n * so a Cockpit preview never flickers. Without it the provider reads the param itself after the first render.\n */\nexport const CockpitProvider = ({\n apiKey: apiKeyProp,\n host: hostProp,\n preview: forced,\n embedded: embeddedProp,\n config: bootstrapConfig,\n locale,\n distinctId: bootstrapId,\n userHash: bootstrapHash,\n consent: consentProp = \"cookieless\",\n respectDnt = false,\n replay: replayProp = false,\n heatmaps = true,\n surveys = true,\n errors = true,\n release,\n attribution = \"consent\",\n referralParam = \"ref\",\n onboarding = true,\n appearance,\n onNavigate,\n onTask,\n forms = true,\n children,\n}: CockpitProviderProps) => {\n const pathname = usePathname();\n const apiKey = apiKeyProp ?? envKey() ?? \"\";\n const host = resolveHost(hostProp);\n const [config, setConfig] = useState<CockpitConfig | null>(bootstrapConfig ?? null);\n // The app's language before any child asks the server for words. Only in the browser: this module's state is shared\n // by all requests on a server.\n useState(() => {\n if (locale && typeof window !== \"undefined\") setLocale(locale);\n });\n const [localeTick, setLocaleTick] = useState(0);\n const [wordsTick, setWordsTick] = useState(0);\n const [consent, setConsentState] = useState<ConsentMode>(consentProp);\n const [replayConsent, setReplayConsent] = useState(replayProp);\n const [mounted, setMounted] = useState(false);\n const [dnt, setDnt] = useState(false);\n // The visitor id and the consent mode it was made for; null until the browser has been read.\n const [visitor, setVisitor] = useState<{ mode: ConsentMode; id: string } | null>(null);\n const [identified, setIdentified] = useState<string | undefined>();\n const [urlPreview, setUrlPreview] = useState<Record<string, VariantId>>({});\n const [urlEmbedded, setUrlEmbedded] = useState(false);\n // 0.26.0, preview mode (`mrr_preview=<token>`): the token, whether the owner edits, and the change once it is read.\n const [pv, setPv] = useState<{ token: string; edit: boolean } | null>(null);\n const [pvPayload, setPvPayload] = useState<PreviewPayload | null>(null);\n const [user, setUser] = useState<CockpitUser | undefined>();\n const [ready, setReady] = useState(!!bootstrapConfig);\n // The id identify() signed and its hash (identity.ts); the ref answers callbacks at once, the state re-renders.\n const [signed, setSigned] = useState<Signed | null>(null);\n const signedRef = useRef<Signed | null>(null);\n const queue = useRef<CockpitEvent[]>([]);\n // Calls from before the visitor was known (a child's effect runs before ours); replayed once it is.\n const early = useRef<(() => void)[]>([]);\n const exposed = useRef(new Set<string>());\n const lastPage = useRef<string | null>(null);\n\n const bootstrap = bootstrapId && bootstrapId !== \"anonymous\" ? bootstrapId : undefined;\n // The `distinctId` prop signed by the server layout (`userHash` prop).\n const bootSigned = useMemo(() => (bootstrap && bootstrapHash ? nextSigned(null, bootstrap, bootstrapHash) : null), [bootstrap, bootstrapHash]);\n const bootSignedRef = useRef(bootSigned);\n bootSignedRef.current = bootSigned;\n /** The identity hash for `id`, only when the SDK holds one for exactly that id. */\n const hashOf = useCallback((id: string | undefined) => hashFor(signedRef.current, id) ?? hashFor(bootSignedRef.current, id), []);\n const preview = useMemo(() => ({ ...urlPreview, ...forced }), [urlPreview, forced]);\n // A preview by token counts as embedded (nothing tracked) and as consent off (nothing stored on the device).\n const embedded = embeddedProp ?? (urlEmbedded || !!pv);\n const effectiveConsent: ConsentMode = pv || (respectDnt && dnt) ? \"off\" : consent;\n const distinctId = identified ?? bootstrap ?? visitor?.id ?? \"anonymous\";\n const tracking = !embedded && effectiveConsent !== \"off\" && visitor?.mode === effectiveConsent;\n // Without cookies, events carry an id only after identify(); the server counts everyone else by its daily hash,\n // which the config hands over as `unit` (0.24.0) so the events carry the id the tests assigned by.\n const sendId = effectiveConsent === \"cookies\" ? distinctId : identified;\n const unit = config?.unit;\n // A config from the server without a unit (its server could not ask for the visitor's) is read again in the browser\n // for one; until then running tests show control and record nothing, so nobody switches version twice.\n const [unitWait, setUnitWait] = useState(() => !!bootstrapConfig && !bootstrapConfig.unit && !bootstrap && consentProp === \"cookieless\" && !!apiKey);\n /**\n * The id tests and flags assign by (0.24.0): a signed-in id or the `ck_id` cookie, else the config's `unit` (the\n * same all day, also in the server render), else this page load's id (an older MRRocket). Null while the unit is on\n * its way.\n */\n const assignId: string | null = identified ?? bootstrap ?? (visitor?.mode === \"cookies\" ? visitor.id : undefined) ?? unit ?? (unitWait ? null : (visitor?.id ?? \"anonymous\"));\n const assignRef = useRef(assignId);\n assignRef.current = assignId;\n const wantUnit = useRef(false);\n wantUnit.current = !bootstrap && effectiveConsent === \"cookieless\";\n const userHash = hashFor(signed, distinctId) ?? hashFor(bootSigned, distinctId);\n\n // Preview flags and the browser's privacy signal, once, in the browser.\n useEffect(() => {\n const params = new URLSearchParams(window.location.search);\n setUrlPreview(parsePreview(params.get(PREVIEW_PARAM)));\n setUrlEmbedded(params.get(EMBED_PARAM) === \"1\");\n const token = params.get(PREVIEW_TOKEN_PARAM);\n if (token) {\n document.documentElement.setAttribute(PREVIEW_ATTR, \"loading\");\n setPv({ token, edit: params.get(PREVIEW_EDIT_PARAM) === \"1\" });\n }\n setDnt(privacySignal());\n setMounted(true);\n // Opened by MRRocket's onboarding editor to pick an element for a tour step (./pick.ts); only then, only in a frame.\n return params.get(EMBED_PARAM) === \"1\" ? (startPicker() ?? undefined) : undefined;\n }, []);\n\n /** Sends these events now, past the queue; a beacon outlives the page. */\n const sendNow = useCallback(\n (events: CockpitEvent[], beacon: boolean, hash: string | undefined) => {\n if (!apiKey) return;\n const url = `${host}/api/sdk/events`;\n for (const body of bodies(apiKey, events, { v: SDK_VERSION, errors }, hash)) {\n const sent = beacon && typeof navigator !== \"undefined\" && \"sendBeacon\" in navigator && navigator.sendBeacon(url, body);\n if (!sent)\n fetch(url, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body, keepalive: true })\n .then((r) => {\n if (r.status === 401) warnUnsigned(401);\n else if (!r.ok) warnOnce(`Events were rejected with ${r.status}. Check the public key (Settings › SDK) and NEXT_PUBLIC_MRROCKET_HOST.`);\n })\n .catch(() => warnOnce(`Could not reach ${host || \"this origin\"} to send events. Check NEXT_PUBLIC_MRROCKET_HOST.`));\n }\n },\n [apiKey, host, errors],\n );\n\n const setConsent = useCallback(\n (choice: ConsentChoice) => {\n const { analytics: mode, replay } = typeof choice === \"string\" ? { analytics: choice, replay: undefined } : choice;\n if (mode === \"off\") {\n queue.current.length = 0;\n // The one thing that still goes out: the signed-in person withdrew, so lists stop sorting them by what they do.\n // Sent here, not queued: the effect below empties the queue when consent turns off. Only a change made here\n // says it: a browser's privacy signal or a page that starts off never tracked anyone.\n const now = live.current;\n const who = now.identified ? now.sendId : bootstrap;\n if (now.tracking && who) {\n live.current = { ...now, tracking: false };\n sendNow([{ event: CONSENT_OFF_EVENT, distinctId: who, ts: Date.now() }], true, hashOf(who));\n }\n }\n if (mode) setConsentState(mode);\n if (typeof replay === \"boolean\") setReplayConsent(replay);\n },\n [bootstrap, hashOf, sendNow],\n );\n\n // Follow the `consent` and `replay` props when they change; setConsent() calls in between stay until they do.\n const lastProp = useRef(consentProp);\n useEffect(() => {\n if (lastProp.current === consentProp) return;\n lastProp.current = consentProp;\n setConsent(consentProp);\n }, [consentProp, setConsent]);\n const lastReplayProp = useRef(replayProp);\n useEffect(() => {\n if (lastReplayProp.current === replayProp) return;\n lastReplayProp.current = replayProp;\n setConsent({ replay: replayProp });\n }, [replayProp, setConsent]);\n\n // Storage follows consent. Leaving \"cookies\" deletes what the SDK stored; this page keeps its id in memory.\n const storedFor = useRef<ConsentMode | null>(null);\n useEffect(() => {\n if (!mounted) return;\n const before = storedFor.current;\n storedFor.current = effectiveConsent;\n if (before === \"cookies\" && effectiveConsent !== \"cookies\") {\n deleteCookie(ID_COOKIE);\n deleteCookie(SESSION_COOKIE);\n forgetStoredDismissals();\n forgetFlowsStorage();\n }\n if (effectiveConsent === \"off\") {\n queue.current.length = 0;\n page.session = undefined;\n }\n setVisitor({ mode: effectiveConsent, id: visitorId(effectiveConsent, !bootstrap) });\n }, [mounted, effectiveConsent, bootstrap]);\n\n useEffect(() => {\n if (locale) setLocale(locale);\n }, [locale]);\n useEffect(() => onLocale(() => setLocaleTick((n) => n + 1)), []);\n // New words: every widget under the provider draws again (the context changes with them).\n useEffect(() => onWords(() => setWordsTick((n) => n + 1)), []);\n\n // Experiments for this key. Without a key or when MRRocket is unreachable the page keeps control and carries on.\n useEffect(() => {\n if (!apiKey) warnOnce(\"No public key. Pass apiKey or set NEXT_PUBLIC_MRROCKET_KEY; nothing is tracked until then.\");\n // A config from the server stays unless the visitor reads another language than the one it brought. In an\n // effect, not in render: the first paint must match the server's, which has no visitor language.\n if (bootstrapConfig) setWords(bootstrapConfig.words, bootstrapConfig.lang);\n const reads = currentLocale()?.split(\"-\")[0].toLowerCase();\n // 0.24.0: a server config without the visitor's unit is read again here for it (cookieless, no id of the app's).\n const lacksUnit = !!bootstrapConfig && !bootstrapConfig.unit && wantUnit.current;\n if (!apiKey || (bootstrapConfig && (!reads || reads === (bootstrapConfig.lang ?? \"en\")) && !lacksUnit)) {\n setReady(true);\n setUnitWait(false);\n return;\n }\n let live = true;\n fetch(`${host}/api/sdk/config?key=${encodeURIComponent(apiKey)}${langParam()}`)\n .then((r) => {\n if (!r.ok) warnOnce(`Config request to ${host || \"this origin\"} answered ${r.status}. Check the public key and NEXT_PUBLIC_MRROCKET_HOST.`);\n return r.ok ? r.json() : null;\n })\n .then((c: CockpitConfig | null) => {\n if (!live) return;\n if (c && Array.isArray(c.experiments)) {\n setWords(c.words, c.lang);\n // The server render's unit stays: it chose the versions this page shows.\n setConfig(bootstrapConfig?.unit ? { ...c, unit: bootstrapConfig.unit } : c);\n }\n setReady(true);\n setUnitWait(false);\n })\n .catch(() => {\n warnOnce(`Could not reach ${host || \"this origin\"}. Check NEXT_PUBLIC_MRROCKET_HOST. The page keeps working with control variants.`);\n if (live) {\n setReady(true);\n setUnitWait(false);\n }\n });\n return () => {\n live = false;\n };\n }, [apiKey, host, bootstrapConfig, localeTick]);\n\n // Preview mode: the waiting change for the token on top of the config, read once the config is there.\n useEffect(() => {\n if (!pv || !ready) return;\n let live = true;\n const failed = () => {\n if (live) document.documentElement.setAttribute(PREVIEW_ATTR, \"failed\");\n };\n void import(\"./preview\")\n .then((m) => m.readPreview(host, pv.token, null))\n .then((r) => {\n if (!live) return;\n if (!r) return failed();\n const p = r.payload;\n setConfig((c) => withPreview(c, p).config);\n setUrlPreview((u) => ({ ...u, ...r.force }));\n setPvPayload(p);\n })\n .catch(failed);\n return () => {\n live = false;\n };\n }, [pv, ready, host]);\n // Then, once React has put the new words on the page (two frames), the rest of the change and the mark for the\n // screenshot; with an edit token, the owner's edit bar (./preview.ts, loaded only here).\n useEffect(() => {\n if (!pv || !pvPayload) return;\n let live = true;\n const frame = requestAnimationFrame(() =>\n requestAnimationFrame(() => {\n void import(\"./preview\").then((m) => {\n if (live) m.finishPreview(document, pvPayload, { host, token: pv.token, edit: pv.edit, path: window.location.pathname, leave: () => window.close() });\n });\n }),\n );\n return () => {\n live = false;\n cancelAnimationFrame(frame);\n };\n }, [pv, pvPayload, host]);\n\n const flush = useCallback(\n (beacon = false) => {\n if (!queue.current.length) return;\n if (!apiKey) {\n queue.current.length = 0;\n return;\n }\n sendNow(queue.current.splice(0), beacon, hashOf(live.current.sendId));\n },\n [apiKey, hashOf, sendNow],\n );\n\n useEffect(() => {\n const timer = window.setInterval(() => flush(), 2000);\n const leave = () => flush(true);\n window.addEventListener(\"pagehide\", leave);\n return () => {\n window.clearInterval(timer);\n window.removeEventListener(\"pagehide\", leave);\n flush(true);\n };\n }, [flush]);\n\n // The latest values for callbacks that must not change identity, so effects that use them run once.\n const live = useRef({ resolved: false, tracking, distinctId, sendId, unit, persist: false, identified: false });\n live.current = { resolved: visitor !== null, tracking, distinctId, sendId, unit, persist: visitor?.mode === \"cookies\", identified: !!identified };\n\n const record = useCallback((event: string, props: Record<string, unknown> | undefined, ts = Date.now(), url?: string) => {\n const now = live.current;\n if (!now.resolved) {\n early.current.push(() => record(event, props, ts, url));\n return;\n }\n // Previews in Cockpit never count, and nothing is sent without consent.\n if (!now.tracking) return;\n const referral = carriesReferral(event) ? getReferral() : null;\n queue.current.push({\n event,\n props: referral ? { ...props, $referral: { code: referral.code, clickId: referral.clickId } } : props,\n // Without an id of its own a cookieless event carries the unit: MRRocket's own daily hash, the id tests\n // assigned by, so a version shown and the events after it count for the same visitor (0.24.0).\n distinctId: now.sendId ?? now.unit,\n sessionId: touchSession(now.persist),\n ts,\n url: url ?? window.location.href,\n referrer: page.referrer,\n ...page.utm,\n screen: { w: window.screen.width, h: window.screen.height },\n });\n }, []);\n\n // The running recorder, if this visit records (see the recording effect below).\n const replayer = useRef<ReplayHandle | null>(null);\n // Error tracking, while `errors` is on (see the effect below).\n const errorer = useRef<ErrorCapture | null>(null);\n\n // The cancel flow, onboarding and in-app messages (flows.ts): one controller for the provider's lifetime.\n const flowsRef = useRef<FlowsController | null>(null);\n // The latest handlers, read when a task is tapped.\n const handlers = useRef({ onNavigate, onTask });\n handlers.current = { onNavigate, onTask };\n // 0.24.0: an onboarding item with a running test records its exposure as it shows (set below, once `expose` exists).\n const exposeTest = useRef<(key: string) => void>(() => undefined);\n const flows = (flowsRef.current ??= createFlows({\n ...webFlowsEnv({\n host,\n apiKey,\n track: (event, props) => record(event, props),\n personId: () => (live.current.tracking && live.current.identified ? live.current.distinctId : undefined),\n userHash: hashOf,\n canStore: () => live.current.persist,\n auto: onboarding,\n onNavigate: () => handlers.current.onNavigate,\n onTask: () => handlers.current.onTask,\n }),\n expose: (key) => exposeTest.current(key),\n }));\n\n // Paywalls (paywall.ts): one controller too; its dialog loads with the first `open` (a dynamic import).\n const configNow = useRef(config);\n configNow.current = config;\n const paywallRef = useRef<{ host: PaywallHost; mounted?: Promise<unknown> } | null>(null);\n const paywall = (paywallRef.current ??= {\n host: createPaywallHost({ config: () => configNow.current, distinctId: () => assignRef.current, track: (event, props) => record(event, props), kept: kept() }),\n });\n\n const track = useCallback(\n (event: string, props?: Record<string, unknown>) => {\n record(event, props);\n if (live.current.tracking) replayer.current?.event(event);\n flows.onEvent(event);\n },\n [record, flows],\n );\n\n const identify = useCallback(\n (id: string, props?: Record<string, unknown>, options?: IdentifyOptions) => {\n const now = live.current;\n if (!now.resolved) {\n early.current.push(() => identify(id, props, options));\n return;\n }\n const previous = now.sendId;\n // The hash belongs to this id; another id without one drops it (identity.ts).\n signedRef.current = nextSigned(signedRef.current ?? bootSignedRef.current, id, options?.hash);\n setSigned(signedRef.current);\n // From here on events carry this id in every mode; only \"cookies\" keeps it for the next visit.\n live.current = { ...now, distinctId: id, sendId: id, identified: true };\n record(\"$identify\", { ...props, id, ...(previous && previous !== id ? { previousId: previous } : {}) });\n replayer.current?.identify(id, hashOf(id));\n if (now.persist) writeCookie(ID_COOKIE, id, YEAR_S);\n setIdentified(id);\n setUser({ id, ...(props as Omit<CockpitUser, \"id\">) });\n },\n [record, hashOf],\n );\n\n // Form leads (forms.ts, a dynamic import): one submit listener on the document while `forms` is on.\n const identifyRef = useRef(identify);\n identifyRef.current = identify;\n useEffect(() => {\n if (!forms || !apiKey || embedded || typeof window === \"undefined\") return;\n let off: (() => void) | undefined;\n let gone = false;\n void import(\"./forms\")\n .then((m) => {\n if (gone) return;\n off = m.watchForms({\n host,\n apiKey,\n auto: forms === \"auto\",\n distinctId: () => (live.current.tracking ? live.current.sendId : undefined),\n userHash: hashOf,\n identified: () => live.current.identified,\n identify: (id, props) => identifyRef.current(id, props),\n tracking: () => live.current.tracking,\n referrer: () => page.referrer,\n utm: () => page.utm,\n });\n })\n .catch(() => undefined);\n return () => {\n gone = true;\n off?.();\n };\n }, [forms, apiKey, host, embedded, hashOf]);\n\n // Replay what came in before the visitor was known: sent when tracking is on, dropped when it is not.\n useEffect(() => {\n if (!visitor) return;\n for (const run of early.current.splice(0)) run();\n }, [visitor]);\n\n // Affiliate referrals: read once the consent is known and the program's cookie days have loaded.\n const referralDays = config?.referral?.cookieDays ?? DEFAULT_REFERRAL_DAYS;\n const storeReferrals = attribution === \"always\" ? effectiveConsent !== \"off\" : attribution === \"consent\" && effectiveConsent === \"cookies\";\n const captured = useRef<string | null>(null);\n const storedReferral = useRef(false);\n useEffect(() => {\n if (!visitor || !ready || embedded) return;\n if (attribution === \"off\" || effectiveConsent === \"off\") {\n resetReferral();\n if (attribution === \"off\" || storedReferral.current) forgetStoredReferral();\n return;\n }\n const href = window.location.href;\n if (captured.current === href) return;\n captured.current = href;\n void captureReferral({\n search: window.location.search,\n param: referralParam,\n store: storeReferrals,\n days: referralDays,\n beacon: apiKey\n ? ({ code, clickId }) =>\n fetch(`${host}/api/sdk/affiliate/click`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ key: apiKey, code, clickId, url: href, referrer: document.referrer || undefined }),\n keepalive: true,\n })\n .then((r) => (r.ok ? (r.json() as Promise<{ clickId?: string | null }>) : null))\n .then((b) => b?.clickId ?? null)\n : undefined,\n });\n }, [visitor, ready, embedded, attribution, effectiveConsent, pathname, referralParam, storeReferrals, referralDays, apiKey, host]);\n\n // Consent given later keeps this page load's referral; consent withdrawn deletes what was stored.\n useEffect(() => {\n if (!mounted) return;\n const r = getReferral();\n if (storeReferrals && r) storeReferral(r, referralDays);\n else if (!storeReferrals && storedReferral.current) forgetStoredReferral();\n storedReferral.current = storeReferrals;\n }, [mounted, storeReferrals, referralDays]);\n\n // `tracking` is a dependency so that variants seen before consent are recorded once tracking starts.\n const expose = useCallback(\n (key: string, variant: VariantId) => {\n if (!tracking) return;\n const mark = `${pathname}|${key}`;\n if (exposed.current.has(mark)) return;\n exposed.current.add(mark);\n track(\"$exposure\", { experiment: key, variant });\n },\n [pathname, track, tracking],\n );\n // A test's exposure with this visitor's version, for callers that only know the test (onboarding items).\n exposeTest.current = (key) => {\n if (assignId === null && !preview[key]) return;\n expose(key, resolveVariant(key, config, assignId, preview, kept()));\n };\n\n // Redirects, once per page: a page redirect or a redirect test's variant sends the visitor on as soon as the config is\n // known (`experimentRedirect` in proxy.ts does it before the page renders, without a flash). A redirect test's\n // control stays and is recorded here; the page a variant lands on records it from `ck_x`, then drops the parameter.\n const decided = useRef<{ path: string; r: ReturnType<typeof redirectFor> } | null>(null);\n const arrived = useRef<string | null | undefined>(undefined);\n useEffect(() => {\n // A cookieless page waiting for its unit decides once it has it, so a redirect test sends the right visitors.\n if (!ready || !visitor || assignId === null) return;\n // A preview by token stays on the page it opened.\n if (new URLSearchParams(window.location.search).has(PREVIEW_TOKEN_PARAM)) return;\n if (decided.current?.path !== pathname) {\n const r = redirectFor(config, window.location.href, assignId, preview, kept());\n decided.current = { path: pathname, r };\n if (r?.to) {\n flush(true);\n window.location.replace(r.to);\n return;\n }\n }\n if (arrived.current === undefined) {\n const params = new URLSearchParams(window.location.search);\n arrived.current = params.get(EXPOSURE_PARAM);\n if (arrived.current !== null) {\n params.delete(EXPOSURE_PARAM);\n const q = params.toString();\n window.history.replaceState(window.history.state, \"\", `${window.location.pathname}${q ? `?${q}` : \"\"}${window.location.hash}`);\n }\n }\n if (!tracking) return;\n const r = decided.current.r;\n if (r?.experiment && !r.to) expose(r.experiment, r.variant!);\n const x = exposureFrom(config, arrived.current);\n if (x) expose(x.experiment, x.variant);\n arrived.current = null;\n }, [ready, visitor, pathname, config, assignId, preview, tracking, expose, flush]);\n\n // The referrer and campaign of each page; before the page view below, so it already carries them.\n useEffect(() => {\n enterPage();\n replayer.current?.page(pathname);\n errorer.current?.crumb(\"navigation\", pathname);\n }, [pathname]);\n\n // Errors of the page for Build › Errors; sent only while tracking (consent, not a preview), like events.\n useEffect(() => {\n if (!errors || !apiKey || embedded) return;\n const capture = startErrorCapture({\n host,\n apiKey,\n release,\n context: () => ({ send: live.current.tracking, distinctId: live.current.sendId, sessionId: page.session?.id, userHash: hashOf(live.current.sendId) }),\n warn: warnOnce,\n });\n errorer.current = capture;\n capture.crumb(\"navigation\", window.location.pathname);\n return () => {\n capture.stop();\n if (errorer.current === capture) errorer.current = null;\n };\n }, [errors, apiKey, host, release, embedded, hashOf]);\n\n const captureError = useCallback((error: unknown) => errorer.current?.capture(error, \"manual\"), []);\n\n // One page view per route change while tracking, so a later setConsent() records the current page right away\n // (a ref keeps React's dev double-run from counting twice).\n useEffect(() => {\n if (!tracking || lastPage.current === pathname) return;\n lastPage.current = pathname;\n // Exposures are remembered per path (\"/pricing|test\"), so nothing needs clearing here.\n track(\"$pageview\", { path: pathname });\n }, [pathname, tracking, track]);\n\n // Clicks on anything marked `data-ck-goal=\"signup_started\"` count as that goal. Every click also feeds Heatmaps\n // (`$click`, `$rageclick` on the third quick click on one spot) and, when this visit records, the recording.\n const rage = useRef(new RageDetector());\n useEffect(() => {\n const onClick = (e: MouseEvent) => {\n const el = (e.target as HTMLElement | null)?.closest<HTMLElement>(\"[data-ck-goal]\");\n if (el?.dataset.ckGoal) track(el.dataset.ckGoal, { text: el.textContent?.trim().slice(0, 80) });\n if (!live.current.tracking) return;\n const c = clickInfo(e);\n if (!c) return;\n const raged = rage.current.push(c.x, c.y, Date.now());\n if (c.label || c.selector) errorer.current?.crumb(\"click\", c.label || c.selector);\n replayer.current?.click(c, raged);\n if (!heatmaps) return;\n const props = { x: c.x, y: c.y, vw: c.vw, vh: c.vh, docH: c.docH, selector: c.selector, label: c.label, dead: !c.interactive };\n record(\"$click\", props);\n if (raged) record(\"$rageclick\", props);\n };\n document.addEventListener(\"click\", onClick);\n return () => document.removeEventListener(\"click\", onClick);\n }, [track, record, heatmaps]);\n\n // Scroll depth for Heatmaps: the deepest point seen on each page, sent when the page changes or hides.\n const depth = useRef<{ url: string; max: number; docH: number } | null>(null);\n useEffect(() => {\n if (!heatmaps || !tracking || embedded) return;\n const send = () => {\n const d = depth.current;\n if (d && d.max > 0) record(\"$scroll\", { depth: d.max, docH: d.docH, vw: window.innerWidth, vh: window.innerHeight }, Date.now(), d.url);\n depth.current = null;\n };\n const measure = () => {\n const doc = document.documentElement;\n const docH = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);\n const max = seenDepth();\n const href = window.location.href;\n if (depth.current?.url !== href) depth.current = { url: href, max, docH };\n else if (max > depth.current.max) depth.current = { url: href, max, docH };\n };\n measure();\n let frame = 0;\n const onScroll = () => {\n if (frame) return;\n frame = window.requestAnimationFrame(() => {\n frame = 0;\n measure();\n });\n };\n const onHide = () => {\n send();\n flush(true);\n };\n window.addEventListener(\"scroll\", onScroll, { passive: true });\n window.addEventListener(\"pagehide\", onHide);\n return () => {\n window.removeEventListener(\"scroll\", onScroll);\n window.removeEventListener(\"pagehide\", onHide);\n window.cancelAnimationFrame(frame);\n send();\n };\n }, [heatmaps, tracking, embedded, pathname, record, flush]);\n\n // Session recording: only with the visitor's replay consent, while tracking, and when the product records. The\n // recorder and rrweb are loaded here, lazily; withdrawing consent stops it and drops what was not sent.\n const replayConfig = config?.replay;\n const recording = tracking && replayConsent && !!replayConfig && !!apiKey;\n useEffect(() => {\n if (!recording || !replayConfig) return;\n let active = true;\n let handle: ReplayHandle | null = null;\n // `typeof window` is a build-time constant in Next.js: on the server this folds to null and the import (with\n // rrweb) never enters the server bundle.\n void (typeof window === \"undefined\" ? Promise.resolve(null) : import(\"./replay\"))\n .then((m) =>\n m?.startReplay({\n host,\n apiKey,\n sessionId: touchSession(live.current.persist),\n distinctId: live.current.sendId,\n identified: live.current.identified,\n userHash: hashOf(live.current.sendId),\n sampleRate: replayConfig.sampleRate,\n warn: warnOnce,\n }),\n )\n .then((h) => {\n if (!active) h?.stop(true);\n else replayer.current = handle = h ?? null;\n })\n .catch(() => warnOnce(\"Session recording could not start (the recorder did not load).\"));\n return () => {\n active = false;\n handle?.stop(true);\n if (replayer.current === handle) replayer.current = null;\n };\n }, [recording, replayConfig, host, apiKey, hashOf]);\n\n // The flows follow the config and the person: their messages and onboarding progress load once both are known.\n useEffect(() => {\n if (!ready || !visitor || embedded) return;\n flows.setConfig(config);\n void flows.refresh();\n }, [flows, ready, visitor, embedded, config, identified, tracking, effectiveConsent]);\n\n // The dialogs load the first time something is about to show (a dynamic import), and stay mounted after.\n const look = useRef(appearance);\n look.current = appearance;\n useEffect(() => {\n if (embedded) return;\n let unmount: (() => void) | null = null;\n let loading = false;\n let gone = false;\n const show = () => {\n if (unmount || loading || !flows.view()) return;\n loading = true;\n void (typeof window === \"undefined\" ? Promise.resolve(null) : import(\"./flows-ui\"))\n .then((m) => {\n if (!m || gone) return;\n unmount = m.mountFlows(flows, look.current);\n })\n .catch(() => warnOnce(\"The cancel flow and onboarding dialogs did not load.\"))\n .finally(() => {\n loading = false;\n });\n };\n const off = flows.subscribe(show);\n show();\n return () => {\n gone = true;\n off();\n unmount?.();\n };\n }, [flows, embedded]);\n\n const openCancelFlow = useCallback((options?: CancelFlowOptions) => flows.openCancelFlow(options), [flows]);\n const startOnboarding = useCallback((id?: string) => flows.startOnboarding(id), [flows]);\n const openPaywall = useCallback(\n (placement: string, options?: PaywallOptions): Promise<PaywallResult> => {\n if (typeof window === \"undefined\") return Promise.resolve({ outcome: \"closed\", index: 0 });\n paywall.mounted ??= import(\"./flows-ui\").then((m) => m.mountPaywall(paywall.host, look.current));\n return paywall.mounted.then(() => paywall.host.open(placement, options));\n },\n [paywall],\n );\n\n // Web push (push-web.ts, a dynamic import on the first call). The permission is asked here, synchronously inside the\n // click that called it: Safari refuses one asked after an await.\n const subscribeToPush = useCallback(\n (options?: WebPushOptions): Promise<PushResult> => {\n if (typeof window === \"undefined\") return Promise.resolve({ status: \"unsupported\" });\n const now = live.current;\n const distinctId = now.tracking && now.identified ? now.distinctId : undefined;\n if (!distinctId) return Promise.resolve({ status: \"not-signed-in\" });\n const N = window.Notification;\n const permission = Promise.resolve(N && N.permission === \"default\" && options?.ask !== false ? N.requestPermission() : N?.permission);\n return import(\"./push-web\").then((m) => m.subscribeWebPush({ host, apiKey, distinctId, userHash: hashOf(distinctId), permission }, options));\n },\n [host, apiKey, hashOf],\n );\n const unsubscribeFromPush = useCallback(\n () => {\n if (typeof window === \"undefined\") return Promise.resolve(false);\n const distinctId = live.current.identified ? live.current.distinctId : undefined;\n return import(\"./push-web\").then((m) => m.unsubscribeWebPush({ host, apiKey, distinctId, userHash: hashOf(distinctId) }));\n },\n [host, apiKey, hashOf],\n );\n\n const texts = useMemo(() => textChanges(config, assignId, preview, kept()), [config, assignId, preview]);\n // Two running tests on one text (0.24.0): the first wins; a development build names both in the console once.\n useEffect(() => {\n if (process.env.NODE_ENV !== \"production\") warnOverlaps(config);\n }, [config]);\n\n const value = useMemo<CockpitContext>(\n () => ({\n apiKey,\n host,\n user,\n ready,\n distinctId,\n assignId,\n userHash,\n config,\n preview,\n embedded,\n previewMode: !!pv,\n consent,\n effectiveConsent,\n replayConsent,\n setConsent,\n texts,\n track,\n identify,\n expose,\n captureError,\n openCancelFlow,\n startOnboarding,\n flows,\n openPaywall,\n subscribeToPush,\n unsubscribeFromPush,\n }),\n [\n wordsTick,\n flows,\n apiKey,\n host,\n user,\n ready,\n distinctId,\n assignId,\n userHash,\n config,\n preview,\n embedded,\n pv,\n consent,\n effectiveConsent,\n replayConsent,\n setConsent,\n texts,\n track,\n identify,\n expose,\n captureError,\n openCancelFlow,\n startOnboarding,\n openPaywall,\n subscribeToPush,\n unsubscribeFromPush,\n ],\n );\n return (\n <Ctx.Provider value={value}>\n {children}\n {surveys ? <Survey /> : null}\n </Ctx.Provider>\n );\n};\n\n/**\n * `track`, `identify`, `captureError`, the consent mode, the replay consent and their setter, the visitor id and whether\n * the experiments and flags have loaded. `setConsent(\"cookies\")` sets the mode, `setConsent({ replay: true })` the\n * replay consent.\n */\nexport const useCockpit = () => {\n const { track, identify, captureError, distinctId, ready, embedded, consent, replayConsent, setConsent, openCancelFlow, startOnboarding } = useCtx();\n return { track, identify, captureError, distinctId, ready, embedded, consent, replay: replayConsent, setConsent, openCancelFlow, startOnboarding };\n};\n\n/**\n * Push notifications from your Lifecycle journeys for the signed-in person (`identify` first). Call `subscribe()` from\n * a click: it asks the browser's permission and signs this browser up (your site hosts `/mrrocket-sw.js`). Call\n * `unsubscribe()` on sign-out. Resolves with `{ status: \"subscribed\" | \"denied\" | \"not-asked\" | \"unsupported\" |\n * \"not-signed-in\" | \"error\" }`.\n *\n * const push = usePush();\n * <button onClick={() => push.subscribe()}>Turn on notifications</button>\n */\nexport const usePush = (): { subscribe: (options?: WebPushOptions) => Promise<PushResult>; unsubscribe: () => Promise<boolean> } => {\n const { subscribeToPush, unsubscribeFromPush } = useCtx();\n return useMemo(() => ({ subscribe: subscribeToPush, unsubscribe: unsubscribeFromPush }), [subscribeToPush, unsubscribeFromPush]);\n};\n\n/**\n * A feature flag from MRRocket › Build › Feature flags: true while it is on for this visitor (its audience and rollout\n * in Production), false while it is off, unknown, or the flags have not loaded yet (`useCockpit().ready`). The person's\n * properties from `identify(id, props)` feed the audience conditions (\"Email\", \"Plan\" …).\n *\n * const newCheckout = useFlag(\"new-checkout\");\n */\nexport const useFlag = (key: string): boolean => useFlagValue(key) !== false;\n\n/** The variant of a multivariate flag for this visitor (\"control\", \"test\" …), or null while the flag is off. */\nexport const useFlagVariant = (key: string): string | null => {\n const v = useFlagValue(key);\n return typeof v === \"string\" ? v : null;\n};\n\n/** A flag's value; one that measures a running test also records its exposure, once per page view (0.24.0). */\nconst useFlagValue = (key: string) => {\n const { config, assignId, user, expose } = useCtx();\n const id = assignId ?? \"anonymous\";\n const value = useMemo(() => flagFor(key, config, id, { ...user }), [key, config, id, user]);\n const x = useMemo(() => (assignId === null ? null : flagExposure(key, config, assignId, { ...user })), [key, config, assignId, user]);\n useEffect(() => {\n if (x) expose(x.experiment, x.variant);\n }, [x?.experiment, x?.variant, expose]);\n return value;\n};\n\n/** The variant this visitor sees, for example `\"control\"` or `\"a\"`. Records the exposure. */\nexport const useVariant = (key: string): VariantId => {\n const { config, assignId, preview, expose } = useCtx();\n const variant = resolveVariant(key, config, assignId, preview, kept());\n useEffect(() => {\n if ((config && assignId !== null) || preview[key]) expose(key, variant);\n }, [config, assignId, preview, key, variant, expose]);\n return variant;\n};\n\n/** Renders the element for the visitor's variant; control when the variant has no element. */\nexport const Experiment = ({ name, variants }: { name: string; variants: Record<VariantId, ReactNode> & { control: ReactNode } }) => {\n const variant = useVariant(name);\n return <>{variants[variant] ?? variants.control}</>;\n};\n\n/**\n * A text that experiments may change without a deploy: Cockpit sends the new copy for `id` and this renders it.\n * Write your default as the children.\n */\nexport const Text = ({ id, children }: { id: string; children: string }) => {\n const { texts, config, assignId, preview, expose, previewMode } = useCtx();\n // Showing a text a running test changes is an exposure to that test, whichever variant the visitor has.\n useEffect(() => {\n for (const key of experimentsOfText(config, id)) if (assignId !== null || preview[key]) expose(key, resolveVariant(key, config, assignId, preview, kept()));\n }, [config, id, assignId, preview, expose]);\n // In preview mode (0.26.0) the words get a mark the page otherwise does not carry, so MRRocket can check that the\n // change found its text and the owner can edit it in place. No box of its own: the layout stays as it is.\n if (previewMode)\n return (\n <span data-ck-text={id} data-mrr-wrap=\"\" style={{ display: \"contents\" }}>\n {texts[id] ?? children}\n </span>\n );\n return <>{texts[id] ?? children}</>;\n};\n\n/**\n * The cancel flow you built in MRRocket › Churn › Cancel flow. Call `open` from your Cancel button: it shows the flow\n * and resolves with what the customer did. MRRocket never changes the subscription; your `onCancel` and `onSave` do.\n *\n * const cancelFlow = useCancelFlow();\n * <button onClick={() => cancelFlow.open({ customer: \"business\", onCancel: cancelSubscription, onSave: applyOffer })}>\n */\nexport const useCancelFlow = (): { open: (options?: CancelFlowOptions) => Promise<CancelFlowResult> } => {\n const { openCancelFlow } = useCtx();\n return useMemo(() => ({ open: openCancelFlow }), [openCancelFlow]);\n};\n\n/**\n * 0.18.0: an onboarding item you draw yourself (\"Shown by: your code\" in MRRocket): its content, the person's progress\n * and the calls that report what they did; MRRocket still counts it and keeps the answers on the contact.\n *\n * const { item, steps, done, complete, dismiss } = useOnboarding(\"flow_123\");\n * if (!item || done) return null;\n * return <MyChecklist title={item.name} tasks={steps} onTick={complete} onClose={dismiss} />;\n */\nexport const useOnboarding = (id?: string): UseOnboarding => {\n const { flows, startOnboarding } = useCtx();\n return useOnboardingItem(flows, id, startOnboarding);\n};\n\n/**\n * 0.22.0: for an onboarding that lives in your own code. Nothing to set up in MRRocket: the first report makes the item\n * under Onboarding, and MRRocket shows who saw each step and what they answered. It follows the visitor's consent.\n *\n * const report = useOnboardingReport(\"Welcome questions\", { order: [\"goal\", \"role\"] });\n * report.saw(\"goal\", \"What brings you here?\");\n * report.answered(\"goal\", \"dream\", \"Dream game\");\n * report.closed(\"goal\");\n */\nexport const useOnboardingReport = (name: string, options?: OnboardingReportOptions): OnboardingReport => useReportWith(useCtx().track, name, options);\n\n/**\n * The paywalls you built in MRRocket › Paywalls, with their pages (benefits, social proof, plans). `open` shows the\n * placement's paywall page by page; on its last page the button hands the chosen plan to `onPurchase`, where your code\n * buys it (Stripe Checkout). MRRocket never takes a payment. A running test gives each visitor their variant's pages.\n *\n * const paywall = usePaywall();\n * <button onClick={() => paywall.open(\"feature_gate\", { onPurchase: (plan) => startCheckout(plan.id) })}>\n */\nexport const usePaywall = (): { open: (placement: string, options?: PaywallOptions) => Promise<PaywallResult> } => {\n const { openPaywall } = useCtx();\n return useMemo(() => ({ open: openPaywall }), [openPaywall]);\n};\n"],"mappings":";;;AAEA,SAAyB,aAAa,WAAW,SAAS,QAAQ,gBAAgB;AAClF,SAAS,mBAAmB;AAC5B,SAAS,KAA4C,cAAc;AACnE,SAAS,QAAQ,8BAA8B;AAC/C,SAAS,cAAc,WAAW,iBAAiB;AAEnD,SAA4B,yBAAyB;AACrD;AAAA,EAEI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP;AAAA,EAKI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAC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C,MAAI;AACA,WACI,oBAAC,UAAK,gBAAc,IAAI,iBAAc,IAAG,OAAO,EAAE,SAAS,WAAW,GACjE,gBAAM,EAAE,KAAK,UAClB;AAER,SAAO,gCAAG,gBAAM,EAAE,KAAK,UAAS;AACpC;AASO,IAAM,gBAAgB,MAA4E;AACrG,QAAM,EAAE,eAAe,IAAI,OAAO;AAClC,SAAO,QAAQ,OAAO,EAAE,MAAM,eAAe,IAAI,CAAC,cAAc,CAAC;AACrE;AAUO,IAAM,gBAAgB,CAAC,OAA+B;AACzD,QAAM,EAAE,OAAO,gBAAgB,IAAI,OAAO;AAC1C,SAAO,kBAAkB,OAAO,IAAI,eAAe;AACvD;AAWO,IAAM,sBAAsB,CAAC,MAAc,YAAwD,cAAc,OAAO,EAAE,OAAO,MAAM,OAAO;AAU9I,IAAM,aAAa,MAAyF;AAC/G,QAAM,EAAE,YAAY,IAAI,OAAO;AAC/B,SAAO,QAAQ,OAAO,EAAE,MAAM,YAAY,IAAI,CAAC,WAAW,CAAC;AAC/D;","names":["live","r","distinctId"]}
package/dist/context.d.ts CHANGED
@@ -27,6 +27,8 @@ export interface CockpitContext {
27
27
  preview: Record<string, VariantId>;
28
28
  /** Embedded in Cockpit as a preview: nothing is tracked. */
29
29
  embedded: boolean;
30
+ /** 0.26.0: the page shows a waiting change by token (`mrr_preview`); `<Text>` marks its words then. */
31
+ previewMode?: boolean;
30
32
  /** The consent mode the site set, with the `consent` prop or setConsent(). */
31
33
  consent: ConsentMode;
32
34
  /** What applies right now: "off" when the browser sends Do Not Track and the provider respects it. */
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/context.ts"],"sourcesContent":["\"use client\";\n\nimport { createContext, useContext } from \"react\";\nimport type { CockpitConfig, ConsentChoice, ConsentMode, VariantId } from \"./core\";\nimport type { CancelFlowOptions, CancelFlowResult, FlowsController } from \"./flows\";\nimport type { PaywallOptions, PaywallResult } from \"./paywall\";\nimport type { IdentifyOptions } from \"./identity\";\nimport type { PushResult, WebPushOptions } from \"./push-web\";\n\n/** Who the visitor is, from identify(). Sent along with feedback and survey answers. */\nexport interface CockpitUser {\n id: string;\n name?: string;\n email?: string;\n [key: string]: unknown;\n}\n\nexport interface CockpitContext {\n apiKey: string;\n host: string;\n user?: CockpitUser;\n ready: boolean;\n distinctId: string;\n /**\n * 0.24.0: the id tests and flags assign by: a signed-in id or the `ck_id` cookie, else the config's `unit`, else this\n * page load's id. Null while a cookieless page waits for its unit (running tests show control, nothing is recorded).\n */\n assignId: string | null;\n /** The identity hash of `distinctId` (0.16.0), from `identify(id, props, { hash })` or the `userHash` prop; undefined for anyone else. */\n userHash?: string;\n config: CockpitConfig | null;\n preview: Record<string, VariantId>;\n /** Embedded in Cockpit as a preview: nothing is tracked. */\n embedded: boolean;\n /** The consent mode the site set, with the `consent` prop or setConsent(). */\n consent: ConsentMode;\n /** What applies right now: \"off\" when the browser sends Do Not Track and the provider respects it. */\n effectiveConsent: ConsentMode;\n /** The visitor's consent to session recordings (`replay` prop or `setConsent({ replay })`). */\n replayConsent: boolean;\n setConsent: (choice: ConsentChoice) => void;\n texts: Record<string, string>;\n track: (event: string, props?: Record<string, unknown>) => void;\n /** Who the visitor is. `options.hash` is the id signed by your server (`userHash(id)`), see identity.ts. */\n identify: (id: string, props?: Record<string, unknown>, options?: IdentifyOptions) => void;\n /** Records that the visitor saw a variant, once per experiment and page view. */\n expose: (key: string, variant: VariantId) => void;\n /** Reports an error you caught to Build › Errors (while error tracking is on). */\n captureError: (error: unknown) => void;\n /** Shows the product's cancel flow; resolves with what the customer did. */\n openCancelFlow: (options?: CancelFlowOptions) => Promise<CancelFlowResult>;\n /** Starts an onboarding flow now (the first live one without an id). */\n startOnboarding: (id?: string) => boolean;\n /** The cancel flow, onboarding and messages controller (0.18.0, for `useOnboarding`). */\n flows?: FlowsController;\n /** Shows the paywall of a placement page by page; resolves with what the visitor did. */\n openPaywall: (placement: string, options?: PaywallOptions) => Promise<PaywallResult>;\n /** Signs the signed-in person's browser up for push (asks the permission from the click that calls it). */\n subscribeToPush: (options?: WebPushOptions) => Promise<PushResult>;\n /** Ends this browser's push subscription (sign-out). */\n unsubscribeFromPush: () => Promise<boolean>;\n}\n\nexport const Ctx = createContext<CockpitContext | null>(null);\n\nexport const useCtx = () => {\n const c = useContext(Ctx);\n if (!c) throw new Error(\"Cockpit: wrap your app in <CockpitProvider apiKey=…>.\");\n return c;\n};\n"],"mappings":";;;AAEA,SAAS,eAAe,kBAAkB;AA6DnC,IAAM,MAAM,cAAqC,IAAI;AAErD,IAAM,SAAS,MAAM;AACxB,QAAM,IAAI,WAAW,GAAG;AACxB,MAAI,CAAC,EAAG,OAAM,IAAI,MAAM,4DAAuD;AAC/E,SAAO;AACX;","names":[]}
1
+ {"version":3,"sources":["../src/context.ts"],"sourcesContent":["\"use client\";\n\nimport { createContext, useContext } from \"react\";\nimport type { CockpitConfig, ConsentChoice, ConsentMode, VariantId } from \"./core\";\nimport type { CancelFlowOptions, CancelFlowResult, FlowsController } from \"./flows\";\nimport type { PaywallOptions, PaywallResult } from \"./paywall\";\nimport type { IdentifyOptions } from \"./identity\";\nimport type { PushResult, WebPushOptions } from \"./push-web\";\n\n/** Who the visitor is, from identify(). Sent along with feedback and survey answers. */\nexport interface CockpitUser {\n id: string;\n name?: string;\n email?: string;\n [key: string]: unknown;\n}\n\nexport interface CockpitContext {\n apiKey: string;\n host: string;\n user?: CockpitUser;\n ready: boolean;\n distinctId: string;\n /**\n * 0.24.0: the id tests and flags assign by: a signed-in id or the `ck_id` cookie, else the config's `unit`, else this\n * page load's id. Null while a cookieless page waits for its unit (running tests show control, nothing is recorded).\n */\n assignId: string | null;\n /** The identity hash of `distinctId` (0.16.0), from `identify(id, props, { hash })` or the `userHash` prop; undefined for anyone else. */\n userHash?: string;\n config: CockpitConfig | null;\n preview: Record<string, VariantId>;\n /** Embedded in Cockpit as a preview: nothing is tracked. */\n embedded: boolean;\n /** 0.26.0: the page shows a waiting change by token (`mrr_preview`); `<Text>` marks its words then. */\n previewMode?: boolean;\n /** The consent mode the site set, with the `consent` prop or setConsent(). */\n consent: ConsentMode;\n /** What applies right now: \"off\" when the browser sends Do Not Track and the provider respects it. */\n effectiveConsent: ConsentMode;\n /** The visitor's consent to session recordings (`replay` prop or `setConsent({ replay })`). */\n replayConsent: boolean;\n setConsent: (choice: ConsentChoice) => void;\n texts: Record<string, string>;\n track: (event: string, props?: Record<string, unknown>) => void;\n /** Who the visitor is. `options.hash` is the id signed by your server (`userHash(id)`), see identity.ts. */\n identify: (id: string, props?: Record<string, unknown>, options?: IdentifyOptions) => void;\n /** Records that the visitor saw a variant, once per experiment and page view. */\n expose: (key: string, variant: VariantId) => void;\n /** Reports an error you caught to Build › Errors (while error tracking is on). */\n captureError: (error: unknown) => void;\n /** Shows the product's cancel flow; resolves with what the customer did. */\n openCancelFlow: (options?: CancelFlowOptions) => Promise<CancelFlowResult>;\n /** Starts an onboarding flow now (the first live one without an id). */\n startOnboarding: (id?: string) => boolean;\n /** The cancel flow, onboarding and messages controller (0.18.0, for `useOnboarding`). */\n flows?: FlowsController;\n /** Shows the paywall of a placement page by page; resolves with what the visitor did. */\n openPaywall: (placement: string, options?: PaywallOptions) => Promise<PaywallResult>;\n /** Signs the signed-in person's browser up for push (asks the permission from the click that calls it). */\n subscribeToPush: (options?: WebPushOptions) => Promise<PushResult>;\n /** Ends this browser's push subscription (sign-out). */\n unsubscribeFromPush: () => Promise<boolean>;\n}\n\nexport const Ctx = createContext<CockpitContext | null>(null);\n\nexport const useCtx = () => {\n const c = useContext(Ctx);\n if (!c) throw new Error(\"Cockpit: wrap your app in <CockpitProvider apiKey=…>.\");\n return c;\n};\n"],"mappings":";;;AAEA,SAAS,eAAe,kBAAkB;AA+DnC,IAAM,MAAM,cAAqC,IAAI;AAErD,IAAM,SAAS,MAAM;AACxB,QAAM,IAAI,WAAW,GAAG;AACxB,MAAI,CAAC,EAAG,OAAM,IAAI,MAAM,4DAAuD;AAC/E,SAAO;AACX;","names":[]}
package/dist/core.d.ts CHANGED
@@ -6,7 +6,7 @@ import type { CancelFlowConfig, OnboardingFlow } from "./flows.js";
6
6
  import type { PaywallConfig } from "./paywall.js";
7
7
  export type VariantId = string;
8
8
  /** This build of the SDK. Sent with the config request so MRRocket knows what the site runs (error tracking, flags). */
9
- export declare const SDK_VERSION = "0.24.0";
9
+ export declare const SDK_VERSION = "0.26.0";
10
10
  /** One variant of an experiment. `changes` replaces texts that the page marks with `<Text id>`. */
11
11
  export interface VariantConfig {
12
12
  id: VariantId;
@@ -242,6 +242,25 @@ export interface AppContext {
242
242
  export declare const PREVIEW_PARAM = "ck_preview";
243
243
  /** Set when Cockpit embeds the page: nothing is tracked, so previews never count as visits. */
244
244
  export declare const EMBED_PARAM = "ck_embed";
245
+ /**
246
+ * 0.26.0, preview mode: `?mrr_preview=<token>` shows a change that waits for the owner's approval in MRRocket (new copy,
247
+ * a test's version, a rewritten page) on the real page, for the before/after pictures of a request. The SDK reads the
248
+ * change for the token from `GET /api/sdk/preview`, applies it like a shipped winner, and marks the page
249
+ * (`PREVIEW_ATTR`). Nothing is tracked, recorded or stored on the device while the parameter is there.
250
+ */
251
+ export declare const PREVIEW_TOKEN_PARAM = "mrr_preview";
252
+ /** With `mrr_preview`: the owner edits the page's words in place (`?mrr_preview=<edit token>&mrr_edit=1`). */
253
+ export declare const PREVIEW_EDIT_PARAM = "mrr_edit";
254
+ /** On `<html>`: "loading" while the change is read, "ready" once it is on the page, "failed" when it could not be read. */
255
+ export declare const PREVIEW_ATTR = "data-mrr-preview";
256
+ /** On `<html>` beside "ready": what of the change found no place on the page, as a JSON list (missing when all did). */
257
+ export declare const PREVIEW_MISSED_ATTR = "data-mrr-preview-missed";
258
+ /**
259
+ * The words of an unseen status line the SDK adds beside the attributes (`<div role="status" data-mrr-preview-status>`,
260
+ * one transparent pixel): "mrr-preview-ready", then what was missed. A browser that can only wait for text and read the
261
+ * page's outline (MRRocket's screenshot browser) knows by it that the change is on the page.
262
+ */
263
+ export declare const PREVIEW_READY_TEXT = "mrr-preview-ready";
245
264
  /** The cookie that keeps a visitor in the same variant across visits. Only written in "cookies" mode. */
246
265
  export declare const ID_COOKIE = "ck_id";
247
266
  /**
@@ -285,6 +304,53 @@ export declare const assign: (experiment: ExperimentConfig, distinctId: string)
285
304
  export type KeptVariants = Map<string, VariantId>;
286
305
  /** `assign`, kept for the session in `kept` when one is given. */
287
306
  export declare const assignKept: (experiment: ExperimentConfig, distinctId: string, kept?: KeptVariants) => VariantId;
307
+ /** One change to a page that marks nothing for MRRocket (a rewritten text, a word the owner edited on the page). */
308
+ export type PreviewOp =
309
+ /** The words of one element. With `from`, only when the element still reads that (or already the new words). */
310
+ {
311
+ op: "set";
312
+ selector: string;
313
+ text: string;
314
+ from?: string;
315
+ }
316
+ /** The page's own text (the element whose paragraphs carry the most words) replaced by this HTML. */
317
+ | {
318
+ op: "body";
319
+ html: string;
320
+ }
321
+ /** The browser tab's title and the description search engines read. */
322
+ | {
323
+ op: "meta";
324
+ title?: string;
325
+ description?: string;
326
+ };
327
+ /** What `GET /api/sdk/preview?token=…` answers: the waiting change, in the shapes the SDK already applies. */
328
+ export interface PreviewPayload {
329
+ /** The request's title and the version shown ("Variant B"), for the edit bar. */
330
+ title?: string;
331
+ version?: string;
332
+ /** Published copy as it will read once approved, by text id (`pricing.headline`). */
333
+ texts?: Record<string, string>;
334
+ /** Tests that are not running yet (or are changed by the request), added to the config or replacing theirs by key. */
335
+ experiments?: ExperimentConfig[];
336
+ /** The version of each test this preview shows, as `ck_preview` would force it. */
337
+ force?: Record<string, VariantId>;
338
+ /** Other parts of the config as they will be (paywalls, onboarding). */
339
+ config?: Partial<Pick<CockpitConfig, "paywalls" | "onboarding" | "onboardingAccent" | "cancelFlow">>;
340
+ ops?: PreviewOp[];
341
+ /** The text ids the request changes: checked on the page, highlighted in edit mode. */
342
+ changed?: string[];
343
+ /** The token may save edits (`PREVIEW_EDIT_PARAM`). */
344
+ edit?: boolean;
345
+ }
346
+ /**
347
+ * The config with a waiting change on top, and the versions it forces: texts over the published ones, a test by its
348
+ * key replacing the config's or added to it. Redirects are left out: a preview stays on the page it opened.
349
+ */
350
+ export declare const withPreview: (config: CockpitConfig | null, p: PreviewPayload) => {
351
+ config: CockpitConfig;
352
+ force: Record<string, VariantId>;
353
+ };
288
354
  /** `"a:b,c:d"` → `{ a: "b", c: "d" }`. Ignores anything malformed. */
289
355
  export declare const parsePreview: (value: string | string[] | null | undefined) => Record<string, VariantId>;
290
356
  /** A link that shows one variant of a page, for example in Cockpit's preview frames. */
package/dist/core.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/core.ts
2
- var SDK_VERSION = "0.24.0";
2
+ var SDK_VERSION = "0.26.0";
3
3
  var propOf = (person, name) => {
4
4
  const want = name.trim().toLowerCase();
5
5
  for (const [k, v] of Object.entries(person)) if (k.toLowerCase() === want) return v;
@@ -58,6 +58,11 @@ var CONSENT_OFF_EVENT = "$consent_off";
58
58
  var UTM_KEYS = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"];
59
59
  var PREVIEW_PARAM = "ck_preview";
60
60
  var EMBED_PARAM = "ck_embed";
61
+ var PREVIEW_TOKEN_PARAM = "mrr_preview";
62
+ var PREVIEW_EDIT_PARAM = "mrr_edit";
63
+ var PREVIEW_ATTR = "data-mrr-preview";
64
+ var PREVIEW_MISSED_ATTR = "data-mrr-preview-missed";
65
+ var PREVIEW_READY_TEXT = "mrr-preview-ready";
61
66
  var ID_COOKIE = "ck_id";
62
67
  var VISITOR_IP_HEADER = "x-mrrocket-visitor-ip";
63
68
  var VISITOR_UA_HEADER = "x-mrrocket-visitor-ua";
@@ -143,6 +148,21 @@ ${distinctId}`;
143
148
  kept.set(mark, id);
144
149
  return id;
145
150
  };
151
+ var withPreview = (config, p) => {
152
+ const base = config ?? { project: "", experiments: [] };
153
+ const added = (p.experiments ?? []).filter((e) => e && typeof e.key === "string" && Array.isArray(e.variants));
154
+ const keys = new Set(added.map((e) => e.key));
155
+ const { redirects: _left, ...rest } = base;
156
+ return {
157
+ config: {
158
+ ...rest,
159
+ ...p.config ?? {},
160
+ experiments: [...base.experiments.filter((e) => !keys.has(e.key)), ...added],
161
+ ...base.texts || p.texts ? { texts: { ...base.texts ?? {}, ...p.texts ?? {} } } : {}
162
+ },
163
+ force: { ...p.force ?? {} }
164
+ };
165
+ };
146
166
  var parsePreview = (value) => {
147
167
  const raw = Array.isArray(value) ? value[0] : value;
148
168
  if (!raw) return {};
@@ -288,7 +308,12 @@ export {
288
308
  EMBED_PARAM,
289
309
  EXPOSURE_PARAM,
290
310
  ID_COOKIE,
311
+ PREVIEW_ATTR,
312
+ PREVIEW_EDIT_PARAM,
313
+ PREVIEW_MISSED_ATTR,
291
314
  PREVIEW_PARAM,
315
+ PREVIEW_READY_TEXT,
316
+ PREVIEW_TOKEN_PARAM,
292
317
  SDK_VERSION,
293
318
  SESSION_COOKIE,
294
319
  SESSION_TIMEOUT_MS,
@@ -318,6 +343,7 @@ export {
318
343
  textChanges,
319
344
  utmFrom,
320
345
  versionAt,
321
- warnOverlaps
346
+ warnOverlaps,
347
+ withPreview
322
348
  };
323
349
  //# sourceMappingURL=core.js.map