@nosto/nosto-react 2.7.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,7 +9,7 @@ Nosto React is a React component library to make it even easier to implement Nos
9
9
 
10
10
  The library provides you everything to get started with personalisation on your React site. It's dead simple, and beginner friendly.
11
11
 
12
- ### Why?
12
+ ## Why?
13
13
 
14
14
  You should be using Nosto React if you want to:
15
15
 
@@ -17,269 +17,14 @@ You should be using Nosto React if you want to:
17
17
  - Customize your components at will and with ease
18
18
  - Follow React principles
19
19
 
20
- ## Feature list
20
+ ## Installation
21
21
 
22
- Our React component library includes the following features:
22
+ yarn add @nosto/nosto-react
23
23
 
24
- - Recommendations, including client-side rendering
25
- - Onsite content personalisation
26
- - Dynamic bundles
27
- - Debug toolbar\* (excluding advanced use cases)
28
- - Pop-ups & personalised emails
29
- - A/B testing
30
- - Segmentation and Insights
31
- - Analytics
32
- - Search\*\* (when implemented via our code editor)
24
+ npm install @nosto/nosto-react
33
25
 
34
- _\*Note: Our React component library currently does not support advanced use cases of the debug toolbar, but we are constantly working to improve our library and provide you with the best possible integration options. We support most use-cases with page tagging and debug workflows._
26
+ ## Documentation
35
27
 
