bitsnap-react 1.9.0 → 1.11.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 (116) hide show
  1. package/README.md +95 -7
  2. package/dist/CartProvider-ONIOELW5.mjs +2 -0
  3. package/dist/CartProvider-Q3CIVK5K.js +2 -0
  4. package/dist/CartProvider-Q3CIVK5K.js.map +1 -0
  5. package/dist/analytics.d.mts +22 -5
  6. package/dist/analytics.d.ts +22 -5
  7. package/dist/analytics.js +1 -1
  8. package/dist/analytics.js.map +1 -1
  9. package/dist/analytics.mjs +1 -1
  10. package/dist/catalog.d.mts +1 -1
  11. package/dist/catalog.d.ts +1 -1
  12. package/dist/catalog.js +1 -1
  13. package/dist/catalog.js.map +1 -1
  14. package/dist/catalog.mjs +1 -1
  15. package/dist/chunk-7RGH57QG.js +2 -0
  16. package/dist/chunk-7RGH57QG.js.map +1 -0
  17. package/dist/chunk-ADYVTMGH.mjs +2 -0
  18. package/dist/chunk-ADYVTMGH.mjs.map +1 -0
  19. package/dist/{chunk-FHDFLSPW.js → chunk-ASNUY3EU.js} +2 -2
  20. package/dist/chunk-ASNUY3EU.js.map +1 -0
  21. package/dist/{chunk-HKVMSMDF.mjs → chunk-C5Q7DGCD.mjs} +2 -2
  22. package/dist/{chunk-LJWS6ZRJ.mjs → chunk-C5RMHUOG.mjs} +2 -2
  23. package/dist/{chunk-KG6RU37U.js → chunk-CUQ2PNCJ.js} +3 -3
  24. package/dist/chunk-CUQ2PNCJ.js.map +1 -0
  25. package/dist/{chunk-VXB7LA4E.js → chunk-ELGNOAH4.js} +2 -2
  26. package/dist/chunk-ELGNOAH4.js.map +1 -0
  27. package/dist/chunk-EZWH6BB2.mjs +2 -0
  28. package/dist/chunk-EZWH6BB2.mjs.map +1 -0
  29. package/dist/{chunk-SLLBTQTW.mjs → chunk-GPNALARZ.mjs} +2 -2
  30. package/dist/chunk-GT3OH55Y.js +2 -0
  31. package/dist/chunk-GT3OH55Y.js.map +1 -0
  32. package/dist/{chunk-SZ256RCC.mjs → chunk-H3YP2QPV.mjs} +2 -2
  33. package/dist/chunk-HG4YOJWE.mjs +4 -0
  34. package/dist/chunk-HG4YOJWE.mjs.map +1 -0
  35. package/dist/chunk-JSDGZ4NY.js.map +1 -1
  36. package/dist/chunk-KOYBZORL.js.map +1 -1
  37. package/dist/{chunk-VM6JEJFZ.js → chunk-PUYK4YHE.js} +2 -2
  38. package/dist/chunk-PUYK4YHE.js.map +1 -0
  39. package/dist/chunk-T57337WD.mjs +2 -0
  40. package/dist/chunk-T57337WD.mjs.map +1 -0
  41. package/dist/{chunk-3IMJALBX.js → chunk-VQQBBSK2.js} +2 -2
  42. package/dist/chunk-VQQBBSK2.js.map +1 -0
  43. package/dist/chunk-XIHGWNTS.js +2 -0
  44. package/dist/chunk-XIHGWNTS.js.map +1 -0
  45. package/dist/{chunk-GN63ITLA.mjs → chunk-XQ43IC4M.mjs} +2 -2
  46. package/dist/{chunk-V4U2PTKN.js → chunk-YFETPEI6.js} +2 -2
  47. package/dist/chunk-YFETPEI6.js.map +1 -0
  48. package/dist/consent.d.mts +7 -0
  49. package/dist/consent.d.ts +7 -0
  50. package/dist/consent.js +29 -15
  51. package/dist/consent.js.map +1 -1
  52. package/dist/consent.mjs +29 -15
  53. package/dist/consent.mjs.map +1 -1
  54. package/dist/course.d.mts +2 -2
  55. package/dist/course.d.ts +2 -2
  56. package/dist/course.js +1 -1
  57. package/dist/course.js.map +1 -1
  58. package/dist/course.mjs +1 -1
  59. package/dist/course.mjs.map +1 -1
  60. package/dist/embed/analytics.js +1 -1
  61. package/dist/embed/consent.js +27 -13
  62. package/dist/errors.js.map +1 -1
  63. package/dist/index.d.mts +40 -8
  64. package/dist/index.d.ts +40 -8
  65. package/dist/index.js +1 -1
  66. package/dist/index.js.map +1 -1
  67. package/dist/index.mjs +1 -1
  68. package/dist/index.mjs.map +1 -1
  69. package/dist/{instrument-C_abZLHk.d.ts → instrument-CmxK7S4T.d.mts} +22 -5
  70. package/dist/{instrument-C_abZLHk.d.mts → instrument-CmxK7S4T.d.ts} +22 -5
  71. package/dist/internal.js.map +1 -1
  72. package/dist/methods-C5HWYPPN.mjs +2 -0
  73. package/dist/methods-CHNMFVFV.js +2 -0
  74. package/dist/methods-CHNMFVFV.js.map +1 -0
  75. package/dist/models.js.map +1 -1
  76. package/dist/returns.d.mts +1 -1
  77. package/dist/returns.d.ts +1 -1
  78. package/dist/returns.js +1 -1
  79. package/dist/returns.js.map +1 -1
  80. package/dist/returns.mjs +1 -1
  81. package/dist/{types-D_WnqwR_.d.mts → types-BnVWLcoB.d.mts} +1 -1
  82. package/dist/{types-BaqLJYuq.d.ts → types-i-IuN4Im.d.ts} +1 -1
  83. package/package.json +2 -2
  84. package/dist/CartProvider-XWTLBIZ5.js +0 -2
  85. package/dist/CartProvider-XWTLBIZ5.js.map +0 -1
  86. package/dist/CartProvider-ZURLJNBW.mjs +0 -2
  87. package/dist/chunk-3IMJALBX.js.map +0 -1
  88. package/dist/chunk-3UHPJ6NK.js +0 -2
  89. package/dist/chunk-3UHPJ6NK.js.map +0 -1
  90. package/dist/chunk-CO2P4FR5.js +0 -2
  91. package/dist/chunk-CO2P4FR5.js.map +0 -1
  92. package/dist/chunk-E6QVQEGZ.mjs +0 -2
  93. package/dist/chunk-E6QVQEGZ.mjs.map +0 -1
  94. package/dist/chunk-FHDFLSPW.js.map +0 -1
  95. package/dist/chunk-KG6RU37U.js.map +0 -1
  96. package/dist/chunk-LZE2E4TE.mjs +0 -4
  97. package/dist/chunk-LZE2E4TE.mjs.map +0 -1
  98. package/dist/chunk-QZJGNLCZ.js +0 -2
  99. package/dist/chunk-QZJGNLCZ.js.map +0 -1
  100. package/dist/chunk-RA452LXZ.mjs +0 -2
  101. package/dist/chunk-RA452LXZ.mjs.map +0 -1
  102. package/dist/chunk-V4U2PTKN.js.map +0 -1
  103. package/dist/chunk-VM6JEJFZ.js.map +0 -1
  104. package/dist/chunk-VXB7LA4E.js.map +0 -1
  105. package/dist/chunk-XVQKEGPO.mjs +0 -2
  106. package/dist/chunk-XVQKEGPO.mjs.map +0 -1
  107. package/dist/methods-CYARZTYL.mjs +0 -2
  108. package/dist/methods-DAPEWVI6.js +0 -2
  109. package/dist/methods-DAPEWVI6.js.map +0 -1
  110. /package/dist/{CartProvider-ZURLJNBW.mjs.map → CartProvider-ONIOELW5.mjs.map} +0 -0
  111. /package/dist/{chunk-HKVMSMDF.mjs.map → chunk-C5Q7DGCD.mjs.map} +0 -0
  112. /package/dist/{chunk-LJWS6ZRJ.mjs.map → chunk-C5RMHUOG.mjs.map} +0 -0
  113. /package/dist/{chunk-SLLBTQTW.mjs.map → chunk-GPNALARZ.mjs.map} +0 -0
  114. /package/dist/{chunk-SZ256RCC.mjs.map → chunk-H3YP2QPV.mjs.map} +0 -0
  115. /package/dist/{chunk-GN63ITLA.mjs.map → chunk-XQ43IC4M.mjs.map} +0 -0
  116. /package/dist/{methods-CYARZTYL.mjs.map → methods-C5HWYPPN.mjs.map} +0 -0
package/README.md CHANGED
@@ -353,7 +353,22 @@ copy per language, pass a different object.
353
353
  ```
354
354
 
355
355
  Checkout keys (`CheckoutTexts`): `cart`, `emptyCart`, `total`, `delivery`,
356
- `chooseCountry`, `nextStep`, `unavailableProducts`.
356
+ `chooseCountry`, `nextStep`, `unavailableProducts`, `checkoutFailed`,
357
+ `noPaymentGateway`, `gatewayNotConfigured`, `shippingNotConfigured`,
358
+ `mixedRecurring`, `currencyUnsupported`, `priceChanged`.
359
+
360
+ When "Next step" fails, the cart shows the text of the backend error code
361
+ (`noPaymentGateway`, `gatewayNotConfigured`, `shippingNotConfigured`,
362
+ `mixedRecurring`, `currencyUnsupported`, `priceChanged`; `unavailableProducts`
363
+ for `product-not-found`). Server errors (5xx, `internal`) and `invalid-request`
364
+ show `checkoutFailed`. For any other 4xx code the cart shows the message sent
365
+ by the server, else `checkoutFailed`. It never shows the bare code, and never
366
+ a message that is HTML, multi-line, longer than 200 characters or a stack
367
+ trace.
368
+
369
+ These keys were added in 1.11.0. If you type your own language
370
+ objects, use `Partial<CheckoutTexts>` (the `texts` prop already accepts it) so
371
+ that they keep compiling when new keys appear.
357
372
 
358
373
  Returns keys (`ReturnsTexts`) cover each step (`emailStepTitle`,
359
374
  `codeStepDescription`, `ordersEmpty`, `confirmationSubmit`, `successTitle`,
@@ -763,6 +778,40 @@ async function handleCheckout() {
763
778
  }
764
779
  ```
765
780
 
781
+ On success `createCheckout` returns `{ status: "ok", redirectURL }`. A failed
782
+ response no longer throws and no longer yields an undefined `redirectURL`: it
783
+ returns an `Err` with `status: "error"` instead (`result.ERR === true`), typed
784
+ as `CreateCheckoutResult`. Check `result.status === "ok"` before reading
785
+ `redirectURL`. `result.error` is the backend code (`invalid-request`,
786
+ `product-not-available`, `product-not-found`, `no-payment-gateway`,
787
+ `gateway-not-configured`, `shipping-not-configured`, `mixed-recurring`,
788
+ `currency-unsupported`, `price-changed`, `internal`). New backends send
789
+ `internal` for their own failures; `internal-error` is what the library uses
790
+ when an older backend sent no code. `result.data` is a `BuyErrorData`
791
+ (`{ message?, itemIds? }`), except for `item-ids-not-found`
792
+ (`ITEM_IDS_NOT_FOUND`), where it is the array of ids; both are exported.
793
+ `message` is the reason sent by the server, when it was usable. `result.type`
794
+ is `internal` for 5xx and `badInput` for 4xx.
795
+
796
+ ```tsx
797
+ import { ITEM_IDS_NOT_FOUND, type BuyErrorData } from "bitsnap-react";
798
+
799
+ if (result.status === "error") {
800
+ if (result.error === ITEM_IDS_NOT_FOUND) {
801
+ const ids = result.data as string[];
802
+ } else {
803
+ const { message } = (result.data ?? {}) as BuyErrorData;
804
+ }
805
+ }
806
+ ```
807
+
808
+ `createPaymentURL` returns the same errors: the backend code in `error`,
809
+ `type: "badInput"` for 4xx (`"internal"` for 5xx) and `data: { message }`.
810
+ When the backend lists unavailable products (`itemIds`) under
811
+ `product-not-available` or `product-not-found` (or sends no code), the error is
812
+ `item-ids-not-found` and `data` is the array of ids. With any other code the
813
+ code is kept and the ids are in `data.itemIds`.
814
+
766
815
  6. Webhook Handler:
767
816
 
768
817
  ```tsx
@@ -1102,11 +1151,11 @@ The panel provides the following screens:
1102
1151
 
1103
1152
  ## Merchant analytics (`bitsnap-react/analytics`)
1104
1153
 
1105
- A small, cookieless tracker that sends buyer-behaviour events (page views, product views, cart and checkout steps) to Bitsnap, so your dashboard can show visits, sources and funnels. It never uses cookies, `localStorage`, `sessionStorage` or IndexedDB: events live in memory and the visitor is recognised on the server by a daily-rotating hash that is never stored.
1154
+ A small tracker that sends buyer-behaviour events (page views, product views, cart and checkout steps) to Bitsnap, so your dashboard can show visits, sources and funnels. By default it is cookieless: it never uses `localStorage`, `sessionStorage` or IndexedDB, events live in memory and the visitor is recognised on the server by a daily-rotating hash that is never stored. The one exception is the consented `bs_vid_<projectKey>` cookie, described in [Returning visitors](#returning-visitors-the-bs_vid_projectkey-cookie).
1106
1155
 
1107
1156
  What an event holds: the event name, a timestamp, the page host and path (no query string, no fragment), the referrer's host, `utm_*` and `ref` from the landing URL, ids of the product/variant/order involved, and a few numbers (price in minor units, quantity). It never holds names, emails, phone numbers, addresses, IPs, coupon codes, form values or free text.
1108
1157
 
1109
- Tracking stays off when `enabled` is `false`, when the browser sends Global Privacy Control (`navigator.globalPrivacyControl`), or when the browser is automated (`navigator.webdriver`). When [Bitsnap Consent](#cookie-consent-bitsnap-consent) is on the page and the visitor rejected analytics, the tracker stops and drops what it had queued. Without a stored choice it keeps going, because it stores nothing on the device.
1158
+ Tracking stays off when `enabled` is `false`, when the browser sends Global Privacy Control (`navigator.globalPrivacyControl`), or when the browser is automated (`navigator.webdriver`). When [Bitsnap Consent](#cookie-consent-bitsnap-consent) is on the page and the visitor rejected analytics, the tracker stops and drops what it had queued. Without a stored choice it keeps going, because it stores nothing on the device (the `bs_vid_<projectKey>` cookie needs a granted choice).
1110
1159
 
1111
1160
  ### Script tag
1112
1161
 
@@ -1114,7 +1163,7 @@ Tracking stays off when `enabled` is `false`, when the browser sends Global Priv
1114
1163
  <script src="https://bitsnap.pl/embed/v1/analytics.js" data-project="pk_…" defer></script>
1115
1164
  ```
