@mrrocket/sdk 0.14.0 → 0.16.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.
Files changed (70) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +45 -4
  3. package/dist/api-client.d.ts +67 -5
  4. package/dist/api-client.js +39 -8
  5. package/dist/api-client.js.map +1 -1
  6. package/dist/api.d.ts +4 -1
  7. package/dist/api.js +2 -1
  8. package/dist/api.js.map +1 -1
  9. package/dist/batch.d.ts +6 -4
  10. package/dist/batch.js +3 -3
  11. package/dist/batch.js.map +1 -1
  12. package/dist/browser/mrrocket-flows.js +2 -2
  13. package/dist/browser/mrrocket-forms.js +1 -1
  14. package/dist/browser/mrrocket-messenger.js +202 -46
  15. package/dist/browser/mrrocket-push.js +1 -1
  16. package/dist/browser/mrrocket-replay.js +3 -3
  17. package/dist/browser/mrrocket.js +1 -1
  18. package/dist/client.d.ts +10 -2
  19. package/dist/client.js +36 -15
  20. package/dist/client.js.map +1 -1
  21. package/dist/context.d.ts +5 -1
  22. package/dist/context.js.map +1 -1
  23. package/dist/core.d.ts +1 -1
  24. package/dist/core.js +1 -1
  25. package/dist/core.js.map +1 -1
  26. package/dist/errors.d.ts +5 -1
  27. package/dist/errors.js +8 -2
  28. package/dist/errors.js.map +1 -1
  29. package/dist/flows-ui.js +48 -1
  30. package/dist/flows-ui.js.map +1 -1
  31. package/dist/flows-web.d.ts +2 -0
  32. package/dist/flows-web.js +4 -1
  33. package/dist/flows-web.js.map +1 -1
  34. package/dist/flows.d.ts +61 -1
  35. package/dist/flows.js +64 -21
  36. package/dist/flows.js.map +1 -1
  37. package/dist/forms.d.ts +4 -0
  38. package/dist/forms.js +4 -1
  39. package/dist/forms.js.map +1 -1
  40. package/dist/identity.d.ts +42 -0
  41. package/dist/identity.js +24 -0
  42. package/dist/identity.js.map +1 -0
  43. package/dist/index.d.ts +2 -0
  44. package/dist/index.js.map +1 -1
  45. package/dist/messenger-ui.d.ts +21 -6
  46. package/dist/messenger-ui.js +334 -80
  47. package/dist/messenger-ui.js.map +1 -1
  48. package/dist/messenger.d.ts +11 -3
  49. package/dist/messenger.js +9 -5
  50. package/dist/messenger.js.map +1 -1
  51. package/dist/push-web.d.ts +2 -13
  52. package/dist/push-web.js +4 -2
  53. package/dist/push-web.js.map +1 -1
  54. package/dist/react-native/index.d.cts +162 -14
  55. package/dist/react-native/index.d.ts +162 -14
  56. package/dist/react-native/index.js +552 -207
  57. package/dist/react-native/index.js.map +1 -1
  58. package/dist/replay.d.ts +4 -1
  59. package/dist/replay.js +8 -2
  60. package/dist/replay.js.map +1 -1
  61. package/dist/server.d.ts +2 -0
  62. package/dist/server.js +2 -0
  63. package/dist/server.js.map +1 -1
  64. package/dist/styles-css.d.ts +1 -1
  65. package/dist/styles-css.js +200 -44
  66. package/dist/styles-css.js.map +1 -1
  67. package/dist/user-hash.d.ts +27 -0
  68. package/dist/user-hash.js +24 -0
  69. package/dist/user-hash.js.map +1 -0
  70. package/package.json +9 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  All notable changes to this package. It follows semantic versioning; before 1.0 a minor version may change an API.
4
4
 
