@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.
- package/CHANGELOG.md +16 -1
- package/README.md +22 -1
- package/dist/browser/mrrocket-flows.js +3 -3
- package/dist/browser/mrrocket-preview.js +1 -0
- package/dist/browser/mrrocket-replay.js +3 -3
- package/dist/browser/mrrocket.js +2 -2
- package/dist/client.js +52 -3
- package/dist/client.js.map +1 -1
- package/dist/context.d.ts +2 -0
- package/dist/context.js.map +1 -1
- package/dist/core.d.ts +67 -1
- package/dist/core.js +28 -2
- package/dist/core.js.map +1 -1
- package/dist/preview.d.ts +101 -0
- package/dist/preview.js +308 -0
- package/dist/preview.js.map +1 -0
- package/dist/react-native/index.d.cts +1 -1
- package/dist/react-native/index.d.ts +1 -1
- package/dist/react-native/index.js +1 -1
- package/dist/react-native/index.js.map +1 -1
- package/dist/server.d.ts +18 -0
- package/dist/server.js +31 -0
- package/dist/server.js.map +1 -1
- package/package.json +1 -1
package/dist/server.d.ts
CHANGED
|
@@ -64,6 +64,24 @@ interface RequestInfo {
|
|
|
64
64
|
export declare const assignIdFor: ({ config, cookies, distinctId }: RequestInfo) => string | null;
|
|
65
65
|
/** The variant of one experiment for this request (control for a running test while the visitor is unknown). */
|
|
66
66
|
export declare const getVariant: (key: string, info: RequestInfo) => VariantId;
|
|
67
|
+
/**
|
|
68
|
+
* The variant of a test your server decides on (a checkout, a price, an email), recorded as seen (0.25.0): returns what
|
|
69
|
+
* `getVariant` returns and sends `$exposure {experiment, variant}` for this person with the product's server key
|
|
70
|
+
* (`serverKey` or `MRROCKET_SERVER_KEY`), so MRRocket counts them for that version. Call it where the person meets the
|
|
71
|
+
* version; calling it again is harmless, MRRocket counts the first time. Pass `distinctId` (your user id, the same your
|
|
72
|
+
* app gives `identify()`) so the goal they reach later counts for them.
|
|
73
|
+
*
|
|
74
|
+
* Nothing is sent while the test is not running or its winner is kept for everyone, for an unknown person, for a
|
|
75
|
+
* version forced by a preview, or without the server key; the variant is returned all the same. A slow or unreachable
|
|
76
|
+
* MRRocket never holds the request longer than 2.5 s. Call it only for people your product may count, as for its
|
|
77
|
+
* other MRRocket events.
|
|
78
|
+
*/
|
|
79
|
+
export declare const trackVariant: (key: string, info: RequestInfo & {
|
|
80
|
+
apiKey?: string;
|
|
81
|
+
serverKey?: string;
|
|
82
|
+
host?: string;
|
|
83
|
+
timeoutMs?: number;
|
|
84
|
+
}) => Promise<VariantId>;
|
|
67
85
|
/**
|
|
68
86
|
* A feature flag for this request: true while it is on for the visitor, false while it is off or unknown (or MRRocket
|
|
69
87
|
* could not be reached). `person` takes the properties the flag's audience reads ("Email", "Plan" …), as you pass them
|
package/dist/server.js
CHANGED
|
@@ -63,6 +63,36 @@ var previewFrom = (searchParams) => {
|
|
|
63
63
|
var distinctIdFrom = (cookies) => cookies?.get(ID_COOKIE)?.value ?? "anonymous";
|
|
64
64
|
var assignIdFor = ({ config, cookies, distinctId }) => distinctId ?? cookies?.get(ID_COOKIE)?.value ?? config?.unit ?? null;
|
|
65
65
|
var getVariant = (key, info) => resolveVariant(key, info.config, assignIdFor(info), previewFrom(info.searchParams).preview);
|
|
66
|
+
var warnedNoServerKey = false;
|
|
67
|
+
var trackVariant = async (key, info) => {
|
|
68
|
+
const variant = getVariant(key, info);
|
|
69
|
+
const id = assignIdFor(info);
|
|
70
|
+
const test = info.config?.experiments.find((x) => x.key === key);
|
|
71
|
+
if (!test || test.status !== "running" || test.winner || !id || previewFrom(info.searchParams).preview[key]) return variant;
|
|
72
|
+
const apiKey = info.apiKey ?? envKey();
|
|
73
|
+
const secret = (info.serverKey ?? envServerKey() ?? "").trim();
|
|
74
|
+
if (!apiKey || !secret) {
|
|
75
|
+
if (!warnedNoServerKey) {
|
|
76
|
+
warnedNoServerKey = true;
|
|
77
|
+
console.warn("[MRRocket] trackVariant needs the public key and the server key (MRROCKET_SERVER_KEY or serverKey) to record who saw which version; nothing was recorded.");
|
|
78
|
+
}
|
|
79
|
+
return variant;
|
|
80
|
+
}
|
|
81
|
+
const ctrl = new AbortController();
|
|
82
|
+
const timer = setTimeout(() => ctrl.abort(), info.timeoutMs ?? CONFIG_TIMEOUT_MS);
|
|
83
|
+
try {
|
|
84
|
+
await fetch(`${resolveHost(info.host)}/api/sdk/events`, {
|
|
85
|
+
method: "POST",
|
|
86
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${secret}` },
|
|
87
|
+
body: JSON.stringify({ key: apiKey, server: true, events: [{ event: "$exposure", distinctId: id, ts: Date.now(), props: { experiment: key, variant } }] }),
|
|
88
|
+
signal: ctrl.signal
|
|
89
|
+
});
|
|
90
|
+
} catch {
|
|
91
|
+
} finally {
|
|
92
|
+
clearTimeout(timer);
|
|
93
|
+
}
|
|
94
|
+
return variant;
|
|
95
|
+
};
|
|
66
96
|
var getFlag = (key, info) => flagFor(key, info.config, assignIdFor(info) ?? "anonymous", info.person) !== false;
|
|
67
97
|
var getFlagVariant = (key, info) => {
|
|
68
98
|
const v = flagFor(key, info.config, assignIdFor(info) ?? "anonymous", info.person);
|
|
@@ -87,6 +117,7 @@ export {
|
|
|
87
117
|
reportAuthDenied,
|
|
88
118
|
reportFailedLogin,
|
|
89
119
|
reportSuspiciousRequest,
|
|
120
|
+
trackVariant,
|
|
90
121
|
userHash,
|
|
91
122
|
watchRequest
|
|
92
123
|
};
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["import {\n type CockpitConfig,\n EMBED_PARAM,\n type FlagPerson,\n ID_COOKIE,\n PREVIEW_PARAM,\n VISITOR_IP_HEADER,\n VISITOR_UA_HEADER,\n type VariantId,\n envKey,\n flagFor,\n parsePreview,\n resolveHost,\n resolveVariant,\n textChanges,\n} from \"./core\";\nimport { envServerKey } from \"./user-hash\";\n\n/**\n * Server helpers for the App Router: load the experiments once per request, then render the right variant on the\n * first paint (no flicker) and hand the same config to `<CockpitProvider config>` so the browser agrees.\n */\n\ntype SearchParams = Record<string, string | string[] | undefined>;\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n/** What Next's `headers()` (and a `Request`'s `headers`) offer. */\ninterface HeaderReader {\n get(name: string): string | null;\n}\n\n/** How long the server waits for MRRocket before it renders with control. */\nconst CONFIG_TIMEOUT_MS = 2500;\n\nlet warnedNoKey = false;\n\n/** The visitor's address in the order MRRocket's event ingest reads it, so both make the same daily hash. */\nconst visitorIpOf = (h: HeaderReader) => (h.get(\"cf-connecting-ip\") ?? h.get(\"x-forwarded-for\")?.split(\",\")[0] ?? h.get(\"x-real-ip\") ?? \"\").trim() || undefined;\n\n/**\n * The experiments for a public key. `null` when MRRocket cannot be reached, answers with an error or is slower than\n * `timeoutMs`: everyone then sees control and the page still renders. Runs on Node, the Edge runtime and Cloudflare\n * Workers (only `fetch` and `AbortController`).\n *\n * `apiKey` and `host` default to `NEXT_PUBLIC_MRROCKET_KEY` and `NEXT_PUBLIC_MRROCKET_HOST`. `locale` (0.21.0): the\n * visitor's language when your server knows it, so the SDK's words come along; without it the browser reads them itself.\n *\n * `headers` (0.24.0): the visitor's request headers (`await headers()` from `next/headers`). With them and the server key\n * (`serverKey` or `MRROCKET_SERVER_KEY`) MRRocket hands over the visitor's `unit`, its daily visitor hash, made from the\n * visitor's address and browser as your server saw them; the address is used for that hash only and never stored.\n * Running tests then render the visitor's version on the first paint in the default cookieless mode, the same all day\n * and the same the browser keeps. Without them the config comes without a unit: running tests render control on the\n * server and the browser asks for the unit itself (a cookie or `distinctId` still decides as before).\n */\nexport const getCockpitConfig = async ({\n apiKey,\n host,\n timeoutMs = CONFIG_TIMEOUT_MS,\n locale,\n headers,\n serverKey,\n}: { apiKey?: string; host?: string; timeoutMs?: number; locale?: string; headers?: HeaderReader; serverKey?: string } = {}): Promise<CockpitConfig | null> => {\n const key = apiKey ?? envKey();\n if (!key) return null;\n // The visitor, as this server saw them, signed by the server key: otherwise MRRocket would hash this server's address.\n const secret = (serverKey ?? envServerKey() ?? \"\").trim();\n const ip = headers ? visitorIpOf(headers) : undefined;\n const forward = !!(secret && ip);\n if (headers && !secret && !warnedNoKey) {\n warnedNoKey = true;\n console.warn(\"[MRRocket] getCockpitConfig({ headers }) needs the server key (MRROCKET_SERVER_KEY or serverKey) to render a cookieless visitor's test version on the server; until then running tests render control there and the browser picks.\");\n }\n const ctl = new AbortController();\n const timer = setTimeout(() => ctl.abort(), timeoutMs);\n try {\n // `next.revalidate: 0` keeps this request uncached in Next.js. Not `cache: \"no-store\"`: Cloudflare Workers\n // throws on the `cache` field of a fetch unless a compatibility flag is on, and every config would be null.\n const res = await fetch(`${resolveHost(host)}/api/sdk/config?key=${encodeURIComponent(key)}${locale ? `&lang=${encodeURIComponent(locale)}` : \"\"}`, {\n signal: ctl.signal,\n next: { revalidate: 0 },\n ...(forward && ip\n ? { headers: { authorization: `Bearer ${secret}`, [VISITOR_IP_HEADER]: ip, [VISITOR_UA_HEADER]: headers?.get(\"user-agent\") ?? \"\" } }\n : {}),\n } as RequestInit);\n if (!res.ok) return null;\n const config = (await res.json()) as CockpitConfig | null;\n if (!config || !Array.isArray(config.experiments)) return null;\n // A unit made without the visitor's headers is this server's own: it would put every visitor in one version.\n if (!forward) delete config.unit;\n return config;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n};\n\n/** Forced variants and the embed flag from a page's search params, for previews in Cockpit. */\nexport const previewFrom = (searchParams: SearchParams | undefined) => {\n const embed = searchParams?.[EMBED_PARAM];\n return { preview: parsePreview(searchParams?.[PREVIEW_PARAM]), embedded: (Array.isArray(embed) ? embed[0] : embed) === \"1\" };\n};\n\n/**\n * The visitor's id from the `ck_id` cookie, if the browser has one yet (only in consent \"cookies\" mode); \"anonymous\"\n * without one. The helpers below no longer assign tests by \"anonymous\" (0.24.0): see `assignIdFor`.\n */\nexport const distinctIdFrom = (cookies: CookieReader | undefined) => cookies?.get(ID_COOKIE)?.value ?? \"anonymous\";\n\n/**\n * Who the visitor is for this request. Pass `distinctId` (your signed-in user id, the same you give\n * `<CockpitProvider distinctId>`) when there is no `ck_id` cookie, as in the default cookieless mode.\n */\ninterface RequestInfo {\n config: CockpitConfig | null;\n searchParams?: SearchParams;\n cookies?: CookieReader;\n distinctId?: string;\n}\n\n/**\n * The id this request's tests and flags assign by (0.24.0): `distinctId`, else the `ck_id` cookie, else the config's\n * `unit` (from `getCockpitConfig({ headers })`), the same the browser then uses. Null when none is known: running\n * tests render control on the server and the browser decides, instead of putting every such visitor in one version.\n */\nexport const assignIdFor = ({ config, cookies, distinctId }: RequestInfo): string | null => distinctId ?? cookies?.get(ID_COOKIE)?.value ?? config?.unit ?? null;\n\n/** The variant of one experiment for this request (control for a running test while the visitor is unknown). */\nexport const getVariant = (key: string, info: RequestInfo): VariantId => resolveVariant(key, info.config, assignIdFor(info), previewFrom(info.searchParams).preview);\n\n/**\n * A feature flag for this request: true while it is on for the visitor, false while it is off or unknown (or MRRocket\n * could not be reached). `person` takes the properties the flag's audience reads (\"Email\", \"Plan\" …), as you pass them\n * to identify(). For a multivariate flag use `getFlagVariant`.\n */\nexport const getFlag = (key: string, info: RequestInfo & { person?: FlagPerson }): boolean => flagFor(key, info.config, assignIdFor(info) ?? \"anonymous\", info.person) !== false;\n\n/** The variant of a multivariate flag for this request, or null while it is off. */\nexport const getFlagVariant = (key: string, info: RequestInfo & { person?: FlagPerson }): string | null => {\n const v = flagFor(key, info.config, assignIdFor(info) ?? \"anonymous\", info.person);\n return typeof v === \"string\" ? v : null;\n};\n\n/** Every text change for this request, to render `<Text>` defaults server-side. */\nexport const getTexts = (info: RequestInfo) => textChanges(info.config, assignIdFor(info), previewFrom(info.searchParams).preview);\n\nexport * from \"./core\";\n/** Identity verification (0.16.0): sign a user id for `identify(id, props, { hash })` with the product's server key. */\nexport { type UserHashOptions, userHash } from \"./user-hash\";\nexport { type AttackKind, type SecurityOptions, attackIn, ipOf, reportAuthDenied, reportFailedLogin, reportSuspiciousRequest, watchRequest } from \"./security\";\n/** Affiliate referrals on the server: read the `mrr_ref` cookie in the route that creates a Stripe Checkout Session. */\nexport { type CheckoutReferral, type Referral, REFERRAL_COOKIE, readReferralCookie, referralForCheckout, referralLink } from \"./referral\";\n"],"mappings":";AAAA;AAAA,EAEI;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,oBAAoB;AAmI7B,cAAc;AAEd,SAA+B,gBAAgB;AAC/C,SAAgD,UAAU,MAAM,kBAAkB,mBAAmB,yBAAyB,oBAAoB;AAElJ,SAA+C,iBAAiB,oBAAoB,qBAAqB,oBAAoB;AAvH7H,IAAM,oBAAoB;AAE1B,IAAI,cAAc;AAGlB,IAAM,cAAc,CAAC,OAAqB,EAAE,IAAI,kBAAkB,KAAK,EAAE,IAAI,iBAAiB,GAAG,MAAM,GAAG,EAAE,CAAC,KAAK,EAAE,IAAI,WAAW,KAAK,IAAI,KAAK,KAAK;AAiB/I,IAAM,mBAAmB,OAAO;AAAA,EACnC;AAAA,EACA;AAAA,EACA,YAAY;AAAA,EACZ;AAAA,EACA;AAAA,EACA;AACJ,IAAyH,CAAC,MAAqC;AAC3J,QAAM,MAAM,UAAU,OAAO;AAC7B,MAAI,CAAC,IAAK,QAAO;AAEjB,QAAM,UAAU,aAAa,aAAa,KAAK,IAAI,KAAK;AACxD,QAAM,KAAK,UAAU,YAAY,OAAO,IAAI;AAC5C,QAAM,UAAU,CAAC,EAAE,UAAU;AAC7B,MAAI,WAAW,CAAC,UAAU,CAAC,aAAa;AACpC,kBAAc;AACd,YAAQ,KAAK,oOAAoO;AAAA,EACrP;AACA,QAAM,MAAM,IAAI,gBAAgB;AAChC,QAAM,QAAQ,WAAW,MAAM,IAAI,MAAM,GAAG,SAAS;AACrD,MAAI;AAGA,UAAM,MAAM,MAAM,MAAM,GAAG,YAAY,IAAI,CAAC,uBAAuB,m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AI,QAAQ,KAAK,KAAK,QAAQ,YAAY,IAAI,KAAK,aAAa,KAAK,MAAM;AACjF,SAAO,OAAO,MAAM,WAAW,IAAI;AACvC;AAGO,IAAM,WAAW,CAAC,SAAsB,YAAY,KAAK,QAAQ,YAAY,IAAI,GAAG,YAAY,KAAK,YAAY,EAAE,OAAO;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["import {\n type CockpitConfig,\n EMBED_PARAM,\n type FlagPerson,\n ID_COOKIE,\n PREVIEW_PARAM,\n VISITOR_IP_HEADER,\n VISITOR_UA_HEADER,\n type VariantId,\n envKey,\n flagFor,\n parsePreview,\n resolveHost,\n resolveVariant,\n textChanges,\n} from \"./core\";\nimport { envServerKey } from \"./user-hash\";\n\n/**\n * Server helpers for the App Router: load the experiments once per request, then render the right variant on the\n * first paint (no flicker) and hand the same config to `<CockpitProvider config>` so the browser agrees.\n */\n\ntype SearchParams = Record<string, string | string[] | undefined>;\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n/** What Next's `headers()` (and a `Request`'s `headers`) offer. */\ninterface HeaderReader {\n get(name: string): string | null;\n}\n\n/** How long the server waits for MRRocket before it renders with control. */\nconst CONFIG_TIMEOUT_MS = 2500;\n\nlet warnedNoKey = false;\n\n/** The visitor's address in the order MRRocket's event ingest reads it, so both make the same daily hash. */\nconst visitorIpOf = (h: HeaderReader) => (h.get(\"cf-connecting-ip\") ?? h.get(\"x-forwarded-for\")?.split(\",\")[0] ?? h.get(\"x-real-ip\") ?? \"\").trim() || undefined;\n\n/**\n * The experiments for a public key. `null` when MRRocket cannot be reached, answers with an error or is slower than\n * `timeoutMs`: everyone then sees control and the page still renders. Runs on Node, the Edge runtime and Cloudflare\n * Workers (only `fetch` and `AbortController`).\n *\n * `apiKey` and `host` default to `NEXT_PUBLIC_MRROCKET_KEY` and `NEXT_PUBLIC_MRROCKET_HOST`. `locale` (0.21.0): the\n * visitor's language when your server knows it, so the SDK's words come along; without it the browser reads them itself.\n *\n * `headers` (0.24.0): the visitor's request headers (`await headers()` from `next/headers`). With them and the server key\n * (`serverKey` or `MRROCKET_SERVER_KEY`) MRRocket hands over the visitor's `unit`, its daily visitor hash, made from the\n * visitor's address and browser as your server saw them; the address is used for that hash only and never stored.\n * Running tests then render the visitor's version on the first paint in the default cookieless mode, the same all day\n * and the same the browser keeps. Without them the config comes without a unit: running tests render control on the\n * server and the browser asks for the unit itself (a cookie or `distinctId` still decides as before).\n */\nexport const getCockpitConfig = async ({\n apiKey,\n host,\n timeoutMs = CONFIG_TIMEOUT_MS,\n locale,\n headers,\n serverKey,\n}: { apiKey?: string; host?: string; timeoutMs?: number; locale?: string; headers?: HeaderReader; serverKey?: string } = {}): Promise<CockpitConfig | null> => {\n const key = apiKey ?? envKey();\n if (!key) return null;\n // The visitor, as this server saw them, signed by the server key: otherwise MRRocket would hash this server's address.\n const secret = (serverKey ?? envServerKey() ?? \"\").trim();\n const ip = headers ? visitorIpOf(headers) : undefined;\n const forward = !!(secret && ip);\n if (headers && !secret && !warnedNoKey) {\n warnedNoKey = true;\n console.warn(\"[MRRocket] getCockpitConfig({ headers }) needs the server key (MRROCKET_SERVER_KEY or serverKey) to render a cookieless visitor's test version on the server; until then running tests render control there and the browser picks.\");\n }\n const ctl = new AbortController();\n const timer = setTimeout(() => ctl.abort(), timeoutMs);\n try {\n // `next.revalidate: 0` keeps this request uncached in Next.js. Not `cache: \"no-store\"`: Cloudflare Workers\n // throws on the `cache` field of a fetch unless a compatibility flag is on, and every config would be null.\n const res = await fetch(`${resolveHost(host)}/api/sdk/config?key=${encodeURIComponent(key)}${locale ? `&lang=${encodeURIComponent(locale)}` : \"\"}`, {\n signal: ctl.signal,\n next: { revalidate: 0 },\n ...(forward && ip\n ? { headers: { authorization: `Bearer ${secret}`, [VISITOR_IP_HEADER]: ip, [VISITOR_UA_HEADER]: headers?.get(\"user-agent\") ?? \"\" } }\n : {}),\n } as RequestInit);\n if (!res.ok) return null;\n const config = (await res.json()) as CockpitConfig | null;\n if (!config || !Array.isArray(config.experiments)) return null;\n // A unit made without the visitor's headers is this server's own: it would put every visitor in one version.\n if (!forward) delete config.unit;\n return config;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n};\n\n/** Forced variants and the embed flag from a page's search params, for previews in Cockpit. */\nexport const previewFrom = (searchParams: SearchParams | undefined) => {\n const embed = searchParams?.[EMBED_PARAM];\n return { preview: parsePreview(searchParams?.[PREVIEW_PARAM]), embedded: (Array.isArray(embed) ? embed[0] : embed) === \"1\" };\n};\n\n/**\n * The visitor's id from the `ck_id` cookie, if the browser has one yet (only in consent \"cookies\" mode); \"anonymous\"\n * without one. The helpers below no longer assign tests by \"anonymous\" (0.24.0): see `assignIdFor`.\n */\nexport const distinctIdFrom = (cookies: CookieReader | undefined) => cookies?.get(ID_COOKIE)?.value ?? \"anonymous\";\n\n/**\n * Who the visitor is for this request. Pass `distinctId` (your signed-in user id, the same you give\n * `<CockpitProvider distinctId>`) when there is no `ck_id` cookie, as in the default cookieless mode.\n */\ninterface RequestInfo {\n config: CockpitConfig | null;\n searchParams?: SearchParams;\n cookies?: CookieReader;\n distinctId?: string;\n}\n\n/**\n * The id this request's tests and flags assign by (0.24.0): `distinctId`, else the `ck_id` cookie, else the config's\n * `unit` (from `getCockpitConfig({ headers })`), the same the browser then uses. Null when none is known: running\n * tests render control on the server and the browser decides, instead of putting every such visitor in one version.\n */\nexport const assignIdFor = ({ config, cookies, distinctId }: RequestInfo): string | null => distinctId ?? cookies?.get(ID_COOKIE)?.value ?? config?.unit ?? null;\n\n/** The variant of one experiment for this request (control for a running test while the visitor is unknown). */\nexport const getVariant = (key: string, info: RequestInfo): VariantId => resolveVariant(key, info.config, assignIdFor(info), previewFrom(info.searchParams).preview);\n\nlet warnedNoServerKey = false;\n\n/**\n * The variant of a test your server decides on (a checkout, a price, an email), recorded as seen (0.25.0): returns what\n * `getVariant` returns and sends `$exposure {experiment, variant}` for this person with the product's server key\n * (`serverKey` or `MRROCKET_SERVER_KEY`), so MRRocket counts them for that version. Call it where the person meets the\n * version; calling it again is harmless, MRRocket counts the first time. Pass `distinctId` (your user id, the same your\n * app gives `identify()`) so the goal they reach later counts for them.\n *\n * Nothing is sent while the test is not running or its winner is kept for everyone, for an unknown person, for a\n * version forced by a preview, or without the server key; the variant is returned all the same. A slow or unreachable\n * MRRocket never holds the request longer than 2.5 s. Call it only for people your product may count, as for its\n * other MRRocket events.\n */\nexport const trackVariant = async (key: string, info: RequestInfo & { apiKey?: string; serverKey?: string; host?: string; timeoutMs?: number }): Promise<VariantId> => {\n const variant = getVariant(key, info);\n const id = assignIdFor(info);\n const test = info.config?.experiments.find((x) => x.key === key);\n if (!test || test.status !== \"running\" || test.winner || !id || previewFrom(info.searchParams).preview[key]) return variant;\n const apiKey = info.apiKey ?? envKey();\n const secret = (info.serverKey ?? envServerKey() ?? \"\").trim();\n if (!apiKey || !secret) {\n if (!warnedNoServerKey) {\n warnedNoServerKey = true;\n console.warn(\"[MRRocket] trackVariant needs the public key and the server key (MRROCKET_SERVER_KEY or serverKey) to record who saw which version; nothing was recorded.\");\n }\n return variant;\n }\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), info.timeoutMs ?? CONFIG_TIMEOUT_MS);\n try {\n await fetch(`${resolveHost(info.host)}/api/sdk/events`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", authorization: `Bearer ${secret}` },\n body: JSON.stringify({ key: apiKey, server: true, events: [{ event: \"$exposure\", distinctId: id, ts: Date.now(), props: { experiment: key, variant } }] }),\n signal: ctrl.signal,\n });\n } catch {\n // MRRocket unreachable: the person still gets their version.\n } finally {\n clearTimeout(timer);\n }\n return variant;\n};\n\n/**\n * A feature flag for this request: true while it is on for the visitor, false while it is off or unknown (or MRRocket\n * could not be reached). `person` takes the properties the flag's audience reads (\"Email\", \"Plan\" …), as you pass them\n * to identify(). For a multivariate flag use `getFlagVariant`.\n */\nexport const getFlag = (key: string, info: RequestInfo & { person?: FlagPerson }): boolean => flagFor(key, info.config, assignIdFor(info) ?? \"anonymous\", info.person) !== false;\n\n/** The variant of a multivariate flag for this request, or null while it is off. */\nexport const getFlagVariant = (key: string, info: RequestInfo & { person?: FlagPerson }): string | null => {\n const v = flagFor(key, info.config, assignIdFor(info) ?? \"anonymous\", info.person);\n return typeof v === \"string\" ? v : null;\n};\n\n/** Every text change for this request, to render `<Text>` defaults server-side. */\nexport const getTexts = (info: RequestInfo) => textChanges(info.config, assignIdFor(info), previewFrom(info.searchParams).preview);\n\nexport * from \"./core\";\n/** Identity verification (0.16.0): sign a user id for `identify(id, props, { hash })` with the product's server key. */\nexport { type UserHashOptions, userHash } from \"./user-hash\";\nexport { type AttackKind, type SecurityOptions, attackIn, ipOf, reportAuthDenied, reportFailedLogin, reportSuspiciousRequest, watchRequest } from \"./security\";\n/** Affiliate referrals on the server: read the `mrr_ref` cookie in the route that creates a Stripe Checkout Session. */\nexport { type CheckoutReferral, type Referral, REFERRAL_COOKIE, readReferralCookie, referralForCheckout, referralLink } from \"./referral\";\n"],"mappings":";AAAA;AAAA,EAEI;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,oBAAoB;AAgL7B,cAAc;AAEd,SAA+B,gBAAgB;AAC/C,SAAgD,UAAU,MAAM,kBAAkB,mBAAmB,yBAAyB,oBAAoB;AAElJ,SAA+C,iBAAiB,oBAAoB,qBAAqB,oBAAoB;AApK7H,IAAM,oBAAoB;AAE1B,IAAI,cAAc;AAGlB,IAAM,cAAc,CAAC,OAAqB,EAAE,IAAI,kBAAkB,KAAK,EAAE,IAAI,iBAAiB,GAAG,MAAM,GAAG,EAAE,CAAC,KAAK,EAAE,IAAI,WAAW,KAAK,IAAI,KAAK,KAAK;AAiB/I,IAAM,mBAAmB,OAAO;AAAA,EACnC;AAAA,EACA;AAAA,EACA,YAAY;AAA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O,aAAa,YAAY,IAAI,IAAI,KAAK,IAAI,GAAG,OAAO,EAAE,YAAY,KAAK,QAAQ,EAAE,CAAC,EAAE,CAAC;AAAA,MACzJ,QAAQ,KAAK;AAAA,IACjB,CAAC;AAAA,EACL,QAAQ;AAAA,EAER,UAAE;AACE,iBAAa,KAAK;AAAA,EACtB;AACA,SAAO;AACX;AAOO,IAAM,UAAU,CAAC,KAAa,SAAyD,QAAQ,KAAK,KAAK,QAAQ,YAAY,IAAI,KAAK,aAAa,KAAK,MAAM,MAAM;AAGpK,IAAM,iBAAiB,CAAC,KAAa,SAA+D;AACvG,QAAM,IAAI,QAAQ,KAAK,KAAK,QAAQ,YAAY,IAAI,KAAK,aAAa,KAAK,MAAM;AACjF,SAAO,OAAO,MAAM,WAAW,IAAI;AACvC;AAGO,IAAM,WAAW,CAAC,SAAsB,YAAY,KAAK,QAAQ,YAAY,IAAI,GAAG,YAAY,KAAK,YAAY,EAAE,OAAO;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mrrocket/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.26.0",
|
|
4
4
|
"description": "MRRocket SDK: page views, events, heatmap clicks, session recordings, A/B tests, feature flags, error tracking, feedback board, surveys, a chat messenger, a cancel flow, onboarding tours and checklists, in-app messages, push notifications and redirect tests that your MRRocket agents can run and read. Next.js (@mrrocket/sdk/next), React Native and Expo (@mrrocket/sdk/react-native), and a script tag for any website.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"nextjs",
|