36
- _\*\*Note: The search feature is available when implemented via our code editor._
28
+ Read [Nosto Techdocs](https://docs.nosto.com/techdocs/apis/frontend/oss/react-support) for more information on how to use the library.
37
29
 
38
- ### Additional features
39
-
40
- - ✓ Lightweight. Almost zero bloat.
41
- - ✓ Full support for the Facebook Pixel and Google Analytics.
42
- - ✓ Full support for leveraging overlays.
43
- - ✓ Full support for the JS API.
44
- - ✓ Full support for placements.
45
-
46
- ### Building
47
-
48
- #### Required versions
49
-
50
- - npm: 10.9.0
51
- - node: v22.12.0
52
-
53
- ### Installation
54
-
55
- ##### Yarn:
56
-
57
- yarn add @nosto/nosto-react
58
-
59
- ##### NPM:
60
-
61
- npm install @nosto/nosto-react
62
-
63
- ### Getting Started
64
-
65
- ##### The root widget
66
-
67
- There’s one very specific widget in Nosto React and it is the `NostoProvider` one.
68
-
69
- This widget is what we call the Nosto root widget, which is responsible for adding the actual Nosto script and the JS API stub. This widget wraps all other React Nosto widgets. Here’s how:
70
-
71
- ```jsx
72
- import { NostoProvider } from "@nosto/nosto-react"
73
- <NostoProvider account="your-nosto-account-id" recommendationComponent={<NostoSlot />}>
74
- <App />
75
- </NostoProvider>
76
- ```
77
-
78
- **Note:** the component also accepts a prop to configure the host `host="connect.nosto.com"`. In advanced use-cases, the need to configure the host may surface.
79
-
80
- #### Client side rendering for recommendations
81
-
82
- In order to implement client-side rendering, the <NostoProvider> requires a designated component to render the recommendations provided by Nosto. This component should be capable of processing the JSON response received from our backend. Notice the `recommendationComponent={<NostoSlot />}` prop passed to `<NostoProvider>` above.
83
-
84
- Learn more [here](https://github.com/Nosto/shopify-hydrogen/blob/main/README.md#client-side-rendering-for-recommendations) and see a [live example](https://github.com/Nosto/shopify-hydrogen-demo) on our demo store.
85
-
86
- ##### Understanding Placements
87
-
88
- Nosto React has a special component called `NostoPlacement`. The component is a simply a <u>hidden</u> `<div>` placeholder into which Nosto injects recommendations or personalises the content between the tags.
89
-
90
- We recommend adding as many placements across your views as needed as these are hidden and only populated when a corresponding campaign (targeting that placement) is configured.
91
-
92
- ##### Managing the session
93
-
94
- Nosto React requires that you pass it the details of current cart contents and the details of the currently logged-in customer, if any, on every route change. This makes it easier to add attribution.
95
-
96
- The `NostoSession` component makes it very easy to keep the session up to date so long as the cart and the customer are provided.
97
-
98
- The `cart` prop requires a value that adheres to the type `Cart`, while the `customer` prop requires a value that adheres to the type `Customer`.
99
-
100
- ```jsx
101
- import { NostoSession } from "@nosto/nosto-react"
102
- <>
103
- <Meta />
104
- <header>
105
- <MainMenu />
106
- <NostoSession cart={currentCart} customer={currentUser} />
107
- </header>
108
- <Routes />
109
- <Footer />
110
- </>
111
- ```
112
-
113
- ### Adding Personalisation
114
-
115
- Nosto React ships with canned components for the different page types. Each component contains all lifecycle methods to dispatch the necessary events.
116
-
117
- ##### Personalising your home page
118
-
119
- The `NostoHome` component must be used to personalise the home page. The component does not require any props.
120
-
121
- By default, your account, when created, has <u>four</u> front-page placements named `frontpage-nosto-1`, `frontpage-nosto-2`, `frontpage-nosto-3` and `frontpage-nosto-4`. You may omit these and use any identifier you need. The identifiers used here are simply provided to illustrate the example.
122
-
123
- The `<NostoHome \>` component needs to be added after the placements. Content and recommendations will be rendered through this component.
124
-
125
- ```jsx
126
- import { NostoHome, NostoPlacement } from "@nosto/nosto-react"
127
- <div className="front-page">
128
- ... ... ...
129
- <NostoPlacement id="frontpage-nosto-1" />
130
- <NostoPlacement id="frontpage-nosto-2" />
131
- <NostoPlacement id="frontpage-nosto-3" />
132
- <NostoPlacement id="frontpage-nosto-4" />
133
- <NostoHome />
134
- </div>
135
- ```
136
-
137
- ##### Personalising your product pages
138
-
139
- The `NostoProduct` component must be used to personalise the product page. The component requires that you provide it the identifier of the current product being viewed.
140
-
141
- By default, your account, when created, has <u>three</u> product-page placements named `productpage-nosto-1`, `productpage-nosto-2` and `productpage-nosto-3`. You may omit these and use any identifier you need. The identifiers used here are simply provided to illustrate the example.
142
-
143
- The `<NostoProduct \>` component needs to be added after the placements. Content and recommendations will be rendered through this component. Pass in the product ID via the `product` prop to pass this information back to Nosto.
144
-
145
- ```jsx
146
- import { NostoPlacement, NostoProduct } from "@nosto/nosto-react"
147
- <div className="product-page">
148
- ... ... ...
149
- <NostoPlacement id="productpage-nosto-1" />
150
- <NostoPlacement id="productpage-nosto-2" />
151
- <NostoPlacement id="productpage-nosto-3" />
152
- <NostoProduct product={product.id} />
153
- </div>
154
- ```
155
-
156
- ##### Personalising your search result pages
157
-
158
- You can personalise your search pages by using the `NostoSearch` component. The component requires that you provide it the current search term.
159
-
160
- By default, your account, when created, has <u>two</u> search-page placements named `searchpage-nosto-1` and `searchpage-nosto-2`. You may omit these and use any identifier you need. The identifiers used here are simply provided to illustrate the example.
161
-
162
- ```jsx
163
- import { NostoPlacement, NostoSearch } from "@nosto/nosto-react"
164
- <div className="search-page">
165
- ... ... ...
166
- <NostoPlacement id="searchpage-nosto-1" />
167
- <NostoPlacement id="searchpage-nosto-2" />
168
- <NostoSearch query={search} />
169
- </div>
170
- ```
171
-
172
- **Note:** Do not encode the search term in any way. It should be provided an unencoded string. A query for "black shoes" must be provided as-is and not as "black+shoes". Doing so will lead to invalid results.
173
-
174
- ##### Personalising your category list pages
175
-
176
- You can personalise your category and collection pages by using the `NostoCategory` component. The component requires that you provide it the the slash-delimited slug representation of the current category.
177
-
178
- By default, your account, when created, has <u>two</u> category placements named `categorypage-nosto-1` and `categorypage-nosto-2`. You may omit these and use any identifier you need. The identifiers used here are simply provided to illustrate the example.
179
-
180
- ```jsx
181
- import { NostoCategory, NostoPlacement } from "@nosto/nosto-react"
182
- <div className="category-page">
183
- ... ... ...
184
- <NostoPlacement id="categorypage-nosto-1" />
185
- <NostoPlacement id="categorypage-nosto-2" />
186
- <NostoCategory category={category.name} />
187
- </div>
188
- ```
189
-
190
- **Note:** Be sure to pass in the correct category representation. If the category being viewed is Mens >> Jackets, you must provide the name as `/Mens/Jackets` . You must ensure that the category path provided here matches that of the categories tagged in your products.
191
-
192
- ##### Personalising your cart checkout pages
193
-
194
- You can personalise your cart and checkout pages by using the `NostoCheckout` component. The component does not require any props.
195
-
196
- By default, your account, when created, has <u>two</u> cart-page placements named `categorypage-nosto-1` and `categorypage-nosto-2`. You may omit these and use any identifier you need. The identifiers used here are simply provided to illustrate the example.
197
-
198
- ```jsx
199
- import { NostoCheckout, NostoPlacement } from "@nosto/nosto-react"
200
- <div className="checkout-page">
201
- ... ... ...
202
- <NostoPlacement id="checkout-nosto-1" />
203
- <NostoPlacement id="checkout-nosto-2" />
204
- <NostoCheckout />
205
- </div>
206
- ```
207
-
208
- ##### Personalising your 404 error pages
209
-
210
- You can personalise not found pages by using the `Nosto404` component. The component does not require any props.
211
-
212
- By default, your account, when created, has three 404-page placements named `notfound-nosto-1`, `notfound-nosto-2` and `notfound-nosto-2`. You may omit these and use any identifier you need. The identifiers used here are simply provided to illustrate the example.
213
-
214
- ```jsx
215
- import { Nosto404, NostoPlacement } from "@nosto/nosto-react"
216
- <div className="notfound-page">
217
- ... ... ...
218
- <NostoPlacement id="notfound-nosto-1" />
219
- <NostoPlacement id="notfound-nosto-2" />
220
- <NostoPlacement id="notfound-nosto-3" />
221
- <Nosto404 />
222
- </div>
223
- ```
224
-
225
- ##### Personalising your miscellaneous pages
226
-
227
- You can personalise your miscellaneous pages by using the `NostoOther` component. The component does not require any props.
228
-
229
- By default, your account, when created, has two other-page placements named `other-nosto-1` and `other-nosto-2`. You may omit these and use any identifier you need. The identifiers used here are simply provided to illustrate the example.
230
-
231
- ```jsx
232
- import { NostoOther, NostoPlacement } from "@nosto/nosto-react"
233
- <div className="other-page">
234
- ... ... ...
235
- <NostoPlacement id="other-nosto-1" />
236
- <NostoPlacement id="other-nosto-2" />
237
- <NostoOther />
238
- </div>
239
- ```
240
-
241
- ##### Personalising your order confirmation page
242
-
243
- You can personalise your order-confirmation/thank-you page by using the `NostoOrder` component. The component requires that you provide it with the details of the order.
244
-
245
- By default, your account, when created, has one other-page placement named `thankyou-nosto-1`. You may omit this and use any identifier you need. The identifier used here is simply provided to illustrate the example.
246
-
247
- ```jsx
248
- import { NostoOrder, NostoPlacement } from "@nosto/nosto-react"
249
- <div className="thankyou-page">
250
- ... ... ...
251
- <NostoPlacement id="thankyou-nosto-1" />
252
- <NostoOrder order={order} />
253
- </div>
254
- ```
255
-
256
- ### Hook alternatives
257
-
258
- For all the page type specific components hooks are also provided with the same props
259
-
260
- - useNosto404
261
- - useNostoOther
262
- - useNostoCheckout
263
- - useNostoProduct
264
- - useNostoCategory
265
- - useNostoSearch
266
- - useNostOrder
267
- - useNostoHome
268
-
269
- ### Detailed technical documentation
270
-
271
- Find our latest technical specs and documentation hosted [here](https://nosto.github.io/nosto-react).
272
-
273
- ### Feedback
274
-
275
- If you've found a feature missing or you would like to report an issue, simply [open up an issue](https://github.com/nosto/nosto-react/issues/new) and let us know.
276
-
277
- We're always collecting feedback and learning from your use-cases. If you find your self customising widgets and forking the repo to make patches - do drop a message. We'd love to know more and understand how we can make React Nosto an even slicker library for you.
278
-
279
- ### Contributing
280
-
281
- Please take a moment to review the guidelines for contributing.
282
-
283
- ### License
284
-
285
- BSD 3-Clause License
30
+ [Library TypeDoc page](https://nosto.github.io/nosto-react/) includes detailed library helpers documentation and examples.
package/dist/index.d.ts CHANGED
@@ -9,8 +9,6 @@ import { ReactElement } from 'react';
9
9
  import { ReactNode } from 'react';
10
10
  import { RenderMode } from '@nosto/nosto-js/client';
11
11
 
12
- declare type AnyFunction = (...args: unknown[]) => unknown;
13
-
14
12
  export { Cart }
15
13
 
16
14
  export { Customer }
@@ -116,7 +114,7 @@ export declare interface NostoContextType {
116
114
  account: string;
117
115
  clientScriptLoaded: boolean;
118
116
  currentVariation?: string;
119
- renderFunction?: AnyFunction;
117
+ renderFunction?: (...args: unknown[]) => unknown;
120
118
  responseMode: RenderMode;
121
119
  recommendationComponent?: RecommendationComponent;
122
120
  }
@@ -296,7 +294,7 @@ export declare function NostoProvider(props: NostoProviderProps): JSX.Element;
296
294
  /**
297
295
  * @group Components
298
296
  */
299
- declare interface NostoProviderProps {
297
+ export declare interface NostoProviderProps {
300
298
  /**
301
299
  * Indicates merchant id
302
300
  */
@@ -412,10 +410,12 @@ export declare interface Recommendation {
412
410
  params: unknown;
413
411
  }
414
412
 
415
- declare type RecommendationComponent = ReactElement<{
413
+ export declare type RecommendationComponent = ReactElement<{
416
414
  nostoRecommendation: Recommendation;
417
415
  }>;
418
416
 
417
+ export { RenderMode }
418
+
419
419
  /**
420
420
  * @group Types
421
421
  */
@@ -430,9 +430,9 @@ export declare type ScriptLoadOptions = {
430
430
  attributes?: Record<string, string>;
431
431
  };
432
432
 
433
- declare type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}` ? `${T}${Capitalize<SnakeToCamelCase<U>>}` : S;
433
+ export declare type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}` ? `${T}${Capitalize<SnakeToCamelCase<U>>}` : S;
434
434
 
435
- declare type ToCamelCase<T> = T extends (infer U)[] ? ToCamelCase<U>[] : T extends Date ? T : T extends object ? {
435
+ export declare type ToCamelCase<T> = T extends (infer U)[] ? ToCamelCase<U>[] : T extends Date ? T : T extends object ? {
436
436
  [K in keyof T as SnakeToCamelCase<K & string>]: ToCamelCase<T[K]>;
437
437
  } : T;
438
438
 
package/dist/index.es.js CHANGED
@@ -1,44 +1,44 @@
1
- import { createContext as k, useContext as x, useEffect as S, useRef as h, useMemo as I, cloneElement as _, useState as M, isValidElement as T } from "react";
2
- import { jsx as v } from "react/jsx-runtime";
3
- import { createRoot as D } from "react-dom/client";
4
- const O = k({
1
+ import { createContext as k, useContext as b, useEffect as g, useRef as h, useMemo as A, cloneElement as x, useState as I, isValidElement as M } from "react";
2
+ import { jsx as C } from "react/jsx-runtime";
3
+ import { createRoot as _ } from "react-dom/client";
4
+ const v = k({
5
5
  account: "",
6
6
  currentVariation: "",
7
7
  responseMode: "HTML",
8
8
  clientScriptLoaded: !1
9
9
  });
10
- function P() {
11
- return x(O);
10
+ function y() {
11
+ return b(v);
12
12
  }
13
- const g = (e) => String(e) === "[object Object]";
14
- function L(e) {
15
- if (!g(e)) return !1;
13
+ const P = (e) => String(e) === "[object Object]";
14
+ function N(e) {
15
+ if (!P(e)) return !1;
16
16
  const t = e.constructor;
17
17
  if (t === void 0) return !0;
18
18
  const n = t.prototype;
19
- return !(!g(n) || !n.hasOwnProperty("isPrototypeOf"));
19
+ return !(!P(n) || !n.hasOwnProperty("isPrototypeOf"));
20
20
  }
21
- function y(e, t) {
21
+ function w(e, t) {
22
22
  if (e === t)
23
23
  return !0;
24
24
  if (e instanceof Date && t instanceof Date)
25
25
  return e.getTime() === t.getTime();
26
26
  if (e instanceof Array && t instanceof Array)
27
- return e.length !== t.length ? !1 : e.every((n, o) => y(n, t[o]));
28
- if (L(e) && L(t)) {
27
+ return e.length !== t.length ? !1 : e.every((n, o) => w(n, t[o]));
28
+ if (N(e) && N(t)) {
29
29
  const n = Object.entries(e);
30
- return n.length !== Object.keys(t).length ? !1 : n.every(([o, r]) => y(r, t[o]));
30
+ return n.length !== Object.keys(t).length ? !1 : n.every(([o, r]) => w(r, t[o]));
31
31
  }
32
32
  return !1;
33
33
  }
34
- function j(e, t) {
35
- return S(e, V(t));
34
+ function L(e, t) {
35
+ return g(e, T(t));
36
36
  }
37
- function V(e) {
37
+ function T(e) {
38
38
  const t = h(e), n = h(0);
39
- return y(e, t.current) || (t.current = e, n.current += 1), I(() => t.current, [n.current]);
39
+ return w(e, t.current) || (t.current = e, n.current += 1), A(() => t.current, [n.current]);
40
40
  }
41
- function N() {
41
+ function S() {
42
42
  window.nostojs = window.nostojs ?? function(e) {
43
43
  (window.nostojs.q = window.nostojs.q ?? []).push(e);
44
44
  };
@@ -46,88 +46,86 @@ function N() {
46
46
  async function m(e) {
47
47
  return window.nostojs(e);
48
48
  }
49
- typeof window < "u" && (N(), m((e) => {
49
+ typeof window < "u" && (S(), m((e) => {
50
50
  e.internal.getSettings();
51
51
  }));
52
- function q() {
52
+ function D() {
53
53
  return typeof window.nosto < "u";
54
54
  }
55
- const H = {
55
+ const V = {
56
56
  production: "https://connect.nosto.com/",
57
57
  staging: "https://connect.staging.nosto.com/",
58
58
  local: "https://connect.nosto.com/"
59
59
  };
60
- function R(e) {
61
- return H[e ?? "production"];
62
- }
63
- function F({ merchantId: e, env: t, options: n, shopifyInternational: o, scriptLoader: r }) {
64
- var c, i;
65
- const s = document.querySelector("script[nosto-language], script[nosto-market-id]"), a = String((o == null ? void 0 : o.marketId) || ""), u = (o == null ? void 0 : o.language) || "", C = (s == null ? void 0 : s.getAttribute("nosto-language")) !== u || (s == null ? void 0 : s.getAttribute("nosto-market-id")) !== a;
66
- if (!s || C) {
67
- const f = document.querySelector("#nosto-sandbox");
68
- (c = s == null ? void 0 : s.parentNode) == null || c.removeChild(s), (i = f == null ? void 0 : f.parentNode) == null || i.removeChild(f);
69
- const p = new URL("/script/shopify/market/nosto.js", R(t));
70
- p.searchParams.append("merchant", e), p.searchParams.append("market", a), p.searchParams.append("locale", u.toLowerCase());
71
- const b = {
72
- ...n == null ? void 0 : n.attributes,
73
- "nosto-language": u,
74
- "nosto-market-id": a
60
+ function O(e) {
61
+ return V[e ?? "production"];
62
+ }
63
+ function q({ merchantId: e, env: t, options: n, shopifyInternational: o, scriptLoader: r }) {
64
+ const s = document.querySelector("script[nosto-language], script[nosto-market-id]"), c = String(o?.marketId || ""), i = o?.language || "", a = s?.getAttribute("nosto-language") !== i || s?.getAttribute("nosto-market-id") !== c;
65
+ if (!s || a) {
66
+ const u = document.querySelector("#nosto-sandbox");
67
+ s?.parentNode?.removeChild(s), u?.parentNode?.removeChild(u);
68
+ const f = new URL("/script/shopify/market/nosto.js", O(t));
69
+ f.searchParams.append("merchant", e), f.searchParams.append("market", c), f.searchParams.append("locale", i.toLowerCase());
70
+ const E = {
71
+ ...n?.attributes,
72
+ "nosto-language": i,
73
+ "nosto-market-id": c
75
74
  };
76
- return (r ?? E)(p.toString(), { ...n, attributes: b });
75
+ return (r ?? j)(f.toString(), { ...n, attributes: E });
77
76
  }
78
77
  return Promise.resolve();
79
78
  }
80
- function z(e) {
79
+ function H(e) {
81
80
  if (e.shopifyInternational)
82
- return F(e);
83
- const { merchantId: t, env: n, options: o, scriptLoader: r } = e, c = r ?? E, i = new URL(`/include/${t}`, R(n));
84
- return c(i.toString(), o);
81
+ return q(e);
82
+ const { merchantId: t, env: n, options: o, scriptLoader: r } = e, s = r ?? j, c = new URL(`/include/${t}`, O(n));
83
+ return s(c.toString(), o);
85
84
  }
86
- function E(e, t) {
85
+ function j(e, t) {
87
86
  return new Promise((n, o) => {
88
87
  const r = document.createElement("script");
89
- r.src = e, r.async = !0, r.type = "text/javascript", r.onload = () => n(), r.onerror = () => o(), Object.entries((t == null ? void 0 : t.attributes) ?? {}).forEach(([c, i]) => r.setAttribute(c, i)), (t == null ? void 0 : t.position) === "head" ? document.head.appendChild(r) : document.body.appendChild(r);
88
+ r.src = e, r.async = !0, r.type = "text/javascript", r.onload = () => n(), r.onerror = () => o(), Object.entries(t?.attributes ?? {}).forEach(([s, c]) => r.setAttribute(s, c)), t?.position === "head" ? document.head.appendChild(r) : document.body.appendChild(r);
90
89
  });
91
90
  }
92
- typeof window < "u" && N();
91
+ typeof window < "u" && S();
93
92
  function d(e, t, n) {
94
- const { clientScriptLoaded: o } = P();
95
- (n != null && n.deep ? j : S)(() => {
93
+ const { clientScriptLoaded: o } = y();
94
+ (n?.deep ? L : g)(() => {
96
95
  o && m(e);
97
96
  }, [o, ...t ?? []]);
98
97
  }
99
- function U(e) {
100
- return _(e.recommendationComponent, {
98
+ function F(e) {
99
+ return x(e.recommendationComponent, {
101
100
  // eslint-disable-next-line react/prop-types
102
101
  nostoRecommendation: e.nostoRecommendation
103
102
  });
104
103
  }
105
- function A(e) {
104
+ function R(e) {
106
105
  m((t) => t.placements.injectCampaigns(e));
107
106
  }
108
- function $(e) {
107
+ function z(e) {
109
108
  if (!window.nostojs)
110
109
  throw new Error("Nosto has not yet been initialized");
111
- A(e.recommendations);
110
+ R(e.recommendations);
112
111
  }
113
112
  function l() {
114
- const { responseMode: e, recommendationComponent: t } = P(), n = h({});
113
+ const { responseMode: e, recommendationComponent: t } = y(), n = h({});
115
114
  if (e == "HTML")
116
- return { renderCampaigns: $ };
115
+ return { renderCampaigns: z };
117
116
  if (!t)
118
117
  throw new Error("recommendationComponent is required for client-side rendering using hook");
119
118
  function o(r) {
120
- var i, s;
121
- A(((i = r.campaigns) == null ? void 0 : i.content) ?? {});
122
- const c = ((s = r.campaigns) == null ? void 0 : s.recommendations) ?? {};
123
- for (const a in c) {
124
- const u = c[a], C = "#" + a, f = document.querySelector(C);
125
- f && (n.current[a] || (n.current[a] = D(f)), n.current[a].render(
126
- /* @__PURE__ */ v(
127
- U,
119
+ R(r.campaigns?.content ?? {});
120
+ const s = r.campaigns?.recommendations ?? {};
121
+ for (const c in s) {
122
+ const i = s[c], a = "#" + c, u = document.querySelector(a);
123
+ u && (n.current[c] || (n.current[c] = _(u)), n.current[c].render(
124
+ /* @__PURE__ */ C(
125
+ F,
128
126
  {
129
127
  recommendationComponent: t,
130
- nostoRecommendation: u
128
+ nostoRecommendation: i
131
129
  }
132
130
  )
133
131
  ));
@@ -135,17 +133,17 @@ function l() {
135
133
  }
136
134
  return { renderCampaigns: o };
137
135
  }
138
- function G(e) {
136
+ function U(e) {
139
137
  const { renderCampaigns: t } = l();
140
138
  d(async (n) => {
141
- const o = await n.defaultSession().viewNotFound().setPlacements((e == null ? void 0 : e.placements) || n.placements.getPlacements()).load();
139
+ const o = await n.defaultSession().viewNotFound().setPlacements(e?.placements || n.placements.getPlacements()).load();
142
140
  t(o);
143
141
  });
144
142
  }
145
- function ae(e) {
146
- return G(e), null;
143
+ function ce(e) {
144
+ return U(e), null;
147
145
  }
148
- function J({ category: e, placements: t }) {
146
+ function $({ category: e, placements: t }) {
149
147
  const { renderCampaigns: n } = l();
150
148
  d(
151
149
  async (o) => {
@@ -155,145 +153,145 @@ function J({ category: e, placements: t }) {
155
153
  [e]
156
154
  );
157
155
  }
158
- function ue(e) {
159
- return J(e), null;
156
+ function ie(e) {
157
+ return $(e), null;
160
158
  }
161
- function W(e) {
159
+ function G(e) {
162
160
  const { renderCampaigns: t } = l();
163
161
  d(async (n) => {
164
- const o = await n.defaultSession().viewCart().setPlacements((e == null ? void 0 : e.placements) || n.placements.getPlacements()).load();
162
+ const o = await n.defaultSession().viewCart().setPlacements(e?.placements || n.placements.getPlacements()).load();
165
163
  t(o);
166
164
  });
167
165
  }
168
- function de(e) {
169
- return W(e), null;
166
+ function ae(e) {
167
+ return G(e), null;
170
168
  }
171
- function Z(e) {
169
+ function J(e) {
172
170
  const { renderCampaigns: t } = l();
173
171
  d(async (n) => {
174
- const o = await n.defaultSession().viewFrontPage().setPlacements((e == null ? void 0 : e.placements) || n.placements.getPlacements()).load();
172
+ const o = await n.defaultSession().viewFrontPage().setPlacements(e?.placements || n.placements.getPlacements()).load();
175
173
  t(o);
176
174
  });
177
175
  }
178
- function le(e) {
179
- return Z(e), null;
176
+ function ue(e) {
177
+ return J(e), null;
180
178
  }
181
- function w(e) {
182
- return !e || typeof e != "object" || B(e) || K(e) ? e : Array.isArray(e) ? e.map(w) : Object.keys(e).reduce((t, n) => {
183
- const o = n[0].toLowerCase() + n.slice(1).replace(/([A-Z]+)/g, (r, c) => "_" + c.toLowerCase());
184
- return t[o] = w(e[n]), t;
179
+ function p(e) {
180
+ return !e || typeof e != "object" || W(e) || Z(e) ? e : Array.isArray(e) ? e.map(p) : Object.keys(e).reduce((t, n) => {
181
+ const o = n[0].toLowerCase() + n.slice(1).replace(/([A-Z]+)/g, (r, s) => "_" + s.toLowerCase());
182
+ return t[o] = p(e[n]), t;
185
183
  }, {});
186
184
  }
187
- function B(e) {
185
+ function W(e) {
188
186
  return Object.prototype.toString.call(e) === "[object Date]";
189
187
  }
190
- function K(e) {
188
+ function Z(e) {
191
189
  return Object.prototype.toString.call(e) === "[object RegExp]";
192
190
  }
193
- function Q({ order: e, placements: t }) {
191
+ function B({ order: e, placements: t }) {
194
192
  const { renderCampaigns: n } = l();
195
193
  d(
196
194
  async (o) => {
197
- const r = await o.defaultSession().addOrder(w(e)).setPlacements(t || o.placements.getPlacements()).load();
195
+ const r = await o.defaultSession().addOrder(p(e)).setPlacements(t || o.placements.getPlacements()).load();
198
196
  n(r);
199
197
  },
200
198
  [e],
201
199
  { deep: !0 }
202
200
  );
203
201
  }
204
- function me(e) {
205
- return Q(e), null;
202
+ function de(e) {
203
+ return B(e), null;
206
204
  }
207
- function X(e) {
205
+ function K(e) {
208
206
  const { renderCampaigns: t } = l();
209
207
  d(async (n) => {
210
- const o = await n.defaultSession().viewOther().setPlacements((e == null ? void 0 : e.placements) || n.placements.getPlacements()).load();
208
+ const o = await n.defaultSession().viewOther().setPlacements(e?.placements || n.placements.getPlacements()).load();
211
209
  t(o);
212
210
  });
213
211
  }
214
- function fe(e) {
215
- return X(e), null;
212
+ function le(e) {
213
+ return K(e), null;
216
214
  }
217
- function pe({ id: e, pageType: t, children: n }) {
218
- return /* @__PURE__ */ v("div", { className: "nosto_element", id: e, children: n }, e + (t || ""));
215
+ function me({ id: e, pageType: t, children: n }) {
216
+ return /* @__PURE__ */ C("div", { className: "nosto_element", id: e, children: n }, e + (t || ""));
219
217
  }
220
- function Y({ product: e, tagging: t, placements: n, reference: o }) {
218
+ function Q({ product: e, tagging: t, placements: n, reference: o }) {
221
219
  const { renderCampaigns: r } = l();
222
220
  if (t && !t.product_id)
223
221
  throw new Error("The product object must contain a product_id property");
224
- const c = (t == null ? void 0 : t.product_id) ?? e;
222
+ const s = t?.product_id ?? e;
225
223
  d(
226
- async (i) => {
227
- const s = i.defaultSession().viewProduct(t ?? e).setPlacements(n || i.placements.getPlacements());
228
- o && s.setRef(c, o);
229
- const a = await s.load();
224
+ async (c) => {
225
+ const i = c.defaultSession().viewProduct(t ?? e).setPlacements(n || c.placements.getPlacements());
226
+ o && i.setRef(s, o);
227
+ const a = await i.load();
230
228
  r(a);
231
229
  },
232
- [c, t == null ? void 0 : t.selected_sku_id]
230
+ [s, t?.selected_sku_id]
233
231
  );
234
232
  }
235
- function we(e) {
236
- return Y(e), null;
233
+ function fe(e) {
234
+ return Q(e), null;
237
235
  }
238
- function ee(e, t) {
236
+ function X(e, t) {
239
237
  return new Promise((n, o) => {
240
238
  const r = document.createElement("script");
241
- r.type = "text/javascript", r.src = e, r.async = !0, r.onload = () => n(), r.onerror = () => o(), Object.entries((t == null ? void 0 : t.attributes) ?? {}).forEach(([c, i]) => r.setAttribute(c, i)), (t == null ? void 0 : t.position) === "head" ? document.head.appendChild(r) : document.body.appendChild(r);
239
+ r.type = "text/javascript", r.src = e, r.async = !0, r.onload = () => n(), r.onerror = () => o(), Object.entries(t?.attributes ?? {}).forEach(([s, c]) => r.setAttribute(s, c)), t?.position === "head" ? document.head.appendChild(r) : document.body.appendChild(r);
242
240
  });
243
241
  }
244
- const te = { "nosto-client-script": "" };
245
- function ne(e) {
242
+ const Y = { "nosto-client-script": "" };
243
+ function ee(e) {
246
244
  const {
247
- scriptLoader: t = ee,
245
+ scriptLoader: t = X,
248
246
  account: n,
249
247
  shopifyMarkets: o,
250
248
  loadScript: r = !0
251
- } = e, [c, i] = M(!1);
252
- return S(() => {
253
- function s() {
254
- i(!0);
249
+ } = e, [s, c] = I(!1);
250
+ return g(() => {
251
+ function i() {
252
+ c(!0);
255
253
  }
256
- if (N(), m((u) => u.setAutoLoad(!1)), !r) {
257
- m(s);
254
+ if (S(), m((u) => u.setAutoLoad(!1)), !r) {
255
+ m(i);
258
256
  return;
259
257
  }
260
258
  async function a() {
261
- await z({
259
+ await H({
262
260
  merchantId: n,
263
261
  shopifyInternational: o,
264
262
  options: {
265
- attributes: te
263
+ attributes: Y
266
264
  },
267
265
  scriptLoader: t
268
- }), s();
266
+ }), i();
269
267
  }
270
- (!q() || o) && a();
271
- }, [o == null ? void 0 : o.marketId, o == null ? void 0 : o.language]), { clientScriptLoaded: c };
268
+ (!D() || o) && a();
269
+ }, [o?.marketId, o?.language]), { clientScriptLoaded: s };
272
270
  }
273
- function Ce(e) {
274
- const { account: t, multiCurrency: n = !1, children: o, recommendationComponent: r, renderMode: c } = e, i = n ? e.currentVariation : "";
275
- if (r && !T(r))
271
+ function pe(e) {
272
+ const { account: t, multiCurrency: n = !1, children: o, recommendationComponent: r, renderMode: s } = e, c = n ? e.currentVariation : "";
273
+ if (r && !M(r))
276
274
  throw new Error(
277
275
  "The recommendationComponent prop must be a valid React element. Please provide a valid React element."
278
276
  );
279
- const s = c || (r ? "JSON_ORIGINAL" : "HTML"), { clientScriptLoaded: a } = ne(e);
277
+ const i = s || (r ? "JSON_ORIGINAL" : "HTML"), { clientScriptLoaded: a } = ee(e);
280
278
  return a && m((u) => {
281
- u.defaultSession().setVariation(i).setResponseMode(s);
282
- }), /* @__PURE__ */ v(
283
- O.Provider,
279
+ u.defaultSession().setVariation(c).setResponseMode(i);
280
+ }), /* @__PURE__ */ C(
281
+ v.Provider,
284
282
  {
285
283
  value: {
286
284
  account: t,
287
285
  clientScriptLoaded: a,
288
- currentVariation: i,
289
- responseMode: s,
286
+ currentVariation: c,
287
+ responseMode: i,
290
288
  recommendationComponent: r
291
289
  },
292
290
  children: o
293
291
  }
294
292
  );
295
293
  }
296
- function oe({ query: e, placements: t }) {
294
+ function te({ query: e, placements: t }) {
297
295
  const { renderCampaigns: n } = l();
298
296
  d(
299
297
  async (o) => {
@@ -304,41 +302,41 @@ function oe({ query: e, placements: t }) {
304
302
  );
305
303
  }
306
304
  function he(e) {
307
- return oe(e), null;
308
- }
309
- function re({ cart: e, customer: t } = {}) {
310
- const { clientScriptLoaded: n } = P();
311
- j(() => {
312
- const o = e ? w(e) : void 0, r = t ? w(t) : void 0;
313
- n && m((c) => {
314
- c.defaultSession().setCart(o).setCustomer(r).viewOther().load({ skipPageViews: !0 });
305
+ return te(e), null;
306
+ }
307
+ function ne({ cart: e, customer: t } = {}) {
308
+ const { clientScriptLoaded: n } = y();
309
+ L(() => {
310
+ const o = e ? p(e) : void 0, r = t ? p(t) : void 0;
311
+ n && m((s) => {
312
+ s.defaultSession().setCart(o).setCustomer(r).viewOther().load({ skipPageViews: !0 });
315
313
  });
316
314
  }, [n, e, t]);
317
315
  }
318
- function ye(e) {
319
- return re(e), null;
316
+ function we(e) {
317
+ return ne(e), null;
320
318
  }
321
319
  export {
322
- ae as Nosto404,
323
- ue as NostoCategory,
324
- de as NostoCheckout,
325
- O as NostoContext,
326
- le as NostoHome,
327
- me as NostoOrder,
328
- fe as NostoOther,
329
- pe as NostoPlacement,
330
- we as NostoProduct,
331
- Ce as NostoProvider,
320
+ ce as Nosto404,
321
+ ie as NostoCategory,
322
+ ae as NostoCheckout,
323
+ v as NostoContext,
324
+ ue as NostoHome,
325
+ de as NostoOrder,
326
+ le as NostoOther,
327
+ me as NostoPlacement,
328
+ fe as NostoProduct,
329
+ pe as NostoProvider,
332
330
  he as NostoSearch,
333
- ye as NostoSession,
334
- G as useNosto404,
335
- J as useNostoCategory,
336
- W as useNostoCheckout,
337
- P as useNostoContext,
338
- Z as useNostoHome,
339
- Q as useNostoOrder,
340
- X as useNostoOther,
341
- Y as useNostoProduct,
342
- oe as useNostoSearch,
343
- re as useNostoSession
331
+ we as NostoSession,
332
+ U as useNosto404,
333
+ $ as useNostoCategory,
334
+ G as useNostoCheckout,
335
+ y as useNostoContext,
336
+ J as useNostoHome,
337
+ B as useNostoOrder,
338
+ K as useNostoOther,
339
+ Q as useNostoProduct,
340
+ te as useNostoSearch,
341
+ ne as useNostoSession
344
342
  };
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- (function(s,u){typeof exports=="object"&&typeof module<"u"?u(exports,require("react"),require("react/jsx-runtime"),require("react-dom/client")):typeof define=="function"&&define.amd?define(["exports","react","react/jsx-runtime","react-dom/client"],u):(s=typeof globalThis<"u"?globalThis:s||self,u(s["@nosto/nosto-react"]={},s.React,s["react/jsx-runtime"],s.client))})(this,function(s,u,y,V){"use strict";const S=u.createContext({account:"",currentVariation:"",responseMode:"HTML",clientScriptLoaded:!1});function N(){return u.useContext(S)}const g=e=>String(e)==="[object Object]";function j(e){if(!g(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!g(n)||!n.hasOwnProperty("isPrototypeOf"))}function P(e,t){if(e===t)return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof Array&&t instanceof Array)return e.length!==t.length?!1:e.every((n,o)=>P(n,t[o]));if(j(e)&&j(t)){const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([o,r])=>P(r,t[o]))}return!1}function L(e,t){return u.useEffect(e,F(t))}function F(e){const t=u.useRef(e),n=u.useRef(0);return P(e,t.current)||(t.current=e,n.current+=1),u.useMemo(()=>t.current,[n.current])}function v(){window.nostojs=window.nostojs??function(e){(window.nostojs.q=window.nostojs.q??[]).push(e)}}async function p(e){return window.nostojs(e)}typeof window<"u"&&(v(),p(e=>{e.internal.getSettings()}));function z(){return typeof window.nosto<"u"}const U={production:"https://connect.nosto.com/",staging:"https://connect.staging.nosto.com/",local:"https://connect.nosto.com/"};function R(e){return U[e??"production"]}function $({merchantId:e,env:t,options:n,shopifyInternational:o,scriptLoader:r}){var c,a;const i=document.querySelector("script[nosto-language], script[nosto-market-id]"),d=String((o==null?void 0:o.marketId)||""),l=(o==null?void 0:o.language)||"",O=(i==null?void 0:i.getAttribute("nosto-language"))!==l||(i==null?void 0:i.getAttribute("nosto-market-id"))!==d;if(!i||O){const h=document.querySelector("#nosto-sandbox");(c=i==null?void 0:i.parentNode)==null||c.removeChild(i),(a=h==null?void 0:h.parentNode)==null||a.removeChild(h);const w=new URL("/script/shopify/market/nosto.js",R(t));w.searchParams.append("merchant",e),w.searchParams.append("market",d),w.searchParams.append("locale",l.toLowerCase());const ue={...n==null?void 0:n.attributes,"nosto-language":l,"nosto-market-id":d};return(r??E)(w.toString(),{...n,attributes:ue})}return Promise.resolve()}function G(e){if(e.shopifyInternational)return $(e);const{merchantId:t,env:n,options:o,scriptLoader:r}=e,c=r??E,a=new URL(`/include/${t}`,R(n));return c(a.toString(),o)}function E(e,t){return new Promise((n,o)=>{const r=document.createElement("script");r.src=e,r.async=!0,r.type="text/javascript",r.onload=()=>n(),r.onerror=()=>o(),Object.entries((t==null?void 0:t.attributes)??{}).forEach(([c,a])=>r.setAttribute(c,a)),(t==null?void 0:t.position)==="head"?document.head.appendChild(r):document.body.appendChild(r)})}typeof window<"u"&&v();function m(e,t,n){const{clientScriptLoaded:o}=N();(n!=null&&n.deep?L:u.useEffect)(()=>{o&&p(e)},[o,...t??[]])}function J(e){return u.cloneElement(e.recommendationComponent,{nostoRecommendation:e.nostoRecommendation})}function A(e){p(t=>t.placements.injectCampaigns(e))}function W(e){if(!window.nostojs)throw new Error("Nosto has not yet been initialized");A(e.recommendations)}function f(){const{responseMode:e,recommendationComponent:t}=N(),n=u.useRef({});if(e=="HTML")return{renderCampaigns:W};if(!t)throw new Error("recommendationComponent is required for client-side rendering using hook");function o(r){var a,i;A(((a=r.campaigns)==null?void 0:a.content)??{});const c=((i=r.campaigns)==null?void 0:i.recommendations)??{};for(const d in c){const l=c[d],O="#"+d,h=document.querySelector(O);h&&(n.current[d]||(n.current[d]=V.createRoot(h)),n.current[d].render(y.jsx(J,{recommendationComponent:t,nostoRecommendation:l})))}}return{renderCampaigns:o}}function b(e){const{renderCampaigns:t}=f();m(async n=>{const o=await n.defaultSession().viewNotFound().setPlacements((e==null?void 0:e.placements)||n.placements.getPlacements()).load();t(o)})}function Z(e){return b(e),null}function k({category:e,placements:t}){const{renderCampaigns:n}=f();m(async o=>{const r=await o.defaultSession().viewCategory(e).setPlacements(t||o.placements.getPlacements()).load();n(r)},[e])}function B(e){return k(e),null}function I(e){const{renderCampaigns:t}=f();m(async n=>{const o=await n.defaultSession().viewCart().setPlacements((e==null?void 0:e.placements)||n.placements.getPlacements()).load();t(o)})}function K(e){return I(e),null}function T(e){const{renderCampaigns:t}=f();m(async n=>{const o=await n.defaultSession().viewFrontPage().setPlacements((e==null?void 0:e.placements)||n.placements.getPlacements()).load();t(o)})}function Q(e){return T(e),null}function C(e){return!e||typeof e!="object"||X(e)||Y(e)?e:Array.isArray(e)?e.map(C):Object.keys(e).reduce((t,n)=>{const o=n[0].toLowerCase()+n.slice(1).replace(/([A-Z]+)/g,(r,c)=>"_"+c.toLowerCase());return t[o]=C(e[n]),t},{})}function X(e){return Object.prototype.toString.call(e)==="[object Date]"}function Y(e){return Object.prototype.toString.call(e)==="[object RegExp]"}function _({order:e,placements:t}){const{renderCampaigns:n}=f();m(async o=>{const r=await o.defaultSession().addOrder(C(e)).setPlacements(t||o.placements.getPlacements()).load();n(r)},[e],{deep:!0})}function x(e){return _(e),null}function q(e){const{renderCampaigns:t}=f();m(async n=>{const o=await n.defaultSession().viewOther().setPlacements((e==null?void 0:e.placements)||n.placements.getPlacements()).load();t(o)})}function ee(e){return q(e),null}function te({id:e,pageType:t,children:n}){return y.jsx("div",{className:"nosto_element",id:e,children:n},e+(t||""))}function M({product:e,tagging:t,placements:n,reference:o}){const{renderCampaigns:r}=f();if(t&&!t.product_id)throw new Error("The product object must contain a product_id property");const c=(t==null?void 0:t.product_id)??e;m(async a=>{const i=a.defaultSession().viewProduct(t??e).setPlacements(n||a.placements.getPlacements());o&&i.setRef(c,o);const d=await i.load();r(d)},[c,t==null?void 0:t.selected_sku_id])}function ne(e){return M(e),null}function oe(e,t){return new Promise((n,o)=>{const r=document.createElement("script");r.type="text/javascript",r.src=e,r.async=!0,r.onload=()=>n(),r.onerror=()=>o(),Object.entries((t==null?void 0:t.attributes)??{}).forEach(([c,a])=>r.setAttribute(c,a)),(t==null?void 0:t.position)==="head"?document.head.appendChild(r):document.body.appendChild(r)})}const re={"nosto-client-script":""};function se(e){const{scriptLoader:t=oe,account:n,shopifyMarkets:o,loadScript:r=!0}=e,[c,a]=u.useState(!1);return u.useEffect(()=>{function i(){a(!0)}if(v(),p(l=>l.setAutoLoad(!1)),!r){p(i);return}async function d(){await G({merchantId:n,shopifyInternational:o,options:{attributes:re},scriptLoader:t}),i()}(!z()||o)&&d()},[o==null?void 0:o.marketId,o==null?void 0:o.language]),{clientScriptLoaded:c}}function ce(e){const{account:t,multiCurrency:n=!1,children:o,recommendationComponent:r,renderMode:c}=e,a=n?e.currentVariation:"";if(r&&!u.isValidElement(r))throw new Error("The recommendationComponent prop must be a valid React element. Please provide a valid React element.");const i=c||(r?"JSON_ORIGINAL":"HTML"),{clientScriptLoaded:d}=se(e);return d&&p(l=>{l.defaultSession().setVariation(a).setResponseMode(i)}),y.jsx(S.Provider,{value:{account:t,clientScriptLoaded:d,currentVariation:a,responseMode:i,recommendationComponent:r},children:o})}function H({query:e,placements:t}){const{renderCampaigns:n}=f();m(async o=>{const r=await o.defaultSession().viewSearch(e).setPlacements(t||o.placements.getPlacements()).load();n(r)},[e])}function ie(e){return H(e),null}function D({cart:e,customer:t}={}){const{clientScriptLoaded:n}=N();L(()=>{const o=e?C(e):void 0,r=t?C(t):void 0;n&&p(c=>{c.defaultSession().setCart(o).setCustomer(r).viewOther().load({skipPageViews:!0})})},[n,e,t])}function ae(e){return D(e),null}s.Nosto404=Z,s.NostoCategory=B,s.NostoCheckout=K,s.NostoContext=S,s.NostoHome=Q,s.NostoOrder=x,s.NostoOther=ee,s.NostoPlacement=te,s.NostoProduct=ne,s.NostoProvider=ce,s.NostoSearch=ie,s.NostoSession=ae,s.useNosto404=b,s.useNostoCategory=k,s.useNostoCheckout=I,s.useNostoContext=N,s.useNostoHome=T,s.useNostoOrder=_,s.useNostoOther=q,s.useNostoProduct=M,s.useNostoSearch=H,s.useNostoSession=D,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})});
1
+ (function(r,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("react"),require("react/jsx-runtime"),require("react-dom/client")):typeof define=="function"&&define.amd?define(["exports","react","react/jsx-runtime","react-dom/client"],a):(r=typeof globalThis<"u"?globalThis:r||self,a(r["@nosto/nosto-react"]={},r.React,r["react/jsx-runtime"],r.client))})(this,function(r,a,w,H){"use strict";const y=a.createContext({account:"",currentVariation:"",responseMode:"HTML",clientScriptLoaded:!1});function g(){return a.useContext(y)}const P=e=>String(e)==="[object Object]";function O(e){if(!P(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!P(n)||!n.hasOwnProperty("isPrototypeOf"))}function N(e,t){if(e===t)return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof Array&&t instanceof Array)return e.length!==t.length?!1:e.every((n,o)=>N(n,t[o]));if(O(e)&&O(t)){const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([o,s])=>N(s,t[o]))}return!1}function v(e,t){return a.useEffect(e,D(t))}function D(e){const t=a.useRef(e),n=a.useRef(0);return N(e,t.current)||(t.current=e,n.current+=1),a.useMemo(()=>t.current,[n.current])}function S(){window.nostojs=window.nostojs??function(e){(window.nostojs.q=window.nostojs.q??[]).push(e)}}async function p(e){return window.nostojs(e)}typeof window<"u"&&(S(),p(e=>{e.internal.getSettings()}));function V(){return typeof window.nosto<"u"}const F={production:"https://connect.nosto.com/",staging:"https://connect.staging.nosto.com/",local:"https://connect.nosto.com/"};function j(e){return F[e??"production"]}function z({merchantId:e,env:t,options:n,shopifyInternational:o,scriptLoader:s}){const c=document.querySelector("script[nosto-language], script[nosto-market-id]"),i=String(o?.marketId||""),u=o?.language||"",d=c?.getAttribute("nosto-language")!==u||c?.getAttribute("nosto-market-id")!==i;if(!c||d){const l=document.querySelector("#nosto-sandbox");c?.parentNode?.removeChild(c),l?.parentNode?.removeChild(l);const C=new URL("/script/shopify/market/nosto.js",j(t));C.searchParams.append("merchant",e),C.searchParams.append("market",i),C.searchParams.append("locale",u.toLowerCase());const ie={...n?.attributes,"nosto-language":u,"nosto-market-id":i};return(s??L)(C.toString(),{...n,attributes:ie})}return Promise.resolve()}function U(e){if(e.shopifyInternational)return z(e);const{merchantId:t,env:n,options:o,scriptLoader:s}=e,c=s??L,i=new URL(`/include/${t}`,j(n));return c(i.toString(),o)}function L(e,t){return new Promise((n,o)=>{const s=document.createElement("script");s.src=e,s.async=!0,s.type="text/javascript",s.onload=()=>n(),s.onerror=()=>o(),Object.entries(t?.attributes??{}).forEach(([c,i])=>s.setAttribute(c,i)),t?.position==="head"?document.head.appendChild(s):document.body.appendChild(s)})}typeof window<"u"&&S();function f(e,t,n){const{clientScriptLoaded:o}=g();(n?.deep?v:a.useEffect)(()=>{o&&p(e)},[o,...t??[]])}function $(e){return a.cloneElement(e.recommendationComponent,{nostoRecommendation:e.nostoRecommendation})}function R(e){p(t=>t.placements.injectCampaigns(e))}function G(e){if(!window.nostojs)throw new Error("Nosto has not yet been initialized");R(e.recommendations)}function m(){const{responseMode:e,recommendationComponent:t}=g(),n=a.useRef({});if(e=="HTML")return{renderCampaigns:G};if(!t)throw new Error("recommendationComponent is required for client-side rendering using hook");function o(s){R(s.campaigns?.content??{});const c=s.campaigns?.recommendations??{};for(const i in c){const u=c[i],d="#"+i,l=document.querySelector(d);l&&(n.current[i]||(n.current[i]=H.createRoot(l)),n.current[i].render(w.jsx($,{recommendationComponent:t,nostoRecommendation:u})))}}return{renderCampaigns:o}}function E(e){const{renderCampaigns:t}=m();f(async n=>{const o=await n.defaultSession().viewNotFound().setPlacements(e?.placements||n.placements.getPlacements()).load();t(o)})}function J(e){return E(e),null}function k({category:e,placements:t}){const{renderCampaigns:n}=m();f(async o=>{const s=await o.defaultSession().viewCategory(e).setPlacements(t||o.placements.getPlacements()).load();n(s)},[e])}function W(e){return k(e),null}function b(e){const{renderCampaigns:t}=m();f(async n=>{const o=await n.defaultSession().viewCart().setPlacements(e?.placements||n.placements.getPlacements()).load();t(o)})}function Z(e){return b(e),null}function A(e){const{renderCampaigns:t}=m();f(async n=>{const o=await n.defaultSession().viewFrontPage().setPlacements(e?.placements||n.placements.getPlacements()).load();t(o)})}function B(e){return A(e),null}function h(e){return!e||typeof e!="object"||K(e)||Q(e)?e:Array.isArray(e)?e.map(h):Object.keys(e).reduce((t,n)=>{const o=n[0].toLowerCase()+n.slice(1).replace(/([A-Z]+)/g,(s,c)=>"_"+c.toLowerCase());return t[o]=h(e[n]),t},{})}function K(e){return Object.prototype.toString.call(e)==="[object Date]"}function Q(e){return Object.prototype.toString.call(e)==="[object RegExp]"}function M({order:e,placements:t}){const{renderCampaigns:n}=m();f(async o=>{const s=await o.defaultSession().addOrder(h(e)).setPlacements(t||o.placements.getPlacements()).load();n(s)},[e],{deep:!0})}function X(e){return M(e),null}function I(e){const{renderCampaigns:t}=m();f(async n=>{const o=await n.defaultSession().viewOther().setPlacements(e?.placements||n.placements.getPlacements()).load();t(o)})}function Y(e){return I(e),null}function x({id:e,pageType:t,children:n}){return w.jsx("div",{className:"nosto_element",id:e,children:n},e+(t||""))}function T({product:e,tagging:t,placements:n,reference:o}){const{renderCampaigns:s}=m();if(t&&!t.product_id)throw new Error("The product object must contain a product_id property");const c=t?.product_id??e;f(async i=>{const u=i.defaultSession().viewProduct(t??e).setPlacements(n||i.placements.getPlacements());o&&u.setRef(c,o);const d=await u.load();s(d)},[c,t?.selected_sku_id])}function ee(e){return T(e),null}function te(e,t){return new Promise((n,o)=>{const s=document.createElement("script");s.type="text/javascript",s.src=e,s.async=!0,s.onload=()=>n(),s.onerror=()=>o(),Object.entries(t?.attributes??{}).forEach(([c,i])=>s.setAttribute(c,i)),t?.position==="head"?document.head.appendChild(s):document.body.appendChild(s)})}const ne={"nosto-client-script":""};function oe(e){const{scriptLoader:t=te,account:n,shopifyMarkets:o,loadScript:s=!0}=e,[c,i]=a.useState(!1);return a.useEffect(()=>{function u(){i(!0)}if(S(),p(l=>l.setAutoLoad(!1)),!s){p(u);return}async function d(){await U({merchantId:n,shopifyInternational:o,options:{attributes:ne},scriptLoader:t}),u()}(!V()||o)&&d()},[o?.marketId,o?.language]),{clientScriptLoaded:c}}function se(e){const{account:t,multiCurrency:n=!1,children:o,recommendationComponent:s,renderMode:c}=e,i=n?e.currentVariation:"";if(s&&!a.isValidElement(s))throw new Error("The recommendationComponent prop must be a valid React element. Please provide a valid React element.");const u=c||(s?"JSON_ORIGINAL":"HTML"),{clientScriptLoaded:d}=oe(e);return d&&p(l=>{l.defaultSession().setVariation(i).setResponseMode(u)}),w.jsx(y.Provider,{value:{account:t,clientScriptLoaded:d,currentVariation:i,responseMode:u,recommendationComponent:s},children:o})}function _({query:e,placements:t}){const{renderCampaigns:n}=m();f(async o=>{const s=await o.defaultSession().viewSearch(e).setPlacements(t||o.placements.getPlacements()).load();n(s)},[e])}function re(e){return _(e),null}function q({cart:e,customer:t}={}){const{clientScriptLoaded:n}=g();v(()=>{const o=e?h(e):void 0,s=t?h(t):void 0;n&&p(c=>{c.defaultSession().setCart(o).setCustomer(s).viewOther().load({skipPageViews:!0})})},[n,e,t])}function ce(e){return q(e),null}r.Nosto404=J,r.NostoCategory=W,r.NostoCheckout=Z,r.NostoContext=y,r.NostoHome=B,r.NostoOrder=X,r.NostoOther=Y,r.NostoPlacement=x,r.NostoProduct=ee,r.NostoProvider=se,r.NostoSearch=re,r.NostoSession=ce,r.useNosto404=E,r.useNostoCategory=k,r.useNostoCheckout=b,r.useNostoContext=g,r.useNostoHome=A,r.useNostoOrder=M,r.useNostoOther=I,r.useNostoProduct=T,r.useNostoSearch=_,r.useNostoSession=q,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nosto/nosto-react",
3
3
  "description": "Component library to simply implementing Nosto on React.",
4
- "version": "2.7.0",
4
+ "version": "2.8.0",
5
5
  "author": "Mridang Agarwalla, Dominik Gilg",
6
6
  "license": "ISC",
7
7
  "repository": {
@@ -12,19 +12,22 @@
12
12
  "nosto",
13
13
  "personalisation"
14
14
  ],
15
+ "engines": {
16
+ "node": ">=22.0.0"
17
+ },
15
18
  "scripts": {
16
19
  "dev": "vite",
17
20
  "build": "tsc && npm run lint && vite build && npm run typedoc",
18
21
  "preview": "vite preview",
19
- "prepare": "vite build",
22
+ "prepare": "husky && vite build",
20
23
  "typecheck": "tsc",
21
24
  "lint": "eslint 'src/**/*.{ts,tsx}' --cache",
22
25
  "clean": "rimraf dist",
23
26
  "prettier": "prettier '{src,spec}/**' --list-different",
24
27
  "prettier:fix": "prettier '{src,spec}/**' --write",
25
- "test": "vitest run --silent",
28
+ "test": "vitest run --silent --coverage",
26
29
  "test-loud": "vitest run",
27
- "typedoc": "typedoc src/index.ts"
30
+ "typedoc": "typedoc --treatWarningsAsErrors src/index.ts"
28
31
  },
29
32
  "files": [
30
33
  "dist",
@@ -35,29 +38,33 @@
35
38
  "react-dom": "^18.3.1 || ^19.0.0"
36
39
  },
37
40
  "devDependencies": {
38
- "@nosto/nosto-js": "^1.3.1",
41
+ "@nosto/nosto-js": "^2.0.0",
42
+ "@commitlint/cli": "^19.8.0",
43
+ "@commitlint/config-conventional": "^19.8.0",
39
44
  "@testing-library/jest-dom": "^6.4.8",
40
45
  "@testing-library/react": "^16.0.0",
41
46
  "@testing-library/user-event": "^14.4.3",
42
47
  "@types/react": "^19.0.2",
43
48
  "@types/react-dom": "^19.0.0",
44
49
  "@types/user-event": "^4.1.1",
45
- "@vitejs/plugin-react": "^4.3.1",
50
+ "@vitejs/plugin-react": "^5.0.0",
51
+ "@vitest/coverage-v8": "^3.0.9",
46
52
  "eslint": "^9.13.0",
47
53
  "eslint-plugin-barrel-files": "^3.0.1",
48
54
  "eslint-plugin-promise": "^7.1.0",
49
55
  "eslint-plugin-react": "^7.33.2",
56
+ "husky": "^9.1.7",
50
57
  "prettier": "^3.3.3",
51
58
  "react": "^19.0.0",
52
59
  "react-dom": "^19.0.0",
53
60
  "react-router": "^7.0.1",
54
61
  "react-router-dom": "^7.0.1",
55
62
  "rimraf": "^6.0.1",
56
- "rollup-plugin-visualizer": "^5.13.1",
57
- "typedoc": "^0.27.2",
58
- "typescript": "^5.6.3",
59
- "typescript-eslint": "^8.13.0",
60
- "vite": "^6.0.3",
63
+ "rollup-plugin-visualizer": "^6.0.0",
64
+ "typedoc": "^0.28.9",
65
+ "typescript": "^5.9.2",
66
+ "typescript-eslint": "^8.39.0",
67
+ "vite": "^7.0.2",
61
68
  "vite-plugin-dts": "^4.2.2",
62
69
  "vitest": "^3.0.2"
63
70
  },
package/src/context.ts CHANGED
@@ -2,8 +2,6 @@ import { createContext, ReactElement } from "react"
2
2
  import { Recommendation } from "./types"
3
3
  import { RenderMode } from "@nosto/nosto-js/client"
4
4
 
5
- type AnyFunction = (...args: unknown[]) => unknown
6
-
7
5
  export type RecommendationComponent = ReactElement<{
8
6
  nostoRecommendation: Recommendation
9
7
  }>
@@ -15,7 +13,7 @@ export interface NostoContextType {
15
13
  account: string
16
14
  clientScriptLoaded: boolean
17
15
  currentVariation?: string
18
- renderFunction?: AnyFunction
16
+ renderFunction?: (...args: unknown[]) => unknown
19
17
  responseMode: RenderMode
20
18
  recommendationComponent?: RecommendationComponent
21
19
  }
package/src/index.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  /* eslint-disable barrel-files/avoid-barrel-files */
2
- export type { Product, PushedCustomer as Customer, Cart, WebsiteOrder as Order } from "@nosto/nosto-js/client"
2
+ export type { Product, PushedCustomer as Customer, Cart, WebsiteOrder as Order, RenderMode } from "@nosto/nosto-js/client"
3
3
  export type { Recommendation } from "./types"
4
+ export type { SnakeToCamelCase, ToCamelCase } from "./utils/types"
4
5
  export { type ScriptLoadOptions } from "./hooks/scriptLoader"
5
- export { NostoContext, type NostoContextType } from "./context"
6
+ export { NostoContext, type NostoContextType, type RecommendationComponent } from "./context"
6
7
  export { useNostoContext } from "./hooks/useNostoContext"
7
8
  export { Nosto404 } from "./components/Nosto404"
8
9
  export { NostoCategory } from "./components/NostoCategory"
@@ -12,7 +13,7 @@ export { NostoOrder } from "./components/NostoOrder"
12
13
  export { NostoOther } from "./components/NostoOther"
13
14
  export { NostoPlacement, type NostoPlacementProps } from "./components/NostoPlacement"
14
15
  export { NostoProduct } from "./components/NostoProduct"
15
- export { NostoProvider } from "./components/NostoProvider"
16
+ export { NostoProvider, type NostoProviderProps } from "./components/NostoProvider"
16
17
  export { NostoSearch } from "./components/NostoSearch"
17
18
  export { NostoSession } from "./components/NostoSession"
18
19
  export { useNosto404, type Nosto404Props } from "./hooks/useNosto404"
@@ -1,4 +1,4 @@
1
- type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}`
1
+ export type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}`
2
2
  ? `${T}${Capitalize<SnakeToCamelCase<U>>}`
3
3
  : S
4
4
 
@@ -13,7 +13,7 @@ export type ToCamelCase<T> = T extends (infer U)[]
13
13
  }
14
14
  : T
15
15
 
16
- type CamelToSnakeCase<S extends string> = S extends `${infer T}${infer U}`
16
+ export type CamelToSnakeCase<S extends string> = S extends `${infer T}${infer U}`
17
17
  ? U extends Uncapitalize<U>
18
18
  ? `${Lowercase<T>}${CamelToSnakeCase<U>}`
19
19
  : `${Lowercase<T>}_${CamelToSnakeCase<Uncapitalize<U>>}`