5
+ ## 0.16.0 (not published yet)
6
+
7
+ - **Identity verification:** your server signs the user id with the product's server key and the SDK sends that signature as `userHash` with every request for the id, so someone who only knows a user's id can no longer read their support chat, register push for them or post feedback and events as them. Server: `userHash(userId, { serverKey? })` from `@mrrocket/sdk/next/server` (WebCrypto only; Node 18+, Edge, Workers; defaults to `MRROCKET_SERVER_KEY`, throws without a key). The formula for other backends: `hex(HMAC-SHA256(key = SHA-256(server key), message = user id))`.
8
+ - **Client:** `identify(id, props, { hash })` in `useCockpit()`, `window.mrrocket.identify` and the React Native client; `<CockpitProvider userHash>` signs the `distinctId` prop from a server layout. The hash belongs to one id: dropped on `reset()` and on `identify` for another id without one; a value that is not 64 hex characters is never sent. React Native keeps it in memory only.
9
+ - **Sent with:** event batches (one top-level `userHash`, checked per event), errors (only when every report is of the signed id), recordings, push register/unregister, in-app messages, surveys (read, seen, answer), the feedback board (list, post, vote, comments, roadmap, a post), article ratings, messenger reads, messages, uploads (form field) and attachment links (query). A 401 is handled like any failed call and the console says once how to fix it; a recording stops on 401.
10
+ - New exports: the type `IdentifyOptions` (Next.js and React Native), `userHash` and `UserHashOptions` (server). `createApi` takes `userHash`.
11
+ - **Store reviews (React Native):** `useReview().request()` / `client.requestReview()` asks for a review at the moment your app picks (the trigger of an in-app request in MRRocket › Reviews › Requests). It asks MRRocket whether this signed-in person may be asked now (a customer within the request's neutral limits, not asked in 120 days; never by rating or mood), then opens the App Store's or Google Play's own rating dialog through `expo-store-review` (new optional peer dependency) and sends `$review_prompt {campaign, store, action: "requested" | "unavailable"}`; only a requested dialog counts as an invitation. Resolves with `"requested" | "not-now" | "unavailable" | "not-signed-in"` (type `NativeReviewResult`). `GET /api/sdk/inapp` answers `review: { campaign, store }` when the person may be asked; the web has no store dialog and ignores it.
12
+ - `sdk.js` budget 15.75 KB gzip (was 15.25).
13
+ - Version reported in event batches: `0.16.0`.
14
+
5
15
  ## 0.14.0 (not published yet)
6
16
 
7
17
  - **Paywalls with pages:** a paywall from MRRocket › Conversion › Paywalls can have several pages (benefits, customer quotes, plans), served as the config's new `paywalls` per placement. `usePaywall().open(placement, { onPurchase, plans, onClose })` (Next.js and React Native, drawn by the provider), `mrrocket.paywall.open(…)` (script tag) show them one after another with Back and dots; the last page hands the chosen plan to `onPurchase`, where the app buys it (StoreKit/Play through RevenueCat or Adapty, Stripe Checkout). MRRocket never takes a payment; only after `onPurchase` resolves is the purchase recorded (`false`: the store sheet was cancelled, the paywall stays). Resolves with `{ outcome: "purchased" | "chosen" | "closed", plan, variant, index }`.
package/README.md CHANGED
@@ -10,7 +10,7 @@ The MRRocket SDK, one package with three ways in:
10
10
 
11
11
  One provider in your layout (or one script tag) gives MRRocket page views, your events, A/B tests, feature flags and errors that the agents can run and read. MRRocket shows every variant of your real pages, because the SDK can render any variant on request.
12
12
 
13
- Status: 0.8.0, MIT licensed, compiled to ESM JavaScript with type declarations (no `transpilePackages`); the React Native entry is CommonJS for Metro. Works with Next.js 15 and 16, React 18 and 19, on Node and on Cloudflare Workers (OpenNext), and with React Native 0.72+ / Expo. The source lives in the MRRocket repo (`prototype/web/packages/cockpit-next`).
13
+ Status: 0.16.0, MIT licensed, compiled to ESM JavaScript with type declarations (no `transpilePackages`); the React Native entry is CommonJS for Metro. Works with Next.js 15 and 16, React 18 and 19, on Node and on Cloudflare Workers (OpenNext), and with React Native 0.72+ / Expo. The source lives in the MRRocket repo (`prototype/web/packages/cockpit-next`).
14
14
 
15
15
  ## Install
16
16
 
@@ -63,6 +63,7 @@ import { useCockpit } from "@mrrocket/sdk/next";
63
63
  const { track, identify } = useCockpit();
64
64
  track("checkout_started", { plan: "team" });
65
65
  identify(user.id, { plan: user.plan });
66
+ identify(user.id, { plan: user.plan }, { hash }); // signed by your server, see 22. Identity verification
66
67
  ```
67
68
 
68
69
  ## 3. A/B tests
@@ -406,6 +407,8 @@ const cancelFlow = useCancelFlow();
406
407
  const result = await cancelFlow.open({
407
408
  customer: account.isBusiness ? "business" : "consumer",
408
409
  price: { amount: 29, currency: "EUR" }, // optional: shows what the discount costs
410
+ plan: account.planId, // optional (0.15.0): for offers by plan, your billing's plan id or name
411
+ customerSince: account.paidSince, // optional (0.15.0): for offers by how long they have paid
409
412
  onCancel: (r) => api.cancelSubscription({ reason: r.reason, comment: r.comment }),
410
413
  onSave: (r) => api.applyOffer(r.offer), // { kind: "discount", percent, months } | { kind: "pause", months } | { kind: "downgrade", plan } | { kind: "contact" }
411
414
  });
@@ -416,6 +419,8 @@ const cancelFlow = useCancelFlow();
416
419
  </button>;
417
420
  ```
418
421
 
422
+ Since 0.15.0 an answer can ask one follow-up question, show a different offer by the follow-up's answer, the plan or how long the customer has paid (the first rule that fits wins; one about the plan or time needs `plan` / `customerSince`), and make a second offer once the first is declined. `result.answer` holds the follow-up's answer.
423
+
419
424
  MRRocket never changes a subscription (its payment key is read-only): `onCancel` and `onSave` are your code. Only after they succeed is the outcome recorded, and MRRocket shows it under Churn as a cancellation or a save with the customer's plan and monthly revenue (matched by your `identify()` id, or the email you passed with it). If one throws, the dialog stays open with "Something went wrong. Please try again." Script tag: `mrrocket.cancelFlow.open({ … })`.
420
425
 
421
426
  **Onboarding** (Conversion › Onboarding): the tour, checklist and modal steps of a live flow. A flow starts on its own when the person does its trigger: `track("Signed up")` (or `signup`, `sign_up`) for "Signed up", `track("first_export")` for "First export", and the first page or screen for "First launch" / "First visit", once per person. Automatic starts need a signed-in person (`identify`) or stored progress (`consent="cookies"` / `"persistent"`), so nobody gets the same tour on every page. `useCockpit().startOnboarding()` (script tag `mrrocket.onboarding.start()`, React Native `useOnboarding().start()`) starts one whenever you want; `onboarding={false}` on the provider switches the automatic start off. A tour step points at the element marked `data-ck-target="…"` (web); a checklist item with an event ticks itself when you track it. Emails of the flow go out from MRRocket.
@@ -447,6 +452,17 @@ mrrocket.push.subscribe();
447
452
 
448
453
  `register({ ask: false })` / `subscribe({ ask: false })` only send an existing token or subscription again. `reset()` on React Native takes the token back; on the web call `push.unsubscribe()` before `reset()`. A site with its own service worker adds `importScripts("/mrrocket-sw.js")` to it and calls `subscribe({ serviceWorker: false })`. Opening a MRRocket notification records `$push { action: "opened", message }`.
449
454
 
455
+
456
+ **Store reviews (0.16.0, React Native).** An in-app review request (Reviews › Requests) opens the App Store's or Google Play's own rating dialog at the moment your app picks. Install `expo-store-review`, then after `identify()`:
457
+
458
+ ```tsx
459
+ import { useReview } from "@mrrocket/sdk/react-native";
460
+ const review = useReview();
461
+ // Where the request's trigger happens (the third finished challenge, a 7-day streak …):
462
+ await review.request(); // "requested" | "not-now" | "unavailable" | "not-signed-in"
463
+ ```
464
+
465
+ MRRocket answers whether this person may be asked now (a customer within the request's neutral limits, not asked in 120 days; never by rating or mood) and counts only dialogs that were requested (`$review_prompt`). The store decides whether its dialog shows (Apple: at most three times a year). Websites have no store dialog: ask by email there.
450
466
  ## 17. Redirects and redirect tests (0.7.0)
451
467
 
452
468
  Page redirects (Landing pages › Redirect) and redirect tests ("Whole page" in Experiments) come with the config: the SDK sends the visitor on before the page shows, keeping the query and hash, and the page a test's variant lands on records the exposure (`ck_x=<test>:<variant>`, removed from the address). Nothing to add for the script tag (the optional `ck-hide` snippet stops a flash of the old page). In Next.js `<CockpitProvider>` redirects after the first paint; to answer before rendering, use the proxy helper:
@@ -483,9 +499,11 @@ const messenger = useMessenger();
483
499
  <a data-ck-messenger>Chat with us</a>;
484
500
  ```
485
501
 
486
- The look and texts (color, light or dark, side, title, greeting, button text, Help tab, sound, preview, asking for an email) are set per product in MRRocket › Support › Messenger and read by the messenger itself (`GET /api/sdk/messenger`), so they change without a deploy. What you pass in code wins.
502
+ The look and texts (color, light or dark, corners, Home's top, font, place, name, greeting, button text, Help tab, sound, preview, asking for an email, and "Powered by MRRocket", which Studio and Agency can switch off) are set per product in MRRocket › Support › Messenger and read by the messenger itself (`GET /api/sdk/messenger`), so they change without a deploy. What you pass in code wins.
487
503
 
488
- Props: `title`, `greeting`, `launcher` (default true), `help` (the Help tab, default true; hidden while there is no published article), `sound` (default true), `preview` (default true), `askEmail` (default true), `position` ("bottom-right", "bottom-left"), `label`, `theme`, `accent`. The panel is plain DOM, loaded with a dynamic import after the page rendered.
504
+ Props: `title`, `greeting`, `launcher` (default true), `help` (the Help tab, default true; hidden while there is no published article), `sound` (default true), `preview` (default true), `askEmail` (default true), `position` ("bottom-right" default, "bottom-left", "bottom-center", "top-left", "top-center", "top-right", "middle-left", "middle-right"), `corners` ("round", "soft", "square"), `header` ("plain", "color"), `font` ("site", "system"), `label`, `theme`, `accent`. The panel is plain DOM, loaded with a dynamic import after the page rendered.
505
+
506
+ Files (0.15): a paperclip in the message field attaches pictures (PNG, JPEG, WebP, GIF) and PDFs, pasting an image (Cmd/Ctrl+V) or dropping files onto the panel does too, and where the browser has `getDisplayMedia` (not on phones) the paperclip offers "Screenshot of this page": the tab is shared once (`preferCurrentTab`), the messenger hides for one frame, the stream stops. Each file uploads when picked (`POST /api/sdk/messages/attachments`, multipart `key`, `distinctId`, `file`; the server checks the bytes, never SVG, at most 10 MB) and answers a signed id; `sendChat({ body, attachments: [id, …] })` sends up to 4, and the body may then be empty. Sent files come back as `message.attachments` and are read with `api.attachmentUrl(id)` (the visitor's own chat only). Each message also sends `context: { viewport }`; the server adds browser and system from the user agent. In React Native the paperclip shows when `expo-image-picker` is installed (optional peer) and picks from the photo library; the app sends its system and screen size.
489
507
 
490
508
  Call `identify(user.id, { name, email })` and chats carry the person's name and email (they are not asked). While the panel is open it reads `GET /api/sdk/messages` every 4 seconds; while a visitor waits for an answer every 8 seconds for ten minutes, then every 30. Articles come from `GET /api/sdk/articles` as blocks, written with textContent, never HTML.
491
509
 
@@ -495,7 +513,7 @@ On sites with the script tag (Webflow, Framer, WordPress …) add `data-messenge
495
513
  <script async src="https://app.mrrocket.dev/sdk.js" data-key="mrr_pub_…" data-messenger="true" data-messenger-title="Acme"></script>
496
514
  ```
497
515
 
498
- Also `data-messenger-greeting`, `-label`, `-position="bottom-left"`, and "false" for `-help`, `-sound`, `-preview`, `-ask-email`. `mrrocket.messenger.open()` opens it from your code.
516
+ Also `data-messenger-greeting`, `-label`, `-position="top-right"`, `-corners="soft"`, `-header="color"`, `-font="system"`, and "false" for `-help`, `-sound`, `-preview`, `-ask-email`. `mrrocket.messenger.open()` opens it from your code.
499
517
 
500
518
  In React Native, `<MRRocketProvider messenger={{ launcher: true }}>` adds the bubble, `useMessenger().open()` opens it from your own button; a new answer shows as a banner at the top, with a light haptic when `expo-haptics` is installed. The provider also shows your live in-app survey (`surveys={false}` to switch off) and the feedback sheet (`useFeedback().open()`). With the person's consent (`replay`) and `react-native-view-shot` installed, the app also records sessions as screen pictures for Sessions: none while the keyboard is open, and `<MRRocketMask>` areas are painted black on the server before storing. Taps go to Heatmaps as clicks on the current screen; the provider then wraps the app in one `View` with `flex: 1` (`heatmaps={false}` to switch off).
501
519
 
@@ -579,6 +597,29 @@ mrrocket.paywall.open("pricing_page", { onPurchase: (plan) => fetch("/checkout",
579
597
  - **Without pages** a paywall keeps working as texts your own paywall marks (`paywall.<placement>.headline`, `.body`, `.cta`).
580
598
  - The script tag loads the paywall dialog from `sdk-flows.js` on the first `open`; `sdk.js` stays within its budget.
581
599
 
600
+ ## 22. Identity verification (0.16.0)
601
+
602
+ After `identify(id)` the SDK sends your app's own user id with every request, and that id is no secret (a Clerk id shows in URLs and logs). On its own it proves nothing: someone who knows it could read that person's support chat, register a push device for them or post feedback as them. Identity verification closes that, like Intercom's: your **server** signs the user id with the product's server key, the SDK sends the signature (`userHash`) with every request for that id, and MRRocket checks it.
603
+
604
+ Next.js, in three lines (the server key is `mrr_sk_…` from MRRocket › Settings › Products › your product › Sign-in, in `MRROCKET_SERVER_KEY`, never `NEXT_PUBLIC_`):
605
+
606
+ ```tsx
607
+ // app/layout.tsx (a server component)
608
+ import { userHash } from "@mrrocket/sdk/next/server";
609
+
610
+ const hash = user ? await userHash(user.id) : undefined;
611
+ // then either: <CockpitProvider distinctId={user?.id} userHash={hash}>
612
+ // or, in the client component that signs people in: identify(user.id, { email: user.email }, { hash })
613
+ ```
614
+
615
+ - **Script tag:** your server renders the hash into the page, the page passes it on: `mrrocket.identify(user.id, { email }, { hash: "…" })`.
616
+ - **React Native:** your backend returns the hash with the signed-in user (in `/me`, say); call `identify(user.id, props, { hash })` on every start. The server key never goes into the app, and the SDK keeps the hash in memory only.
617
+ - **Other languages:** `userHash = lowercase hex( HMAC-SHA256( key = SHA-256(server key) as its 32 raw bytes, message = user id as UTF-8 ) )`. MRRocket stores only the SHA-256 of the server key, which is why that is the key. Node: `crypto.createHmac("sha256", crypto.createHash("sha256").update(serverKey).digest()).update(userId).digest("hex")`; Python: `hmac.new(hashlib.sha256(server_key.encode()).digest(), user_id.encode(), hashlib.sha256).hexdigest()`; PHP: `hash_hmac("sha256", $userId, hash("sha256", $serverKey, true))`; Ruby: `OpenSSL::HMAC.hexdigest("SHA256", Digest::SHA256.digest(server_key), user_id)`.
618
+ - **What carries it:** events (one `userHash` per batch; MRRocket checks it against each event's id), errors, recordings, push sign-up, in-app messages, surveys, the feedback board, help article ratings and the messenger (its messages, uploads and file links). A JSON field next to `distinctId`, a query parameter on reads, a form field on uploads.
619
+ - **One id, one hash:** the hash is forgotten on `reset()` and when `identify` is called for another id without one, so it never goes out with someone else's id. A value that is not 64 hex characters (the server key pasted by mistake) is never sent; the console says so.
620
+ - **Refused:** a hash that does not match is answered 401; with "Only signed users" on (Sign-in settings), so is a signed-in user's id without one. The SDK never throws for it: the request fails like any other and the console says once how to fix it. Turn "Only signed users" on after the app sends hashes.
621
+ - `userHash()` runs on Node 18+ (Next.js provides WebCrypto there), the Edge runtime and Cloudflare Workers; it throws when there is no server key, so a missing setting shows on your server.
622
+
582
623
  ## Privacy and consent
583
624
 
584
625
  ```tsx
@@ -1,7 +1,3 @@
1
- /**
2
- * The SDK's fetch client and the shapes it reads, without React, so the script tag's widgets (src/script) use it too.
3
- * `./api` re-exports all of it with the `useApi` hook.
4
- */
5
1
  export type PostStatus = "review" | "planned" | "progress" | "shipped";
6
2
  export declare const STATUS_LABEL: Record<PostStatus, string>;
7
3
  export interface FeedbackBoardInfo {
@@ -76,6 +72,32 @@ export interface SurveyDefinition {
76
72
  questions: SurveyQuestion[];
77
73
  }
78
74
  export type SurveyAnswer = number | string | string[];
75
+ /** A file in the messenger's chat: a screenshot, a photo or a PDF the visitor sent (servers from SDK 0.15 on). */
76
+ export interface ChatFile {
77
+ /** From an upload: the signed id a message sends. In a message: the file's own id (`attachmentUrl` reads it). */
78
+ id: string;
79
+ name: string;
80
+ type: "image/png" | "image/jpeg" | "image/webp" | "image/gif" | "application/pdf";
81
+ /** Bytes. */
82
+ size: number;
83
+ }
84
+ /** What the messenger can send: pictures and PDFs, at most 10 MB each, 4 per message. */
85
+ export declare const CHAT_FILE_TYPES: readonly ["image/png", "image/jpeg", "image/webp", "image/gif", "application/pdf"];
86
+ export declare const CHAT_FILE_MAX_BYTES: number;
87
+ export declare const CHAT_FILES_PER_MESSAGE = 4;
88
+ /** A file to upload: a Blob or File on the web, the image picker's `{ uri, name, type }` in React Native. */
89
+ export type ChatUpload = Blob | {
90
+ uri: string;
91
+ name: string;
92
+ type: string;
93
+ };
94
+ /** The bug context a visitor message carries; the server fills browser and system from the user agent when left out. */
95
+ export interface ChatContext {
96
+ browser?: string;
97
+ os?: string;
98
+ /** "1440×900". */
99
+ viewport?: string;
100
+ }
79
101
  /** One message of the messenger's chat. "visitor" is the person on the site; the rest come from the product's team. */
80
102
  export interface ChatMessage {
81
103
  id: string;
@@ -87,6 +109,8 @@ export interface ChatMessage {
87
109
  id: string;
88
110
  title: string;
89
111
  }[];
112
+ /** Files sent with it (servers from SDK 0.15 on). */
113
+ attachments?: ChatFile[];
90
114
  }
91
115
  /** A published help article in a list (the messenger's Help tab). */
92
116
  export interface ArticleSummary {
@@ -124,11 +148,25 @@ export interface Article {
124
148
  updatedAt: string;
125
149
  blocks: ArticleBlock[];
126
150
  }
151
+ /** Where the chat button sits: a corner, the middle of the top or bottom edge, or the middle of a side. */
152
+ export type MessengerPosition = "top-left" | "top-center" | "top-right" | "middle-left" | "middle-right" | "bottom-left" | "bottom-center" | "bottom-right";
153
+ /** How round the messenger is. */
154
+ export type MessengerCorners = "round" | "soft" | "square";
155
+ /** The radii per corner style, in px: the panel or sheet, message bubbles (and their tail), cards, fields and buttons. */
156
+ export declare const CORNERS: Record<MessengerCorners, {
157
+ panel: number;
158
+ bubble: number;
159
+ tail: number;
160
+ card: number;
161
+ field: number;
162
+ }>;
127
163
  /** The messenger's look and texts as set in MRRocket › Support › Messenger (servers from SDK 0.9 on). */
128
164
  export interface MessengerLook {
129
165
  accent: string;
166
+ /** Up to two more colors blended into Home's background glow (MRRocket from 0.16; older servers leave it out). */
167
+ glow?: string[];
130
168
  theme: "light" | "dark" | "auto";
131
- position: "bottom-right" | "bottom-left";
169
+ position: MessengerPosition;
132
170
  title: string;
133
171
  greeting: string;
134
172
  label: string;
@@ -140,7 +178,19 @@ export interface MessengerLook {
140
178
  sound: boolean;
141
179
  preview: boolean;
142
180
  askEmail: boolean;
181
+ /** How round panel, bubbles, cards and fields are (MRRocket from 0.15; older servers leave it out: round). */
182
+ corners?: MessengerCorners;
183
+ /** The site's own font (the default) or the system's (web only; from 0.15). */
184
+ font?: "site" | "system";
185
+ /** Home's top: plain like the rest, or in the accent color (from 0.15; older servers leave it out: plain). */
186
+ header?: "plain" | "color";
187
+ /** "Powered by MRRocket" at the bottom; the server sends false only on plans that may hide it (from 0.15). */
188
+ branding?: boolean;
189
+ /** The product's icon (its favicon) at the top left of Home; without it the title's first letter. */
190
+ logo?: string;
143
191
  }
192
+ /** The link behind "Powered by MRRocket". */
193
+ export declare const BRAND_URL = "https://mrrocket.dev/?utm_source=messenger&utm_medium=powered-by";
144
194
  /** The line under "Send us a message" and in the chat's head. */
145
195
  export declare const replyLine: (t: MessengerLook["replyTime"]) => "We usually reply in a few minutes" | "We usually reply within a day" | "We usually reply in a few hours";
146
196
  /** Black or white, whichever reads better on the accent (a light custom color gets dark text). */
@@ -167,6 +217,11 @@ interface Conn {
167
217
  id?: string;
168
218
  [key: string]: unknown;
169
219
  };
220
+ /**
221
+ * The identity hash of `distinctId` (0.16.0, see identity.ts), sent with every request that names the visitor: a
222
+ * JSON field next to `distinctId`, a query parameter, a form field. Leave it out for any other id.
223
+ */
224
+ userHash?: string;
170
225
  }
171
226
  /** The small fetch client behind the widgets. Every read takes an AbortSignal so unmounting cancels it. */
172
227
  export declare const createApi: (c: Conn) => {
@@ -203,11 +258,18 @@ export declare const createApi: (c: Conn) => {
203
258
  seconds: number;
204
259
  }) => Promise<unknown>;
205
260
  chat: (signal?: AbortSignal) => Promise<ChatThread>;
261
+ /** A message; `attachments` are upload ids from `uploadChatFile` (then the body may be empty). */
206
262
  sendChat: (m: {
207
263
  body: string;
208
264
  email?: string;
209
265
  url?: string;
266
+ attachments?: string[];
267
+ context?: ChatContext;
210
268
  }) => Promise<ChatThread>;
269
+ /** Uploads one picked file for the next message (pictures and PDFs, at most 10 MB); answers its upload id. */
270
+ uploadChatFile: (file: ChatUpload, signal?: AbortSignal) => Promise<ChatFile>;
271
+ /** Where a sent file of this visitor's chat is read (an image's src, a PDF's link). */
272
+ attachmentUrl: (id: string) => string;
211
273
  articles: (q?: string, signal?: AbortSignal) => Promise<{
212
274
  articles: ArticleSummary[];
213
275
  }>;
@@ -1,10 +1,20 @@
1
1
  // src/api-client.ts
2
+ import { warnUnsigned } from "./identity.js";
2
3
  var STATUS_LABEL = {
3
4
  review: "Under review",
4
5
  planned: "Planned",
5
6
  progress: "In progress",
6
7
  shipped: "Shipped"
7
8
  };
9
+ var CHAT_FILE_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif", "application/pdf"];
10
+ var CHAT_FILE_MAX_BYTES = 10 * 1024 * 1024;
11
+ var CHAT_FILES_PER_MESSAGE = 4;
12
+ var CORNERS = {
13
+ round: { panel: 22, bubble: 18, tail: 6, card: 16, field: 20 },
14
+ soft: { panel: 14, bubble: 12, tail: 4, card: 10, field: 10 },
15
+ square: { panel: 6, bubble: 6, tail: 2, card: 4, field: 4 }
16
+ };
17
+ var BRAND_URL = "https://mrrocket.dev/?utm_source=messenger&utm_medium=powered-by";
8
18
  var replyLine = (t) => t === "minutes" ? "We usually reply in a few minutes" : t === "day" ? "We usually reply within a day" : "We usually reply in a few hours";
9
19
  var inkOn = (hex) => {
10
20
  const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);
@@ -29,13 +39,15 @@ var call = async (url, init, signal) => {
29
39
  res = await fetch(url, {
30
40
  ...init,
31
41
  signal,
32
- headers: init?.body ? { "content-type": "application/json" } : void 0
42
+ // A form (a file upload) sets its own multipart type with the boundary.
43
+ headers: typeof init?.body === "string" ? { "content-type": "application/json" } : void 0
33
44
  });
34
45
  } catch (e) {
35
46
  if (e.name === "AbortError") throw e;
36
47
  throw new ApiError("Could not reach the server. Check your connection and try again.", 0);
37
48
  }
38
49
  if (!res.ok) {
50
+ warnUnsigned(res.status);
39
51
  let detail = "";
40
52
  try {
41
53
  detail = (await res.json()).error ?? "";
@@ -47,30 +59,49 @@ var call = async (url, init, signal) => {
47
59
  };
48
60
  var createApi = (c) => {
49
61
  const base = `${c.host}/api/sdk`;
50
- const who = { key: c.apiKey, distinctId: c.distinctId, user: c.user };
62
+ const who = { key: c.apiKey, distinctId: c.distinctId, user: c.user, userHash: c.userHash };
63
+ const me = { key: c.apiKey, distinctId: c.distinctId, userHash: c.userHash };
51
64
  const post = (path, body, signal) => call(`${base}${path}`, { method: "POST", body: JSON.stringify({ ...who, ...body }) }, signal);
52
65
  return {
53
- list: (o, signal) => call(`${base}/feedback?${qs({ key: c.apiKey, distinctId: c.distinctId, board: o.board, sort: o.sort, q: o.q })}`, void 0, signal),
54
- post: (id, signal) => call(`${base}/feedback/${encodeURIComponent(id)}?${qs({ key: c.apiKey, distinctId: c.distinctId })}`, void 0, signal),
55
- roadmap: (signal) => call(`${base}/feedback/roadmap?${qs({ key: c.apiKey, distinctId: c.distinctId })}`, void 0, signal),
66
+ list: (o, signal) => call(`${base}/feedback?${qs({ ...me, board: o.board, sort: o.sort, q: o.q })}`, void 0, signal),
67
+ post: (id, signal) => call(`${base}/feedback/${encodeURIComponent(id)}?${qs(me)}`, void 0, signal),
68
+ roadmap: (signal) => call(`${base}/feedback/roadmap?${qs(me)}`, void 0, signal),
56
69
  changelog: (signal) => call(`${base}/feedback/changelog?${qs({ key: c.apiKey })}`, void 0, signal),
57
70
  submit: (p) => post("/feedback", p),
58
71
  vote: (id) => post(`/feedback/${encodeURIComponent(id)}/vote`, {}),
59
72
  comments: (id, signal) => call(`${base}/feedback/${encodeURIComponent(id)}/comments?${qs({ key: c.apiKey })}`, void 0, signal),
60
73
  comment: (id, body) => post(`/feedback/${encodeURIComponent(id)}/comments`, { body }),
61
- survey: (url, signal) => call(`${base}/surveys?${qs({ key: c.apiKey, distinctId: c.distinctId, url })}`, void 0, signal),
74
+ survey: (url, signal) => call(`${base}/surveys?${qs({ ...me, url })}`, void 0, signal),
62
75
  seen: (id) => post(`/surveys/${encodeURIComponent(id)}/seen`, { user: void 0 }),
63
76
  respond: (id, r) => post(`/surveys/${encodeURIComponent(id)}/respond`, r),
64
- chat: (signal) => call(`${base}/messages?${qs({ key: c.apiKey, distinctId: c.distinctId })}`, void 0, signal),
77
+ chat: (signal) => call(`${base}/messages?${qs(me)}`, void 0, signal),
78
+ /** A message; `attachments` are upload ids from `uploadChatFile` (then the body may be empty). */
65
79
  sendChat: (m) => post("/messages", m),
80
+ /** Uploads one picked file for the next message (pictures and PDFs, at most 10 MB); answers its upload id. */
81
+ uploadChatFile: (file, signal) => {
82
+ const form = new FormData();
83
+ form.append("key", c.apiKey);
84
+ form.append("distinctId", c.distinctId);
85
+ if (c.userHash) form.append("userHash", c.userHash);
86
+ if ("uri" in file) form.append("file", file);
87
+ else form.append("file", file, file.name || "file");
88
+ return call(`${base}/messages/attachments`, { method: "POST", body: form }, signal);
89
+ },
90
+ /** Where a sent file of this visitor's chat is read (an image's src, a PDF's link). */
91
+ attachmentUrl: (id) => `${base}/messages/attachments/${encodeURIComponent(id)}?${qs(me)}`,
66
92
  articles: (q, signal) => call(`${base}/articles?${qs({ key: c.apiKey, q })}`, void 0, signal),
67
- article: (id, signal) => call(`${base}/articles/${encodeURIComponent(id)}?${qs({ key: c.apiKey, distinctId: c.distinctId })}`, void 0, signal),
93
+ article: (id, signal) => call(`${base}/articles/${encodeURIComponent(id)}?${qs(me)}`, void 0, signal),
68
94
  messengerLook: (signal) => call(`${base}/messenger?${qs({ key: c.apiKey })}`, void 0, signal),
69
95
  rateArticle: (id, helpful) => post(`/articles/${encodeURIComponent(id)}/rate`, { helpful })
70
96
  };
71
97
  };
72
98
  export {
73
99
  ApiError,
100
+ BRAND_URL,
101
+ CHAT_FILES_PER_MESSAGE,
102
+ CHAT_FILE_MAX_BYTES,
103
+ CHAT_FILE_TYPES,
104
+ CORNERS,
74
105
  STATUS_LABEL,
75
106
  createApi,
76
107
  inkOn,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/api-client.ts"],"sourcesContent":["/**\n * The SDK's fetch client and the shapes it reads, without React, so the script tag's widgets (src/script) use it too.\n * `./api` re-exports all of it with the `useApi` hook.\n */\nexport type PostStatus = \"review\" | \"planned\" | \"progress\" | \"shipped\";\n\nexport const STATUS_LABEL: Record<PostStatus, string> = {\n review: \"Under review\",\n planned: \"Planned\",\n progress: \"In progress\",\n shipped: \"Shipped\",\n};\n\nexport interface FeedbackBoardInfo {\n id: string;\n label: string;\n}\n\nexport interface FeedbackPost {\n id: string;\n title: string;\n body: string;\n board: string;\n status: PostStatus;\n votes: number;\n comments: number;\n voted: boolean;\n createdAt: string;\n /** \"Lena K.\", \"Anonymous\" or \"Team\". Missing from servers before SDK 0.6. */\n author?: string;\n}\n\n/** The product's public face for the board's header. */\nexport interface FeedbackProduct {\n name: string;\n logo: string | null;\n /** The domain's favicon, tried when `logo` does not load. Older servers leave it out. */\n logoFallback?: string | null;\n}\n\nexport interface FeedbackList {\n boards: FeedbackBoardInfo[];\n posts: FeedbackPost[];\n product?: FeedbackProduct;\n}\n\nexport interface FeedbackRoadmap {\n /** `review` (Backlog) comes from servers of SDK 0.6 on. */\n columns: { review?: FeedbackPost[]; planned: FeedbackPost[]; progress: FeedbackPost[]; shipped: FeedbackPost[] };\n}\n\nexport interface ChangelogEntry {\n id: string;\n title: string;\n body: string;\n publishedAt: string;\n}\n\nexport interface FeedbackComment {\n id: string;\n body: string;\n author: string;\n isTeam: boolean;\n postedAt: string;\n}\n\nexport type SurveyQuestionKind = \"nps\" | \"rating\" | \"single\" | \"multi\" | \"text\";\n\nexport interface SurveyQuestion {\n key: string;\n kind: SurveyQuestionKind;\n title: string;\n description?: string;\n required: boolean;\n options?: string[];\n scale?: number;\n low?: string;\n high?: string;\n placeholder?: string;\n}\n\nexport interface SurveyDefinition {\n id: string;\n name: string;\n type: string;\n thanks: string;\n questions: SurveyQuestion[];\n}\n\nexport type SurveyAnswer = number | string | string[];\n\n/** One message of the messenger's chat. \"visitor\" is the person on the site; the rest come from the product's team. */\nexport interface ChatMessage {\n id: string;\n from: \"visitor\" | \"team\" | \"ai\" | \"auto\";\n body: string;\n at: string;\n /** Help articles an answer drew on (servers from SDK 0.9 on). */\n articles?: { id: string; title: string }[];\n}\n\n/** A published help article in a list (the messenger's Help tab). */\nexport interface ArticleSummary {\n id: string;\n title: string;\n collection: string;\n excerpt: string;\n updatedAt: string;\n}\n\n/** A run of text inside an article block. Links are http(s), mailto or tel only. */\nexport interface ArticleSpan {\n text: string;\n href?: string;\n bold?: boolean;\n italic?: boolean;\n code?: boolean;\n}\n\n/** An article's content as blocks, written with textContent (never parsed as HTML). */\nexport type ArticleBlock =\n | { type: \"h2\" | \"h3\" | \"p\" | \"quote\"; spans: ArticleSpan[] }\n | { type: \"ul\" | \"ol\"; items: ArticleSpan[][] }\n | { type: \"code\"; text: string }\n | { type: \"hr\" };\n\nexport interface Article {\n id: string;\n title: string;\n collection: string;\n updatedAt: string;\n blocks: ArticleBlock[];\n}\n\n/** The messenger's look and texts as set in MRRocket › Support › Messenger (servers from SDK 0.9 on). */\nexport interface MessengerLook {\n accent: string;\n theme: \"light\" | \"dark\" | \"auto\";\n position: \"bottom-right\" | \"bottom-left\";\n title: string;\n greeting: string;\n label: string;\n /** How soon the team usually answers (MRRocket from 0.10; older servers leave it out). */\n replyTime?: \"minutes\" | \"hours\" | \"day\";\n /** A round chat button in the app (React Native) too. */\n appLauncher?: boolean;\n help: boolean;\n sound: boolean;\n preview: boolean;\n askEmail: boolean;\n}\n\n/** The line under \"Send us a message\" and in the chat's head. */\nexport const replyLine = (t: MessengerLook[\"replyTime\"]) =>\n t === \"minutes\" ? \"We usually reply in a few minutes\" : t === \"day\" ? \"We usually reply within a day\" : \"We usually reply in a few hours\";\n\n/** Black or white, whichever reads better on the accent (a light custom color gets dark text). */\nexport const inkOn = (hex: string) => {\n const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);\n if (!m) return \"#ffffff\";\n const [r, g, b] = [m[1], m[2], m[3]].map((x) => {\n const c = parseInt(x, 16) / 255;\n return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n });\n return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.45 ? \"#111214\" : \"#ffffff\";\n};\n\n/** The visitor's newest chat (open or closed) and its messages. */\nexport interface ChatThread {\n conversation: { id: string; status: \"open\" | \"solved\" } | null;\n messages: ChatMessage[];\n /** The visitor gave an email already: the messenger stops asking. */\n hasEmail: boolean;\n}\n\nexport class ApiError extends Error {\n status: number;\n constructor(message: string, status: number) {\n super(message);\n this.status = status;\n }\n}\n\ninterface Conn {\n host: string;\n apiKey: string;\n distinctId: string;\n user?: { id?: string; [key: string]: unknown };\n}\n\n// Not URLSearchParams: React Native's lacks `set` in older versions, and the apps use this client too.\nconst qs = (params: Record<string, string | undefined>) =>\n Object.entries(params)\n .filter((e): e is [string, string] => !!e[1])\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join(\"&\");\n\nconst call = async <T>(url: string, init: RequestInit | undefined, signal?: AbortSignal): Promise<T> => {\n let res: Response;\n try {\n res = await fetch(url, {\n ...init,\n signal,\n headers: init?.body ? { \"content-type\": \"application/json\" } : undefined,\n });\n } catch (e) {\n if ((e as Error).name === \"AbortError\") throw e;\n throw new ApiError(\"Could not reach the server. Check your connection and try again.\", 0);\n }\n if (!res.ok) {\n let detail = \"\";\n try {\n detail = ((await res.json()) as { error?: string }).error ?? \"\";\n } catch {\n // Not JSON; the status is enough.\n }\n throw new ApiError(detail || (res.status === 429 ? \"Too many requests. Try again in a minute.\" : \"Something went wrong. Please try again.\"), res.status);\n }\n return (await res.json()) as T;\n};\n\n/** The small fetch client behind the widgets. Every read takes an AbortSignal so unmounting cancels it. */\nexport const createApi = (c: Conn) => {\n const base = `${c.host}/api/sdk`;\n const who = { key: c.apiKey, distinctId: c.distinctId, user: c.user };\n const post = <T>(path: string, body: Record<string, unknown>, signal?: AbortSignal) =>\n call<T>(`${base}${path}`, { method: \"POST\", body: JSON.stringify({ ...who, ...body }) }, signal);\n return {\n list: (o: { board?: string; sort?: \"top\" | \"new\"; q?: string }, signal?: AbortSignal) =>\n call<FeedbackList>(`${base}/feedback?${qs({ key: c.apiKey, distinctId: c.distinctId, board: o.board, sort: o.sort, q: o.q })}`, undefined, signal),\n post: (id: string, signal?: AbortSignal) =>\n call<FeedbackPost>(`${base}/feedback/${encodeURIComponent(id)}?${qs({ key: c.apiKey, distinctId: c.distinctId })}`, undefined, signal),\n roadmap: (signal?: AbortSignal) => call<FeedbackRoadmap>(`${base}/feedback/roadmap?${qs({ key: c.apiKey, distinctId: c.distinctId })}`, undefined, signal),\n changelog: (signal?: AbortSignal) => call<{ entries: ChangelogEntry[] }>(`${base}/feedback/changelog?${qs({ key: c.apiKey })}`, undefined, signal),\n submit: (p: { title: string; body?: string; board: string }) => post<FeedbackPost>(\"/feedback\", p),\n vote: (id: string) => post<{ voted: boolean; votes: number }>(`/feedback/${encodeURIComponent(id)}/vote`, {}),\n comments: (id: string, signal?: AbortSignal) =>\n call<{ comments: FeedbackComment[] }>(`${base}/feedback/${encodeURIComponent(id)}/comments?${qs({ key: c.apiKey })}`, undefined, signal),\n comment: (id: string, body: string) => post<FeedbackComment>(`/feedback/${encodeURIComponent(id)}/comments`, { body }),\n survey: (url: string, signal?: AbortSignal) =>\n call<{ survey: SurveyDefinition | null }>(`${base}/surveys?${qs({ key: c.apiKey, distinctId: c.distinctId, url })}`, undefined, signal),\n seen: (id: string) => post<unknown>(`/surveys/${encodeURIComponent(id)}/seen`, { user: undefined }),\n respond: (id: string, r: { answers: Record<string, SurveyAnswer>; completed: boolean; seconds: number }) =>\n post<unknown>(`/surveys/${encodeURIComponent(id)}/respond`, r),\n chat: (signal?: AbortSignal) => call<ChatThread>(`${base}/messages?${qs({ key: c.apiKey, distinctId: c.distinctId })}`, undefined, signal),\n sendChat: (m: { body: string; email?: string; url?: string }) => post<ChatThread>(\"/messages\", m),\n articles: (q?: string, signal?: AbortSignal) => call<{ articles: ArticleSummary[] }>(`${base}/articles?${qs({ key: c.apiKey, q })}`, undefined, signal),\n article: (id: string, signal?: AbortSignal) =>\n call<Article>(`${base}/articles/${encodeURIComponent(id)}?${qs({ key: c.apiKey, distinctId: c.distinctId })}`, undefined, signal),\n messengerLook: (signal?: AbortSignal) => call<MessengerLook>(`${base}/messenger?${qs({ key: c.apiKey })}`, undefined, signal),\n rateArticle: (id: string, helpful: boolean) => post<{ counted: boolean }>(`/articles/${encodeURIComponent(id)}/rate`, { helpful }),\n };\n};\n\nexport type Api = ReturnType<typeof createApi>;\n"],"mappings":";AAMO,IAAM,eAA2C;AAAA,EACpD,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,UAAU;AAAA,EACV,SAAS;AACb;AA8IO,IAAM,YAAY,CAAC,MACtB,MAAM,YAAY,sCAAsC,MAAM,QAAQ,kCAAkC;AAGrG,IAAM,QAAQ,CAAC,QAAgB;AAClC,QAAM,IAAI,8CAA8C,KAAK,GAAG;AAChE,MAAI,CAAC,EAAG,QAAO;AACf,QAAM,CAAC,GAAG,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,MAAM;AAC5C,UAAM,IAAI,SAAS,GAAG,EAAE,IAAI;AAC5B,WAAO,KAAK,UAAU,IAAI,UAAU,IAAI,SAAS,UAAU;AAAA,EAC/D,CAAC;AACD,SAAO,SAAS,IAAI,SAAS,IAAI,SAAS,IAAI,OAAO,YAAY;AACrE;AAUO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAChC;AAAA,EACA,YAAY,SAAiB,QAAgB;AACzC,UAAM,OAAO;AACb,SAAK,SAAS;AAAA,EAClB;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ACjE,MAAM,CAAC,WAAyB,KAAiB,GAAG,IAAI,aAAa,GAAG,EAAE,KAAK,EAAE,QAAQ,YAAY,EAAE,WAAW,CAAC,CAAC,IAAI,QAAW,MAAM;AAAA,IACzI,UAAU,CAAC,MAAsD,KAAiB,aAAa,CAAC;AAAA,IAChG,UAAU,CAAC,GAAY,WAAyB,KAAqC,GAAG,IAAI,aAAa,GAAG,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC,IAAI,QAAW,MAAM;AAAA,IACtJ,SAAS,CAAC,IAAY,WAClB,KAAc,GAAG,IAAI,aAAa,mBAAmB,EAAE,CAAC,IAAI,GAAG,EAAE,KAAK,EAAE,QAAQ,YAAY,EAAE,WAAW,CAAC,CAAC,IAAI,QAAW,MAAM;AAAA,IACpI,eAAe,CAAC,WAAyB,KAAoB,GAAG,IAAI,cAAc,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI,QAAW,MAAM;AAAA,IAC5H,aAAa,CAAC,IAAY,YAAqB,KAA2B,aAAa,mBAAmB,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC;AAAA,EACrI;AACJ;","names":[]}
1
+ {"version":3,"sources":["../src/api-client.ts"],"sourcesContent":["/**\n * The SDK's fetch client and the shapes it reads, without React, so the script tag's widgets (src/script) use it too.\n * `./api` re-exports all of it with the `useApi` hook.\n */\nimport { warnUnsigned } from \"./identity\";\n\nexport type PostStatus = \"review\" | \"planned\" | \"progress\" | \"shipped\";\n\nexport const STATUS_LABEL: Record<PostStatus, string> = {\n review: \"Under review\",\n planned: \"Planned\",\n progress: \"In progress\",\n shipped: \"Shipped\",\n};\n\nexport interface FeedbackBoardInfo {\n id: string;\n label: string;\n}\n\nexport interface FeedbackPost {\n id: string;\n title: string;\n body: string;\n board: string;\n status: PostStatus;\n votes: number;\n comments: number;\n voted: boolean;\n createdAt: string;\n /** \"Lena K.\", \"Anonymous\" or \"Team\". Missing from servers before SDK 0.6. */\n author?: string;\n}\n\n/** The product's public face for the board's header. */\nexport interface FeedbackProduct {\n name: string;\n logo: string | null;\n /** The domain's favicon, tried when `logo` does not load. Older servers leave it out. */\n logoFallback?: string | null;\n}\n\nexport interface FeedbackList {\n boards: FeedbackBoardInfo[];\n posts: FeedbackPost[];\n product?: FeedbackProduct;\n}\n\nexport interface FeedbackRoadmap {\n /** `review` (Backlog) comes from servers of SDK 0.6 on. */\n columns: { review?: FeedbackPost[]; planned: FeedbackPost[]; progress: FeedbackPost[]; shipped: FeedbackPost[] };\n}\n\nexport interface ChangelogEntry {\n id: string;\n title: string;\n body: string;\n publishedAt: string;\n}\n\nexport interface FeedbackComment {\n id: string;\n body: string;\n author: string;\n isTeam: boolean;\n postedAt: string;\n}\n\nexport type SurveyQuestionKind = \"nps\" | \"rating\" | \"single\" | \"multi\" | \"text\";\n\nexport interface SurveyQuestion {\n key: string;\n kind: SurveyQuestionKind;\n title: string;\n description?: string;\n required: boolean;\n options?: string[];\n scale?: number;\n low?: string;\n high?: string;\n placeholder?: string;\n}\n\nexport interface SurveyDefinition {\n id: string;\n name: string;\n type: string;\n thanks: string;\n questions: SurveyQuestion[];\n}\n\nexport type SurveyAnswer = number | string | string[];\n\n/** A file in the messenger's chat: a screenshot, a photo or a PDF the visitor sent (servers from SDK 0.15 on). */\nexport interface ChatFile {\n /** From an upload: the signed id a message sends. In a message: the file's own id (`attachmentUrl` reads it). */\n id: string;\n name: string;\n type: \"image/png\" | \"image/jpeg\" | \"image/webp\" | \"image/gif\" | \"application/pdf\";\n /** Bytes. */\n size: number;\n}\n\n/** What the messenger can send: pictures and PDFs, at most 10 MB each, 4 per message. */\nexport const CHAT_FILE_TYPES = [\"image/png\", \"image/jpeg\", \"image/webp\", \"image/gif\", \"application/pdf\"] as const;\nexport const CHAT_FILE_MAX_BYTES = 10 * 1024 * 1024;\nexport const CHAT_FILES_PER_MESSAGE = 4;\n\n/** A file to upload: a Blob or File on the web, the image picker's `{ uri, name, type }` in React Native. */\nexport type ChatUpload = Blob | { uri: string; name: string; type: string };\n\n/** The bug context a visitor message carries; the server fills browser and system from the user agent when left out. */\nexport interface ChatContext {\n browser?: string;\n os?: string;\n /** \"1440×900\". */\n viewport?: string;\n}\n\n/** One message of the messenger's chat. \"visitor\" is the person on the site; the rest come from the product's team. */\nexport interface ChatMessage {\n id: string;\n from: \"visitor\" | \"team\" | \"ai\" | \"auto\";\n body: string;\n at: string;\n /** Help articles an answer drew on (servers from SDK 0.9 on). */\n articles?: { id: string; title: string }[];\n /** Files sent with it (servers from SDK 0.15 on). */\n attachments?: ChatFile[];\n}\n\n/** A published help article in a list (the messenger's Help tab). */\nexport interface ArticleSummary {\n id: string;\n title: string;\n collection: string;\n excerpt: string;\n updatedAt: string;\n}\n\n/** A run of text inside an article block. Links are http(s), mailto or tel only. */\nexport interface ArticleSpan {\n text: string;\n href?: string;\n bold?: boolean;\n italic?: boolean;\n code?: boolean;\n}\n\n/** An article's content as blocks, written with textContent (never parsed as HTML). */\nexport type ArticleBlock =\n | { type: \"h2\" | \"h3\" | \"p\" | \"quote\"; spans: ArticleSpan[] }\n | { type: \"ul\" | \"ol\"; items: ArticleSpan[][] }\n | { type: \"code\"; text: string }\n | { type: \"hr\" };\n\nexport interface Article {\n id: string;\n title: string;\n collection: string;\n updatedAt: string;\n blocks: ArticleBlock[];\n}\n\n/** Where the chat button sits: a corner, the middle of the top or bottom edge, or the middle of a side. */\nexport type MessengerPosition = \"top-left\" | \"top-center\" | \"top-right\" | \"middle-left\" | \"middle-right\" | \"bottom-left\" | \"bottom-center\" | \"bottom-right\";\n\n/** How round the messenger is. */\nexport type MessengerCorners = \"round\" | \"soft\" | \"square\";\n\n/** The radii per corner style, in px: the panel or sheet, message bubbles (and their tail), cards, fields and buttons. */\nexport const CORNERS: Record<MessengerCorners, { panel: number; bubble: number; tail: number; card: number; field: number }> = {\n round: { panel: 22, bubble: 18, tail: 6, card: 16, field: 20 },\n soft: { panel: 14, bubble: 12, tail: 4, card: 10, field: 10 },\n square: { panel: 6, bubble: 6, tail: 2, card: 4, field: 4 },\n};\n\n/** The messenger's look and texts as set in MRRocket › Support › Messenger (servers from SDK 0.9 on). */\nexport interface MessengerLook {\n accent: string;\n /** Up to two more colors blended into Home's background glow (MRRocket from 0.16; older servers leave it out). */\n glow?: string[];\n theme: \"light\" | \"dark\" | \"auto\";\n position: MessengerPosition;\n title: string;\n greeting: string;\n label: string;\n /** How soon the team usually answers (MRRocket from 0.10; older servers leave it out). */\n replyTime?: \"minutes\" | \"hours\" | \"day\";\n /** A round chat button in the app (React Native) too. */\n appLauncher?: boolean;\n help: boolean;\n sound: boolean;\n preview: boolean;\n askEmail: boolean;\n /** How round panel, bubbles, cards and fields are (MRRocket from 0.15; older servers leave it out: round). */\n corners?: MessengerCorners;\n /** The site's own font (the default) or the system's (web only; from 0.15). */\n font?: \"site\" | \"system\";\n /** Home's top: plain like the rest, or in the accent color (from 0.15; older servers leave it out: plain). */\n header?: \"plain\" | \"color\";\n /** \"Powered by MRRocket\" at the bottom; the server sends false only on plans that may hide it (from 0.15). */\n branding?: boolean;\n /** The product's icon (its favicon) at the top left of Home; without it the title's first letter. */\n logo?: string;\n}\n\n/** The link behind \"Powered by MRRocket\". */\nexport const BRAND_URL = \"https://mrrocket.dev/?utm_source=messenger&utm_medium=powered-by\";\n\n/** The line under \"Send us a message\" and in the chat's head. */\nexport const replyLine = (t: MessengerLook[\"replyTime\"]) =>\n t === \"minutes\" ? \"We usually reply in a few minutes\" : t === \"day\" ? \"We usually reply within a day\" : \"We usually reply in a few hours\";\n\n/** Black or white, whichever reads better on the accent (a light custom color gets dark text). */\nexport const inkOn = (hex: string) => {\n const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);\n if (!m) return \"#ffffff\";\n const [r, g, b] = [m[1], m[2], m[3]].map((x) => {\n const c = parseInt(x, 16) / 255;\n return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n });\n return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.45 ? \"#111214\" : \"#ffffff\";\n};\n\n/** The visitor's newest chat (open or closed) and its messages. */\nexport interface ChatThread {\n conversation: { id: string; status: \"open\" | \"solved\" } | null;\n messages: ChatMessage[];\n /** The visitor gave an email already: the messenger stops asking. */\n hasEmail: boolean;\n}\n\nexport class ApiError extends Error {\n status: number;\n constructor(message: string, status: number) {\n super(message);\n this.status = status;\n }\n}\n\ninterface Conn {\n host: string;\n apiKey: string;\n distinctId: string;\n user?: { id?: string; [key: string]: unknown };\n /**\n * The identity hash of `distinctId` (0.16.0, see identity.ts), sent with every request that names the visitor: a\n * JSON field next to `distinctId`, a query parameter, a form field. Leave it out for any other id.\n */\n userHash?: string;\n}\n\n// Not URLSearchParams: React Native's lacks `set` in older versions, and the apps use this client too.\nconst qs = (params: Record<string, string | undefined>) =>\n Object.entries(params)\n .filter((e): e is [string, string] => !!e[1])\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join(\"&\");\n\nconst call = async <T>(url: string, init: RequestInit | undefined, signal?: AbortSignal): Promise<T> => {\n let res: Response;\n try {\n res = await fetch(url, {\n ...init,\n signal,\n // A form (a file upload) sets its own multipart type with the boundary.\n headers: typeof init?.body === \"string\" ? { \"content-type\": \"application/json\" } : undefined,\n });\n } catch (e) {\n if ((e as Error).name === \"AbortError\") throw e;\n throw new ApiError(\"Could not reach the server. Check your connection and try again.\", 0);\n }\n if (!res.ok) {\n // A missing or wrong identity hash: the console says once how to sign the user id.\n warnUnsigned(res.status);\n let detail = \"\";\n try {\n detail = ((await res.json()) as { error?: string }).error ?? \"\";\n } catch {\n // Not JSON; the status is enough.\n }\n throw new ApiError(detail || (res.status === 429 ? \"Too many requests. Try again in a minute.\" : \"Something went wrong. Please try again.\"), res.status);\n }\n return (await res.json()) as T;\n};\n\n/** The small fetch client behind the widgets. Every read takes an AbortSignal so unmounting cancels it. */\nexport const createApi = (c: Conn) => {\n const base = `${c.host}/api/sdk`;\n const who = { key: c.apiKey, distinctId: c.distinctId, user: c.user, userHash: c.userHash };\n // Every query that names the visitor names its hash too.\n const me = { key: c.apiKey, distinctId: c.distinctId, userHash: c.userHash };\n const post = <T>(path: string, body: Record<string, unknown>, signal?: AbortSignal) =>\n call<T>(`${base}${path}`, { method: \"POST\", body: JSON.stringify({ ...who, ...body }) }, signal);\n return {\n list: (o: { board?: string; sort?: \"top\" | \"new\"; q?: string }, signal?: AbortSignal) =>\n call<FeedbackList>(`${base}/feedback?${qs({ ...me, board: o.board, sort: o.sort, q: o.q })}`, undefined, signal),\n post: (id: string, signal?: AbortSignal) =>\n call<FeedbackPost>(`${base}/feedback/${encodeURIComponent(id)}?${qs(me)}`, undefined, signal),\n roadmap: (signal?: AbortSignal) => call<FeedbackRoadmap>(`${base}/feedback/roadmap?${qs(me)}`, undefined, signal),\n changelog: (signal?: AbortSignal) => call<{ entries: ChangelogEntry[] }>(`${base}/feedback/changelog?${qs({ key: c.apiKey })}`, undefined, signal),\n submit: (p: { title: string; body?: string; board: string }) => post<FeedbackPost>(\"/feedback\", p),\n vote: (id: string) => post<{ voted: boolean; votes: number }>(`/feedback/${encodeURIComponent(id)}/vote`, {}),\n comments: (id: string, signal?: AbortSignal) =>\n call<{ comments: FeedbackComment[] }>(`${base}/feedback/${encodeURIComponent(id)}/comments?${qs({ key: c.apiKey })}`, undefined, signal),\n comment: (id: string, body: string) => post<FeedbackComment>(`/feedback/${encodeURIComponent(id)}/comments`, { body }),\n survey: (url: string, signal?: AbortSignal) =>\n call<{ survey: SurveyDefinition | null }>(`${base}/surveys?${qs({ ...me, url })}`, undefined, signal),\n seen: (id: string) => post<unknown>(`/surveys/${encodeURIComponent(id)}/seen`, { user: undefined }),\n respond: (id: string, r: { answers: Record<string, SurveyAnswer>; completed: boolean; seconds: number }) =>\n post<unknown>(`/surveys/${encodeURIComponent(id)}/respond`, r),\n chat: (signal?: AbortSignal) => call<ChatThread>(`${base}/messages?${qs(me)}`, undefined, signal),\n /** A message; `attachments` are upload ids from `uploadChatFile` (then the body may be empty). */\n sendChat: (m: { body: string; email?: string; url?: string; attachments?: string[]; context?: ChatContext }) => post<ChatThread>(\"/messages\", m),\n /** Uploads one picked file for the next message (pictures and PDFs, at most 10 MB); answers its upload id. */\n uploadChatFile: (file: ChatUpload, signal?: AbortSignal) => {\n const form = new FormData();\n form.append(\"key\", c.apiKey);\n form.append(\"distinctId\", c.distinctId);\n if (c.userHash) form.append(\"userHash\", c.userHash);\n if (\"uri\" in file) form.append(\"file\", file as unknown as Blob);\n else form.append(\"file\", file, (file as Blob & { name?: string }).name || \"file\");\n return call<ChatFile>(`${base}/messages/attachments`, { method: \"POST\", body: form }, signal);\n },\n /** Where a sent file of this visitor's chat is read (an image's src, a PDF's link). */\n attachmentUrl: (id: string) => `${base}/messages/attachments/${encodeURIComponent(id)}?${qs(me)}`,\n articles: (q?: string, signal?: AbortSignal) => call<{ articles: ArticleSummary[] }>(`${base}/articles?${qs({ key: c.apiKey, q })}`, undefined, signal),\n article: (id: string, signal?: AbortSignal) =>\n call<Article>(`${base}/articles/${encodeURIComponent(id)}?${qs(me)}`, undefined, signal),\n messengerLook: (signal?: AbortSignal) => call<MessengerLook>(`${base}/messenger?${qs({ key: c.apiKey })}`, undefined, signal),\n rateArticle: (id: string, helpful: boolean) => post<{ counted: boolean }>(`/articles/${encodeURIComponent(id)}/rate`, { helpful }),\n };\n};\n\nexport type Api = ReturnType<typeof createApi>;\n"],"mappings":";AAIA,SAAS,oBAAoB;AAItB,IAAM,eAA2C;AAAA,EACpD,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,UAAU;AAAA,EACV,SAAS;AACb;AA2FO,IAAM,kBAAkB,CAAC,aAAa,cAAc,cAAc,aAAa,iBAAiB;AAChG,IAAM,sBAAsB,KAAK,OAAO;AACxC,IAAM,yBAAyB;AAiE/B,IAAM,UAAkH;AAAA,EAC3H,OAAO,EAAE,OAAO,IAAI,QAAQ,IAAI,MAAM,GAAG,MAAM,IAAI,OAAO,GAAG;A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O,QAAQ,MAAO,KAAkC,QAAQ,MAAM;AAChF,aAAO,KAAe,GAAG,IAAI,yBAAyB,EAAE,QAAQ,QAAQ,MAAM,KAAK,GAAG,MAAM;AAAA,IAChG;AAAA;AAAA,IAEA,eAAe,CAAC,OAAe,GAAG,IAAI,yBAAyB,mBAAmB,EAAE,CAAC,IAAI,GAAG,EAAE,CAAC;AAAA,IAC/F,UAAU,CAAC,GAAY,WAAyB,KAAqC,GAAG,IAAI,aAAa,GAAG,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC,IAAI,QAAW,MAAM;AAAA,IACtJ,SAAS,CAAC,IAAY,WAClB,KAAc,GAAG,IAAI,aAAa,mBAAmB,EAAE,CAAC,IAAI,GAAG,EAAE,CAAC,IAAI,QAAW,MAAM;AAAA,IAC3F,eAAe,CAAC,WAAyB,KAAoB,GAAG,IAAI,cAAc,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI,QAAW,MAAM;AAAA,IAC5H,aAAa,CAAC,IAAY,YAAqB,KAA2B,aAAa,mBAAmB,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC;AAAA,EACrI;AACJ;","names":[]}
package/dist/api.d.ts CHANGED
@@ -9,5 +9,8 @@ export interface Writer {
9
9
  email?: string;
10
10
  };
11
11
  }
12
- /** The client for the provider's key, host and visitor, or for `as` when given. */
12
+ /**
13
+ * The client for the provider's key, host and visitor, or for `as` when given. The visitor's identity hash goes along;
14
+ * `as` (a board identity the visitor typed in) is no signed user and goes without.
15
+ */
13
16
  export declare const useApi: (as?: Writer | null) => Api;
package/dist/api.js CHANGED
@@ -7,8 +7,9 @@ var useApi = (as) => {
7
7
  const ctx = useCtx();
8
8
  const distinctId = as?.distinctId ?? ctx.distinctId;
9
9
  const user = as ? as.user : ctx.user;
10
+ const userHash = as ? void 0 : ctx.userHash;
10
11
  const { apiKey, host } = ctx;
11
- return useMemo(() => createApi({ apiKey, host, distinctId, user }), [apiKey, host, distinctId, user]);
12
+ return useMemo(() => createApi({ apiKey, host, distinctId, user, userHash }), [apiKey, host, distinctId, user, userHash]);
12
13
  };
13
14
  export {
14
15
  useApi
package/dist/api.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/api.ts"],"sourcesContent":["import { useMemo } from \"react\";\nimport { type Api, createApi } from \"./api-client\";\nimport { useCtx } from \"./context\";\n\nexport * from \"./api-client\";\n\n/** Who writes: the provider's visitor, or the name and email a visitor gave the board (see useBoardIdentity). */\nexport interface Writer {\n distinctId: string;\n user?: { id?: string; name?: string; email?: string };\n}\n\n/** The client for the provider's key, host and visitor, or for `as` when given. */\nexport const useApi = (as?: Writer | null): Api => {\n const ctx = useCtx();\n const distinctId = as?.distinctId ?? ctx.distinctId;\n const user = as ? as.user : ctx.user;\n const { apiKey, host } = ctx;\n return useMemo(() => createApi({ apiKey, host, distinctId, user }), [apiKey, host, distinctId, user]);\n};\n"],"mappings":";AAAA,SAAS,eAAe;AACxB,SAAmB,iBAAiB;AACpC,SAAS,cAAc;AAEvB,cAAc;AASP,IAAM,SAAS,CAAC,OAA4B;AAC/C,QAAM,MAAM,OAAO;AACnB,QAAM,aAAa,IAAI,cAAc,IAAI;AACzC,QAAM,OAAO,KAAK,GAAG,OAAO,IAAI;AAChC,QAAM,EAAE,QAAQ,KAAK,IAAI;AACzB,SAAO,QAAQ,MAAM,UAAU,EAAE,QAAQ,MAAM,YAAY,KAAK,CAAC,GAAG,CAAC,QAAQ,MAAM,YAAY,IAAI,CAAC;AACxG;","names":[]}
1
+ {"version":3,"sources":["../src/api.ts"],"sourcesContent":["import { useMemo } from \"react\";\nimport { type Api, createApi } from \"./api-client\";\nimport { useCtx } from \"./context\";\n\nexport * from \"./api-client\";\n\n/** Who writes: the provider's visitor, or the name and email a visitor gave the board (see useBoardIdentity). */\nexport interface Writer {\n distinctId: string;\n user?: { id?: string; name?: string; email?: string };\n}\n\n/**\n * The client for the provider's key, host and visitor, or for `as` when given. The visitor's identity hash goes along;\n * `as` (a board identity the visitor typed in) is no signed user and goes without.\n */\nexport const useApi = (as?: Writer | null): Api => {\n const ctx = useCtx();\n const distinctId = as?.distinctId ?? ctx.distinctId;\n const user = as ? as.user : ctx.user;\n const userHash = as ? undefined : ctx.userHash;\n const { apiKey, host } = ctx;\n return useMemo(() => createApi({ apiKey, host, distinctId, user, userHash }), [apiKey, host, distinctId, user, userHash]);\n};\n"],"mappings":";AAAA,SAAS,eAAe;AACxB,SAAmB,iBAAiB;AACpC,SAAS,cAAc;AAEvB,cAAc;AAYP,IAAM,SAAS,CAAC,OAA4B;AAC/C,QAAM,MAAM,OAAO;AACnB,QAAM,aAAa,IAAI,cAAc,IAAI;AACzC,QAAM,OAAO,KAAK,GAAG,OAAO,IAAI;AAChC,QAAM,WAAW,KAAK,SAAY,IAAI;AACtC,QAAM,EAAE,QAAQ,KAAK,IAAI;AACzB,SAAO,QAAQ,MAAM,UAAU,EAAE,QAAQ,MAAM,YAAY,MAAM,SAAS,CAAC,GAAG,CAAC,QAAQ,MAAM,YAAY,MAAM,QAAQ,CAAC;AAC5H;","names":[]}
package/dist/batch.d.ts CHANGED
@@ -23,11 +23,13 @@ export interface BatchRequest<E> {
23
23
  }
24
24
  /**
25
25
  * Splits events into request bodies of at most 100 events each, under the size limit. An event too large on its own is
26
- * dropped (it is in no request).
26
+ * dropped (it is in no request). `userHash` (0.16.0) is the identity hash of the signed-in person: one per request, and
27
+ * MRRocket checks it against each event's `distinctId`, so only that person's events count as verified.
27
28
  */
28
- export declare const batchRequests: <E extends CockpitEvent>(key: string, events: E[], sdk: SdkInfo) => BatchRequest<E>[];
29
+ export declare const batchRequests: <E extends CockpitEvent>(key: string, events: E[], sdk: SdkInfo, userHash?: string) => BatchRequest<E>[];
29
30
  /**
30
31
  * Request bodies of at most 100 events each, under the size limit. An event too large on its own is dropped. `sdk` tells
31
- * MRRocket which SDK the site runs and whether it reports errors (Build › Errors and Feature flags show it).
32
+ * MRRocket which SDK the site runs and whether it reports errors (Build › Errors and Feature flags show it); `userHash`
33
+ * as in `batchRequests`.
32
34
  */
33
- export declare const bodies: (key: string, events: CockpitEvent[], sdk: SdkInfo) => string[];
35
+ export declare const bodies: (key: string, events: CockpitEvent[], sdk: SdkInfo, userHash?: string) => string[];
package/dist/batch.js CHANGED
@@ -14,8 +14,8 @@ var byteLength = (s) => {
14
14
  }
15
15
  return n;
16
16
  };
17
- var batchRequests = (key, events, sdk) => {
18
- const head = `{"key":${JSON.stringify(key)},"sdk":${JSON.stringify(sdk)},"events":[`;
17
+ var batchRequests = (key, events, sdk, userHash) => {
18
+ const head = `{"key":${JSON.stringify(key)},${userHash ? `"userHash":${JSON.stringify(userHash)},` : ""}"sdk":${JSON.stringify(sdk)},"events":[`;
19
19
  const empty = byteLength(head) + 2;
20
20
  const out = [];
21
21
  let chunk = [];
@@ -39,7 +39,7 @@ var batchRequests = (key, events, sdk) => {
39
39
  close();
40
40
  return out;
41
41
  };
42
- var bodies = (key, events, sdk) => batchRequests(key, events, sdk).map((r) => r.body);
42
+ var bodies = (key, events, sdk, userHash) => batchRequests(key, events, sdk, userHash).map((r) => r.body);
43
43
  export {
44
44
  MAX_BATCH,
45
45
  MAX_BYTES,
package/dist/batch.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/batch.ts"],"sourcesContent":["/**\n * How events go over the wire to `POST /api/sdk/events`, shared by every runtime (Next.js, the script tag, React\n * Native): request bodies of at most 100 events each, under the server's 64 KB. No React, no browser APIs, no\n * TextEncoder (Hermes on older React Native lacks it), so it runs anywhere.\n */\nimport type { CockpitEvent } from \"./core\";\n\n/** The server takes at most 100 events and 64 KB per request; stay a little under the size. */\nexport const MAX_BATCH = 100;\nexport const MAX_BYTES = 60_000;\n\n/** What a batch says about the SDK that sent it (Build › Errors and Feature flags show it). */\nexport interface SdkInfo {\n v: string;\n errors: boolean;\n /** \"web\" (script tag), \"ios\" or \"android\" (React Native). Missing from the Next.js provider. */\n platform?: string;\n}\n\n/** UTF-8 length of a string, the way TextEncoder counts it (a lone surrogate becomes U+FFFD, three bytes). */\nexport const byteLength = (s: string) => {\n let n = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c < 0x80) n += 1;\n else if (c < 0x800) n += 2;\n else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length && (s.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n n += 4;\n i++;\n } else n += 3;\n }\n return n;\n};\n\n/** One request: its body and the events in it (so a client can keep the ones that did not arrive). */\nexport interface BatchRequest<E> {\n body: string;\n events: E[];\n}\n\n/**\n * Splits events into request bodies of at most 100 events each, under the size limit. An event too large on its own is\n * dropped (it is in no request).\n */\nexport const batchRequests = <E extends CockpitEvent>(key: string, events: E[], sdk: SdkInfo): BatchRequest<E>[] => {\n const head = `{\"key\":${JSON.stringify(key)},\"sdk\":${JSON.stringify(sdk)},\"events\":[`;\n const empty = byteLength(head) + 2;\n const out: BatchRequest<E>[] = [];\n let chunk: string[] = [];\n let items: E[] = [];\n let size = empty;\n const close = () => {\n if (chunk.length) out.push({ body: `${head}${chunk.join(\",\")}]}`, events: items });\n chunk = [];\n items = [];\n size = empty;\n };\n for (const event of events) {\n const json = JSON.stringify(event);\n const n = byteLength(json) + 1;\n if (empty + n > MAX_BYTES) continue;\n if (chunk.length === MAX_BATCH || size + n > MAX_BYTES) close();\n chunk.push(json);\n items.push(event);\n size += n;\n }\n close();\n return out;\n};\n\n/**\n * Request bodies of at most 100 events each, under the size limit. An event too large on its own is dropped. `sdk` tells\n * MRRocket which SDK the site runs and whether it reports errors (Build › Errors and Feature flags show it).\n */\nexport const bodies = (key: string, events: CockpitEvent[], sdk: SdkInfo) => batchRequests(key, events, sdk).map((r) => r.body);\n"],"mappings":";AAQO,IAAM,YAAY;AAClB,IAAM,YAAY;AAWlB,IAAM,aAAa,CAAC,MAAc;AACrC,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;AAC/B,UAAM,IAAI,EAAE,WAAW,CAAC;AACxB,QAAI,IAAI,IAAM,MAAK;AAAA,aACV,IAAI,KAAO,MAAK;AAAA,aAChB,KAAK,SAAU,KAAK,SAAU,IAAI,IAAI,EAAE,WAAW,EAAE,WAAW,IAAI,CAAC,IAAI,WAAY,OAAQ;AAClG,WAAK;AACL;AAAA,IACJ,MAAO,MAAK;AAAA,EAChB;AACA,SAAO;AACX;AAYO,IAAM,gBAAgB,CAAyB,KAAa,QAAa,QAAoC;AAChH,QAAM,OAAO,UAAU,KAAK,UAAU,GAAG,CAAC,UAAU,KAAK,UAAU,GAAG,CAAC;AACvE,QAAM,QAAQ,WAAW,IAAI,IAAI;AACjC,QAAM,MAAyB,CAAC;AAChC,MAAI,QAAkB,CAAC;AACvB,MAAI,QAAa,CAAC;AAClB,MAAI,OAAO;AACX,QAAM,QAAQ,MAAM;AAChB,QAAI,MAAM,OAAQ,KAAI,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,KAAK,GAAG,CAAC,MAAM,QAAQ,MAAM,CAAC;AACjF,YAAQ,CAAC;AACT,YAAQ,CAAC;AACT,WAAO;AAAA,EACX;AACA,aAAW,SAAS,QAAQ;AACxB,UAAM,OAAO,KAAK,UAAU,KAAK;AACjC,UAAM,IAAI,WAAW,IAAI,IAAI;AAC7B,QAAI,QAAQ,IAAI,UAAW;AAC3B,QAAI,MAAM,WAAW,aAAa,OAAO,IAAI,UAAW,OAAM;AAC9D,UAAM,KAAK,IAAI;AACf,UAAM,KAAK,KAAK;AAChB,YAAQ;AAAA,EACZ;AACA,QAAM;AACN,SAAO;AACX;AAMO,IAAM,SAAS,CAAC,KAAa,QAAwB,QAAiB,cAAc,KAAK,QAAQ,GAAG,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI;","names":[]}
1
+ {"version":3,"sources":["../src/batch.ts"],"sourcesContent":["/**\n * How events go over the wire to `POST /api/sdk/events`, shared by every runtime (Next.js, the script tag, React\n * Native): request bodies of at most 100 events each, under the server's 64 KB. No React, no browser APIs, no\n * TextEncoder (Hermes on older React Native lacks it), so it runs anywhere.\n */\nimport type { CockpitEvent } from \"./core\";\n\n/** The server takes at most 100 events and 64 KB per request; stay a little under the size. */\nexport const MAX_BATCH = 100;\nexport const MAX_BYTES = 60_000;\n\n/** What a batch says about the SDK that sent it (Build › Errors and Feature flags show it). */\nexport interface SdkInfo {\n v: string;\n errors: boolean;\n /** \"web\" (script tag), \"ios\" or \"android\" (React Native). Missing from the Next.js provider. */\n platform?: string;\n}\n\n/** UTF-8 length of a string, the way TextEncoder counts it (a lone surrogate becomes U+FFFD, three bytes). */\nexport const byteLength = (s: string) => {\n let n = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c < 0x80) n += 1;\n else if (c < 0x800) n += 2;\n else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length && (s.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n n += 4;\n i++;\n } else n += 3;\n }\n return n;\n};\n\n/** One request: its body and the events in it (so a client can keep the ones that did not arrive). */\nexport interface BatchRequest<E> {\n body: string;\n events: E[];\n}\n\n/**\n * Splits events into request bodies of at most 100 events each, under the size limit. An event too large on its own is\n * dropped (it is in no request). `userHash` (0.16.0) is the identity hash of the signed-in person: one per request, and\n * MRRocket checks it against each event's `distinctId`, so only that person's events count as verified.\n */\nexport const batchRequests = <E extends CockpitEvent>(key: string, events: E[], sdk: SdkInfo, userHash?: string): BatchRequest<E>[] => {\n const head = `{\"key\":${JSON.stringify(key)},${userHash ? `\"userHash\":${JSON.stringify(userHash)},` : \"\"}\"sdk\":${JSON.stringify(sdk)},\"events\":[`;\n const empty = byteLength(head) + 2;\n const out: BatchRequest<E>[] = [];\n let chunk: string[] = [];\n let items: E[] = [];\n let size = empty;\n const close = () => {\n if (chunk.length) out.push({ body: `${head}${chunk.join(\",\")}]}`, events: items });\n chunk = [];\n items = [];\n size = empty;\n };\n for (const event of events) {\n const json = JSON.stringify(event);\n const n = byteLength(json) + 1;\n if (empty + n > MAX_BYTES) continue;\n if (chunk.length === MAX_BATCH || size + n > MAX_BYTES) close();\n chunk.push(json);\n items.push(event);\n size += n;\n }\n close();\n return out;\n};\n\n/**\n * Request bodies of at most 100 events each, under the size limit. An event too large on its own is dropped. `sdk` tells\n * MRRocket which SDK the site runs and whether it reports errors (Build › Errors and Feature flags show it); `userHash`\n * as in `batchRequests`.\n */\nexport const bodies = (key: string, events: CockpitEvent[], sdk: SdkInfo, userHash?: string) => batchRequests(key, events, sdk, userHash).map((r) => r.body);\n"],"mappings":";AAQO,IAAM,YAAY;AAClB,IAAM,YAAY;AAWlB,IAAM,aAAa,CAAC,MAAc;AACrC,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;AAC/B,UAAM,IAAI,EAAE,WAAW,CAAC;AACxB,QAAI,IAAI,IAAM,MAAK;AAAA,aACV,IAAI,KAAO,MAAK;AAAA,aAChB,KAAK,SAAU,KAAK,SAAU,IAAI,IAAI,EAAE,WAAW,EAAE,WAAW,IAAI,CAAC,IAAI,WAAY,OAAQ;AAClG,WAAK;AACL;AAAA,IACJ,MAAO,MAAK;AAAA,EAChB;AACA,SAAO;AACX;AAaO,IAAM,gBAAgB,CAAyB,KAAa,QAAa,KAAc,aAAyC;AACnI,QAAM,OAAO,UAAU,KAAK,UAAU,GAAG,CAAC,IAAI,WAAW,cAAc,KAAK,UAAU,QAAQ,CAAC,MAAM,EAAE,SAAS,KAAK,UAAU,GAAG,CAAC;AACnI,QAAM,QAAQ,WAAW,IAAI,IAAI;AACjC,QAAM,MAAyB,CAAC;AAChC,MAAI,QAAkB,CAAC;AACvB,MAAI,QAAa,CAAC;AAClB,MAAI,OAAO;AACX,QAAM,QAAQ,MAAM;AAChB,QAAI,MAAM,OAAQ,KAAI,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,KAAK,GAAG,CAAC,MAAM,QAAQ,MAAM,CAAC;AACjF,YAAQ,CAAC;AACT,YAAQ,CAA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