1116
1165
 
1117
- The standalone file is `dist/embed/analytics.js` (about 6 KB gzipped, no React). It sends a `page_view` on load and on every `history.pushState`/`replaceState`/back-forward navigation. Attributes: `data-project` (required), `data-env="live|test"`, `data-endpoint` (default `https://collect.bitsnap.pl`), `data-auto="on|off"` (default `on`), `data-page-type="shop|catalog|product|cart|checkout|…"`.
1166
+ The standalone file is `dist/embed/analytics.js` (about 7.8 KB gzipped, no React). It sends a `page_view` on load and when the path changes through `history.pushState`/`replaceState`/back-forward (a change of the query string or hash alone is not a new page). Attributes: `data-project` (required), `data-env="live|test"`, `data-endpoint` (default `https://collect.bitsnap.pl`), `data-auto="on|off"` (default `on`), `data-page-type="shop|catalog|product|cart|checkout|…"`.
1118
1167
 
1119
1168
  Bitsnap's own pages set three more: `data-source="script|storefront|dashboard"` (default `script`), `data-channel="embed|hosted|custom_domain"` (default `embed`) and `data-visitor-id`, a 22-character id that is only honoured with `data-source="dashboard"` (on any other source the collector computes the visitor id itself). With `data-source="dashboard"` the script sends `app_page_view` (with the route) instead of `page_view`. Unknown values fall back to the defaults.
1120
1169
 
@@ -1141,9 +1190,11 @@ function Product({ id }: { id: string }) {
1141
1190
  }
1142
1191
  ```
1143
1192
 
1193
+ The provider sends a `page_view` on mount and on every path change (`pushState`, `replaceState`, Back/Forward), like the script tag. Pass `autoPageViews={false}` to turn that off and call `page()` yourself; otherwise drop your own `page()` calls, or each page is counted twice. The same goes for instrumented components used without a provider: they start the automatic page views too, so a manual `page()` next to them double-counts unless you pass `analytics={false}` to them. An automatic page view carries no page type of its own (a component without a provider supplies its own), so it does not inherit one set by an earlier manual `page(type)`. The page views are a per-page singleton too: the page gets exactly one `page_view` per path change however many providers, instrumented components or `analytics.js` embeds it has.
1194
+
1144
1195
  `useAnalytics()` returns no-ops outside the provider and on the server. `onEvent` receives every event before it is sent, so you can forward it to your own tools after your own consent step; it is not called while tracking is off. The tracker is a per-page singleton: the first provider's `projectKey`, `env` and `endpoint` win.
1145
1196
 
1146
- Without React, use the core directly: `initTracker({ projectKey })` returns the page's tracker (`track`, `page`, `flush`, `setEnabled`, `onEvent`). Events are batched: sent every 5 seconds, at 20 events, and when the page is hidden (`navigator.sendBeacon`, with a `fetch` `keepalive` fallback). Failed sends are not retried.
1197
+ Without React, use the core directly (`startAutoPageViews(() => tracker.page(null))` gives you the same automatic page views): `initTracker({ projectKey })` returns the page's tracker (`track`, `page`, `flush`, `setEnabled`, `onEvent`). Events are batched: sent every 5 seconds, at 20 events, and when the page is hidden (`fetch` with `keepalive`, with `navigator.sendBeacon` as the fallback). Failed sends are not retried.
1147
1198
 
1148
1199
  ### Automatic analytics in components
1149
1200
 
@@ -1155,7 +1206,7 @@ The Bitsnap components report their own events, so a project key is all you need
1155
1206
  <ProductList projectID="…" analytics={{ onEvent: (e) => myTool.track(e.event, e.props), env: "test" }} />
1156
1207
  ```
1157
1208
 
1158
- `onEvent` receives only the events of that component. `env: "test"` events are stored but never reach the merchant's stats. Parts inside a component inherit its setting; a surrounding `<BitsnapAnalyticsProvider>` owns the tracker and its `onEvent` still sees everything. Nothing is written to cookies or Storage, and events carry no personal data (no emails, names, order contents or free text).
1209
+ `onEvent` receives only the events of that component. `env: "test"` events are stored but never reach the merchant's stats. Parts inside a component inherit its setting; a surrounding `<BitsnapAnalyticsProvider>` owns the tracker and its `onEvent` still sees everything (and its `autoPageViews` decides on the page views). Nothing is written to Storage, cookies only as described under [Returning visitors](#returning-visitors-the-bs_vid_projectkey-cookie), and events carry no personal data (no emails, names, order contents or free text).
1159
1210
 
1160
1211
  | Component | Events |
1161
1212
  | --- | --- |
@@ -1168,10 +1219,45 @@ The Bitsnap components report their own events, so a project key is all you need
1168
1219
  | Returns | `return_started`, `return_submitted` |
1169
1220
  | Course | `course_opened`, `lesson_started`, `lesson_completed`, `video_progress` (25/50/75/100% of naturally played time), `test_submitted`, `lesson_rated` |
1170
1221
 
1171
- The components do not emit `page_view`, `product_view`, `checkout_step_completed`, `checkout_validation_error`, `coupon_applied` or `coupon_rejected` (the drawer hands over to the hosted checkout). Use `useAnalytics()` or the embed script for page views. Because the tracker is a per-page singleton, the first project key wins: use one project per page. The course sends nothing in creator preview.
1222
+ Without a `<BitsnapAnalyticsProvider>`, an instrumented component that starts the tracker also sends the automatic `page_view`s (it does not when `analytics={false}`). The components do not emit `product_view`, `checkout_step_completed`, `checkout_validation_error`, `coupon_applied` or `coupon_rejected` (the drawer hands over to the hosted checkout). Use `useAnalytics()` or the embed script for those. Because the tracker is a per-page singleton, the first project key wins: use one project per page. The course sends nothing in creator preview.
1172
1223
 
1173
1224
  For your own components, `useInstrument(projectKey, analytics)` returns the same `{ track }` helper and `<InstrumentProvider value={instrument}>` shares it with the parts below.
1174
1225
 
