@nosto/nosto-react 2.0.0 → 2.1.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/dist/index.umd.js CHANGED
@@ -1,4 +1,4 @@
1
- (function(E,_){typeof exports=="object"&&typeof module<"u"?_(exports,require("react"),require("react-dom/client")):typeof define=="function"&&define.amd?define(["exports","react","react-dom/client"],_):(E=typeof globalThis<"u"?globalThis:E||self,_(E["@nosto/nosto-react"]={},E.React,E.ReactDOM))})(this,function(E,_,We){"use strict";const ce=r=>String(r)==="[object Object]";function le(r){if(!ce(r))return!1;const o=r.constructor;if(o===void 0)return!0;const a=o.prototype;return!(!ce(a)||!a.hasOwnProperty("isPrototypeOf"))}function Z(r,o){if(r===o)return!0;if(r instanceof Date&&o instanceof Date)return r.getTime()===o.getTime();if(r instanceof Array&&o instanceof Array)return r.length!==o.length?!1:r.every((a,s)=>Z(a,o[s]));if(le(r)&&le(o)){const a=Object.entries(r);return a.length!==Object.keys(o).length?!1:a.every(([s,d])=>Z(d,o[s]))}return!1}function fe(r,o){return _.useEffect(r,Ve(o))}function Ve(r){const o=_.useRef(r),a=_.useRef(0);return Z(r,o.current)||(o.current=r,a.current+=1),_.useMemo(()=>o.current,[a.current])}const Q=_.createContext({account:"",currentVariation:"",responseMode:"HTML",clientScriptLoaded:!1});function B(){const r=_.useContext(Q);if(!r)throw new Error("No nosto context found");return r}function k(r,o,a){const{clientScriptLoaded:s,currentVariation:d,responseMode:v}=B();(a!=null&&a.deep?fe:_.useEffect)(()=>{s&&window.nostojs(g=>{g.defaultSession().setVariation(d).setResponseMode(v),r(g)})},[s,d,v,...o??[]])}var ee={exports:{}},W={};/**
1
+ (function(h,w){typeof exports=="object"&&typeof module<"u"?w(exports,require("react"),require("react-dom/client")):typeof define=="function"&&define.amd?define(["exports","react","react-dom/client"],w):(h=typeof globalThis<"u"?globalThis:h||self,w(h["@nosto/nosto-react"]={},h.React,h.ReactDOM))})(this,function(h,w,Me){"use strict";const ue=r=>String(r)==="[object Object]";function le(r){if(!ue(r))return!1;const n=r.constructor;if(n===void 0)return!0;const a=n.prototype;return!(!ue(a)||!a.hasOwnProperty("isPrototypeOf"))}function Z(r,n){if(r===n)return!0;if(r instanceof Date&&n instanceof Date)return r.getTime()===n.getTime();if(r instanceof Array&&n instanceof Array)return r.length!==n.length?!1:r.every((a,c)=>Z(a,n[c]));if(le(r)&&le(n)){const a=Object.entries(r);return a.length!==Object.keys(n).length?!1:a.every(([c,i])=>Z(i,n[c]))}return!1}function fe(r,n){return w.useEffect(r,We(n))}function We(r){const n=w.useRef(r),a=w.useRef(0);return Z(r,n.current)||(n.current=r,a.current+=1),w.useMemo(()=>n.current,[a.current])}const Q=w.createContext({account:"",currentVariation:"",responseMode:"HTML",clientScriptLoaded:!1});function H(){return w.useContext(Q)}function k(r,n,a){const{clientScriptLoaded:c,currentVariation:i,responseMode:m}=H();(a!=null&&a.deep?fe:w.useEffect)(()=>{c&&window.nostojs(p=>{p.defaultSession().setVariation(i).setResponseMode(m),r(p)})},[c,i,m,...n??[]])}var ee={exports:{}},M={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.min.js
4
4
  *
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var de;function Ye(){if(de)return W;de=1;var r=_,o=Symbol.for("react.element"),a=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,d=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,v={key:!0,ref:!0,__self:!0,__source:!0};function l(g,y,T){var w,S={},j=null,F=null;T!==void 0&&(j=""+T),y.key!==void 0&&(j=""+y.key),y.ref!==void 0&&(F=y.ref);for(w in y)s.call(y,w)&&!v.hasOwnProperty(w)&&(S[w]=y[w]);if(g&&g.defaultProps)for(w in y=g.defaultProps,y)S[w]===void 0&&(S[w]=y[w]);return{$$typeof:o,type:g,key:j,ref:F,props:S,_owner:d.current}}return W.Fragment=a,W.jsx=l,W.jsxs=l,W}var V={};/**
9
+ */var de;function Ve(){if(de)return M;de=1;var r=w,n=Symbol.for("react.element"),a=Symbol.for("react.fragment"),c=Object.prototype.hasOwnProperty,i=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,m={key:!0,ref:!0,__self:!0,__source:!0};function R(p,g,O){var b,f={},P=null,j=null;O!==void 0&&(P=""+O),g.key!==void 0&&(P=""+g.key),g.ref!==void 0&&(j=g.ref);for(b in g)c.call(g,b)&&!m.hasOwnProperty(b)&&(f[b]=g[b]);if(p&&p.defaultProps)for(b in g=p.defaultProps,g)f[b]===void 0&&(f[b]=g[b]);return{$$typeof:n,type:p,key:P,ref:j,props:f,_owner:i.current}}return M.Fragment=a,M.jsx=R,M.jsxs=R,M}var W={};/**
10
10
  * @license React
11
11
  * react-jsx-runtime.development.js
12
12
  *
@@ -14,12 +14,12 @@
14
14
  *
15
15
  * This source code is licensed under the MIT license found in the
16
16
  * LICENSE file in the root directory of this source tree.
17
- */var me;function Me(){return me||(me=1,process.env.NODE_ENV!=="production"&&function(){var r=_,o=Symbol.for("react.element"),a=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),d=Symbol.for("react.strict_mode"),v=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),g=Symbol.for("react.context"),y=Symbol.for("react.forward_ref"),T=Symbol.for("react.suspense"),w=Symbol.for("react.suspense_list"),S=Symbol.for("react.memo"),j=Symbol.for("react.lazy"),F=Symbol.for("react.offscreen"),M=Symbol.iterator,p="@@iterator";function N(e){if(e===null||typeof e!="object")return null;var t=M&&e[M]||e[p];return typeof t=="function"?t:null}var C=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function R(e){{for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];it("error",e,n)}}function it(e,t,n){{var i=C.ReactDebugCurrentFrame,f=i.getStackAddendum();f!==""&&(t+="%s",n=n.concat([f]));var m=n.map(function(c){return String(c)});m.unshift("Warning: "+t),Function.prototype.apply.call(console[e],console,m)}}var st=!1,ut=!1,ct=!1,lt=!1,ft=!1,pe;pe=Symbol.for("react.module.reference");function dt(e){return!!(typeof e=="string"||typeof e=="function"||e===s||e===v||ft||e===d||e===T||e===w||lt||e===F||st||ut||ct||typeof e=="object"&&e!==null&&(e.$$typeof===j||e.$$typeof===S||e.$$typeof===l||e.$$typeof===g||e.$$typeof===y||e.$$typeof===pe||e.getModuleId!==void 0))}function mt(e,t,n){var i=e.displayName;if(i)return i;var f=t.displayName||t.name||"";return f!==""?n+"("+f+")":n}function ge(e){return e.displayName||"Context"}function x(e){if(e==null)return null;if(typeof e.tag=="number"&&R("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case s:return"Fragment";case a:return"Portal";case v:return"Profiler";case d:return"StrictMode";case T:return"Suspense";case w:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case g:var t=e;return ge(t)+".Consumer";case l:var n=e;return ge(n._context)+".Provider";case y:return mt(e,e.render,"ForwardRef");case S:var i=e.displayName||null;return i!==null?i:x(e.type)||"Memo";case j:{var f=e,m=f._payload,c=f._init;try{return x(c(m))}catch{return null}}}return null}var L=Object.assign,U=0,ye,he,Ee,be,_e,we,Re;function Ce(){}Ce.__reactDisabledLog=!0;function vt(){{if(U===0){ye=console.log,he=console.info,Ee=console.warn,be=console.error,_e=console.group,we=console.groupCollapsed,Re=console.groupEnd;var e={configurable:!0,enumerable:!0,value:Ce,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}U++}}function pt(){{if(U--,U===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:L({},e,{value:ye}),info:L({},e,{value:he}),warn:L({},e,{value:Ee}),error:L({},e,{value:be}),group:L({},e,{value:_e}),groupCollapsed:L({},e,{value:we}),groupEnd:L({},e,{value:Re})})}U<0&&R("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var te=C.ReactCurrentDispatcher,re;function z(e,t,n){{if(re===void 0)try{throw Error()}catch(f){var i=f.stack.trim().match(/\n( *(at )?)/);re=i&&i[1]||""}return`
18
- `+re+e}}var ne=!1,J;{var gt=typeof WeakMap=="function"?WeakMap:Map;J=new gt}function Pe(e,t){if(!e||ne)return"";{var n=J.get(e);if(n!==void 0)return n}var i;ne=!0;var f=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var m;m=te.current,te.current=null,vt();try{if(t){var c=function(){throw Error()};if(Object.defineProperty(c.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(c,[])}catch(A){i=A}Reflect.construct(e,[],c)}else{try{c.call()}catch(A){i=A}e.call(c.prototype)}}else{try{throw Error()}catch(A){i=A}e()}}catch(A){if(A&&i&&typeof A.stack=="string"){for(var u=A.stack.split(`
19
- `),P=i.stack.split(`
20
- `),h=u.length-1,b=P.length-1;h>=1&&b>=0&&u[h]!==P[b];)b--;for(;h>=1&&b>=0;h--,b--)if(u[h]!==P[b]){if(h!==1||b!==1)do if(h--,b--,b<0||u[h]!==P[b]){var O=`
21
- `+u[h].replace(" at new "," at ");return e.displayName&&O.includes("<anonymous>")&&(O=O.replace("<anonymous>",e.displayName)),typeof e=="function"&&J.set(e,O),O}while(h>=1&&b>=0);break}}}finally{ne=!1,te.current=m,pt(),Error.prepareStackTrace=f}var $=e?e.displayName||e.name:"",$e=$?z($):"";return typeof e=="function"&&J.set(e,$e),$e}function yt(e,t,n){return Pe(e,!1)}function ht(e){var t=e.prototype;return!!(t&&t.isReactComponent)}function G(e,t,n){if(e==null)return"";if(typeof e=="function")return Pe(e,ht(e));if(typeof e=="string")return z(e);switch(e){case T:return z("Suspense");case w:return z("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case y:return yt(e.render);case S:return G(e.type,t,n);case j:{var i=e,f=i._payload,m=i._init;try{return G(m(f),t,n)}catch{}}}return""}var K=Object.prototype.hasOwnProperty,Se={},Oe=C.ReactDebugCurrentFrame;function X(e){if(e){var t=e._owner,n=G(e.type,e._source,t?t.type:null);Oe.setExtraStackFrame(n)}else Oe.setExtraStackFrame(null)}function Et(e,t,n,i,f){{var m=Function.call.bind(K);for(var c in e)if(m(e,c)){var u=void 0;try{if(typeof e[c]!="function"){var P=Error((i||"React class")+": "+n+" type `"+c+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[c]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw P.name="Invariant Violation",P}u=e[c](t,c,i,n,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(h){u=h}u&&!(u instanceof Error)&&(X(f),R("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",i||"React class",n,c,typeof u),X(null)),u instanceof Error&&!(u.message in Se)&&(Se[u.message]=!0,X(f),R("Failed %s type: %s",n,u.message),X(null))}}}var bt=Array.isArray;function oe(e){return bt(e)}function _t(e){{var t=typeof Symbol=="function"&&Symbol.toStringTag,n=t&&e[Symbol.toStringTag]||e.constructor.name||"Object";return n}}function wt(e){try{return Te(e),!1}catch{return!0}}function Te(e){return""+e}function je(e){if(wt(e))return R("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",_t(e)),Te(e)}var q=C.ReactCurrentOwner,Rt={key:!0,ref:!0,__self:!0,__source:!0},Ne,xe,ae;ae={};function Ct(e){if(K.call(e,"ref")){var t=Object.getOwnPropertyDescriptor(e,"ref").get;if(t&&t.isReactWarning)return!1}return e.ref!==void 0}function Pt(e){if(K.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return e.key!==void 0}function St(e,t){if(typeof e.ref=="string"&&q.current&&t&&q.current.stateNode!==t){var n=x(q.current.type);ae[n]||(R('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',x(q.current.type),e.ref),ae[n]=!0)}}function Ot(e,t){{var n=function(){Ne||(Ne=!0,R("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};n.isReactWarning=!0,Object.defineProperty(e,"key",{get:n,configurable:!0})}}function Tt(e,t){{var n=function(){xe||(xe=!0,R("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};n.isReactWarning=!0,Object.defineProperty(e,"ref",{get:n,configurable:!0})}}var jt=function(e,t,n,i,f,m,c){var u={$$typeof:o,type:e,key:t,ref:n,props:c,_owner:m};return u._store={},Object.defineProperty(u._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(u,"_self",{configurable:!1,enumerable:!1,writable:!1,value:i}),Object.defineProperty(u,"_source",{configurable:!1,enumerable:!1,writable:!1,value:f}),Object.freeze&&(Object.freeze(u.props),Object.freeze(u)),u};function Nt(e,t,n,i,f){{var m,c={},u=null,P=null;n!==void 0&&(je(n),u=""+n),Pt(t)&&(je(t.key),u=""+t.key),Ct(t)&&(P=t.ref,St(t,f));for(m in t)K.call(t,m)&&!Rt.hasOwnProperty(m)&&(c[m]=t[m]);if(e&&e.defaultProps){var h=e.defaultProps;for(m in h)c[m]===void 0&&(c[m]=h[m])}if(u||P){var b=typeof e=="function"?e.displayName||e.name||"Unknown":e;u&&Ot(c,b),P&&Tt(c,b)}return jt(e,u,P,f,i,q.current,c)}}var ie=C.ReactCurrentOwner,Ae=C.ReactDebugCurrentFrame;function I(e){if(e){var t=e._owner,n=G(e.type,e._source,t?t.type:null);Ae.setExtraStackFrame(n)}else Ae.setExtraStackFrame(null)}var se;se=!1;function ue(e){return typeof e=="object"&&e!==null&&e.$$typeof===o}function ke(){{if(ie.current){var e=x(ie.current.type);if(e)return`
17
+ */var me;function Ye(){return me||(me=1,process.env.NODE_ENV!=="production"&&function(){var r=w,n=Symbol.for("react.element"),a=Symbol.for("react.portal"),c=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),m=Symbol.for("react.profiler"),R=Symbol.for("react.provider"),p=Symbol.for("react.context"),g=Symbol.for("react.forward_ref"),O=Symbol.for("react.suspense"),b=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),P=Symbol.for("react.lazy"),j=Symbol.for("react.offscreen"),F=Symbol.iterator,z="@@iterator";function J(e){if(e===null||typeof e!="object")return null;var t=F&&e[F]||e[z];return typeof t=="function"?t:null}var T=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function _(e){{for(var t=arguments.length,o=new Array(t>1?t-1:0),s=1;s<t;s++)o[s-1]=arguments[s];it("error",e,o)}}function it(e,t,o){{var s=T.ReactDebugCurrentFrame,d=s.getStackAddendum();d!==""&&(t+="%s",o=o.concat([d]));var v=o.map(function(l){return String(l)});v.unshift("Warning: "+t),Function.prototype.apply.call(console[e],console,v)}}var st=!1,ct=!1,ut=!1,lt=!1,ft=!1,ve;ve=Symbol.for("react.module.reference");function dt(e){return!!(typeof e=="string"||typeof e=="function"||e===c||e===m||ft||e===i||e===O||e===b||lt||e===j||st||ct||ut||typeof e=="object"&&e!==null&&(e.$$typeof===P||e.$$typeof===f||e.$$typeof===R||e.$$typeof===p||e.$$typeof===g||e.$$typeof===ve||e.getModuleId!==void 0))}function mt(e,t,o){var s=e.displayName;if(s)return s;var d=t.displayName||t.name||"";return d!==""?o+"("+d+")":o}function pe(e){return e.displayName||"Context"}function N(e){if(e==null)return null;if(typeof e.tag=="number"&&_("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case c:return"Fragment";case a:return"Portal";case m:return"Profiler";case i:return"StrictMode";case O:return"Suspense";case b:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case p:var t=e;return pe(t)+".Consumer";case R:var o=e;return pe(o._context)+".Provider";case g:return mt(e,e.render,"ForwardRef");case f:var s=e.displayName||null;return s!==null?s:N(e.type)||"Memo";case P:{var d=e,v=d._payload,l=d._init;try{return N(l(v))}catch{return null}}}return null}var D=Object.assign,U=0,ge,ye,he,Re,Ee,we,be;function _e(){}_e.__reactDisabledLog=!0;function vt(){{if(U===0){ge=console.log,ye=console.info,he=console.warn,Re=console.error,Ee=console.group,we=console.groupCollapsed,be=console.groupEnd;var e={configurable:!0,enumerable:!0,value:_e,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}U++}}function pt(){{if(U--,U===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:D({},e,{value:ge}),info:D({},e,{value:ye}),warn:D({},e,{value:he}),error:D({},e,{value:Re}),group:D({},e,{value:Ee}),groupCollapsed:D({},e,{value:we}),groupEnd:D({},e,{value:be})})}U<0&&_("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var te=T.ReactCurrentDispatcher,re;function G(e,t,o){{if(re===void 0)try{throw Error()}catch(d){var s=d.stack.trim().match(/\n( *(at )?)/);re=s&&s[1]||""}return`
18
+ `+re+e}}var ne=!1,K;{var gt=typeof WeakMap=="function"?WeakMap:Map;K=new gt}function Ce(e,t){if(!e||ne)return"";{var o=K.get(e);if(o!==void 0)return o}var s;ne=!0;var d=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var v;v=te.current,te.current=null,vt();try{if(t){var l=function(){throw Error()};if(Object.defineProperty(l.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(l,[])}catch(x){s=x}Reflect.construct(e,[],l)}else{try{l.call()}catch(x){s=x}e.call(l.prototype)}}else{try{throw Error()}catch(x){s=x}e()}}catch(x){if(x&&s&&typeof x.stack=="string"){for(var u=x.stack.split(`
19
+ `),C=s.stack.split(`
20
+ `),y=u.length-1,E=C.length-1;y>=1&&E>=0&&u[y]!==C[E];)E--;for(;y>=1&&E>=0;y--,E--)if(u[y]!==C[E]){if(y!==1||E!==1)do if(y--,E--,E<0||u[y]!==C[E]){var S=`
21
+ `+u[y].replace(" at new "," at ");return e.displayName&&S.includes("<anonymous>")&&(S=S.replace("<anonymous>",e.displayName)),typeof e=="function"&&K.set(e,S),S}while(y>=1&&E>=0);break}}}finally{ne=!1,te.current=v,pt(),Error.prepareStackTrace=d}var I=e?e.displayName||e.name:"",Ie=I?G(I):"";return typeof e=="function"&&K.set(e,Ie),Ie}function yt(e,t,o){return Ce(e,!1)}function ht(e){var t=e.prototype;return!!(t&&t.isReactComponent)}function $(e,t,o){if(e==null)return"";if(typeof e=="function")return Ce(e,ht(e));if(typeof e=="string")return G(e);switch(e){case O:return G("Suspense");case b:return G("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case g:return yt(e.render);case f:return $(e.type,t,o);case P:{var s=e,d=s._payload,v=s._init;try{return $(v(d),t,o)}catch{}}}return""}var X=Object.prototype.hasOwnProperty,Pe={},Se=T.ReactDebugCurrentFrame;function q(e){if(e){var t=e._owner,o=$(e.type,e._source,t?t.type:null);Se.setExtraStackFrame(o)}else Se.setExtraStackFrame(null)}function Rt(e,t,o,s,d){{var v=Function.call.bind(X);for(var l in e)if(v(e,l)){var u=void 0;try{if(typeof e[l]!="function"){var C=Error((s||"React class")+": "+o+" type `"+l+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[l]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw C.name="Invariant Violation",C}u=e[l](t,l,s,o,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(y){u=y}u&&!(u instanceof Error)&&(q(d),_("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",s||"React class",o,l,typeof u),q(null)),u instanceof Error&&!(u.message in Pe)&&(Pe[u.message]=!0,q(d),_("Failed %s type: %s",o,u.message),q(null))}}}var Et=Array.isArray;function oe(e){return Et(e)}function wt(e){{var t=typeof Symbol=="function"&&Symbol.toStringTag,o=t&&e[Symbol.toStringTag]||e.constructor.name||"Object";return o}}function bt(e){try{return Oe(e),!1}catch{return!0}}function Oe(e){return""+e}function Te(e){if(bt(e))return _("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",wt(e)),Oe(e)}var B=T.ReactCurrentOwner,_t={key:!0,ref:!0,__self:!0,__source:!0},je,Ne,ae;ae={};function Ct(e){if(X.call(e,"ref")){var t=Object.getOwnPropertyDescriptor(e,"ref").get;if(t&&t.isReactWarning)return!1}return e.ref!==void 0}function Pt(e){if(X.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return e.key!==void 0}function St(e,t){if(typeof e.ref=="string"&&B.current&&t&&B.current.stateNode!==t){var o=N(B.current.type);ae[o]||(_('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',N(B.current.type),e.ref),ae[o]=!0)}}function Ot(e,t){{var o=function(){je||(je=!0,_("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};o.isReactWarning=!0,Object.defineProperty(e,"key",{get:o,configurable:!0})}}function Tt(e,t){{var o=function(){Ne||(Ne=!0,_("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};o.isReactWarning=!0,Object.defineProperty(e,"ref",{get:o,configurable:!0})}}var jt=function(e,t,o,s,d,v,l){var u={$$typeof:n,type:e,key:t,ref:o,props:l,_owner:v};return u._store={},Object.defineProperty(u._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(u,"_self",{configurable:!1,enumerable:!1,writable:!1,value:s}),Object.defineProperty(u,"_source",{configurable:!1,enumerable:!1,writable:!1,value:d}),Object.freeze&&(Object.freeze(u.props),Object.freeze(u)),u};function Nt(e,t,o,s,d){{var v,l={},u=null,C=null;o!==void 0&&(Te(o),u=""+o),Pt(t)&&(Te(t.key),u=""+t.key),Ct(t)&&(C=t.ref,St(t,d));for(v in t)X.call(t,v)&&!_t.hasOwnProperty(v)&&(l[v]=t[v]);if(e&&e.defaultProps){var y=e.defaultProps;for(v in y)l[v]===void 0&&(l[v]=y[v])}if(u||C){var E=typeof e=="function"?e.displayName||e.name||"Unknown":e;u&&Ot(l,E),C&&Tt(l,E)}return jt(e,u,C,d,s,B.current,l)}}var ie=T.ReactCurrentOwner,xe=T.ReactDebugCurrentFrame;function L(e){if(e){var t=e._owner,o=$(e.type,e._source,t?t.type:null);xe.setExtraStackFrame(o)}else xe.setExtraStackFrame(null)}var se;se=!1;function ce(e){return typeof e=="object"&&e!==null&&e.$$typeof===n}function ke(){{if(ie.current){var e=N(ie.current.type);if(e)return`
22
22
 
23
- Check the render method of \``+e+"`."}return""}}function xt(e){return""}var De={};function At(e){{var t=ke();if(!t){var n=typeof e=="string"?e:e.displayName||e.name;n&&(t=`
23
+ Check the render method of \``+e+"`."}return""}}function xt(e){return""}var Ae={};function kt(e){{var t=ke();if(!t){var o=typeof e=="string"?e:e.displayName||e.name;o&&(t=`
24
24
 
25
- Check the top-level render call using <`+n+">.")}return t}}function Fe(e,t){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var n=At(t);if(De[n])return;De[n]=!0;var i="";e&&e._owner&&e._owner!==ie.current&&(i=" It was passed a child from "+x(e._owner.type)+"."),I(e),R('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',n,i),I(null)}}function Le(e,t){{if(typeof e!="object")return;if(oe(e))for(var n=0;n<e.length;n++){var i=e[n];ue(i)&&Fe(i,t)}else if(ue(e))e._store&&(e._store.validated=!0);else if(e){var f=N(e);if(typeof f=="function"&&f!==e.entries)for(var m=f.call(e),c;!(c=m.next()).done;)ue(c.value)&&Fe(c.value,t)}}}function kt(e){{var t=e.type;if(t==null||typeof t=="string")return;var n;if(typeof t=="function")n=t.propTypes;else if(typeof t=="object"&&(t.$$typeof===y||t.$$typeof===S))n=t.propTypes;else return;if(n){var i=x(t);Et(n,e.props,"prop",i,e)}else if(t.PropTypes!==void 0&&!se){se=!0;var f=x(t);R("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",f||"Unknown")}typeof t.getDefaultProps=="function"&&!t.getDefaultProps.isReactClassApproved&&R("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Dt(e){{for(var t=Object.keys(e.props),n=0;n<t.length;n++){var i=t[n];if(i!=="children"&&i!=="key"){I(e),R("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",i),I(null);break}}e.ref!==null&&(I(e),R("Invalid attribute `ref` supplied to `React.Fragment`."),I(null))}}function Ie(e,t,n,i,f,m){{var c=dt(e);if(!c){var u="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(u+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var P=xt();P?u+=P:u+=ke();var h;e===null?h="null":oe(e)?h="array":e!==void 0&&e.$$typeof===o?(h="<"+(x(e.type)||"Unknown")+" />",u=" Did you accidentally export a JSX literal instead of a component?"):h=typeof e,R("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",h,u)}var b=Nt(e,t,n,f,m);if(b==null)return b;if(c){var O=t.children;if(O!==void 0)if(i)if(oe(O)){for(var $=0;$<O.length;$++)Le(O[$],e);Object.freeze&&Object.freeze(O)}else R("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Le(O,e)}return e===s?Dt(b):kt(b),b}}function Ft(e,t,n){return Ie(e,t,n,!0)}function Lt(e,t,n){return Ie(e,t,n,!1)}var It=Lt,$t=Ft;V.Fragment=s,V.jsx=It,V.jsxs=$t}()),V}process.env.NODE_ENV==="production"?ee.exports=Ye():ee.exports=Me();var ve=ee.exports;const H=ve.jsx,Ue=ve.Fragment;function qe(r){return _.cloneElement(r.recommendationComponent,{nostoRecommendation:r.nostoRecommendation})}function Be(r){if(!window.nostojs)throw new Error("Nosto has not yet been initialized");window.nostojs(o=>{o.placements.injectCampaigns(r.recommendations)})}function D(){const{responseMode:r,recommendationComponent:o}=B(),a=_.useRef({});if(r=="HTML")return{renderCampaigns:Be};function s(d){var l;const v=((l=d.campaigns)==null?void 0:l.recommendations)??{};for(const g in v){const y=v[g],T="#"+g,w=document.querySelector(T);w&&(a.current[g]||(a.current[g]=We.createRoot(w)),a.current[g].render(H(qe,{recommendationComponent:o,nostoRecommendation:y})))}}return{renderCampaigns:s}}function He(r){const{renderCampaigns:o}=D();return k(async a=>{const s=await a.defaultSession().viewNotFound().setPlacements(r.placements||a.placements.getPlacements()).load();o(s)}),null}function ze(r){const{renderCampaigns:o}=D();return k(async a=>{const s=await a.defaultSession().viewOther().setPlacements(r.placements||a.placements.getPlacements()).load();o(s)}),null}function Je(r){const{renderCampaigns:o}=D();return k(async a=>{const s=await a.defaultSession().viewCart().setPlacements(r.placements||a.placements.getPlacements()).load();o(s)}),null}function Ge(r){const{product:o,tagging:a,placements:s}=r,{renderCampaigns:d}=D();return k(async v=>{const l=await v.defaultSession().viewProduct(a??o).setPlacements(s||v.placements.getPlacements()).load();d(l)},[o,a==null?void 0:a.selected_sku_id]),null}function Ke(r){const{category:o,placements:a}=r,{renderCampaigns:s}=D();return k(async d=>{const v=await d.defaultSession().viewCategory(o).setPlacements(a||d.placements.getPlacements()).load();s(v)},[o]),null}function Xe(r){const{query:o,placements:a}=r,{renderCampaigns:s}=D();return k(async d=>{const v=await d.defaultSession().viewSearch(o).setPlacements(a||d.placements.getPlacements()).load();s(v)},[o]),null}function Y(r){return!r||typeof r!="object"||Ze(r)||Qe(r)?r:Array.isArray(r)?r.map(Y):Object.keys(r).reduce((o,a)=>{const s=a[0].toLowerCase()+a.slice(1).replace(/([A-Z]+)/g,(d,v)=>"_"+v.toLowerCase());return o[s]=Y(r[a]),o},{})}function Ze(r){return Object.prototype.toString.call(r)==="[object Date]"}function Qe(r){return Object.prototype.toString.call(r)==="[object RegExp]"}function et(r){const{order:o,placements:a}=r,{renderCampaigns:s}=D();return k(async d=>{const v=await d.defaultSession().addOrder(Y(o)).setPlacements(a||d.placements.getPlacements()).load();s(v)},[o],{deep:!0}),null}function tt(r){const{renderCampaigns:o}=D();return k(async a=>{const s=await a.defaultSession().viewFrontPage().setPlacements(r.placements||a.placements.getPlacements()).load();o(s)}),null}function rt(r){const{id:o,pageType:a}=r;return H("div",{className:"nosto_element",id:o},o+(a||""))}function nt(){return typeof window.nosto<"u"}function ot(r){const{account:o,multiCurrency:a=!1,host:s,children:d,recommendationComponent:v,shopifyMarkets:l}=r,[g,y]=_.useState(!1),T=_.useMemo(()=>g,[g]),w=a?r.currentVariation:"",S=_.isValidElement(v)?"JSON_ORIGINAL":"HTML";return _.useEffect(()=>{var j,F,M;if(window.nostojs||(window.nostojs=p=>{(window.nostojs.q=window.nostojs.q||[]).push(p)},window.nostojs(p=>p.setAutoLoad(!1))),!nt()&&!l){const p=document.createElement("script");p.type="text/javascript",p.src="//"+(s||"connect.nosto.com")+"/include/"+o,p.async=!0,p.setAttribute("nosto-client-script",""),p.onload=()=>{var N;typeof jest<"u"&&((N=window.nosto)==null||N.reload({site:"localhost"})),y(!0)},document.body.appendChild(p)}if(l){const p=document.querySelector("[nosto-client-script]"),N=document.querySelector("#nosto-sandbox");if(!p||(p==null?void 0:p.getAttribute("nosto-language"))!==(l==null?void 0:l.language)||(p==null?void 0:p.getAttribute("nosto-market-id"))!==(l==null?void 0:l.marketId)){g&&y(!1),(j=p==null?void 0:p.parentNode)==null||j.removeChild(p),(F=N==null?void 0:N.parentNode)==null||F.removeChild(N);const C=document.createElement("script");C.type="text/javascript",C.src="//"+(s||"connect.nosto.com")+`/script/shopify/market/nosto.js?merchant=${o}&market=${l.marketId||""}&locale=${((M=l==null?void 0:l.language)==null?void 0:M.toLowerCase())||""}`,C.async=!0,C.setAttribute("nosto-client-script",""),C.setAttribute("nosto-language",(l==null?void 0:l.language)||""),C.setAttribute("nosto-market-id",String(l==null?void 0:l.marketId)),C.onload=()=>{var R;typeof jest<"u"&&((R=window.nosto)==null||R.reload({site:"localhost"})),y(!0)},document.body.appendChild(C)}}},[g,l]),H(Q.Provider,{value:{account:o,clientScriptLoaded:T,currentVariation:w,responseMode:S,recommendationComponent:v},children:d})}function at(r){const{cart:o,customer:a}=r??{},{clientScriptLoaded:s}=B();return fe(()=>{const d=o?Y(o):void 0,v=a?Y(a):void 0;s&&window.nostojs(l=>{l.defaultSession().setResponseMode("HTML").setCart(d).setCustomer(v).viewOther().load()})},[s,o,a]),H(Ue,{})}E.Nosto404=He,E.NostoCategory=Ke,E.NostoCheckout=Je,E.NostoContext=Q,E.NostoHome=tt,E.NostoOrder=et,E.NostoOther=ze,E.NostoPlacement=rt,E.NostoProduct=Ge,E.NostoProvider=ot,E.NostoSearch=Xe,E.NostoSession=at,E.useNostoContext=B,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})});
25
+ Check the top-level render call using <`+o+">.")}return t}}function De(e,t){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var o=kt(t);if(Ae[o])return;Ae[o]=!0;var s="";e&&e._owner&&e._owner!==ie.current&&(s=" It was passed a child from "+N(e._owner.type)+"."),L(e),_('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',o,s),L(null)}}function Fe(e,t){{if(typeof e!="object")return;if(oe(e))for(var o=0;o<e.length;o++){var s=e[o];ce(s)&&De(s,t)}else if(ce(e))e._store&&(e._store.validated=!0);else if(e){var d=J(e);if(typeof d=="function"&&d!==e.entries)for(var v=d.call(e),l;!(l=v.next()).done;)ce(l.value)&&De(l.value,t)}}}function At(e){{var t=e.type;if(t==null||typeof t=="string")return;var o;if(typeof t=="function")o=t.propTypes;else if(typeof t=="object"&&(t.$$typeof===g||t.$$typeof===f))o=t.propTypes;else return;if(o){var s=N(t);Rt(o,e.props,"prop",s,e)}else if(t.PropTypes!==void 0&&!se){se=!0;var d=N(t);_("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",d||"Unknown")}typeof t.getDefaultProps=="function"&&!t.getDefaultProps.isReactClassApproved&&_("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Dt(e){{for(var t=Object.keys(e.props),o=0;o<t.length;o++){var s=t[o];if(s!=="children"&&s!=="key"){L(e),_("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",s),L(null);break}}e.ref!==null&&(L(e),_("Invalid attribute `ref` supplied to `React.Fragment`."),L(null))}}function Le(e,t,o,s,d,v){{var l=dt(e);if(!l){var u="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(u+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var C=xt();C?u+=C:u+=ke();var y;e===null?y="null":oe(e)?y="array":e!==void 0&&e.$$typeof===n?(y="<"+(N(e.type)||"Unknown")+" />",u=" Did you accidentally export a JSX literal instead of a component?"):y=typeof e,_("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",y,u)}var E=Nt(e,t,o,d,v);if(E==null)return E;if(l){var S=t.children;if(S!==void 0)if(s)if(oe(S)){for(var I=0;I<S.length;I++)Fe(S[I],e);Object.freeze&&Object.freeze(S)}else _("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Fe(S,e)}return e===c?Dt(E):At(E),E}}function Ft(e,t,o){return Le(e,t,o,!0)}function Lt(e,t,o){return Le(e,t,o,!1)}var It=Lt,Mt=Ft;W.Fragment=c,W.jsx=It,W.jsxs=Mt}()),W}process.env.NODE_ENV==="production"?ee.exports=Ve():ee.exports=Ye();var V=ee.exports;function Ue(r){return w.cloneElement(r.recommendationComponent,{nostoRecommendation:r.nostoRecommendation})}function Be(r){if(!window.nostojs)throw new Error("Nosto has not yet been initialized");window.nostojs(n=>{n.placements.injectCampaigns(r.recommendations)})}function A(){const{responseMode:r,recommendationComponent:n}=H(),a=w.useRef({});if(r=="HTML")return{renderCampaigns:Be};function c(i){var R;const m=((R=i.campaigns)==null?void 0:R.recommendations)??{};for(const p in m){const g=m[p],O="#"+p,b=document.querySelector(O);b&&(a.current[p]||(a.current[p]=Me.createRoot(b)),a.current[p].render(V.jsx(Ue,{recommendationComponent:n,nostoRecommendation:g})))}}return{renderCampaigns:c}}function He(){return typeof window.nosto<"u"}function ze(r,n){return new Promise((a,c)=>{const i=document.createElement("script");i.type="text/javascript",i.src=r,i.async=!0,i.onload=()=>a(),i.onerror=()=>c(),Object.entries((n==null?void 0:n.attributes)??{}).forEach(([m,R])=>i.setAttribute(m,R)),(n==null?void 0:n.position)==="head"?document.head.appendChild(i):document.body.appendChild(i)})}function Je(r){const{host:n="connect.nosto.com",scriptLoader:a=ze,account:c,shopifyMarkets:i,loadScript:m=!0}=r,[R,p]=w.useState(!1);return w.useEffect(()=>{function g(){var f;"nostoReactTest"in window&&((f=window.nosto)==null||f.reload({site:"localhost"})),p(!0)}async function O(f,P={}){const j=`//${n}${f}`,F={"nosto-client-script":"",...P};await a(j,{attributes:F}),g()}function b(){var z,J;const f=document.querySelector("[nosto-client-script]"),P=String((i==null?void 0:i.marketId)||""),j=(i==null?void 0:i.language)||"",F=(f==null?void 0:f.getAttribute("nosto-language"))!==j||(f==null?void 0:f.getAttribute("nosto-market-id"))!==P;if(!f||F){R&&p(!1);const T=document.querySelector("#nosto-sandbox");(z=f==null?void 0:f.parentNode)==null||z.removeChild(f),(J=T==null?void 0:T.parentNode)==null||J.removeChild(T);const _=`/script/shopify/market/nosto.js?merchant=${c}&market=${P}&locale=${j.toLowerCase()}`;O(_,{"nosto-language":j,"nosto-market-id":P})}}if(window.nostojs||(window.nostojs=f=>{(window.nostojs.q=window.nostojs.q||[]).push(f)},window.nostojs(f=>f.setAutoLoad(!1))),!m){window.nosto?g():window.nostojs(g);return}if(!He()&&!i){const f=`/include/${c}`;O(f)}i&&b()},[i==null?void 0:i.marketId,i==null?void 0:i.language]),{clientScriptLoaded:R}}function Ge(r){const{renderCampaigns:n}=A();return k(async a=>{const c=await a.defaultSession().viewNotFound().setPlacements(r.placements||a.placements.getPlacements()).load();n(c)}),null}function Ke(r){const{renderCampaigns:n}=A();return k(async a=>{const c=await a.defaultSession().viewOther().setPlacements(r.placements||a.placements.getPlacements()).load();n(c)}),null}function $e(r){const{renderCampaigns:n}=A();return k(async a=>{const c=await a.defaultSession().viewCart().setPlacements(r.placements||a.placements.getPlacements()).load();n(c)}),null}function Xe(r){const{product:n,tagging:a,placements:c}=r,{renderCampaigns:i}=A();return k(async m=>{const R=await m.defaultSession().viewProduct(a??n).setPlacements(c||m.placements.getPlacements()).load();i(R)},[n,a==null?void 0:a.selected_sku_id]),null}function qe(r){const{category:n,placements:a}=r,{renderCampaigns:c}=A();return k(async i=>{const m=await i.defaultSession().viewCategory(n).setPlacements(a||i.placements.getPlacements()).load();c(m)},[n]),null}function Ze(r){const{query:n,placements:a}=r,{renderCampaigns:c}=A();return k(async i=>{const m=await i.defaultSession().viewSearch(n).setPlacements(a||i.placements.getPlacements()).load();c(m)},[n]),null}function Y(r){return!r||typeof r!="object"||Qe(r)||et(r)?r:Array.isArray(r)?r.map(Y):Object.keys(r).reduce((n,a)=>{const c=a[0].toLowerCase()+a.slice(1).replace(/([A-Z]+)/g,(i,m)=>"_"+m.toLowerCase());return n[c]=Y(r[a]),n},{})}function Qe(r){return Object.prototype.toString.call(r)==="[object Date]"}function et(r){return Object.prototype.toString.call(r)==="[object RegExp]"}function tt(r){const{order:n,placements:a}=r,{renderCampaigns:c}=A();return k(async i=>{const m=await i.defaultSession().addOrder(Y(n)).setPlacements(a||i.placements.getPlacements()).load();c(m)},[n],{deep:!0}),null}function rt(r){const{renderCampaigns:n}=A();return k(async a=>{const c=await a.defaultSession().viewFrontPage().setPlacements(r.placements||a.placements.getPlacements()).load();n(c)}),null}function nt(r){const{id:n,pageType:a}=r;return V.jsx("div",{className:"nosto_element",id:n},n+(a||""))}function ot(r){const{account:n,multiCurrency:a=!1,children:c,recommendationComponent:i}=r,m=a?r.currentVariation:"";if(i&&!w.isValidElement(i))throw new Error("The recommendationComponent prop must be a valid React element. Please provide a valid React element.");const R=i?"JSON_ORIGINAL":"HTML",{clientScriptLoaded:p}=Je(r);return V.jsx(Q.Provider,{value:{account:n,clientScriptLoaded:p,currentVariation:m,responseMode:R,recommendationComponent:i},children:c})}function at(r){const{cart:n,customer:a}=r??{},{clientScriptLoaded:c}=H();return fe(()=>{const i=n?Y(n):void 0,m=a?Y(a):void 0;c&&window.nostojs(R=>{R.defaultSession().setResponseMode("HTML").setCart(i).setCustomer(m).viewOther().load()})},[c,n,a]),V.jsx(V.Fragment,{})}h.Nosto404=Ge,h.NostoCategory=qe,h.NostoCheckout=$e,h.NostoContext=Q,h.NostoHome=rt,h.NostoOrder=tt,h.NostoOther=Ke,h.NostoPlacement=nt,h.NostoProduct=Xe,h.NostoProvider=ot,h.NostoSearch=Ze,h.NostoSession=at,h.useNostoContext=H,Object.defineProperty(h,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.0.0",
4
+ "version": "2.1.0",
5
5
  "author": "Mridang Agarwalla, Dominik Gilg",
6
6
  "license": "ISC",
7
7
  "repository": {
@@ -22,7 +22,7 @@
22
22
  "clean": "rimraf dist",
23
23
  "prettier": "prettier '{src,spec}/**' --list-different",
24
24
  "prettier:fix": "prettier '{src,spec}/**' --write",
25
- "test": "jest spec",
25
+ "test": "vitest run --silent",
26
26
  "typedoc": "typedoc src/index.ts"
27
27
  },
28
28
  "files": [
@@ -30,32 +30,29 @@
30
30
  "src"
31
31
  ],
32
32
  "devDependencies": {
33
- "@testing-library/jest-dom": "^5.16.5",
34
- "@testing-library/react": "^14.0.0",
33
+ "@testing-library/jest-dom": "^6.4.8",
34
+ "@testing-library/react": "^16.0.0",
35
35
  "@testing-library/user-event": "^14.4.3",
36
- "@types/jest": "^29.5.0",
37
36
  "@types/react": "^18.0.0",
38
37
  "@types/react-dom": "^18.0.0",
39
38
  "@types/user-event": "^4.1.1",
40
39
  "@typescript-eslint/eslint-plugin": "^6.11.0",
41
40
  "@typescript-eslint/parser": "^6.11.0",
42
- "@vitejs/plugin-react": "^1.3.0",
41
+ "@vitejs/plugin-react": "^4.3.1",
43
42
  "eslint": "^8.53.0",
44
43
  "eslint-plugin-promise": "^6.1.1",
45
44
  "eslint-plugin-react": "^7.33.2",
46
- "jest": "^29.5.0",
47
- "jest-environment-jsdom": "^29.5.0",
48
45
  "prettier": "^2.0.5",
49
46
  "react": "*",
50
47
  "react-dom": "*",
51
48
  "react-router": "^6.25.1",
52
49
  "react-router-dom": "^6.25.1",
53
50
  "rimraf": "^3.0.2",
54
- "ts-jest": "^29.1.0",
55
51
  "typedoc": "^0.24.1",
56
52
  "typescript": "^4.6.3",
57
53
  "vite": "^5.2.10",
58
- "vite-plugin-dts": "^3.9.1"
54
+ "vite-plugin-dts": "^3.9.1",
55
+ "vitest": "^2.0.5"
59
56
  },
60
57
  "main": "./dist/index.umd.js",
61
58
  "module": "./dist/index.es.js",
@@ -70,13 +67,5 @@
70
67
  "bugs": {
71
68
  "url": "https://github.com/Nosto/nosto-react/issues"
72
69
  },
73
- "homepage": "https://github.com/Nosto/nosto-react#readme",
74
- "jest": {
75
- "preset": "ts-jest",
76
- "testEnvironment": "jsdom",
77
- "testEnvironmentOptions": {
78
- "resources": "usable",
79
- "runScripts": "dangerously"
80
- }
81
- }
70
+ "homepage": "https://github.com/Nosto/nosto-react#readme"
82
71
  }
@@ -1,5 +1,3 @@
1
- import React from "react"
2
-
3
1
  /**
4
2
  * Nosto React has a special component called NostoPlacement.
5
3
  * The component is a simply a hidden `<div>` placeholder into which Nosto injects recommendations or personalises the content between the tags.
@@ -1,7 +1,8 @@
1
- import React, { useEffect, isValidElement } from "react"
1
+ import { isValidElement } from "react"
2
2
  import { NostoContext, RecommendationComponent } from "../context"
3
- import { NostoClient } from "../types"
4
- import { isNostoLoaded } from "./helpers"
3
+ import { useLoadClientScript } from "../hooks"
4
+ import type { ReactElement } from "react"
5
+ import { ScriptLoadOptions } from "../hooks/scriptLoader"
5
6
 
6
7
  /**
7
8
  * @group Components
@@ -22,7 +23,7 @@ export interface NostoProviderProps {
22
23
  /**
23
24
  * children
24
25
  */
25
- children: React.ReactElement | React.ReactElement[]
26
+ children: ReactElement | ReactElement[]
26
27
  /**
27
28
  * Indicates if merchant uses multiple currencies
28
29
  */
@@ -38,6 +39,14 @@ export interface NostoProviderProps {
38
39
  language?: string
39
40
  marketId?: string | number
40
41
  }
42
+ /**
43
+ * Load nosto script (should be false if loading the script outside of nosto-react)
44
+ */
45
+ loadScript?: boolean
46
+ /**
47
+ * Custom script loader
48
+ */
49
+ scriptLoader?: (scriptSrc: string, options?: ScriptLoadOptions) => Promise<void>
41
50
  }
42
51
 
43
52
  /**
@@ -65,88 +74,23 @@ export default function NostoProvider(props: NostoProviderProps) {
65
74
  const {
66
75
  account,
67
76
  multiCurrency = false,
68
- host,
69
77
  children,
70
78
  recommendationComponent,
71
- shopifyMarkets
72
79
  } = props
73
- const [clientScriptLoadedState, setClientScriptLoadedState] = React.useState(false)
74
- const clientScriptLoaded = React.useMemo(() => clientScriptLoadedState, [clientScriptLoadedState])
75
80
 
76
81
  // Pass currentVariation as empty string if multiCurrency is disabled
77
82
  const currentVariation = multiCurrency ? props.currentVariation : ""
78
83
 
79
- // Set responseMode for loading campaigns:
80
- const responseMode = isValidElement(recommendationComponent) ? "JSON_ORIGINAL" : "HTML"
81
-
82
- useEffect(() => {
83
- if (!window.nostojs) {
84
- window.nostojs = (cb: (api: NostoClient) => void) => {
85
- (window.nostojs.q = window.nostojs.q || []).push(cb)
86
- }
87
- window.nostojs(api => api.setAutoLoad(false))
88
- }
89
-
90
- if (!isNostoLoaded() && !shopifyMarkets) {
91
- const script = document.createElement("script")
92
- script.type = "text/javascript"
93
- script.src = "//" + (host || "connect.nosto.com") + "/include/" + account
94
- script.async = true
95
- script.setAttribute("nosto-client-script", "")
96
-
97
- script.onload = () => {
98
- if (typeof jest !== "undefined") {
99
- window.nosto?.reload({
100
- site: "localhost",
101
- })
102
- }
103
- setClientScriptLoadedState(true)
104
- }
105
- document.body.appendChild(script)
106
- }
107
-
108
- // Enable Shopify markets functionality:
109
- if (shopifyMarkets) {
110
- const existingScript = document.querySelector("[nosto-client-script]")
111
- const nostoSandbox = document.querySelector("#nosto-sandbox")
112
-
113
- if (
114
- !existingScript ||
115
- existingScript?.getAttribute("nosto-language") !== shopifyMarkets?.language ||
116
- existingScript?.getAttribute("nosto-market-id") !== shopifyMarkets?.marketId
117
- ) {
118
- if (clientScriptLoadedState) {
119
- setClientScriptLoadedState(false)
120
- }
121
-
122
- existingScript?.parentNode?.removeChild(existingScript)
123
- nostoSandbox?.parentNode?.removeChild(nostoSandbox)
84
+ if (recommendationComponent && !isValidElement(recommendationComponent)) {
85
+ throw new Error(
86
+ "The recommendationComponent prop must be a valid React element. Please provide a valid React element."
87
+ )
88
+ }
124
89
 
125
- const script = document.createElement("script")
126
- script.type = "text/javascript"
127
- script.src =
128
- "//" +
129
- (host || "connect.nosto.com") +
130
- `/script/shopify/market/nosto.js?merchant=${account}&market=${
131
- shopifyMarkets.marketId || ""
132
- }&locale=${shopifyMarkets?.language?.toLowerCase() || ""}`
133
- script.async = true
134
- script.setAttribute("nosto-client-script", "")
135
- script.setAttribute("nosto-language", shopifyMarkets?.language || "")
136
- script.setAttribute("nosto-market-id", String(shopifyMarkets?.marketId))
90
+ // Set responseMode for loading campaigns:
91
+ const responseMode = recommendationComponent ? "JSON_ORIGINAL" : "HTML"
137
92
 
138
- script.onload = () => {
139
- if (typeof jest !== "undefined") {
140
- window.nosto?.reload({
141
- site: "localhost",
142
- })
143
- }
144
- setClientScriptLoadedState(true)
145
- }
146
- document.body.appendChild(script)
147
- }
148
- }
149
- }, [clientScriptLoadedState, shopifyMarkets])
93
+ const { clientScriptLoaded } = useLoadClientScript(props)
150
94
 
151
95
  return (
152
96
  <NostoContext.Provider
@@ -7,5 +7,5 @@ export { default as NostoSearch } from "./NostoSearch"
7
7
  export { default as NostoOrder } from "./NostoOrder"
8
8
  export { default as NostoHome } from "./NostoHome"
9
9
  export { default as NostoPlacement } from "./NostoPlacement"
10
- export { default as NostoProvider } from "./NostoProvider"
10
+ export { default as NostoProvider, type NostoProviderProps } from "./NostoProvider"
11
11
  export { default as NostoSession } from "./NostoSession"
package/src/context.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { createContext } from "react"
1
+ import { createContext, ReactElement } from "react"
2
2
  import { Recommendation, RenderMode } from "./types"
3
3
 
4
4
  type AnyFunction = (...args: unknown[]) => unknown
5
5
 
6
- export type RecommendationComponent = React.ReactElement<{
6
+ export type RecommendationComponent = ReactElement<{
7
7
  nostoRecommendation: Recommendation
8
8
  }>
9
9
 
@@ -1,4 +1,5 @@
1
1
  export { useDeepCompareEffect } from "./useDeepCompareEffect"
2
2
  export { useNostoApi } from "./useNostoApi"
3
3
  export { useNostoContext } from "./useNostoContext"
4
- export { useRenderCampaigns } from "./useRenderCampaigns"
4
+ export { useRenderCampaigns } from "./useRenderCampaigns"
5
+ export { useLoadClientScript } from "./useLoadClientScript"
@@ -0,0 +1,30 @@
1
+ export default function scriptLoader(scriptSrc: string, options?: ScriptLoadOptions): Promise<void> {
2
+ return new Promise((resolve, reject) => {
3
+ const script = document.createElement("script")
4
+ script.type = "text/javascript"
5
+ script.src = scriptSrc
6
+ script.async = true
7
+ script.onload = () => resolve()
8
+ script.onerror = () => reject()
9
+ Object.entries(options?.attributes ?? {}).forEach(([k, v]) => script.setAttribute(k, v))
10
+ if (options?.position === "head") {
11
+ document.head.appendChild(script)
12
+ } else {
13
+ document.body.appendChild(script)
14
+ }
15
+ })
16
+ }
17
+
18
+ /**
19
+ * @group Types
20
+ */
21
+ export type ScriptLoadOptions = {
22
+ /**
23
+ * Indicates the position of the script, default is "body"
24
+ */
25
+ position?: "head" | "body"
26
+ /**
27
+ * Indicates the attributes of the script element
28
+ */
29
+ attributes?: Record<string, string>
30
+ }
@@ -0,0 +1,84 @@
1
+ import { useState, useEffect } from "react"
2
+ import { isNostoLoaded } from "../components/helpers"
3
+ import type { NostoClient } from "../types"
4
+ import type { NostoProviderProps } from "../components/NostoProvider"
5
+ import scriptLoaderFn from "./scriptLoader"
6
+
7
+ type NostoScriptProps = Pick<NostoProviderProps, "account" | "host" | "shopifyMarkets" | "loadScript" | "scriptLoader">
8
+
9
+ export function useLoadClientScript(props: NostoScriptProps) {
10
+ const { host = "connect.nosto.com", scriptLoader = scriptLoaderFn, account, shopifyMarkets, loadScript = true } = props
11
+ const [clientScriptLoaded, setClientScriptLoaded] = useState(false)
12
+
13
+ useEffect(() => {
14
+ function scriptOnload() {
15
+ // Override for production scripts to work in unit tests
16
+ if ("nostoReactTest" in window) {
17
+ window.nosto?.reload({
18
+ site: "localhost"
19
+ })
20
+ }
21
+ setClientScriptLoaded(true)
22
+ }
23
+
24
+ // Create and append script element
25
+ async function injectScriptElement(urlPartial: string, extraAttributes: Record<string, string> = {}) {
26
+ const scriptSrc = `//${host}${urlPartial}`
27
+ const attributes = { "nosto-client-script": "", ...extraAttributes }
28
+ await scriptLoader(scriptSrc, { attributes })
29
+ scriptOnload()
30
+ }
31
+
32
+ function prepareShopifyMarketsScript() {
33
+ const existingScript = document.querySelector("[nosto-client-script]")
34
+
35
+ const marketId = String(shopifyMarkets?.marketId || "")
36
+ const language = shopifyMarkets?.language || ""
37
+
38
+ const attributeMismatch =
39
+ existingScript?.getAttribute("nosto-language") !== language ||
40
+ existingScript?.getAttribute("nosto-market-id") !== marketId
41
+
42
+ if (!existingScript || attributeMismatch) {
43
+ if (clientScriptLoaded) {
44
+ setClientScriptLoaded(false)
45
+ }
46
+
47
+ const nostoSandbox = document.querySelector("#nosto-sandbox")
48
+
49
+ existingScript?.parentNode?.removeChild(existingScript)
50
+ nostoSandbox?.parentNode?.removeChild(nostoSandbox)
51
+
52
+ const urlPartial =
53
+ `/script/shopify/market/nosto.js?merchant=${account}&market=${marketId}&locale=${language.toLowerCase()}`
54
+ injectScriptElement(urlPartial, { "nosto-language": language, "nosto-market-id": marketId })
55
+ }
56
+ }
57
+
58
+ // Load Nosto API stub
59
+ if (!window.nostojs) {
60
+ window.nostojs = (cb: (api: NostoClient) => void) => {
61
+ (window.nostojs.q = window.nostojs.q || []).push(cb)
62
+ }
63
+ window.nostojs(api => api.setAutoLoad(false))
64
+ }
65
+
66
+ if (!loadScript) {
67
+ window.nosto ? scriptOnload() : window.nostojs(scriptOnload)
68
+ return
69
+ }
70
+
71
+ // Load Nosto client script if not already loaded externally
72
+ if (!isNostoLoaded() && !shopifyMarkets) {
73
+ const urlPartial = `/include/${account}`
74
+ injectScriptElement(urlPartial)
75
+ }
76
+
77
+ // Load Shopify Markets scripts
78
+ if (shopifyMarkets) {
79
+ prepareShopifyMarketsScript()
80
+ }
81
+ }, [shopifyMarkets?.marketId, shopifyMarkets?.language])
82
+
83
+ return { clientScriptLoaded }
84
+ }
@@ -1,11 +1,11 @@
1
- import { useEffect } from "react"
1
+ import { DependencyList, useEffect } from "react"
2
2
  import { useNostoContext } from "./useNostoContext"
3
3
  import { NostoClient } from "../types"
4
4
  import { useDeepCompareEffect } from "./useDeepCompareEffect"
5
5
 
6
6
  export function useNostoApi(
7
7
  cb: (api: NostoClient) => void,
8
- deps?: React.DependencyList,
8
+ deps?: DependencyList,
9
9
  flags?: { deep?: boolean }
10
10
  ): void {
11
11
  const { clientScriptLoaded, currentVariation, responseMode } = useNostoContext()
@@ -7,12 +7,6 @@ import { NostoContext, NostoContextType } from "../context"
7
7
  * @group Essential Functions
8
8
  */
9
9
  export function useNostoContext(): NostoContextType {
10
- const context = useContext(NostoContext)
11
-
12
- if (!context) {
13
- throw new Error("No nosto context found")
14
- }
15
-
16
- return context
10
+ return useContext(NostoContext)
17
11
  }
18
12
 
@@ -1,8 +1,7 @@
1
- import { useRef } from "react"
1
+ import { cloneElement, useRef } from "react"
2
2
  import { createRoot, Root } from "react-dom/client"
3
3
  import { ActionResponse, Recommendation } from "../types"
4
4
  import { useNostoContext } from "./useNostoContext"
5
- import React from "react"
6
5
  import { RecommendationComponent } from "../context"
7
6
 
8
7
  // RecommendationComponent for client-side rendering:
@@ -10,7 +9,7 @@ function RecommendationComponentWrapper(props: {
10
9
  recommendationComponent: RecommendationComponent,
11
10
  nostoRecommendation: Recommendation }) {
12
11
 
13
- return React.cloneElement(props.recommendationComponent, {
12
+ return cloneElement(props.recommendationComponent, {
14
13
  // eslint-disable-next-line react/prop-types
15
14
  nostoRecommendation: props.nostoRecommendation,
16
15
  })
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export type { Cart, Customer, Product, Order, Recommendation } from "./types"
2
2
  export * from "./components"
3
+ export { type ScriptLoadOptions } from "./hooks/scriptLoader"
3
4
  export { NostoContext, type NostoContextType } from "./context"
4
5
  export { useNostoContext } from "./hooks/useNostoContext"