1226
+ ### Returning visitors: the `bs_vid_<projectKey>` cookie
1227
+
1228
+ Without a cookie the server can only tell visitors apart for one day. When [Bitsnap Consent](#cookie-consent-bitsnap-consent) is on the page and the visitor grants **analytics**, the tracker sets one first-party cookie:
1229
+
1230
+ | | |
1231
+ | --- | --- |
1232
+ | Name | `bs_vid_<projectKey>`, with your bare public project key (like `bitsnap_consent_<projectKey>`). It is per project because consent is: on bitsnap.pl many merchants share one site, and one merchant's consent or refusal must never grant or delete another's id |
1233
+ | Value | 22 random base64url characters (16 bytes from `crypto.getRandomValues`); not derived from anything about the visitor |
1234
+ | Lifetime | 390 days (under the 13 months the CNIL allows), set once and not extended on later visits |
1235
+ | Domain | The widest registrable domain the browser accepts (like Google Analytics), host-only on `localhost` and IP hosts |
1236
+ | Attributes | `Path=/; SameSite=Lax`, plus `Secure` on https |
1237
+ | Set when | Bitsnap Consent reports `analytics` granted, on load or on the `bitsnap:consent` event |
1238
+ | Deleted when | `analytics` is withdrawn or the choice is reset: on the host and every parent domain |
1239
+
1240
+ While analytics is granted and the cookie exists, every event carries it as `client_id`, and the requests that create a checkout or payment link (the cart's `/buy` and `/api/payment/link/auto` calls) send it as the `X-Bitsnap-Visitor` header. The server derives a stable visitor id from it, which lets your stats count returning visitors and credit a purchase to the visit that led to it. Without a granted choice (no banner, a refusal, a choice still loading, Global Privacy Control) there is no cookie, no `client_id` and no header, and tracking stays cookieless as before.
1241
+
1242
+ The cookie only follows a banner that speaks for the project: a project-scope banner (`scope: "project"`) with the same project key, or, on your own site, a site-scope banner. A banner for another project never sets, reads or deletes it, and on bitsnap.pl (and its subdomains) the site-wide choice is bitsnap's own, so only a project-scope choice for your key counts.
1243
+
1244
+ Declare the cookie in your banner's cookie list (category `analytics`, purpose "shop statistics: recognising returning visitors", lifetime 13 months): add `{ name: "Bitsnap statistics", category: "analytics", cookies: ["bs_vid_<projectKey>"] }` to `services` in the banner config, with your exact bare project key, which also lets the banner delete it on withdrawal from pages that run no tracker. Do not use a `bs_vid_*` prefix: the banner deletes every cookie that matches it, which on a site shared by several merchants (bitsnap.pl) would wipe other projects' ids too.
1245
+
1246
+ ### Release notes (1.11.0)
1247
+
1248
+ - **The cart shows why it cannot continue to payment.** When `/buy` fails, the cart shows a localized text for the backend code (no payment gateway, delivery not configured, changed price, mixed subscription cart, unsupported currency), else the server's reason, else `checkoutFailed`. It never shows a bare code such as `internal-error`. Older bitsnap.pl responses are read too.
1249
+ - **`createCheckout` returns an error instead of a broken success.** A failed response returns an `Err` with `status: "error"` (typed `CreateCheckoutResult`) instead of `{ status: "ok", redirectURL: undefined }` or a thrown error. Check `result.status === "ok"` before reading `redirectURL`.
1250
+ - **`createPaymentURL` errors carry the backend code** in `error` (`badInput` for 4xx, `internal` for 5xx) and `data: { message }`, instead of always `internal-error`.
1251
+ - **New checkout text keys** (`checkoutFailed`, `noPaymentGateway`, `gatewayNotConfigured`, `shippingNotConfigured`, `mixedRecurring`, `currencyUnsupported`, `priceChanged`). Type your language objects as `Partial<CheckoutTexts>`.
1252
+
1253
+ ### Release notes (1.10.0)
1254
+
1255
+ - **Requires bitsnap.pl with `X-Bitsnap-Visitor` support.** The cart's `/buy` and `/api/payment/link/auto` requests now send that header while analytics is granted, and a server whose CORS preflight does not allow it makes those checkouts fail in the browser. Deploy bitsnap.pl first, then publish and install this version.
1256
+ - **Page views are now automatic by default.** `<BitsnapAnalyticsProvider>` and instrumented components without a provider send a `page_view` on mount and on every path change. If you call `page()` yourself, pass `autoPageViews={false}` to the provider (and `analytics={false}` to components used without one), or each page is counted twice.
1257
+ - **Update the consent script too.** The tracker only sets `bs_vid_<projectKey>` for a banner that reports its `scope` and `projectKey` (1.10.0 and later); an older consent script is treated as not speaking for the project, so the tracker stays cookieless.
1258
+ - **Update `analytics.js` and the npm package together.** Both share one page-wide registry to send a single `page_view` per path change; an older copy of either does not know about it, and the page is counted twice while both run.
1259
+ - New consented first-party cookie `bs_vid_<projectKey>` and `client_id` on events (see above); declare it in your banner's cookie list by its exact name.
1260
+
1175
1261
  ## Cookie consent (Bitsnap Consent)
1176
1262
 
1177
1263
  An embeddable cookie banner with equal "Accept all" / "Reject all" buttons, per-category settings, light and dark themes, Polish and English texts, and Google Consent Mode v2. It renders in a Shadow DOM, stores only one first-party cookie (`bitsnap_consent`) and never uses `localStorage`.
@@ -1222,6 +1308,8 @@ BitsnapConsent.open(); // settings layer; any [data-bitsnap-cons
1222
1308
  BitsnapConsent.acceptAll(); BitsnapConsent.rejectAll(); BitsnapConsent.accept({ analytics: true });
1223
1309
  BitsnapConsent.reset(); // clears the choice and asks again
1224
1310
  BitsnapConsent.ready; // Promise, resolves once config and the stored choice are applied
1311
+ BitsnapConsent.scope; // "global" (bitsnap_consent) or "project" (bitsnap_consent_<projectKey>)
1312
+ BitsnapConsent.projectKey; // the bare public project key the banner was started with, or null
1225
1313
  ```
1226
1314
 
1227
1315
  `window` also receives `CustomEvent("bitsnap:consent", { detail })` on every choice. Categories missing from `accept()` are denied. When a visitor withdraws a category, the cookies listed in `services[].cookies` are deleted (best effort; a trailing `*` matches a prefix), and the page reloads if `reloadOnWithdraw` is set.
@@ -0,0 +1,2 @@
1
+ import{D as c,E as d,F as e,G as f,H as g,I as h,J as i}from"./chunk-HG4YOJWE.mjs";import"./chunk-H3YP2QPV.mjs";import"./chunk-KOVKUJAW.mjs";import"./chunk-C5RMHUOG.mjs";import"./chunk-C5Q7DGCD.mjs";import{l as a,m as b}from"./chunk-EZWH6BB2.mjs";import"./chunk-T57337WD.mjs";import"./chunk-ADYVTMGH.mjs";import"./chunk-U6FLIRIV.mjs";export{c as MARKETING_AGREEMENT_ID,d as bitsnapProjectID,h as default,i as getCheckoutMethods,b as getLocale,f as getProjectID,a as setLocale,e as setProjectID,g as useCartProvider};
2
+ //# sourceMappingURL=CartProvider-ONIOELW5.mjs.map
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkCUQ2PNCJjs = require('./chunk-CUQ2PNCJ.js');require('./chunk-YFETPEI6.js');require('./chunk-KOYBZORL.js');require('./chunk-VQQBBSK2.js');require('./chunk-ASNUY3EU.js');var _chunk7RGH57QGjs = require('./chunk-7RGH57QG.js');require('./chunk-GT3OH55Y.js');require('./chunk-XIHGWNTS.js');require('./chunk-JSDGZ4NY.js');exports.MARKETING_AGREEMENT_ID = _chunkCUQ2PNCJjs.D; exports.bitsnapProjectID = _chunkCUQ2PNCJjs.E; exports.default = _chunkCUQ2PNCJjs.I; exports.getCheckoutMethods = _chunkCUQ2PNCJjs.J; exports.getLocale = _chunk7RGH57QGjs.m; exports.getProjectID = _chunkCUQ2PNCJjs.G; exports.setLocale = _chunk7RGH57QGjs.l; exports.setProjectID = _chunkCUQ2PNCJjs.F; exports.useCartProvider = _chunkCUQ2PNCJjs.H;
2
+ //# sourceMappingURL=CartProvider-Q3CIVK5K.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/CartProvider-Q3CIVK5K.js"],"names":[],"mappings":"AAAA,+HAAiF,+BAA4B,+BAA4B,+BAA4B,+BAA4B,sDAA+C,+BAA4B,+BAA4B,+BAA4B,8YAAsL","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/CartProvider-Q3CIVK5K.js"}
@@ -1,8 +1,16 @@
1
- import { T as Tracker, a as TrackerOptions, C as ClientEvent } from './instrument-C_abZLHk.mjs';
2
- export { A as AnalyticsOption, d as AppEventName, B as BrowserEventName, e as Channel, D as DEFAULT_ENDPOINT, E as Env, f as EventName, h as EventProps, l as Instrument, I as InstrumentProvider, P as PageType, S as Source, j as StorefrontEventName, b as TrackExtra, c as createTracker, g as getTracker, i as initTracker, n as noopInstrument, r as resetTracker, s as scoreBucket, u as useInstrument, k as useInstrumentContext } from './instrument-C_abZLHk.mjs';
1
+ import { T as Tracker, a as TrackerOptions, C as ClientEvent } from './instrument-CmxK7S4T.mjs';
2
+ export { A as AnalyticsOption, d as AppEventName, B as BrowserEventName, e as Channel, D as DEFAULT_ENDPOINT, E as Env, f as EventName, h as EventProps, l as Instrument, I as InstrumentProvider, P as PageType, S as Source, j as StorefrontEventName, b as TrackExtra, c as createTracker, g as getTracker, i as initTracker, n as noopInstrument, r as resetTracker, s as scoreBucket, u as useInstrument, k as useInstrumentContext } from './instrument-CmxK7S4T.mjs';
3
3
  import * as react from 'react';
4
4
  import { ReactNode } from 'react';
5
5
 
6
+ /**
7
+ * Calls `send` for the current path and again on every path change, unless
8
+ * another starter on the page already reported that path: the page gets one
9
+ * `page_view` per path change however many providers, components and embeds
10
+ * start it. Returns the function that stops this starter.
11
+ */
12
+ declare function startAutoPageViews(send: () => void, win?: Window): () => void;
13
+
6
14
  type AnalyticsApi = Pick<Tracker, "track" | "page">;
7
15
  type BitsnapAnalyticsProviderProps = {
8
16
  /** Public project key (the `projectID` the rest of the SDK uses). */
@@ -13,16 +21,25 @@ type BitsnapAnalyticsProviderProps = {
13
21
  endpoint?: string;
14
22
  /** Called with every event before it is sent, e.g. to forward it to the merchant's own tools. */
15
23
  onEvent?: (event: ClientEvent) => void;
24
+ /**
25
+ * Sends `page_view` on mount and on every path change (`pushState`, `replaceState`, Back/Forward).
26
+ * Default `true`; set `false` to call `page()` yourself.
27
+ */
28
+ autoPageViews?: boolean;
16
29
  children?: ReactNode;
17
30
  };
18
31
  /**
19
32
  * Starts the page's tracker and hands `track` and `page` to `useAnalytics()`.
20
33
  * The tracker is a per-page singleton: the first valid `projectKey` wins, but
21
34
  * `env`, `endpoint` and `enabled` of any provider update the running tracker.
22
- * Nothing is tracked on the server, and nothing is stored on the visitor's device.
35
+ * It sends a `page_view` for the current page and every path change, once per
36
+ * path however many providers, instrumented components or `analytics.js`
37
+ * embeds the page has.
38
+ * Nothing is tracked on the server. The only thing stored on the visitor's
39
+ * device is the `bs_vid_<projectKey>` cookie, and only while Bitsnap Consent grants analytics.
23
40
  */
24
- declare function BitsnapAnalyticsProvider({ projectKey, env, enabled, endpoint, onEvent, children, }: BitsnapAnalyticsProviderProps): react.FunctionComponentElement<react.ProviderProps<AnalyticsApi>>;
41
+ declare function BitsnapAnalyticsProvider({ projectKey, env, enabled, endpoint, onEvent, autoPageViews, children, }: BitsnapAnalyticsProviderProps): react.FunctionComponentElement<react.ProviderProps<AnalyticsApi>>;
25
42
  /** `track` and `page`; no-ops outside a `<BitsnapAnalyticsProvider>`. */
26
43
  declare function useAnalytics(): AnalyticsApi;
27
44
 
28
- export { type AnalyticsApi, BitsnapAnalyticsProvider, type BitsnapAnalyticsProviderProps, ClientEvent, Tracker, TrackerOptions, useAnalytics };
45
+ export { type AnalyticsApi, BitsnapAnalyticsProvider, type BitsnapAnalyticsProviderProps, ClientEvent, Tracker, TrackerOptions, startAutoPageViews, useAnalytics };
@@ -1,8 +1,16 @@
1
- import { T as Tracker, a as TrackerOptions, C as ClientEvent } from './instrument-C_abZLHk.js';
2
- export { A as AnalyticsOption, d as AppEventName, B as BrowserEventName, e as Channel, D as DEFAULT_ENDPOINT, E as Env, f as EventName, h as EventProps, l as Instrument, I as InstrumentProvider, P as PageType, S as Source, j as StorefrontEventName, b as TrackExtra, c as createTracker, g as getTracker, i as initTracker, n as noopInstrument, r as resetTracker, s as scoreBucket, u as useInstrument, k as useInstrumentContext } from './instrument-C_abZLHk.js';
1
+ import { T as Tracker, a as TrackerOptions, C as ClientEvent } from './instrument-CmxK7S4T.js';
2
+ export { A as AnalyticsOption, d as AppEventName, B as BrowserEventName, e as Channel, D as DEFAULT_ENDPOINT, E as Env, f as EventName, h as EventProps, l as Instrument, I as InstrumentProvider, P as PageType, S as Source, j as StorefrontEventName, b as TrackExtra, c as createTracker, g as getTracker, i as initTracker, n as noopInstrument, r as resetTracker, s as scoreBucket, u as useInstrument, k as useInstrumentContext } from './instrument-CmxK7S4T.js';
3
3
  import * as react from 'react';
4
4
  import { ReactNode } from 'react';
5
5
 
6
+ /**
7
+ * Calls `send` for the current path and again on every path change, unless
8
+ * another starter on the page already reported that path: the page gets one
9
+ * `page_view` per path change however many providers, components and embeds
10
+ * start it. Returns the function that stops this starter.
11
+ */
12
+ declare function startAutoPageViews(send: () => void, win?: Window): () => void;
13
+
6
14
  type AnalyticsApi = Pick<Tracker, "track" | "page">;
7
15
  type BitsnapAnalyticsProviderProps = {
8
16
  /** Public project key (the `projectID` the rest of the SDK uses). */
@@ -13,16 +21,25 @@ type BitsnapAnalyticsProviderProps = {
13
21
  endpoint?: string;
14
22
  /** Called with every event before it is sent, e.g. to forward it to the merchant's own tools. */
15
23
  onEvent?: (event: ClientEvent) => void;
24
+ /**
25
+ * Sends `page_view` on mount and on every path change (`pushState`, `replaceState`, Back/Forward).
26
+ * Default `true`; set `false` to call `page()` yourself.
27
+ */
28
+ autoPageViews?: boolean;
16
29
  children?: ReactNode;
17
30
  };
18
31
  /**
19
32
  * Starts the page's tracker and hands `track` and `page` to `useAnalytics()`.
20
33
  * The tracker is a per-page singleton: the first valid `projectKey` wins, but
21
34
  * `env`, `endpoint` and `enabled` of any provider update the running tracker.
22
- * Nothing is tracked on the server, and nothing is stored on the visitor's device.
35
+ * It sends a `page_view` for the current page and every path change, once per
36
+ * path however many providers, instrumented components or `analytics.js`
37
+ * embeds the page has.
38
+ * Nothing is tracked on the server. The only thing stored on the visitor's
39
+ * device is the `bs_vid_<projectKey>` cookie, and only while Bitsnap Consent grants analytics.
23
40
  */
24
- declare function BitsnapAnalyticsProvider({ projectKey, env, enabled, endpoint, onEvent, children, }: BitsnapAnalyticsProviderProps): react.FunctionComponentElement<react.ProviderProps<AnalyticsApi>>;
41
+ declare function BitsnapAnalyticsProvider({ projectKey, env, enabled, endpoint, onEvent, autoPageViews, children, }: BitsnapAnalyticsProviderProps): react.FunctionComponentElement<react.ProviderProps<AnalyticsApi>>;
25
42
  /** `track` and `page`; no-ops outside a `<BitsnapAnalyticsProvider>`. */
26
43
  declare function useAnalytics(): AnalyticsApi;
27
44
 
28
- export { type AnalyticsApi, BitsnapAnalyticsProvider, type BitsnapAnalyticsProviderProps, ClientEvent, Tracker, TrackerOptions, useAnalytics };
45
+ export { type AnalyticsApi, BitsnapAnalyticsProvider, type BitsnapAnalyticsProviderProps, ClientEvent, Tracker, TrackerOptions, startAutoPageViews, useAnalytics };
package/dist/analytics.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkQZJGNLCZjs = require('./chunk-QZJGNLCZ.js');require('./chunk-3UHPJ6NK.js');require('./chunk-JSDGZ4NY.js');exports.BitsnapAnalyticsProvider = _chunkQZJGNLCZjs.g; exports.DEFAULT_ENDPOINT = _chunkQZJGNLCZjs.b; exports.InstrumentProvider = _chunkQZJGNLCZjs.j; exports.createTracker = _chunkQZJGNLCZjs.c; exports.getTracker = _chunkQZJGNLCZjs.e; exports.initTracker = _chunkQZJGNLCZjs.d; exports.noopInstrument = _chunkQZJGNLCZjs.i; exports.resetTracker = _chunkQZJGNLCZjs.f; exports.scoreBucket = _chunkQZJGNLCZjs.p; exports.useAnalytics = _chunkQZJGNLCZjs.h; exports.useInstrument = _chunkQZJGNLCZjs.l; exports.useInstrumentContext = _chunkQZJGNLCZjs.k;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkGT3OH55Yjs = require('./chunk-GT3OH55Y.js');require('./chunk-XIHGWNTS.js');require('./chunk-JSDGZ4NY.js');exports.BitsnapAnalyticsProvider = _chunkGT3OH55Yjs.i; exports.DEFAULT_ENDPOINT = _chunkGT3OH55Yjs.c; exports.InstrumentProvider = _chunkGT3OH55Yjs.l; exports.createTracker = _chunkGT3OH55Yjs.d; exports.getTracker = _chunkGT3OH55Yjs.f; exports.initTracker = _chunkGT3OH55Yjs.e; exports.noopInstrument = _chunkGT3OH55Yjs.k; exports.resetTracker = _chunkGT3OH55Yjs.g; exports.scoreBucket = _chunkGT3OH55Yjs.r; exports.startAutoPageViews = _chunkGT3OH55Yjs.b; exports.useAnalytics = _chunkGT3OH55Yjs.j; exports.useInstrument = _chunkGT3OH55Yjs.n; exports.useInstrumentContext = _chunkGT3OH55Yjs.m;
2
2
  //# sourceMappingURL=analytics.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/analytics.js"],"names":[],"mappings":"AAAA,+HAAoH,+BAA4B,+BAA4B,iiBAA8P","file":"/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/analytics.js"}
1
+ {"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/analytics.js"],"names":[],"mappings":"AAAA,+HAAsH,+BAA4B,+BAA4B,klBAAsR","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/analytics.js"}
@@ -1,2 +1,2 @@
1
- import{b as e,c as r,d as t,e as n,f as o,g as a,h as p,i as s,j as c,k as i,l as m,p as u}from"./chunk-XVQKEGPO.mjs";import"./chunk-E6QVQEGZ.mjs";import"./chunk-U6FLIRIV.mjs";export{a as BitsnapAnalyticsProvider,e as DEFAULT_ENDPOINT,c as InstrumentProvider,r as createTracker,n as getTracker,t as initTracker,s as noopInstrument,o as resetTracker,u as scoreBucket,p as useAnalytics,m as useInstrument,i as useInstrumentContext};
1
+ import{b as e,c as t,d as r,e as n,f as o,g as a,i as s,j as p,k as c,l as i,m,n as u,r as v}from"./chunk-T57337WD.mjs";import"./chunk-ADYVTMGH.mjs";import"./chunk-U6FLIRIV.mjs";export{s as BitsnapAnalyticsProvider,t as DEFAULT_ENDPOINT,i as InstrumentProvider,r as createTracker,o as getTracker,n as initTracker,c as noopInstrument,a as resetTracker,v as scoreBucket,e as startAutoPageViews,p as useAnalytics,u as useInstrument,m as useInstrumentContext};
2
2
  //# sourceMappingURL=analytics.mjs.map
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode } from 'react';
3
- import { A as AnalyticsOption } from './instrument-C_abZLHk.mjs';
3
+ import { A as AnalyticsOption } from './instrument-CmxK7S4T.mjs';
4
4
  import { S as SlotAppearance, A as AppearanceElements } from './appearance-core-Dt2grZdl.mjs';
5
5
  import { BitsnapModels } from './models.mjs';
6
6
  import 'zod';
package/dist/catalog.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode } from 'react';
3
- import { A as AnalyticsOption } from './instrument-C_abZLHk.js';
3
+ import { A as AnalyticsOption } from './instrument-CmxK7S4T.js';
4
4
  import { S as SlotAppearance, A as AppearanceElements } from './appearance-core-Dt2grZdl.js';
5
5
  import { BitsnapModels } from './models.js';
6
6
  import 'zod';
package/dist/catalog.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkVM6JEJFZjs = require('./chunk-VM6JEJFZ.js');require('./chunk-KOYBZORL.js');require('./chunk-CO2P4FR5.js');require('./chunk-QZJGNLCZ.js');require('./chunk-3UHPJ6NK.js');require('./chunk-JSDGZ4NY.js');exports.PRODUCT_LIST_SLOT_NAMES = _chunkVM6JEJFZjs.a; exports.ProductList = _chunkVM6JEJFZjs.d; exports.formatProductPrice = _chunkVM6JEJFZjs.b; exports.useProducts = _chunkVM6JEJFZjs.c;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkPUYK4YHEjs = require('./chunk-PUYK4YHE.js');require('./chunk-KOYBZORL.js');require('./chunk-7RGH57QG.js');require('./chunk-GT3OH55Y.js');require('./chunk-XIHGWNTS.js');require('./chunk-JSDGZ4NY.js');exports.PRODUCT_LIST_SLOT_NAMES = _chunkPUYK4YHEjs.a; exports.ProductList = _chunkPUYK4YHEjs.d; exports.formatProductPrice = _chunkPUYK4YHEjs.b; exports.useProducts = _chunkPUYK4YHEjs.c;
2
2
  //# sourceMappingURL=catalog.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/catalog.js"],"names":[],"mappings":"AAAA,+HAA4D,+BAA4B,+BAA4B,+BAA4B,+BAA4B,+BAA4B,0LAA+F","file":"/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/catalog.js"}
1
+ {"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/catalog.js"],"names":[],"mappings":"AAAA,+HAA4D,+BAA4B,+BAA4B,+BAA4B,+BAA4B,+BAA4B,0LAA+F","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/catalog.js"}
package/dist/catalog.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{a as o,b as r,c as e,d as f}from"./chunk-SLLBTQTW.mjs";import"./chunk-KOVKUJAW.mjs";import"./chunk-RA452LXZ.mjs";import"./chunk-XVQKEGPO.mjs";import"./chunk-E6QVQEGZ.mjs";import"./chunk-U6FLIRIV.mjs";export{o as PRODUCT_LIST_SLOT_NAMES,f as ProductList,r as formatProductPrice,e as useProducts};
1
+ import{a as o,b as r,c as e,d as f}from"./chunk-GPNALARZ.mjs";import"./chunk-KOVKUJAW.mjs";import"./chunk-EZWH6BB2.mjs";import"./chunk-T57337WD.mjs";import"./chunk-ADYVTMGH.mjs";import"./chunk-U6FLIRIV.mjs";export{o as PRODUCT_LIST_SLOT_NAMES,f as ProductList,r as formatProductPrice,e as useProducts};
2
2
  //# sourceMappingURL=catalog.mjs.map
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkGT3OH55Yjs = require('./chunk-GT3OH55Y.js');var l="X-Bitsnap-Client",s=`bitsnap-react@${_chunkGT3OH55Yjs.a}`,g="bs_client",w= exports.a ={[l]:s},K= exports.b =e=>t=>(t.header.set(l,s),e(t));function z(e){let t=e.indexOf("#"),n=t===-1?e:e.slice(0,t),a=t===-1?"":e.slice(t),r=n.includes("?")?/[?&]$/.test(n)?"":"&":"?";return`${n}${r}${g}=${encodeURIComponent(s)}${a}`}var d="https://bitsnap.pl",T= exports.f =d;function j(e){console.log("setCustomHost",e),T= exports.f =e}function x(e,t){return t.toLowerCase().startsWith("en")?e.en:e.pl}function f(e,t){let n={...e};if(t!=null)for(let[a,r]of Object.entries(t))r!=null&&(n[a]=r);return n}function u(e,t,n){return f(x(e,t),n)}function y(e,t){return _nullishCoalesce(e[t], () => (t))}var h={en:{cart:"Cart",emptyCart:"Your cart is empty.",total:"Total:",delivery:"+ delivery",chooseCountry:"Choose a country",nextStep:"Next step",unavailableProducts:"Not all products are available.",checkoutFailed:"Something went wrong. Please try again later.",noPaymentGateway:"This shop doesn't accept online payments yet. Try again later or contact the seller.",gatewayNotConfigured:"Payments in this shop are not set up correctly. Try again later or contact the seller.",shippingNotConfigured:"Delivery in this shop is not configured yet. Try again later or contact the seller.",mixedRecurring:"Subscriptions and one-time products cannot be paid for together. Pay for them in separate orders.",currencyUnsupported:"The shop doesn't accept payments in this currency. Contact the seller.",priceChanged:"The product price has changed. Refresh the page to see the current price."},pl:{cart:"Koszyk",emptyCart:"Brak produkt\xF3w w koszyku.",total:"Suma:",delivery:"+ dostawa",chooseCountry:"Wybierz kraj",nextStep:"Nast\u0119pny krok",unavailableProducts:"Nie wszystkie produkty s\u0105 dost\u0119pne w magazynie.",checkoutFailed:"Co\u015B posz\u0142o nie tak. Spr\xF3buj ponownie p\xF3\u017Aniej.",noPaymentGateway:"Ten sklep nie przyjmuje jeszcze p\u0142atno\u015Bci online. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",gatewayNotConfigured:"P\u0142atno\u015Bci w tym sklepie nie s\u0105 poprawnie skonfigurowane. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",shippingNotConfigured:"Dostawa w tym sklepie nie jest jeszcze skonfigurowana. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",mixedRecurring:"Subskrypcji i produkt\xF3w jednorazowych nie mo\u017Cna op\u0142aci\u0107 razem. Op\u0142a\u0107 je w osobnych zam\xF3wieniach.",currencyUnsupported:"Sklep nie przyjmuje p\u0142atno\u015Bci w tej walucie. Skontaktuj si\u0119 ze sprzedawc\u0105.",priceChanged:"Cena produktu si\u0119 zmieni\u0142a. Od\u015Bwie\u017C stron\u0119, aby zobaczy\u0107 aktualn\u0105 cen\u0119."}};function m(e,t){return u(h,e,t)}function R(e,t,n){return y(m(t,n),e)}var i="pl-PL",c="bitsnap-locale",o;function N(e){let t=_optionalChain([e, 'optionalAccess', _2 => _2.trim, 'call', _3 => _3()]);o=t?t.toLowerCase()==="en"?"en-US":t.toLowerCase()==="pl"?i:t:void 0,typeof localStorage<"u"&&(o==null?localStorage.removeItem(c):localStorage.setItem(c,o))}function _(){return _nullishCoalesce(o, () => ((typeof localStorage<"u"?_nullishCoalesce(localStorage.getItem(c), () => (i)):i)))}var _clsx = require('clsx');var _tailwindmerge = require('tailwind-merge');function U(...e){return _tailwindmerge.twMerge.call(void 0, _clsx.clsx.call(void 0, e))}exports.a = w; exports.b = K; exports.c = z; exports.d = U; exports.e = d; exports.f = T; exports.g = j; exports.h = x; exports.i = u; exports.j = R; exports.k = i; exports.l = N; exports.m = _;
2
+ //# sourceMappingURL=chunk-7RGH57QG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-7RGH57QG.js","../src/lib/client-header.ts"],"names":["CLIENT_HEADER_NAME","CLIENT_HEADER_VALUE","SDK_VERSION"],"mappings":"AAAA,uuBAAuC,ICG1BA,CAAAA,CAAqB,kBAAA,CACrBC,CAAAA,CAAsB,CAAA,cAAA,EAAiBC,kBAAW,CAAA,CAAA","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-7RGH57QG.js","sourcesContent":[null,"import type { Interceptor } from \"@connectrpc/connect\";\nimport { SDK_VERSION } from \"../version\";\n\nexport const CLIENT_HEADER_NAME = \"X-Bitsnap-Client\";\nexport const CLIENT_HEADER_VALUE = `bitsnap-react@${SDK_VERSION}`;\n\nexport const CLIENT_QUERY_PARAM = \"bs_client\";\n\n/**\n * Spread into the `headers` of a fetch that already triggers a CORS preflight\n * (JSON POST, Connect RPC). Never use it on a simple cross-origin GET: the\n * custom header would force a preflight that older servers and merchant\n * proxies do not allow. Use `withClientParam` there.\n */\nexport const clientHeaders: Record<string, string> = {\n [CLIENT_HEADER_NAME]: CLIENT_HEADER_VALUE,\n};\n\n/** Connect interceptor adding the client header to every RPC. */\nexport const clientHeaderInterceptor: Interceptor = (next) => (req) => {\n req.header.set(CLIENT_HEADER_NAME, CLIENT_HEADER_VALUE);\n return next(req);\n};\n\n/** Adds `bs_client=<pkg>@<ver>` to a URL, for simple GETs that must stay preflight-free. */\nexport function withClientParam(url: string): string {\n const hash = url.indexOf(\"#\");\n const base = hash === -1 ? url : url.slice(0, hash);\n const fragment = hash === -1 ? \"\" : url.slice(hash);\n const separator = base.includes(\"?\") ? (/[?&]$/.test(base) ? \"\" : \"&\") : \"?\";\n return `${base}${separator}${CLIENT_QUERY_PARAM}=${encodeURIComponent(CLIENT_HEADER_VALUE)}${fragment}`;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ var s={maxBatchEvents:50,maxBodyBytes:65536,maxPropsChars:4096,maxPropString:200,maxPropArray:50,host:253,path:512,referrerHost:253,utm:100,refCode:64,id:64,sdk:64,pageId:32,region:64,osBrowser:32,tsSkewMs:864e5},w=["storefront_events","app_events","business_events"],N=["live","test"],A=["storefront","sdk_react","script","server","dashboard"],P=["hosted","custom_domain","embed","api","panel"],$=["shop","catalog","product","cart","checkout","payment","panel","course","custom_page","order","returns","app","other"];var T={storefront_events:["storefront","sdk_react","script"],app_events:["dashboard"],business_events:["server"]},_={value_minor:"number",currency:"string"},h={page_view:{landing:"boolean"},product_list_viewed:{list_id:"string?",item_count:"number"},product_impression:{list_id:"string?",product_ids:"string[]",positions:"number[]"},product_clicked:{list_id:"string?",position:"number?"},product_view:{price_minor:"number",currency:"string",availability:"enum:in_stock|out_of_stock|preorder"},variant_selected:{},add_to_cart:{qty:"number",..._},remove_from_cart:{qty:"number",..._},cart_opened:{item_count:"number",..._},checkout_started:{item_count:"number",checkout_type:"enum:single|cart|link",..._},checkout_step_completed:{step:"enum:contact|delivery|invoice|consents"},checkout_validation_error:{field:"string",rule:"string"},coupon_applied:{coupon_id:"string"},coupon_rejected:{coupon_id:"string?",reason:"string"},delivery_method_selected:{method:"string"},payment_method_selected:{gateway:"string",method:"string"},payment_submitted:{gateway:"string",method:"string"},apple_pay_clicked:{},apple_pay_result:{outcome:"enum:success|fail|cancel"},payment_returned:{gateway:"string",method:"string?",outcome:"enum:success|fail|cancel|pending",error_code:"string?"},availability_signup:{},panel_login:{},panel_order_viewed:{},panel_download:{},return_started:{},return_submitted:{reason_code:"string",item_count:"number"},course_opened:{course_id:"string"},lesson_started:{course_id:"string",lesson_id:"string",position:"number"},lesson_completed:{course_id:"string",lesson_id:"string",position:"number"},video_progress:{course_id:"string",lesson_id:"string",milestone:"number"},test_submitted:{course_id:"string",lesson_id:"string",score_bucket:"enum:0-24|25-49|50-74|75-99|100"},lesson_rated:{course_id:"string",lesson_id:"string",rating:"number"},consent_updated:{consent_id:"string",action:"enum:accept_all|reject_all|custom|withdraw",analytics:"boolean",marketing:"boolean",preferences:"boolean",banner_version:"number"}},E={app_page_view:{route:"string",previous_route:"string?"},insight_shown:{insight_type:"string",rank:"number",category:"string"},insight_clicked:{insight_type:"string",rank:"number",category:"string"},insight_dismissed:{insight_type:"string",rank:"number",category:"string"},checklist_step_viewed:{step:"string"},checklist_step_completed:{step:"string"},gateway_connect_started:{gateway:"string",step:"string?"},gateway_connect_completed:{gateway:"string",step:"string?"},gateway_connect_failed:{gateway:"string",step:"string?",error_code:"string?"},domain_connect_started:{},domain_connect_verified:{},domain_connect_failed:{error_code:"string?"},product_created:{product_type:"string?"},product_published:{product_type:"string?"},product_editor_section_opened:{section:"string"},feature_enabled:{feature:"string"},stats_viewed:{tab:"string"},stats_filter_changed:{tab:"string",filter:"string"},report_exported:{report:"string",format:"string?"},search_performed:{result_count:"number"},error_shown:{code:"string",route:"string"},help_opened:{topic:"string?"},ai_assistant_used:{topic:"string?"},member_invited:{role:"string"}},d={gateway:"string?",method:"string?",value_minor:"number?",currency:"string?"},u={subscription_id:"string?",value_minor:"number?",currency:"string?"},S={transaction_created:d,transaction_success:d,transaction_failure:{...d,error_code:"string?"},transaction_expired:d,transaction_charge:d,subscription_created:u,subscription_paused:u,subscription_resumed:u,subscription_updated:u,subscription_deleted:u,subscription_charge_paid:u,subscription_charge_failed:{...u,error_code:"string?"},subscription_past_due:u,subscription_canceled:u,access_expires_in_3_days:{},access_expired:{},cart_recovery:{value_minor:"number?",currency:"string?"},testimonial_email_send:{},testimonial_fulfilled:{},partner_commission_earned:{partner_id:"string",commission_minor:"number",currency:"string"},checkout_session_created:{item_count:"number",checkout_type:"enum:single|cart|link",gateway:"string?",..._},order_paid:{gateway:"string",method:"string?",item_count:"number?",visitor_day:"string?",items:"line_items?",..._},refund_issued:{gateway:"string?",reason:"string?",..._},return_requested:{item_count:"number",reason_code:"string?"},automation_run_completed:{automation_id:"string",status:"string",trigger:"string?"},notification_sent:{medium:"string",template:"string?"},notification_failed:{medium:"string",template:"string?",error_code:"string?"},recovery_email_sent:{step:"number?"},recovery_link_clicked:{},api_request:{endpoint:"string",client:"string?",status:"number",latency_bucket:"enum:lt_50|lt_200|lt_1000|gte_1000",sample_rate:"number"}};var O={...h,...E,...S},R={storefront_events:Object.keys(h),app_events:Object.keys(E),business_events:Object.keys(S)},v=Object.fromEntries(w.flatMap(t=>R[t].map(e=>[e,t])));function x(t){return typeof t=="string"&&Object.hasOwn(v,t)}var et=365*24*60*60;function nt(t){let e=t.startsWith("pk_")?t.slice(3):t;return/^[A-Za-z0-9]{1,32}$/.test(e)?e:null}var I=/^([a-z][a-z0-9-]{0,39})@(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]{1,20})?)$/;function k(t){if(!t||t.length>s.sdk)return null;let e=I.exec(t);return e?{package:e[1],version:e[2]}:null}var m=s.utm;function g(t,e){if(t==null)return null;let r=t.trim();return r.length===0||r.includes("@")?null:r.slice(0,e)}function M(t){let r=t.split("/").map(n=>n.includes("@")||n.includes("%40")?":email":/^[A-Za-z0-9_-]{24,}$/.test(n)?":token":n).join("/")||"/";return(r.startsWith("/")?r:`/${r}`).slice(0,s.path)}function rt(t,e){let r;try{r=new URL(t,e)}catch{return null}if(r.protocol!=="https:"&&r.protocol!=="http:")return null;let n=r.searchParams;return{host:r.hostname.toLowerCase().slice(0,s.host),path:M(r.pathname),utm_source:g(n.get("utm_source"),m),utm_medium:g(n.get("utm_medium"),m),utm_campaign:g(n.get("utm_campaign"),m),utm_content:g(n.get("utm_content"),m),utm_term:g(n.get("utm_term"),m),ref_code:g(n.get("ref"),s.refCode)}}var U=/^[A-Za-z0-9_-]{1,64}$/;function st(t){if(!t)return null;try{let e=new URL(t);return e.protocol!=="https:"&&e.protocol!=="http:"?null:e.hostname.toLowerCase().slice(0,s.referrerHost)}catch{return null}}var ot=new TextEncoder;function it(t){return`bs_vid_${t}`}var V=/^[A-Za-z0-9_-]{22}$/;var D=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,L=/^[A-Za-z0-9_-]{8,32}$/,j=/[^\s@]+@[^\s@]+\.[A-Za-z]{2,}\b/;function f(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function z(t,e,r){let n=t[e];return n==null?null:typeof n!="string"?`bad_${e}`:n.length>r?`too_long_${e}`:null}function B(t,e){let n=t.endsWith("?")?t.slice(0,-1):t;if(n.startsWith("enum:"))return typeof e=="string"&&n.slice(5).split("|").includes(e);switch(n){case"string":return typeof e=="string"&&e.length<=s.maxPropString;case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"string[]":return Array.isArray(e)&&e.length<=s.maxPropArray&&e.every(o=>typeof o=="string"&&o.length<=s.maxPropString);case"number[]":return Array.isArray(e)&&e.length<=s.maxPropArray&&e.every(o=>typeof o=="number"&&Number.isFinite(o));case"line_items":return Array.isArray(e)&&e.length<=s.maxPropArray&&e.every(o=>f(o)&&typeof o.product_id=="string"&&U.test(o.product_id)&&b(o.qty)&&b(o.value_minor));default:return!1}}function b(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}function K(t){return k(t)!==null?!1:j.test(t)}function y(t){return typeof t=="string"?K(t):Array.isArray(t)?t.some(y):f(t)?Object.values(t).some(y):!1}function H(t,e){if(!x(t))return{ok:!1,reason:"unknown_event"};let r=O[t];if(!r)return{ok:!1,reason:"unknown_event"};if(!f(e))return{ok:!1,reason:"bad_props"};let n={};for(let[o,c]of Object.entries(r)){let a=e[o];if(a==null){if(!c.endsWith("?"))return{ok:!1,reason:`props_missing_${o}`};continue}if(!B(c,a))return{ok:!1,reason:`props_bad_${o}`};if(y(a))return{ok:!1,reason:`props_pii_${o}`};n[o]=c.startsWith("line_items")&&Array.isArray(a)?a.map(i=>({product_id:i.product_id,qty:i.qty,value_minor:i.value_minor})):a}return JSON.stringify(n).length>s.maxPropsChars?{ok:!1,reason:"props_too_large"}:{ok:!0,props:n}}function at(t,e={}){let r=e.from??"browser",n=i=>({ok:!1,reason:i});if(!f(t))return n("not_object");if(typeof t.event_id!="string"||!D.test(t.event_id))return n("bad_event_id");if(!x(t.event))return n("unknown_event");let o=v[t.event];if(r==="browser"){if(o==="business_events")return n("server_only_event");if(t.event==="consent_updated")return n("consent_via_consent_endpoint")}if(typeof t.ts!="number"||!Number.isInteger(t.ts)||t.ts<=0||t.ts>4e12)return n("bad_ts");if(t.schema_version!==1)return n("bad_schema_version");if(!N.includes(t.env))return n("bad_env");if(!A.includes(t.source))return n("bad_source");if(!T[o].includes(t.source))return n("source_not_allowed_for_event");if(!P.includes(t.channel))return n("bad_channel");if(t.sdk!=null&&(typeof t.sdk!="string"||k(t.sdk)===null))return n("bad_sdk");if(t.page_id!=null&&(typeof t.page_id!="string"||!L.test(t.page_id)))return n("bad_page_id");if(t.page_type!=null&&!$.includes(t.page_type))return n("bad_page_type");if(r==="browser"){if(typeof t.host!="string"||t.host.length===0)return n("bad_host");if(typeof t.path!="string"||!t.path.startsWith("/"))return n("bad_path")}if(typeof t.path=="string"&&t.path.includes("?"))return n("path_has_query");if(typeof t.path=="string"&&t.path.includes("#"))return n("path_has_fragment");let c=[["host",s.host],["path",s.path],["referrer_host",s.referrerHost],["utm_source",s.utm],["utm_medium",s.utm],["utm_campaign",s.utm],["utm_content",s.utm],["utm_term",s.utm],["ref_code",s.refCode],["product_id",s.id],["variant_id",s.id],["order_ref",s.id]];for(let[i,p]of c){let l=z(t,i,p);if(l)return n(l)}if(t.visitor_id!=null&&(typeof t.visitor_id!="string"||!/^[A-Za-z0-9_-]{22}$/.test(t.visitor_id)))return n("bad_visitor_id");if(t.client_id!=null&&(typeof t.client_id!="string"||!V.test(t.client_id)))return n("bad_client_id");let a=H(t.event,t.props);return a.ok?{ok:!0}:n(a.reason)}var C="bitsnap_consent";function ut(t,e){return e==="project"&&t?`${C}_${t.replace(/[^A-Za-z0-9_-]/g,"_")}`:C}function q(t){return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Y(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return atob(e+"=".repeat((4-e.length%4)%4))}function W(t){return q(JSON.stringify({v:1,id:t.id,ts:t.ts,bv:t.bv,c:t.c}))}function Z(t){try{let e=JSON.parse(Y(t));return!e||e.v!==1||typeof e.id!="string"||e.id===""||typeof e.ts!="number"||typeof e.bv!="number"||!e.c||typeof e.c.analytics!="boolean"||typeof e.c.marketing!="boolean"||typeof e.c.preferences!="boolean"?null:{id:e.id,ts:e.ts,bv:e.bv,c:{analytics:e.c.analytics,marketing:e.c.marketing,preferences:e.c.preferences}}}catch{return null}}function F(t,e,r){return`${t}=${W(e)}; Max-Age=31536000; Path=/; SameSite=Lax`+(r?"; Secure":"")}function X(t){return t.split(";").map(e=>e.split("=")[0].trim()).filter(Boolean)}function G(t,e){for(let r of t.split(";")){let n=r.indexOf("=");if(n!==-1&&r.slice(0,n).trim()===e)return Z(r.slice(n+1).trim())}return null}function lt(){try{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch{}let t="";for(let e=0;e<32;e++)t+=Math.floor(Math.random()*16).toString(16);return t}function pt(t,e){try{return G(t.cookie,e)}catch{return null}}function _t(t,e,r){try{t.cookie=F(e,r,t.location?.protocol==="https:")}catch{}}function gt(t,e){try{t.cookie=`${e}=; Max-Age=0; Path=/; SameSite=Lax`}catch{}}function J(t){if(!t||/^[\d.]+$/.test(t)||t.includes(":"))return[];let e=t.split("."),r=[];for(let n=0;n<=e.length-2;n++)r.push(e.slice(n).join("."));return r}function dt(t,e,r){try{let n=e.filter(i=>r.includes(i.category)).flatMap(i=>i.cookies??[]);if(n.length===0)return;let o=X(t.cookie),c=new Set;for(let i of n)if(i.endsWith("*")){let p=i.slice(0,-1);for(let l of o)l.startsWith(p)&&c.add(l)}else c.add(i);let a=J(t.location?.hostname??"");for(let i of c){let p=`${encodeURIComponent(i)}=; Max-Age=0; Path=/`;t.cookie=p;for(let l of a)t.cookie=`${p}; Domain=${l}`,t.cookie=`${p}; Domain=.${l}`}}catch{}}import{useEffect as Q,useLayoutEffect as tt}from"react";function yt(t,e){(typeof window<"u"?tt:Q)(t,e)}export{s as a,nt as b,M as c,rt as d,st as e,it as f,H as g,at as h,ut as i,lt as j,pt as k,_t as l,gt as m,J as n,dt as o,yt as p};
2
+ //# sourceMappingURL=chunk-ADYVTMGH.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/analytics/contract.ts","../src/consent/core/cookie.ts","../src/lib/isomorphic-layout-effect.ts"],"sourcesContent":["/**\n * Bitsnap merchant analytics: the wire contract.\n *\n * SOURCE OF TRUTH: instapay `apps/collector/src/contract.ts` (prose version:\n * `docs/merchant-analytics-contract.md`). This file is a verbatim copy of it\n * (everything below the next comment block). Do not edit it here: change\n * instapay's file and copy it over. `computeVisitorId` and\n * `computeConsentedVisitorId` are pure but need the server secret; they are\n * server-only: the browser never calls them, so bundlers drop them.\n */\n\nexport const SCHEMA_VERSION = 1;\n\n// ---------------------------------------------------------------------------\n// Limits\n// ---------------------------------------------------------------------------\n\nexport const LIMITS = {\n /** Events in one POST /e. */\n maxBatchEvents: 50,\n /** Body of one POST /e or /consent, in bytes. */\n maxBodyBytes: 64 * 1024,\n /** `JSON.stringify(props)` of one event, in UTF-16 code units. */\n maxPropsChars: 4096,\n maxPropString: 200,\n maxPropArray: 50,\n host: 253,\n path: 512,\n referrerHost: 253,\n utm: 100,\n refCode: 64,\n id: 64,\n sdk: 64,\n pageId: 32,\n region: 64,\n osBrowser: 32,\n /** Collector replaces a client `ts` farther than this from `received_at`. */\n tsSkewMs: 24 * 60 * 60 * 1000,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Enumerations\n// ---------------------------------------------------------------------------\n\nexport const STREAMS = [\n \"storefront_events\",\n \"app_events\",\n \"business_events\",\n] as const;\nexport type Stream = (typeof STREAMS)[number];\n\nexport const ENVS = [\"live\", \"test\"] as const;\nexport type Env = (typeof ENVS)[number];\n\nexport const SOURCES = [\n \"storefront\",\n \"sdk_react\",\n \"script\",\n \"server\",\n \"dashboard\",\n] as const;\nexport type Source = (typeof SOURCES)[number];\n\nexport const CHANNELS = [\n \"hosted\",\n \"custom_domain\",\n \"embed\",\n \"api\",\n \"panel\",\n] as const;\nexport type Channel = (typeof CHANNELS)[number];\n\nexport const PAGE_TYPES = [\n \"shop\",\n \"catalog\",\n \"product\",\n \"cart\",\n \"checkout\",\n \"payment\",\n \"panel\",\n \"course\",\n \"custom_page\",\n \"order\",\n \"returns\",\n \"app\",\n \"other\",\n] as const;\nexport type PageType = (typeof PAGE_TYPES)[number];\n\nexport const DEVICE_TYPES = [\"desktop\", \"mobile\", \"tablet\", \"other\"] as const;\nexport type DeviceType = (typeof DEVICE_TYPES)[number];\n\n/** Sources a browser may claim, per stream. `business_events` is server-only. */\nexport const SOURCES_FOR_STREAM: Record<Stream, readonly Source[]> = {\n storefront_events: [\"storefront\", \"sdk_react\", \"script\"],\n app_events: [\"dashboard\"],\n business_events: [\"server\"],\n};\n\n// ---------------------------------------------------------------------------\n// Event catalogue\n//\n// Each prop is `<type>[?]`: type is `string`, `number`, `boolean`, `string[]`,\n// `number[]` or `enum:a|b|c`; a trailing `?` makes the prop optional.\n// Money is always integer minor units (`*_minor`, grosze/cents) + `currency`\n// (ISO 4217, upper case). `product_id`, `variant_id` and `order_ref` live in\n// the envelope, never in props. Strings never hold PII (see the prose doc).\n// ---------------------------------------------------------------------------\n\nconst MONEY = { value_minor: \"number\", currency: \"string\" } as const;\n\n/** Browser events from hosted pages (H), bitsnap-react (R) and the script (S). */\nexport const STOREFRONT_EVENT_SPEC = {\n page_view: { landing: \"boolean\" },\n product_list_viewed: { list_id: \"string?\", item_count: \"number\" },\n product_impression: {\n list_id: \"string?\",\n product_ids: \"string[]\",\n positions: \"number[]\",\n },\n product_clicked: { list_id: \"string?\", position: \"number?\" },\n product_view: {\n price_minor: \"number\",\n currency: \"string\",\n availability: \"enum:in_stock|out_of_stock|preorder\",\n },\n variant_selected: {},\n add_to_cart: { qty: \"number\", ...MONEY },\n remove_from_cart: { qty: \"number\", ...MONEY },\n cart_opened: { item_count: \"number\", ...MONEY },\n checkout_started: {\n item_count: \"number\",\n checkout_type: \"enum:single|cart|link\",\n ...MONEY,\n },\n checkout_step_completed: {\n step: \"enum:contact|delivery|invoice|consents\",\n },\n checkout_validation_error: { field: \"string\", rule: \"string\" },\n coupon_applied: { coupon_id: \"string\" },\n coupon_rejected: { coupon_id: \"string?\", reason: \"string\" },\n delivery_method_selected: { method: \"string\" },\n payment_method_selected: { gateway: \"string\", method: \"string\" },\n payment_submitted: { gateway: \"string\", method: \"string\" },\n apple_pay_clicked: {},\n apple_pay_result: { outcome: \"enum:success|fail|cancel\" },\n payment_returned: {\n gateway: \"string\",\n method: \"string?\",\n outcome: \"enum:success|fail|cancel|pending\",\n error_code: \"string?\",\n },\n availability_signup: {},\n panel_login: {},\n panel_order_viewed: {},\n panel_download: {},\n return_started: {},\n return_submitted: { reason_code: \"string\", item_count: \"number\" },\n course_opened: { course_id: \"string\" },\n lesson_started: {\n course_id: \"string\",\n lesson_id: \"string\",\n position: \"number\",\n },\n lesson_completed: {\n course_id: \"string\",\n lesson_id: \"string\",\n position: \"number\",\n },\n video_progress: {\n course_id: \"string\",\n lesson_id: \"string\",\n /** 25, 50, 75 or 100. */\n milestone: \"number\",\n },\n test_submitted: {\n course_id: \"string\",\n lesson_id: \"string\",\n score_bucket: \"enum:0-24|25-49|50-74|75-99|100\",\n },\n lesson_rated: {\n course_id: \"string\",\n lesson_id: \"string\",\n /** 1..5. */\n rating: \"number\",\n },\n /** Written by the collector's POST /consent, never sent to POST /e. */\n consent_updated: {\n consent_id: \"string\",\n action: \"enum:accept_all|reject_all|custom|withdraw\",\n analytics: \"boolean\",\n marketing: \"boolean\",\n preferences: \"boolean\",\n banner_version: \"number\",\n },\n} as const;\n\n/** Merchant behaviour in /app, sent through the same tracker core. */\nexport const APP_EVENT_SPEC = {\n app_page_view: { route: \"string\", previous_route: \"string?\" },\n insight_shown: { insight_type: \"string\", rank: \"number\", category: \"string\" },\n insight_clicked: {\n insight_type: \"string\",\n rank: \"number\",\n category: \"string\",\n },\n insight_dismissed: {\n insight_type: \"string\",\n rank: \"number\",\n category: \"string\",\n },\n checklist_step_viewed: { step: \"string\" },\n checklist_step_completed: { step: \"string\" },\n gateway_connect_started: { gateway: \"string\", step: \"string?\" },\n gateway_connect_completed: { gateway: \"string\", step: \"string?\" },\n gateway_connect_failed: {\n gateway: \"string\",\n step: \"string?\",\n error_code: \"string?\",\n },\n domain_connect_started: {},\n domain_connect_verified: {},\n domain_connect_failed: { error_code: \"string?\" },\n product_created: { product_type: \"string?\" },\n product_published: { product_type: \"string?\" },\n product_editor_section_opened: { section: \"string\" },\n feature_enabled: { feature: \"string\" },\n stats_viewed: { tab: \"string\" },\n stats_filter_changed: { tab: \"string\", filter: \"string\" },\n report_exported: { report: \"string\", format: \"string?\" },\n search_performed: { result_count: \"number\" },\n error_shown: { code: \"string\", route: \"string\" },\n help_opened: { topic: \"string?\" },\n ai_assistant_used: { topic: \"string?\" },\n member_invited: { role: \"string\" },\n} as const;\n\nconst TX = {\n gateway: \"string?\",\n method: \"string?\",\n value_minor: \"number?\",\n currency: \"string?\",\n} as const;\nconst SUB = {\n subscription_id: \"string?\",\n value_minor: \"number?\",\n currency: \"string?\",\n} as const;\n\n/**\n * Emitted by instapay only. The lower-cased `EventType` of\n * server/event-system/event.list.ts maps 1:1 to the first group.\n */\nexport const BUSINESS_EVENT_SPEC = {\n // Mirror of the event bus (EventType.X -> x.toLowerCase()).\n transaction_created: TX,\n transaction_success: TX,\n transaction_failure: { ...TX, error_code: \"string?\" },\n transaction_expired: TX,\n transaction_charge: TX,\n subscription_created: SUB,\n subscription_paused: SUB,\n subscription_resumed: SUB,\n subscription_updated: SUB,\n subscription_deleted: SUB,\n subscription_charge_paid: SUB,\n subscription_charge_failed: { ...SUB, error_code: \"string?\" },\n subscription_past_due: SUB,\n subscription_canceled: SUB,\n access_expires_in_3_days: {},\n access_expired: {},\n cart_recovery: { value_minor: \"number?\", currency: \"string?\" },\n testimonial_email_send: {},\n testimonial_fulfilled: {},\n partner_commission_earned: {\n partner_id: \"string\",\n commission_minor: \"number\",\n currency: \"string\",\n },\n // Added by the analytics work.\n checkout_session_created: {\n item_count: \"number\",\n checkout_type: \"enum:single|cart|link\",\n gateway: \"string?\",\n ...MONEY,\n },\n order_paid: {\n gateway: \"string\",\n method: \"string?\",\n item_count: \"number?\",\n /** UTC date (`YYYY-MM-DD`) the envelope `visitor_id` was computed for. */\n visitor_day: \"string?\",\n /** Every line of the order (public hashed product ids), at most 50. */\n items: \"line_items?\",\n ...MONEY,\n },\n refund_issued: {\n gateway: \"string?\",\n reason: \"string?\",\n ...MONEY,\n },\n return_requested: { item_count: \"number\", reason_code: \"string?\" },\n automation_run_completed: {\n automation_id: \"string\",\n status: \"string\",\n trigger: \"string?\",\n },\n notification_sent: { medium: \"string\", template: \"string?\" },\n notification_failed: {\n medium: \"string\",\n template: \"string?\",\n error_code: \"string?\",\n },\n recovery_email_sent: { step: \"number?\" },\n recovery_link_clicked: {},\n api_request: {\n /** Route template without ids or query, e.g. `/api/rpc/public.v1.PublicApiService/ListProducts`. */\n endpoint: \"string\",\n /** `X-Bitsnap-Client` value, absent when the caller sent none. */\n client: \"string?\",\n status: \"number\",\n latency_bucket: \"enum:lt_50|lt_200|lt_1000|gte_1000\",\n /** 1 for errors, <1 for sampled successes; rollups divide counts by it. */\n sample_rate: \"number\",\n },\n} as const;\n\nexport const EVENT_SPEC_BY_STREAM = {\n storefront_events: STOREFRONT_EVENT_SPEC,\n app_events: APP_EVENT_SPEC,\n business_events: BUSINESS_EVENT_SPEC,\n} as const;\n\nexport const EVENT_SPEC = {\n ...STOREFRONT_EVENT_SPEC,\n ...APP_EVENT_SPEC,\n ...BUSINESS_EVENT_SPEC,\n} as const;\n\nexport type StorefrontEventName = keyof typeof STOREFRONT_EVENT_SPEC;\nexport type AppEventName = keyof typeof APP_EVENT_SPEC;\nexport type BusinessEventName = keyof typeof BUSINESS_EVENT_SPEC;\nexport type EventName = StorefrontEventName | AppEventName | BusinessEventName;\n\nexport const EVENT_NAMES = {\n storefront_events: Object.keys(STOREFRONT_EVENT_SPEC) as StorefrontEventName[],\n app_events: Object.keys(APP_EVENT_SPEC) as AppEventName[],\n business_events: Object.keys(BUSINESS_EVENT_SPEC) as BusinessEventName[],\n} as const;\n\nexport const STREAM_FOR_EVENT: Record<EventName, Stream> = Object.fromEntries(\n STREAMS.flatMap((stream) =>\n (EVENT_NAMES[stream] as string[]).map((name) => [name, stream] as const),\n ),\n) as Record<EventName, Stream>;\n\n/** True for a catalogue event name; own keys only (`constructor`, `toString` are not events). */\nexport function isEventName(name: unknown): name is EventName {\n return typeof name === \"string\" && Object.hasOwn(STREAM_FOR_EVENT, name);\n}\n\n// -- props types, derived from the spec ------------------------------------\n\ntype PropPrimitives = {\n string: string;\n number: number;\n boolean: boolean;\n \"string[]\": string[];\n \"number[]\": number[];\n line_items: Array<{ product_id: string; qty: number; value_minor: number }>;\n};\ntype SplitEnum<S extends string> = S extends `${infer H}|${infer R}`\n ? H | SplitEnum<R>\n : S;\ntype StripOpt<S extends string> = S extends `${infer B}?` ? B : S;\ntype ResolveProp<S extends string> =\n StripOpt<S> extends `enum:${infer E}`\n ? SplitEnum<E>\n : StripOpt<S> extends keyof PropPrimitives\n ? PropPrimitives[StripOpt<S>]\n : never;\ntype PropsFromSpec<S extends Record<string, string>> = {\n [K in keyof S as S[K] extends `${string}?` ? never : K]: ResolveProp<S[K]>;\n} & {\n [K in keyof S as S[K] extends `${string}?` ? K : never]?: ResolveProp<S[K]>;\n};\n\nexport type EventProps<E extends EventName> = PropsFromSpec<\n (typeof EVENT_SPEC)[E]\n>;\n\n// ---------------------------------------------------------------------------\n// Envelope\n// ---------------------------------------------------------------------------\n\n/** Fields the emitter fills in. Everything else is derived by the collector. */\nexport interface ClientEvent<E extends EventName = EventName> {\n /** UUIDv7, generated by the emitter. Dedupe key. */\n event_id: string;\n event: E;\n /** Client clock, unix ms. */\n ts: number;\n schema_version: typeof SCHEMA_VERSION;\n env: Env;\n source: Source;\n channel: Channel;\n /** `<package>@<version>`, e.g. `bitsnap-react@1.9.0`. */\n sdk?: string | null;\n /** Random per page load, in memory only. */\n page_id?: string | null;\n page_type?: PageType | null;\n host?: string | null;\n /** Path without query string and fragment, already run through `sanitizePath`. */\n path?: string | null;\n referrer_host?: string | null;\n utm_source?: string | null;\n utm_medium?: string | null;\n utm_campaign?: string | null;\n utm_content?: string | null;\n utm_term?: string | null;\n ref_code?: string | null;\n product_id?: string | null;\n variant_id?: string | null;\n order_ref?: string | null;\n /** Object on the wire; the collector stores `JSON.stringify(props)`. */\n props: EventProps<E>;\n /**\n * Only honoured for `source: \"dashboard\"`: the hashed Clerk user id computed\n * by instapay and handed to the dashboard tracker. Ignored for every other\n * source (the collector computes `visitor_id` itself).\n */\n visitor_id?: string | null;\n /**\n * The value of the first-party `bs_vid_<projectKey>` cookie (`CLIENT_ID_RE`), sent only\n * while analytics consent is granted. The collector turns it into a stable\n * `consentedVisitorId` and never stores it.\n */\n client_id?: string | null;\n}\n\n/** One row as stored in Basin (all three streams share this shape). */\nexport interface StoredEvent {\n event_id: string;\n event: EventName;\n /** Unix ms, client clock after `clampTs`. */\n ts: number;\n /** Unix ms, collector clock. */\n received_at: number;\n schema_version: number;\n /** Numeric database id. Resolved by the collector, never taken from the client. */\n project_id: number;\n env: Env;\n source: Source;\n channel: Channel;\n sdk: string | null;\n visitor_id: string | null;\n page_id: string | null;\n page_type: PageType | null;\n host: string | null;\n path: string | null;\n referrer_host: string | null;\n utm_source: string | null;\n utm_medium: string | null;\n utm_campaign: string | null;\n utm_content: string | null;\n utm_term: string | null;\n ref_code: string | null;\n country: string | null;\n region: string | null;\n device_type: DeviceType | null;\n os: string | null;\n browser: string | null;\n product_id: string | null;\n variant_id: string | null;\n order_ref: string | null;\n /** `JSON.stringify` of the props object. */\n props: string;\n}\n\n/** POST /e body. */\nexport interface IngestBody {\n /** Project key, see `normalizeProjectKey`. */\n k: string;\n events: ClientEvent[];\n}\n\n// ---------------------------------------------------------------------------\n// Consent shapes\n// ---------------------------------------------------------------------------\n\nexport const CONSENT_TEXT_KEYS = [\n \"title\",\n \"description\",\n \"acceptAll\",\n \"rejectAll\",\n \"settings\",\n \"save\",\n \"close\",\n \"necessaryTitle\",\n \"necessaryDescription\",\n \"analyticsTitle\",\n \"analyticsDescription\",\n \"marketingTitle\",\n \"marketingDescription\",\n \"preferencesTitle\",\n \"preferencesDescription\",\n \"poweredBy\",\n] as const;\nexport type ConsentTextKey = (typeof CONSENT_TEXT_KEYS)[number];\nexport type ConsentTexts = Record<ConsentTextKey, string>;\n\nexport type ConsentCategory = \"analytics\" | \"marketing\" | \"preferences\";\nexport type ConsentChoice = Record<ConsentCategory, boolean>;\n\nexport type ConsentConfig = {\n version: number;\n theme: \"auto\" | \"light\" | \"dark\";\n accentColor?: string;\n position: \"bottom\" | \"bottom-left\" | \"bottom-right\";\n privacyPolicyUrl?: string;\n categories: { analytics: boolean; marketing: boolean; preferences: boolean };\n services: Array<{\n name: string;\n category: \"analytics\" | \"marketing\" | \"preferences\";\n cookies?: string[];\n }>;\n texts?: Partial<Record<\"pl\" | \"en\", Partial<ConsentTexts>>>;\n poweredBy: true;\n};\n\n/** Value of the consent cookie, JSON then base64url. */\nexport interface ConsentCookie {\n v: 1;\n /** Random consent id (also sent to POST /consent). */\n id: string;\n /** Unix seconds. */\n ts: number;\n /** Banner version (`ConsentConfig.version`) the visitor answered. */\n bv: number;\n c: ConsentChoice;\n}\n\nexport const CONSENT_COOKIE_NAME = \"bitsnap_consent\";\nexport const CONSENT_COOKIE_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;\nexport const CONSENT_ACTIONS = [\n \"accept_all\",\n \"reject_all\",\n \"custom\",\n \"withdraw\",\n] as const;\nexport type ConsentAction = (typeof CONSENT_ACTIONS)[number];\n\n/** POST /consent body. */\nexport interface ConsentLogBody {\n k: string;\n /** Same random id as `ConsentCookie.id`. 16 to 64 chars of `[A-Za-z0-9_-]`. */\n consent_id: string;\n action: ConsentAction;\n c: ConsentChoice;\n /** Banner version. */\n bv: number;\n /** Hostname the banner ran on. Collector overwrites it with the Origin host. */\n host: string;\n /** Unix SECONDS (like the cookie), not ms. */\n ts: number;\n}\n\n/** `bitsnap_consent`, or `bitsnap_consent_<projectKey>` for `data-scope=\"project\"`. */\nexport function consentCookieName(scope: \"site\" | \"project\", projectKey?: string): string {\n if (scope === \"project\") {\n if (!projectKey) throw new Error(\"projectKey required for project scope\");\n return `${CONSENT_COOKIE_NAME}_${normalizeProjectKey(projectKey)}`;\n }\n return CONSENT_COOKIE_NAME;\n}\n\n/**\n * Decodes the value of a consent cookie (§11.3). Null when it is not base64url\n * JSON of the documented shape (`v` 1 and a boolean per category).\n */\nexport function parseConsentCookie(value: string | null | undefined): ConsentCookie | null {\n if (!value || !/^[A-Za-z0-9_-]+$/.test(value)) return null;\n try {\n const padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const bin = atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n const json: unknown = JSON.parse(\n new TextDecoder().decode(Uint8Array.from(bin, (ch) => ch.charCodeAt(0))),\n );\n if (!isRecord(json) || json.v !== 1) return null;\n const c = json.c;\n if (!isRecord(c)) return null;\n if (\n typeof c.analytics !== \"boolean\" ||\n typeof c.marketing !== \"boolean\" ||\n typeof c.preferences !== \"boolean\"\n ) {\n return null;\n }\n return json as unknown as ConsentCookie;\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Project key\n// ---------------------------------------------------------------------------\n\n/**\n * The project key is the existing public hashed project id\n * (`hashId(projectId)` in apps/bitsnap/queries/hashids.ts, the `projectID`\n * of bitsnap-react). A leading `pk_` is accepted and dropped so the\n * documented `pk_…` snippets work too. Returns null when it is not a plausible\n * key (hashids default alphabet).\n */\nexport function normalizeProjectKey(key: string): string | null {\n const bare = key.startsWith(\"pk_\") ? key.slice(3) : key;\n return /^[A-Za-z0-9]{1,32}$/.test(bare) ? bare : null;\n}\n\n// ---------------------------------------------------------------------------\n// X-Bitsnap-Client\n// ---------------------------------------------------------------------------\n\nconst CLIENT_RE = /^([a-z][a-z0-9-]{0,39})@(\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.+-]{1,20})?)$/;\n\n/** `<package>@<version>`, e.g. `bitsnap-react@1.9.0`. Also the shape of `sdk`. */\nexport function parseClientHeader(\n value: string | null | undefined,\n): { package: string; version: string } | null {\n if (!value || value.length > LIMITS.sdk) return null;\n const m = CLIENT_RE.exec(value);\n return m ? { package: m[1], version: m[2] } : null;\n}\n\n// ---------------------------------------------------------------------------\n// URL stripping\n// ---------------------------------------------------------------------------\n\nconst MAX_QUERY_VALUE = LIMITS.utm;\n\n/**\n * Campaign/ref value: trimmed, capped, null when empty or when it holds an \"@\"\n * (someone put an email in a tag). The collector runs every client-supplied\n * `utm_*` and `ref_code` through it again.\n */\nexport function cleanValue(v: string | null | undefined, max: number): string | null {\n if (v == null) return null;\n const t = v.trim();\n // An \"@\" means someone put an email in a campaign tag: drop the value.\n if (t.length === 0 || t.includes(\"@\")) return null;\n return t.slice(0, max);\n}\n\n/**\n * Path sanitiser: no query, no fragment, capped. Opaque segments (24+ chars of\n * `[A-Za-z0-9_-]`, i.e. tokens in order/panel links) become `:token` and\n * segments containing `@` become `:email`.\n */\nexport function sanitizePath(pathname: string): string {\n const segments = pathname.split(\"/\").map((seg) => {\n if (seg.includes(\"@\") || seg.includes(\"%40\")) return \":email\";\n if (/^[A-Za-z0-9_-]{24,}$/.test(seg)) return \":token\";\n return seg;\n });\n const joined = segments.join(\"/\") || \"/\";\n return (joined.startsWith(\"/\") ? joined : `/${joined}`).slice(0, LIMITS.path);\n}\n\nexport interface UrlParts {\n host: string;\n /** Sanitised path, no query. */\n path: string;\n utm_source: string | null;\n utm_medium: string | null;\n utm_campaign: string | null;\n utm_content: string | null;\n utm_term: string | null;\n /** The `ref` query parameter. */\n ref_code: string | null;\n}\n\n/**\n * Parses a URL and keeps only what may leave the browser: host, sanitised path\n * and the `utm_*` and `ref` query parameters. Returns null for non-http(s) or\n * unparseable input. `base` resolves relative URLs.\n */\nexport function parseUrl(url: string, base?: string): UrlParts | null {\n let u: URL;\n try {\n u = new URL(url, base);\n } catch {\n return null;\n }\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n const q = u.searchParams;\n return {\n host: u.hostname.toLowerCase().slice(0, LIMITS.host),\n path: sanitizePath(u.pathname),\n utm_source: cleanValue(q.get(\"utm_source\"), MAX_QUERY_VALUE),\n utm_medium: cleanValue(q.get(\"utm_medium\"), MAX_QUERY_VALUE),\n utm_campaign: cleanValue(q.get(\"utm_campaign\"), MAX_QUERY_VALUE),\n utm_content: cleanValue(q.get(\"utm_content\"), MAX_QUERY_VALUE),\n utm_term: cleanValue(q.get(\"utm_term\"), MAX_QUERY_VALUE),\n ref_code: cleanValue(q.get(\"ref\"), LIMITS.refCode),\n };\n}\n\n/**\n * Returns the URL with userinfo, fragment and every query parameter removed\n * except `utm_*` and `ref`. Null when `url` is not a usable http(s) URL.\n */\nexport function stripUrl(url: string, base?: string): string | null {\n let u: URL;\n try {\n u = new URL(url, base);\n } catch {\n return null;\n }\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n const keep = new URLSearchParams();\n for (const [key, value] of u.searchParams) {\n if (key !== \"ref\" && !key.startsWith(\"utm_\")) continue;\n const cleaned = cleanValue(value, MAX_QUERY_VALUE);\n if (cleaned != null) keep.append(key, cleaned);\n }\n const qs = keep.toString();\n return `${u.protocol}//${u.host}${sanitizePath(u.pathname)}${qs ? `?${qs}` : \"\"}`;\n}\n\nconst HOSTNAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;\n\n/** A plain DNS hostname (lower-cased), or null: no scheme, port, path, userinfo or \"@\". */\nexport function cleanHostname(\n v: string | null | undefined,\n max: number = LIMITS.referrerHost,\n): string | null {\n if (typeof v !== \"string\") return null;\n const h = v.trim().toLowerCase();\n return h.length > 0 && h.length <= max && HOSTNAME_RE.test(h) ? h : null;\n}\n\n/** Public hashed ids (`product_id`, `variant_id`, `order_ref`): URL-safe, at most `LIMITS.id`. */\nexport const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;\n\nexport function cleanId(v: string | null | undefined): string | null {\n return typeof v === \"string\" && ID_RE.test(v) ? v : null;\n}\n\n/** Host of a referrer URL, or null (also null for non-http(s) referrers). */\nexport function referrerHost(referrer: string | null | undefined): string | null {\n if (!referrer) return null;\n try {\n const u = new URL(referrer);\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n return u.hostname.toLowerCase().slice(0, LIMITS.referrerHost);\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Bot rule\n// ---------------------------------------------------------------------------\n\nconst BOT_UA =\n /bot\\b|crawl|spider|slurp|facebookexternalhit|bingpreview|headless|phantomjs|lighthouse|pagespeed|gtmetrix|pingdom|uptime|statuscake|monitor|preview|scrapy|curl\\/|wget|python-|go-http-client|java\\/|okhttp|axios|node-fetch|undici|libwww|httpclient|aiohttp|postman|insomnia/i;\n\n/** True when the User-Agent is empty or looks automated. Such events are dropped. */\nexport function isBotUserAgent(ua: string | null | undefined): boolean {\n if (!ua || ua.trim().length === 0) return true;\n return BOT_UA.test(ua);\n}\n\n// ---------------------------------------------------------------------------\n// visitor_id\n// ---------------------------------------------------------------------------\n\nconst encoder = new TextEncoder();\n\nasync function hmacSha256(\n key: Uint8Array,\n message: string,\n): Promise<Uint8Array> {\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n key,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n return new Uint8Array(\n await crypto.subtle.sign(\"HMAC\", cryptoKey, encoder.encode(message)),\n );\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** `YYYY-MM-DD` of a unix-ms timestamp in UTC. */\nexport function utcDate(ms: number): string {\n return new Date(ms).toISOString().slice(0, 10);\n}\n\n/**\n * IP as hashed: lower-case; IPv4 unchanged; IPv4-mapped IPv6 (`::ffff:1.2.3.4`\n * or `::ffff:102:304`) becomes plain IPv4; any other IPv6, including one with\n * an embedded dotted quad (`64:ff9b::1.2.3.4`), is cut to its /64 (first four\n * hextets, canonical form `a:b:c:d::`). Both the Worker and the instapay\n * server MUST call this on the client IP before `computeVisitorId`.\n */\nexport function normalizeIp(ip: string): string {\n let s = ip.trim().toLowerCase();\n const zone = s.indexOf(\"%\");\n if (zone >= 0) s = s.slice(0, zone);\n if (!s.includes(\":\")) return s; // plain IPv4 (or not an IP at all)\n\n // Embedded dotted quad in the last 32 bits: turn it into two hextets.\n const quad = /^(.*:)(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(s);\n if (quad) {\n const o = [quad[2], quad[3], quad[4], quad[5]].map(Number);\n if (o.some((n) => n > 255)) return s;\n const hex = (hi: number, lo: number) => (hi * 256 + lo).toString(16);\n s = `${quad[1]}${hex(o[0], o[1])}:${hex(o[2], o[3])}`;\n }\n\n const [head, tail] = s.split(\"::\");\n const headParts = head ? head.split(\":\") : [];\n const tailParts = tail !== undefined && tail !== \"\" ? tail.split(\":\") : [];\n const fill =\n tail === undefined ? 0 : Math.max(0, 8 - headParts.length - tailParts.length);\n const groups = [...headParts, ...Array<string>(fill).fill(\"0\"), ...tailParts];\n if (groups.length !== 8) return s;\n const h = groups.map((g) => Number.parseInt(g, 16) || 0);\n\n // ::ffff:a.b.c.d in hex form.\n if (h.slice(0, 5).every((x) => x === 0) && h[5] === 0xffff) {\n return `${h[6] >> 8}.${h[6] & 255}.${h[7] >> 8}.${h[7] & 255}`;\n }\n return `${h\n .slice(0, 4)\n .map((g) => g.toString(16))\n .join(\":\")}::`;\n}\n\n/**\n * Cookieless visitor id, identical in the Worker and the instapay server.\n *\n * day_secret = HMAC-SHA256(key = utf8(masterSecret), msg = utf8(\"YYYY-MM-DD\")) // 32 raw bytes\n * visitor_id = base64url(HMAC-SHA256(key = day_secret, msg = utf8(ip + \"\\n\" + ua + \"\\n\" + projectId))).slice(0, 22)\n *\n * `dateUtc` is the UTC date of the request; `ip` is `normalizeIp(<client IP>)`;\n * `ua` is the raw `User-Agent` request header; `projectId` is the decimal\n * numeric project id.\n */\nexport async function computeVisitorId(\n masterSecret: string,\n dateUtc: string,\n ip: string,\n ua: string,\n projectId: number | string,\n): Promise<string> {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(dateUtc)) {\n throw new Error(`dateUtc must be YYYY-MM-DD, got ${dateUtc}`);\n }\n const daySecret = await hmacSha256(encoder.encode(masterSecret), dateUtc);\n const mac = await hmacSha256(daySecret, `${ip}\\n${ua}\\n${projectId}`);\n return base64url(mac).slice(0, 22);\n}\n\n/**\n * The `bs_vid_<projectKey>` cookie name. `projectKey` is the bare public key\n * (like `consentCookieName`): consent is per project, so is the client id.\n */\nexport function clientIdCookieName(projectKey: string): string {\n return `bs_vid_${projectKey}`;\n}\n\n/** Value of the `bs_vid_<projectKey>` cookie: 16 random bytes, base64url without padding. */\nexport const CLIENT_ID_RE = /^[A-Za-z0-9_-]{22}$/;\n\n/**\n * Stable visitor id of a browser that granted analytics consent (contract §6).\n *\n * consented_visitor_id = \"p_\" + base64url(HMAC-SHA256(key = utf8(masterSecret),\n * msg = utf8(\"client\\n\" + clientId + \"\\n\" + projectId))).slice(0, 22)\n *\n * 24 characters; daily ids are 22, so `isConsentedVisitorId` tells them apart.\n * `clientId` is the `bs_vid_<projectKey>` cookie value and is never stored.\n */\nexport async function computeConsentedVisitorId(\n masterSecret: string,\n clientId: string,\n projectId: number | string,\n): Promise<string> {\n if (!CLIENT_ID_RE.test(clientId)) {\n throw new Error(\"clientId must be 22 base64url characters\");\n }\n const mac = await hmacSha256(\n encoder.encode(masterSecret),\n `client\\n${clientId}\\n${projectId}`,\n );\n return `p_${base64url(mac).slice(0, 22)}`;\n}\n\n/** Whether `visitorId` came from `computeConsentedVisitorId` (not a daily id). */\nexport function isConsentedVisitorId(visitorId: string): boolean {\n return visitorId.length === 24 && visitorId.startsWith(\"p_\");\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nexport type ValidationResult = { ok: true } | { ok: false; reason: string };\n\nconst UUID_V7 =\n /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst PAGE_ID_RE = /^[A-Za-z0-9_-]{8,32}$/;\n/** A letter TLD is required: `bitsnap-react@1.9.0` and `v@1.2` are not addresses. */\nconst EMAIL_LIKE = /[^\\s@]+@[^\\s@]+\\.[A-Za-z]{2,}\\b/;\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction nullableString(\n e: Record<string, unknown>,\n key: string,\n max: number,\n): string | null {\n const v = e[key];\n if (v === undefined || v === null) return null;\n if (typeof v !== \"string\") return `bad_${key}`;\n return v.length > max ? `too_long_${key}` : null;\n}\n\nfunction checkPropValue(spec: string, value: unknown): boolean {\n const optional = spec.endsWith(\"?\");\n const type = optional ? spec.slice(0, -1) : spec;\n if (type.startsWith(\"enum:\")) {\n return typeof value === \"string\" && type.slice(5).split(\"|\").includes(value);\n }\n switch (type) {\n case \"string\":\n return typeof value === \"string\" && value.length <= LIMITS.maxPropString;\n case \"number\":\n return typeof value === \"number\" && Number.isFinite(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"string[]\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every((x) => typeof x === \"string\" && x.length <= LIMITS.maxPropString)\n );\n case \"number[]\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every((x) => typeof x === \"number\" && Number.isFinite(x))\n );\n case \"line_items\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every(\n (x) =>\n isRecord(x) &&\n typeof x.product_id === \"string\" &&\n ID_RE.test(x.product_id) &&\n isNonNegativeSafeInteger(x.qty) &&\n isNonNegativeSafeInteger(x.value_minor),\n )\n );\n default:\n return false;\n }\n}\n\nfunction isNonNegativeSafeInteger(value: unknown): boolean {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\n/** True when `value` looks like an email address (also exported for the collector's re-checks). */\nexport function looksLikeEmail(value: string): boolean {\n // A well-formed `<package>@<version>` client id is never an address.\n if (parseClientHeader(value) !== null) return false;\n return EMAIL_LIKE.test(value);\n}\n\nfunction hasEmailLike(value: unknown): boolean {\n if (typeof value === \"string\") return looksLikeEmail(value);\n if (Array.isArray(value)) return value.some(hasEmailLike);\n if (isRecord(value)) return Object.values(value).some(hasEmailLike);\n return false;\n}\n\n/**\n * Validates `props` against the catalogue and returns a copy without keys the\n * catalogue does not know (forward compatibility: a newer SDK adding an\n * optional prop must not get its events dropped by an older collector).\n * Fails on missing required props, wrong types, bad enum values, oversize\n * props and string values that look like an email address.\n */\nexport function sanitizeProps(\n event: string,\n props: unknown,\n): { ok: true; props: Record<string, unknown> } | { ok: false; reason: string } {\n if (!isEventName(event)) return { ok: false, reason: \"unknown_event\" };\n const spec = (EVENT_SPEC as Record<string, Record<string, string>>)[event];\n if (!spec) return { ok: false, reason: \"unknown_event\" };\n if (!isRecord(props)) return { ok: false, reason: \"bad_props\" };\n const out: Record<string, unknown> = {};\n for (const [key, type] of Object.entries(spec)) {\n const value = props[key];\n if (value === undefined || value === null) {\n if (!type.endsWith(\"?\")) return { ok: false, reason: `props_missing_${key}` };\n continue;\n }\n if (!checkPropValue(type, value)) return { ok: false, reason: `props_bad_${key}` };\n if (hasEmailLike(value)) return { ok: false, reason: `props_pii_${key}` };\n out[key] =\n type.startsWith(\"line_items\") && Array.isArray(value)\n ? value.map((x) => ({ product_id: x.product_id, qty: x.qty, value_minor: x.value_minor }))\n : value;\n }\n if (JSON.stringify(out).length > LIMITS.maxPropsChars) {\n return { ok: false, reason: \"props_too_large\" };\n }\n return { ok: true, props: out };\n}\n\nexport interface ValidateOptions {\n /**\n * Who sent it. `browser` (default) is POST /e: the event must belong to\n * `storefront_events` or `app_events`, `consent_updated` is refused (only\n * POST /consent writes it) and `source` must fit the stream. `server` is the\n * instapay emitter: any stream, `source` must fit the stream.\n */\n from?: \"browser\" | \"server\";\n}\n\n/**\n * Validates the emitter-controlled part of an event: names, types, enums,\n * lengths, the event/source/stream pairing and `props`. It does not check\n * that `ts` is plausible (use `clampTs`), origins or project keys.\n */\nexport function validateEnvelope(\n e: unknown,\n options: ValidateOptions = {},\n): ValidationResult {\n const from = options.from ?? \"browser\";\n const fail = (reason: string): ValidationResult => ({ ok: false, reason });\n if (!isRecord(e)) return fail(\"not_object\");\n\n if (typeof e.event_id !== \"string\" || !UUID_V7.test(e.event_id)) {\n return fail(\"bad_event_id\");\n }\n if (!isEventName(e.event)) return fail(\"unknown_event\");\n const stream = STREAM_FOR_EVENT[e.event as EventName];\n if (from === \"browser\") {\n if (stream === \"business_events\") return fail(\"server_only_event\");\n if (e.event === \"consent_updated\") return fail(\"consent_via_consent_endpoint\");\n }\n if (\n typeof e.ts !== \"number\" ||\n !Number.isInteger(e.ts) ||\n e.ts <= 0 ||\n e.ts > 4e12\n ) {\n return fail(\"bad_ts\");\n }\n if (e.schema_version !== SCHEMA_VERSION) return fail(\"bad_schema_version\");\n if (!ENVS.includes(e.env as Env)) return fail(\"bad_env\");\n if (!SOURCES.includes(e.source as Source)) return fail(\"bad_source\");\n if (!SOURCES_FOR_STREAM[stream].includes(e.source as Source)) {\n return fail(\"source_not_allowed_for_event\");\n }\n if (!CHANNELS.includes(e.channel as Channel)) return fail(\"bad_channel\");\n\n if (e.sdk != null) {\n if (typeof e.sdk !== \"string\" || parseClientHeader(e.sdk) === null) {\n return fail(\"bad_sdk\");\n }\n }\n if (e.page_id != null) {\n if (typeof e.page_id !== \"string\" || !PAGE_ID_RE.test(e.page_id)) {\n return fail(\"bad_page_id\");\n }\n }\n if (e.page_type != null && !PAGE_TYPES.includes(e.page_type as PageType)) {\n return fail(\"bad_page_type\");\n }\n if (from === \"browser\") {\n if (typeof e.host !== \"string\" || e.host.length === 0) return fail(\"bad_host\");\n if (typeof e.path !== \"string\" || !e.path.startsWith(\"/\")) return fail(\"bad_path\");\n }\n if (typeof e.path === \"string\" && e.path.includes(\"?\")) return fail(\"path_has_query\");\n if (typeof e.path === \"string\" && e.path.includes(\"#\")) return fail(\"path_has_fragment\");\n\n const lengths: Array<[string, number]> = [\n [\"host\", LIMITS.host],\n [\"path\", LIMITS.path],\n [\"referrer_host\", LIMITS.referrerHost],\n [\"utm_source\", LIMITS.utm],\n [\"utm_medium\", LIMITS.utm],\n [\"utm_campaign\", LIMITS.utm],\n [\"utm_content\", LIMITS.utm],\n [\"utm_term\", LIMITS.utm],\n [\"ref_code\", LIMITS.refCode],\n [\"product_id\", LIMITS.id],\n [\"variant_id\", LIMITS.id],\n [\"order_ref\", LIMITS.id],\n ];\n for (const [key, max] of lengths) {\n const problem = nullableString(e, key, max);\n if (problem) return fail(problem);\n }\n if (e.visitor_id != null) {\n if (typeof e.visitor_id !== \"string\" || !/^[A-Za-z0-9_-]{22}$/.test(e.visitor_id)) {\n return fail(\"bad_visitor_id\");\n }\n }\n if (e.client_id != null) {\n if (typeof e.client_id !== \"string\" || !CLIENT_ID_RE.test(e.client_id)) {\n return fail(\"bad_client_id\");\n }\n }\n\n const props = sanitizeProps(e.event, e.props);\n if (!props.ok) return fail(props.reason);\n return { ok: true };\n}\n\n/** Client `ts` as stored: replaced by `receivedAt` when more than 24 h away from it. */\nexport function clampTs(ts: number, receivedAt: number): number {\n return Math.abs(ts - receivedAt) > LIMITS.tsSkewMs ? receivedAt : ts;\n}\n","import type { ConsentChoices, ConsentService, ConsentState } from \"./types\";\n\nexport const COOKIE_NAME = \"bitsnap_consent\";\nexport const COOKIE_MAX_AGE = 31536000;\n\n/** `bitsnap_consent`, or `bitsnap_consent_<projectKey>` when the cookie is scoped to a project. */\nexport function cookieName(projectKey?: string, scope?: \"global\" | \"project\"): string {\n if (scope === \"project\" && projectKey) {\n return `${COOKIE_NAME}_${projectKey.replace(/[^A-Za-z0-9_-]/g, \"_\")}`;\n }\n return COOKIE_NAME;\n}\n\nfunction toBase64Url(text: string): string {\n return btoa(text).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction fromBase64Url(text: string): string {\n const padded = text.replace(/-/g, \"+\").replace(/_/g, \"/\");\n return atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n}\n\nexport function encodeState(state: ConsentState): string {\n return toBase64Url(\n JSON.stringify({ v: 1, id: state.id, ts: state.ts, bv: state.bv, c: state.c }),\n );\n}\n\nexport function decodeState(value: string): ConsentState | null {\n try {\n const raw = JSON.parse(fromBase64Url(value));\n if (\n !raw ||\n raw.v !== 1 ||\n typeof raw.id !== \"string\" ||\n raw.id === \"\" ||\n typeof raw.ts !== \"number\" ||\n typeof raw.bv !== \"number\" ||\n !raw.c ||\n typeof raw.c.analytics !== \"boolean\" ||\n typeof raw.c.marketing !== \"boolean\" ||\n typeof raw.c.preferences !== \"boolean\"\n ) {\n return null;\n }\n return {\n id: raw.id,\n ts: raw.ts,\n bv: raw.bv,\n c: {\n analytics: raw.c.analytics,\n marketing: raw.c.marketing,\n preferences: raw.c.preferences,\n },\n };\n } catch {\n return null;\n }\n}\n\n/** The `Set-Cookie`-style string for `document.cookie`. */\nexport function serializeCookie(name: string, state: ConsentState, secure: boolean): string {\n return (\n `${name}=${encodeState(state)}; Max-Age=${COOKIE_MAX_AGE}; Path=/; SameSite=Lax` +\n (secure ? \"; Secure\" : \"\")\n );\n}\n\nexport function cookieNames(header: string): string[] {\n return header\n .split(\";\")\n .map((part) => part.split(\"=\")[0].trim())\n .filter(Boolean);\n}\n\n/** Reads the consent from a `document.cookie` header. */\nexport function parseCookie(header: string, name: string): ConsentState | null {\n for (const part of header.split(\";\")) {\n const index = part.indexOf(\"=\");\n if (index === -1) continue;\n if (part.slice(0, index).trim() === name) {\n return decodeState(part.slice(index + 1).trim());\n }\n }\n return null;\n}\n\nexport function newConsentId(): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // fall through to the random fallback\n }\n let id = \"\";\n for (let i = 0; i < 32; i++) id += Math.floor(Math.random() * 16).toString(16);\n return id;\n}\n\nexport function readConsent(doc: Document, name: string): ConsentState | null {\n try {\n return parseCookie(doc.cookie, name);\n } catch {\n return null;\n }\n}\n\nexport function writeConsent(doc: Document, name: string, state: ConsentState): void {\n try {\n doc.cookie = serializeCookie(name, state, doc.location?.protocol === \"https:\");\n } catch {\n // cookies blocked (sandboxed frame)\n }\n}\n\nexport function clearConsent(doc: Document, name: string): void {\n try {\n doc.cookie = `${name}=; Max-Age=0; Path=/; SameSite=Lax`;\n } catch {\n // ignore\n }\n}\n\n/** `a.b.example.com` -> the host and every parent with at least two labels. */\nexport function domainCandidates(hostname: string): string[] {\n if (!hostname || /^[\\d.]+$/.test(hostname) || hostname.includes(\":\")) return [];\n const labels = hostname.split(\".\");\n const result: string[] = [];\n for (let i = 0; i <= labels.length - 2; i++) result.push(labels.slice(i).join(\".\"));\n return result;\n}\n\n/**\n * Best-effort deletion of cookies the withdrawn categories declared, on the\n * current host and its parent domains. A trailing `*` matches a name prefix.\n */\nexport function deleteServiceCookies(\n doc: Document,\n services: ConsentService[],\n categories: (keyof ConsentChoices)[],\n): void {\n try {\n const wanted = services\n .filter((service) => categories.includes(service.category))\n .flatMap((service) => service.cookies ?? []);\n if (wanted.length === 0) return;\n const present = cookieNames(doc.cookie);\n const names = new Set<string>();\n for (const pattern of wanted) {\n if (pattern.endsWith(\"*\")) {\n const prefix = pattern.slice(0, -1);\n for (const name of present) if (name.startsWith(prefix)) names.add(name);\n } else {\n names.add(pattern);\n }\n }\n const domains = domainCandidates(doc.location?.hostname ?? \"\");\n for (const name of names) {\n const base = `${encodeURIComponent(name)}=; Max-Age=0; Path=/`;\n doc.cookie = base;\n for (const domain of domains) {\n doc.cookie = `${base}; Domain=${domain}`;\n doc.cookie = `${base}; Domain=.${domain}`;\n }\n }\n } catch {\n // best effort\n }\n}\n","import { useEffect, useLayoutEffect, type DependencyList, type EffectCallback } from \"react\";\n\n/**\n * `useLayoutEffect` in the browser (it runs before any passive effect), `useEffect` on the server,\n * where React warns about layout effects. Chosen per call: a page's `window` can appear after import.\n */\nexport function useIsomorphicLayoutEffect(effect: EffectCallback, deps?: DependencyList): void {\n // eslint-disable-next-line react-hooks/rules-of-hooks -- the environment never changes between renders\n (typeof window !== \"undefined\" ? useLayoutEffect : useEffect)(effect, deps);\n}\n"],"mappings":"AAiBO,IAAMA,EAAS,CAEpB,eAAgB,GAEhB,aAAc,MAEd,cAAe,KACf,cAAe,IACf,aAAc,GACd,KAAM,IACN,KAAM,IACN,aAAc,IACd,IAAK,IACL,QAAS,GACT,GAAI,GACJ,IAAK,GACL,OAAQ,GACR,OAAQ,GACR,UAAW,GAEX,SAAU,KACZ,EAMaC,EAAU,CACrB,oBACA,aACA,iBACF,EAGaC,EAAO,CAAC,OAAQ,MAAM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AO,CACxB,IAAMI,EAAO,GAAG,mBAAmB5B,CAAI,CAAC,uBACxCW,EAAI,OAASiB,EACb,QAAWC,KAAUF,EACnBhB,EAAI,OAAS,GAAGiB,CAAI,YAAYC,CAAM,GACtClB,EAAI,OAAS,GAAGiB,CAAI,aAAaC,CAAM,EAE3C,CACF,MAAQ,CAER,CACF,CCzKA,OAAS,aAAAC,EAAW,mBAAAC,OAAiE,QAM9E,SAASC,GAA0BC,EAAwBC,EAA6B,EAE5F,OAAO,OAAW,IAAcH,GAAkBD,GAAWG,EAAQC,CAAI,CAC5E","names":["LIMITS","STREAMS","ENVS","SOURCES","CHANNELS","PAGE_TYPES","SOURCES_FOR_STREAM","MONEY","STOREFRONT_EVENT_SPEC","APP_EVENT_SPEC","TX","SUB","BUSINESS_EVENT_SPEC","EVENT_SPEC","STOREFRONT_EVENT_SPEC","APP_EVENT_SPEC","BUSINESS_EVENT_SPEC","EVENT_NAMES","STREAM_FOR_EVENT","STREAMS","stream","name","isEventName","CONSENT_COOKIE_MAX_AGE_SECONDS","normalizeProjectKey","key","bare","CLIENT_RE","parseClientHeader","value","LIMITS","m","MAX_QUERY_VALUE","cleanValue","v","max","t","sanitizePath","pathname","joined","seg","parseUrl","url","base","u","q","ID_RE","referrerHost","referrer","u","LIMITS","encoder","clientIdCookieName","projectKey","CLIENT_ID_RE","UUID_V7","PAGE_ID_RE","EMAIL_LIKE","isRecord","v","nullableString","e","key","max","checkPropValue","spec","value","type","LIMITS","x","ID_RE","isNonNegativeSafeInteger","looksLikeEmail","parseClientHeader","hasEmailLike","sanitizeProps","event","props","isEventName","EVENT_SPEC","out","validateEnvelope","options","from","fail","reason","stream","STREAM_FOR_EVENT","ENVS","SOURCES","SOURCES_FOR_STREAM","CHANNELS","PAGE_TYPES","lengths","problem","CLIENT_ID_RE","COOKIE_NAME","cookieName","projectKey","scope","COOKIE_NAME","toBase64Url","text","fromBase64Url","padded","encodeState","state","decodeState","value","raw","serializeCookie","name","secure","cookieNames","header","part","parseCookie","index","newConsentId","id","i","readConsent","doc","writeConsent","clearConsent","domainCandidates","hostname","labels","result","deleteServiceCookies","services","categories","wanted","service","present","names","pattern","prefix","domains","base","domain","useEffect","useLayoutEffect","useIsomorphicLayoutEffect","effect","deps"]}