@embeddable/sdk 1.0.18 → 1.0.20
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/{EmbeddableProvider-DLBbGfn0.js → EmbeddableProvider-BiwCAPla.js} +74 -3
- package/dist/EmbeddableProvider-CT_fGWcI.cjs +10 -0
- package/dist/hooks/usePayment.d.ts +6 -1
- package/dist/hooks/usePayment.d.ts.map +1 -1
- package/dist/hooks.cjs +1 -1
- package/dist/hooks.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/{storage-EjA7Lhbb.cjs → storage-BtXo3gya.cjs} +1 -1
- package/dist/utils.cjs +1 -1
- package/package.json +1 -1
- package/dist/EmbeddableProvider-CuoI64E1.cjs +0 -10
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import require$$0, { useState, useCallback, useEffect, useMemo, createContext, useContext } from "react";
|
|
1
|
+
import require$$0, { useState, useCallback, useEffect, useMemo, useRef, createContext, useContext } from "react";
|
|
2
2
|
import { s as storage } from "./storage-B4eeCFyo.js";
|
|
3
3
|
var jsxRuntime = { exports: {} };
|
|
4
4
|
var reactJsxRuntime_production_min = {};
|
|
@@ -1373,8 +1373,72 @@ function usePayment(options = {}) {
|
|
|
1373
1373
|
error: null,
|
|
1374
1374
|
success: false
|
|
1375
1375
|
});
|
|
1376
|
+
const pollingIntervalRef = useRef(null);
|
|
1377
|
+
useEffect(() => {
|
|
1378
|
+
return () => {
|
|
1379
|
+
if (pollingIntervalRef.current) {
|
|
1380
|
+
window.clearInterval(pollingIntervalRef.current);
|
|
1381
|
+
}
|
|
1382
|
+
};
|
|
1383
|
+
}, []);
|
|
1384
|
+
const pollSessionStatus = useCallback(
|
|
1385
|
+
async (sessionId) => {
|
|
1386
|
+
var _a, _b;
|
|
1387
|
+
try {
|
|
1388
|
+
const response = await fetch(
|
|
1389
|
+
`${EVENTS_BASE_URL}/api/integrations/stripe/session/${sessionId}?widgetId=${widgetId}`,
|
|
1390
|
+
{
|
|
1391
|
+
method: "GET",
|
|
1392
|
+
headers: {
|
|
1393
|
+
"Content-Type": "application/json"
|
|
1394
|
+
},
|
|
1395
|
+
credentials: "omit"
|
|
1396
|
+
}
|
|
1397
|
+
);
|
|
1398
|
+
const responseData = await response.json();
|
|
1399
|
+
if (!response.ok) {
|
|
1400
|
+
console.error("Error polling session status:", responseData);
|
|
1401
|
+
return;
|
|
1402
|
+
}
|
|
1403
|
+
if (responseData.success && responseData.session) {
|
|
1404
|
+
const { status, payment_status } = responseData.session;
|
|
1405
|
+
if (payment_status === "paid" && status === "complete") {
|
|
1406
|
+
if (pollingIntervalRef.current) {
|
|
1407
|
+
window.clearInterval(pollingIntervalRef.current);
|
|
1408
|
+
pollingIntervalRef.current = null;
|
|
1409
|
+
}
|
|
1410
|
+
setState({ loading: false, error: null, success: true });
|
|
1411
|
+
(_a = options.onSuccess) == null ? void 0 : _a.call(options, responseData.session);
|
|
1412
|
+
} else if (status === "expired") {
|
|
1413
|
+
if (pollingIntervalRef.current) {
|
|
1414
|
+
window.clearInterval(pollingIntervalRef.current);
|
|
1415
|
+
pollingIntervalRef.current = null;
|
|
1416
|
+
}
|
|
1417
|
+
setState({ loading: false, error: "Payment session expired", success: false });
|
|
1418
|
+
(_b = options.onFailure) == null ? void 0 : _b.call(options, responseData.session);
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
} catch (error) {
|
|
1422
|
+
console.error("Error polling session status:", error);
|
|
1423
|
+
}
|
|
1424
|
+
},
|
|
1425
|
+
[widgetId, options]
|
|
1426
|
+
);
|
|
1427
|
+
const startPolling = useCallback(
|
|
1428
|
+
(sessionId) => {
|
|
1429
|
+
if (pollingIntervalRef.current) {
|
|
1430
|
+
window.clearInterval(pollingIntervalRef.current);
|
|
1431
|
+
}
|
|
1432
|
+
pollingIntervalRef.current = window.setInterval(() => {
|
|
1433
|
+
pollSessionStatus(sessionId);
|
|
1434
|
+
}, 1e4);
|
|
1435
|
+
pollSessionStatus(sessionId);
|
|
1436
|
+
},
|
|
1437
|
+
[pollSessionStatus]
|
|
1438
|
+
);
|
|
1376
1439
|
const createCheckout = useCallback(
|
|
1377
1440
|
async (inputs) => {
|
|
1441
|
+
var _a;
|
|
1378
1442
|
setState({ loading: true, error: null, success: false });
|
|
1379
1443
|
try {
|
|
1380
1444
|
const requestData = {
|
|
@@ -1402,7 +1466,10 @@ function usePayment(options = {}) {
|
|
|
1402
1466
|
};
|
|
1403
1467
|
}
|
|
1404
1468
|
if (responseData.success) {
|
|
1405
|
-
|
|
1469
|
+
if ((_a = responseData.data) == null ? void 0 : _a.sessionId) {
|
|
1470
|
+
startPolling(responseData.data.sessionId);
|
|
1471
|
+
}
|
|
1472
|
+
setState({ loading: false, error: null, success: false });
|
|
1406
1473
|
return {
|
|
1407
1474
|
success: true,
|
|
1408
1475
|
message: "Checkout session created successfully",
|
|
@@ -1426,9 +1493,13 @@ function usePayment(options = {}) {
|
|
|
1426
1493
|
};
|
|
1427
1494
|
}
|
|
1428
1495
|
},
|
|
1429
|
-
[options.capabilityId, options.integrationKey, widgetId]
|
|
1496
|
+
[options.capabilityId, options.integrationKey, widgetId, startPolling]
|
|
1430
1497
|
);
|
|
1431
1498
|
const reset = useCallback(() => {
|
|
1499
|
+
if (pollingIntervalRef.current) {
|
|
1500
|
+
window.clearInterval(pollingIntervalRef.current);
|
|
1501
|
+
pollingIntervalRef.current = null;
|
|
1502
|
+
}
|
|
1432
1503
|
setState({ loading: false, error: null, success: false });
|
|
1433
1504
|
}, []);
|
|
1434
1505
|
return {
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";const e=require("react"),t=require("./storage-BtXo3gya.cjs");var r,n={exports:{}},a={};var o,s={};
|
|
2
|
+
/**
|
|
3
|
+
* @license React
|
|
4
|
+
* react-jsx-runtime.development.js
|
|
5
|
+
*
|
|
6
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
7
|
+
*
|
|
8
|
+
* This source code is licensed under the MIT license found in the
|
|
9
|
+
* LICENSE file in the root directory of this source tree.
|
|
10
|
+
*/"production"===process.env.NODE_ENV?n.exports=function(){if(r)return a;r=1;var t=e,n=Symbol.for("react.element"),o=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,c=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function l(e,t,r){var a,o={},l=null,u=null;for(a in void 0!==r&&(l=""+r),void 0!==t.key&&(l=""+t.key),void 0!==t.ref&&(u=t.ref),t)s.call(t,a)&&!i.hasOwnProperty(a)&&(o[a]=t[a]);if(e&&e.defaultProps)for(a in t=e.defaultProps)void 0===o[a]&&(o[a]=t[a]);return{$$typeof:n,type:e,key:l,ref:u,props:o,_owner:c.current}}return a.Fragment=o,a.jsx=l,a.jsxs=l,a}():n.exports=(o||(o=1,"production"!==process.env.NODE_ENV&&function(){var t,r=e,n=Symbol.for("react.element"),a=Symbol.for("react.portal"),o=Symbol.for("react.fragment"),c=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),u=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),p=Symbol.for("react.suspense_list"),m=Symbol.for("react.memo"),g=Symbol.for("react.lazy"),y=Symbol.for("react.offscreen"),v=Symbol.iterator,b=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function h(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];!function(e,t,r){var n=b.ReactDebugCurrentFrame.getStackAddendum();""!==n&&(t+="%s",r=r.concat([n]));var a=r.map(function(e){return String(e)});a.unshift("Warning: "+t),Function.prototype.apply.call(console[e],console,a)}("error",e,r)}function w(e){return e.displayName||"Context"}function k(e){if(null==e)return null;if("number"==typeof e.tag&&h("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),"function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case o:return"Fragment";case a:return"Portal";case i:return"Profiler";case c:return"StrictMode";case f:return"Suspense";case p:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case u:return w(e)+".Consumer";case l:return w(e._context)+".Provider";case d:return function(e,t,r){var n=e.displayName;if(n)return n;var a=t.displayName||t.name||"";return""!==a?r+"("+a+")":r}(e,e.render,"ForwardRef");case m:var t=e.displayName||null;return null!==t?t:k(e.type)||"Memo";case g:var r=e,n=r._payload,s=r._init;try{return k(s(n))}catch(y){return null}}return null}t=Symbol.for("react.module.reference");var _,S,E,C,j,O,T,I=Object.assign,P=0;function x(){}x.__reactDisabledLog=!0;var $,R=b.ReactCurrentDispatcher;function N(e,t,r){if(void 0===$)try{throw Error()}catch(a){var n=a.stack.trim().match(/\n( *(at )?)/);$=n&&n[1]||""}return"\n"+$+e}var D,F=!1,L="function"==typeof WeakMap?WeakMap:Map;function U(e,t){if(!e||F)return"";var r,n=D.get(e);if(void 0!==n)return n;F=!0;var a,o=Error.prepareStackTrace;Error.prepareStackTrace=void 0,a=R.current,R.current=null,function(){if(0===P){_=console.log,S=console.info,E=console.warn,C=console.error,j=console.group,O=console.groupCollapsed,T=console.groupEnd;var e={configurable:!0,enumerable:!0,value:x,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}P++}();try{if(t){var s=function(){throw Error()};if(Object.defineProperty(s.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(s,[])}catch(m){r=m}Reflect.construct(e,[],s)}else{try{s.call()}catch(m){r=m}e.call(s.prototype)}}else{try{throw Error()}catch(m){r=m}e()}}catch(g){if(g&&r&&"string"==typeof g.stack){for(var c=g.stack.split("\n"),i=r.stack.split("\n"),l=c.length-1,u=i.length-1;l>=1&&u>=0&&c[l]!==i[u];)u--;for(;l>=1&&u>=0;l--,u--)if(c[l]!==i[u]){if(1!==l||1!==u)do{if(l--,--u<0||c[l]!==i[u]){var d="\n"+c[l].replace(" at new "," at ");return e.displayName&&d.includes("<anonymous>")&&(d=d.replace("<anonymous>",e.displayName)),"function"==typeof e&&D.set(e,d),d}}while(l>=1&&u>=0);break}}}finally{F=!1,R.current=a,function(){if(0===--P){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:I({},e,{value:_}),info:I({},e,{value:S}),warn:I({},e,{value:E}),error:I({},e,{value:C}),group:I({},e,{value:j}),groupCollapsed:I({},e,{value:O}),groupEnd:I({},e,{value:T})})}P<0&&h("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}(),Error.prepareStackTrace=o}var f=e?e.displayName||e.name:"",p=f?N(f):"";return"function"==typeof e&&D.set(e,p),p}function A(e,t,r){if(null==e)return"";if("function"==typeof e)return U(e,!(!(n=e.prototype)||!n.isReactComponent));var n;if("string"==typeof e)return N(e);switch(e){case f:return N("Suspense");case p:return N("SuspenseList")}if("object"==typeof e)switch(e.$$typeof){case d:return U(e.render,!1);case m:return A(e.type,t,r);case g:var a=e,o=a._payload,s=a._init;try{return A(s(o),t,r)}catch(c){}}return""}D=new L;var V=Object.prototype.hasOwnProperty,W={},z=b.ReactDebugCurrentFrame;function B(e){if(e){var t=e._owner,r=A(e.type,e._source,t?t.type:null);z.setExtraStackFrame(r)}else z.setExtraStackFrame(null)}var J=Array.isArray;function K(e){return J(e)}function M(e){return""+e}function H(e){if(function(e){try{return M(e),!1}catch(t){return!0}}(e))return h("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",function(e){return"function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object"}(e)),M(e)}var Y,q,G=b.ReactCurrentOwner,X={key:!0,ref:!0,__self:!0,__source:!0};function Q(e,t,r,a,o){var s,c={},i=null,l=null;for(s in void 0!==r&&(H(r),i=""+r),function(e){if(V.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(t)&&(H(t.key),i=""+t.key),function(e){if(V.call(e,"ref")){var t=Object.getOwnPropertyDescriptor(e,"ref").get;if(t&&t.isReactWarning)return!1}return void 0!==e.ref}(t)&&(l=t.ref,function(e){"string"==typeof e.ref&&G.current}(t)),t)V.call(t,s)&&!X.hasOwnProperty(s)&&(c[s]=t[s]);if(e&&e.defaultProps){var u=e.defaultProps;for(s in u)void 0===c[s]&&(c[s]=u[s])}if(i||l){var d="function"==typeof e?e.displayName||e.name||"Unknown":e;i&&function(e,t){var r=function(){Y||(Y=!0,h("%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))};r.isReactWarning=!0,Object.defineProperty(e,"key",{get:r,configurable:!0})}(c,d),l&&function(e,t){var r=function(){q||(q=!0,h("%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))};r.isReactWarning=!0,Object.defineProperty(e,"ref",{get:r,configurable:!0})}(c,d)}return function(e,t,r,a,o,s,c){var i={$$typeof:n,type:e,key:t,ref:r,props:c,_owner:s,_store:{}};return Object.defineProperty(i._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(i,"_self",{configurable:!1,enumerable:!1,writable:!1,value:a}),Object.defineProperty(i,"_source",{configurable:!1,enumerable:!1,writable:!1,value:o}),Object.freeze&&(Object.freeze(i.props),Object.freeze(i)),i}(e,i,l,o,a,G.current,c)}var Z,ee=b.ReactCurrentOwner,te=b.ReactDebugCurrentFrame;function re(e){if(e){var t=e._owner,r=A(e.type,e._source,t?t.type:null);te.setExtraStackFrame(r)}else te.setExtraStackFrame(null)}function ne(e){return"object"==typeof e&&null!==e&&e.$$typeof===n}function ae(){if(ee.current){var e=k(ee.current.type);if(e)return"\n\nCheck the render method of `"+e+"`."}return""}Z=!1;var oe={};function se(e,t){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;var r=function(e){var t=ae();if(!t){var r="string"==typeof e?e:e.displayName||e.name;r&&(t="\n\nCheck the top-level render call using <"+r+">.")}return t}(t);if(!oe[r]){oe[r]=!0;var n="";e&&e._owner&&e._owner!==ee.current&&(n=" It was passed a child from "+k(e._owner.type)+"."),re(e),h('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',r,n),re(null)}}}function ce(e,t){if("object"==typeof e)if(K(e))for(var r=0;r<e.length;r++){var n=e[r];ne(n)&&se(n,t)}else if(ne(e))e._store&&(e._store.validated=!0);else if(e){var a=function(e){if(null===e||"object"!=typeof e)return null;var t=v&&e[v]||e["@@iterator"];return"function"==typeof t?t:null}(e);if("function"==typeof a&&a!==e.entries)for(var o,s=a.call(e);!(o=s.next()).done;)ne(o.value)&&se(o.value,t)}}function ie(e){var t,r=e.type;if(null!=r&&"string"!=typeof r){if("function"==typeof r)t=r.propTypes;else{if("object"!=typeof r||r.$$typeof!==d&&r.$$typeof!==m)return;t=r.propTypes}if(t){var n=k(r);!function(e,t,r,n,a){var o=Function.call.bind(V);for(var s in e)if(o(e,s)){var c=void 0;try{if("function"!=typeof e[s]){var i=Error((n||"React class")+": "+r+" type `"+s+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[s]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw i.name="Invariant Violation",i}c=e[s](t,s,n,r,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(l){c=l}!c||c instanceof Error||(B(a),h("%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).",n||"React class",r,s,typeof c),B(null)),c instanceof Error&&!(c.message in W)&&(W[c.message]=!0,B(a),h("Failed %s type: %s",r,c.message),B(null))}}(t,e.props,"prop",n,e)}else void 0===r.PropTypes||Z||(Z=!0,h("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",k(r)||"Unknown"));"function"!=typeof r.getDefaultProps||r.getDefaultProps.isReactClassApproved||h("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}var le={};function ue(e,r,a,s,v,b){var w=function(e){return"string"==typeof e||"function"==typeof e||e===o||e===i||e===c||e===f||e===p||e===y||"object"==typeof e&&null!==e&&(e.$$typeof===g||e.$$typeof===m||e.$$typeof===l||e.$$typeof===u||e.$$typeof===d||e.$$typeof===t||void 0!==e.getModuleId)}(e);if(!w){var _,S="";(void 0===e||"object"==typeof e&&null!==e&&0===Object.keys(e).length)&&(S+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."),S+=ae(),null===e?_="null":K(e)?_="array":void 0!==e&&e.$$typeof===n?(_="<"+(k(e.type)||"Unknown")+" />",S=" Did you accidentally export a JSX literal instead of a component?"):_=typeof e,h("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",_,S)}var E=Q(e,r,a,v,b);if(null==E)return E;if(w){var C=r.children;if(void 0!==C)if(s)if(K(C)){for(var j=0;j<C.length;j++)ce(C[j],e);Object.freeze&&Object.freeze(C)}else h("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 ce(C,e)}if(V.call(r,"key")){var O=k(e),T=Object.keys(r).filter(function(e){return"key"!==e}),I=T.length>0?"{key: someKey, "+T.join(": ..., ")+": ...}":"{key: someKey}";le[O+I]||(h('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',I,O,T.length>0?"{"+T.join(": ..., ")+": ...}":"{}",O),le[O+I]=!0)}return e===o?function(e){for(var t=Object.keys(e.props),r=0;r<t.length;r++){var n=t[r];if("children"!==n&&"key"!==n){re(e),h("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",n),re(null);break}}null!==e.ref&&(re(e),h("Invalid attribute `ref` supplied to `React.Fragment`."),re(null))}(E):ie(E),E}var de=function(e,t,r){return ue(e,t,r,!1)},fe=function(e,t,r){return ue(e,t,r,!0)};s.Fragment=o,s.jsx=de,s.jsxs=fe}()),s);var c=n.exports;const i="https://events.embeddable.co";function l(){const{config:e}=m();if(!e)throw new Error("No Embeddable configuration found. Make sure to wrap your app with EmbeddableProvider and provide a valid config.");return e}const u=()=>{const{widgetId:t}=l(),r=`${i}/api`,[n,a]=e.useState(!1),o=e.useCallback(async e=>{if(!t)return[];const n=[];try{a(!0);const o=await fetch(`${r}/marketing/track`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify({widgetId:t,capabilityId:"trackEvent",inputs:e})}),s=await o.json();s.success?s.results?s.results.forEach(e=>{n.push({success:e.success,integrationKey:e.integrationKey,data:e.data,error:e.error})}):n.push({success:!0,data:s.data}):n.push({success:!1,error:s.error||"Unknown error"})}catch(o){n.push({success:!1,error:o instanceof Error?o.message:"Network error"})}finally{a(!1)}return n},[t,r]),s=e.useCallback(async(e={})=>o({event_name:"page_view",event_category:"engagement",custom_parameters:{page_url:window.location.href,page_title:document.title,referrer:document.referrer,...e}}),[o]),c=e.useCallback(async(e,t={})=>o({event_name:"form_submit",event_category:"conversion",custom_parameters:{form_data:e,...t}}),[o]),u=e.useCallback(async(e,t={})=>{let r={};return r="string"==typeof e?{element_selector:e}:{element_id:e.id,element_class:e.className,element_text:e.textContent||e.innerText,element_tag:e.tagName.toLowerCase()},o({event_name:"button_click",event_category:"interaction",custom_parameters:{...r,...t}})},[o]),d=e.useCallback(async(e,t,r={})=>o({event_name:"conversion",event_category:"conversion",value:t,custom_parameters:{conversion_type:e,currency:r.currency||"USD",...r}}),[o]),f=e.useCallback(async(e,t={})=>o({event_name:"signup",event_category:"conversion",user_data:e,custom_parameters:t}),[o]),p=e.useCallback(async(e,t={})=>o({event_name:"purchase",event_category:"ecommerce",value:e.amount,custom_parameters:{transaction_id:e.id,currency:e.currency||"USD",items:e.items||[],...t}}),[o]),m=e.useCallback(()=>{s()},[s]),g=e.useCallback(()=>{const e=async e=>{try{const t=e.target,r=new FormData(t),n=Object.fromEntries(r.entries());await c(n,{form_id:t.id,form_class:t.className,form_action:t.action,form_method:t.method})}catch(t){}};return document.addEventListener("submit",e),()=>{document.removeEventListener("submit",e)}},[c]),y=e.useCallback((e='button, .btn, [role="button"], a, input[type="submit"]')=>{const t=async t=>{const r=t.target.closest(e);if(r)try{await u(r)}catch(n){}};return document.addEventListener("click",t),()=>{document.removeEventListener("click",t)}},[u]);return{isLoading:n,track:o,trackPageView:s,trackFormSubmit:c,trackClick:u,trackConversion:d,trackSignup:f,trackPurchase:p,enableAutoPageView:m,enableAutoFormTracking:g,enableAutoClickTracking:y}};const d={version:"latest",mode:"embeddable",ignoreCache:!1,lazyLoad:!1,loader:!0,widgetId:"",_containerId:"",_shadowRoot:void 0},f=e.createContext({config:{...d},setConfig:()=>{},data:{},setData:()=>{}});function p(){const{trackPageView:t}=u(),{config:r}=m();return e.useEffect(()=>{(null==r?void 0:r.widgetId)&&"preview"!==(null==r?void 0:r.mode)&&t()},[null==r?void 0:r.widgetId,null==r?void 0:r.mode,t]),null}function m(){const t=e.useContext(f);if(!t)throw new Error("useEmbeddableContext must be used within an EmbeddableProvider");return t}exports.EmbeddableProvider=function({config:t,data:r,children:n}){const[a,o]=e.useState(d),[s,i]=e.useState(r||{});return e.useEffect(()=>{const e={...d,...t};o(e)},[t]),e.useEffect(()=>{const e=e=>{("https://embeddable.co"===e.origin||e.origin.includes("localhost"))&&e.data&&"object"==typeof e.data&&"embeddable-update-data"===e.data.type&&i(e.data.data||{})};return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}},[]),c.jsxs(f.Provider,{value:{config:a,setConfig:o,data:s,setData:i},children:[c.jsx(p,{}),n]})},exports.useAI=function(t){const{widgetId:r}=l(),[n,a]=e.useState({loading:!1,error:null,success:!1});return{...n,callAI:e.useCallback(async(e,n)=>{var o;a({loading:!0,error:null,success:!1});try{const s={widgetId:r,capabilityId:"ai_call",integrationKey:t.platform,prompt:e,history:n||[]},c=await fetch(`${i}/api/execute/ai`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify(s)}),l=await c.json();if(!c.ok){const e=l.message||l.error||`HTTP ${c.status}`;return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}if(l.success)return a({loading:!1,error:null,success:!0}),{success:!0,message:(null==(o=l.data)?void 0:o.response)||"AI call completed successfully",data:l.data,metadata:l.metadata};{const e=l.message||l.error||"AI call failed";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}}catch(s){const e=s instanceof Error?s.message:"Unknown error occurred";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}},[t.platform,r]),reset:e.useCallback(()=>{a({loading:!1,error:null,success:!1})},[])}},exports.useDebounce=function(t,r){const[n,a]=e.useState(t);return e.useEffect(()=>{const e=setTimeout(()=>{a(t)},r);return()=>{clearTimeout(e)}},[t,r]),n},exports.useEmbeddableConfig=l,exports.useEmbeddableContext=m,exports.useEmbeddableData=function(){const{data:e}=m();return{data:e}},exports.useEventTracking=u,exports.useFormSubmission=function(t){const{widgetId:r}=l(),[n,a]=e.useState({loading:!1,error:null,success:!1});return{...n,submit:e.useCallback(async e=>{var n,o,s;a({loading:!0,error:null,success:!1});try{if(null==t?void 0:t.validatePayload){const r=t.validatePayload(e);if(r)return a({loading:!1,error:r,success:!1}),{success:!1,message:r}}const c={payload:e,widgetId:r,collectionName:(null==t?void 0:t.collectionName)||"submissions"},l=await fetch(`${i}/api/submissions`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify(c)}),u=await l.json();if(!l.ok){const e=u.message||u.error||`HTTP ${l.status}`;return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}if(u.success)return a({loading:!1,error:null,success:!0}),{id:(null==(n=u.data)?void 0:n.id)||(null==(o=u.data)?void 0:o._id),success:!0,message:(null==(s=u.data)?void 0:s.message)||"Submission successful"};{const e=u.message||u.error||"Submission failed";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}}catch(c){const e=c instanceof Error?c.message:"Unknown error occurred";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}},[t,r]),reset:e.useCallback(()=>{a({loading:!1,error:null,success:!1})},[])}},exports.useLocalStorage=function(r,n,a={}){const{widgetId:o}=l(),s=e.useMemo(()=>({...a,prefix:`embd-${o}-${a.prefix||""}`}),[o,a]),[c,i]=e.useState(()=>{const e=t.storage.get(r,s);return null!==e?e:n}),u=e.useCallback(e=>{try{const n=e instanceof Function?e(c):e;i(n),t.storage.set(r,n,s)}catch(n){}},[r,c,s]),d=e.useCallback(()=>{try{i(n),t.storage.remove(r,s)}catch(e){}},[r,n,s]);return e.useEffect(()=>{const e=e=>{const t=s.prefix+r;if(e.key===t&&null!==e.newValue)try{const{deserialize:t=JSON.parse}=s,r=t(e.newValue);i(r)}catch(n){}};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[r,s]),[c,u,d]},exports.usePayment=function(t={}){const{widgetId:r}=l(),[n,a]=e.useState({loading:!1,error:null,success:!1}),o=e.useRef(null);e.useEffect(()=>()=>{o.current&&window.clearInterval(o.current)},[]);const s=e.useCallback(async e=>{var n,s;try{const c=await fetch(`${i}/api/integrations/stripe/session/${e}?widgetId=${r}`,{method:"GET",headers:{"Content-Type":"application/json"},credentials:"omit"}),l=await c.json();if(!c.ok)return;if(l.success&&l.session){const{status:e,payment_status:r}=l.session;"paid"===r&&"complete"===e?(o.current&&(window.clearInterval(o.current),o.current=null),a({loading:!1,error:null,success:!0}),null==(n=t.onSuccess)||n.call(t,l.session)):"expired"===e&&(o.current&&(window.clearInterval(o.current),o.current=null),a({loading:!1,error:"Payment session expired",success:!1}),null==(s=t.onFailure)||s.call(t,l.session))}}catch(c){}},[r,t]),c=e.useCallback(e=>{o.current&&window.clearInterval(o.current),o.current=window.setInterval(()=>{s(e)},1e4),s(e)},[s]);return{...n,createCheckout:e.useCallback(async e=>{var n;a({loading:!0,error:null,success:!1});try{const o={widgetId:r,capabilityId:t.capabilityId||"getCheckout",integrationKey:t.integrationKey||"stripe",inputs:e},s=await fetch(`${i}/api/execute/payments`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify(o)}),l=await s.json();if(!s.ok){const e=l.message||l.error||`HTTP ${s.status}`;return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}if(l.success)return(null==(n=l.data)?void 0:n.sessionId)&&c(l.data.sessionId),a({loading:!1,error:null,success:!1}),{success:!0,message:"Checkout session created successfully",data:l.data,metadata:l.metadata};{const e=l.message||l.error||"Payment checkout failed";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}}catch(o){const e=o instanceof Error?o.message:"Unknown error occurred";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}},[t.capabilityId,t.integrationKey,r,c]),reset:e.useCallback(()=>{o.current&&(window.clearInterval(o.current),o.current=null),a({loading:!1,error:null,success:!1})},[])}},exports.usePublicSubmissions=function(t){const{widgetId:r}=l(),[n,a]=e.useState({loading:!1,error:null,data:null,pagination:null}),o=e.useCallback(async e=>{a(e=>({...e,loading:!0,error:null}));try{const n={...t,...e},o=new URLSearchParams;o.append("widgetId",r),(null==n?void 0:n.collectionName)&&o.append("collectionName",n.collectionName),o.append("page",String((null==n?void 0:n.page)||1)),o.append("limit",String((null==n?void 0:n.limit)||10)),o.append("sortBy",(null==n?void 0:n.sortBy)||"createdAt"),o.append("sortOrder",(null==n?void 0:n.sortOrder)||"desc"),(null==n?void 0:n.fromDate)&&o.append("fromDate",n.fromDate),(null==n?void 0:n.toDate)&&o.append("toDate",n.toDate);const s=await fetch(`${i}/api/submissions/public?${o.toString()}`,{method:"GET",headers:{"Content-Type":"application/json"},credentials:"omit"}),c=await s.json();if(!s.ok){const e=c.message||c.error||`HTTP ${s.status}`;return a(t=>({...t,loading:!1,error:e})),{success:!1,data:[],pagination:{page:1,limit:10,total:0,pages:0},message:e}}if(c.success)return a(e=>({...e,loading:!1,error:null,data:c.data||[],pagination:c.pagination||{page:1,limit:10,total:0,pages:0}})),{success:!0,data:c.data||[],pagination:c.pagination||{page:1,limit:10,total:0,pages:0}};{const e=c.message||c.error||"Failed to fetch submissions";return a(t=>({...t,loading:!1,error:e})),{success:!1,data:[],pagination:{page:1,limit:10,total:0,pages:0},message:e}}}catch(n){const e=n instanceof Error?n.message:"Unknown error occurred";return a(t=>({...t,loading:!1,error:e})),{success:!1,data:[],pagination:{page:1,limit:10,total:0,pages:0},message:e}}},[t,r]),s=e.useCallback(()=>{a({loading:!1,error:null,data:null,pagination:null})},[]);return e.useEffect(()=>{t&&void 0===t.page&&void 0===t.limit||o()},[o,t]),{...n,fetchSubmissions:o,reset:s}},exports.useVote=function(t){const{widgetId:r}=l(),[n,a]=e.useState({loading:!1,error:null,success:!1});return{...n,vote:e.useCallback(async e=>{var n,o,s;a({loading:!0,error:null,success:!1});try{const c={voteFor:e,widgetId:r,collectionName:(null==t?void 0:t.collectionName)||"votes"},l=await fetch(`${i}/api/votes`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify(c)}),u=await l.json();if(!l.ok){const e=u.message||u.error||`HTTP ${l.status}`;return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}if(u.success)return a({loading:!1,error:null,success:!0}),{id:(null==(n=u.data)?void 0:n.id)||(null==(o=u.data)?void 0:o._id),success:!0,message:(null==(s=u.data)?void 0:s.message)||"Vote submitted successfully"};{const e=u.message||u.error||"Vote submission failed";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}}catch(c){const e=c instanceof Error?c.message:"Unknown error occurred";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}},[t,r]),reset:e.useCallback(()=>{a({loading:!1,error:null,success:!1})},[])}},exports.useVoteAggregations=function(t){const{widgetId:r}=l(),[n,a]=e.useState({data:null,loading:!1,error:null}),o=e.useCallback(async()=>{if(!r)return a({data:null,loading:!1,error:"Widget ID is required"}),{success:!1,data:{results:[],summary:{totalVotes:0,totalOptions:0,groupBy:""}}};a(e=>({...e,loading:!0,error:null}));try{const e=(null==t?void 0:t.collectionName)||"votes",n=new URL(`${i}/api/votes/aggregations`);n.searchParams.append("widgetId",r),n.searchParams.append("collectionName",e);const o=await fetch(n.toString(),{method:"GET",headers:{"Content-Type":"application/json"},credentials:"omit"}),s=await o.json();if(!o.ok){const e=s.message||s.error||`HTTP ${o.status}`;return a({data:null,loading:!1,error:e}),{success:!1,data:{results:[],summary:{totalVotes:0,totalOptions:0,groupBy:""}}}}return a({data:s.data,loading:!1,error:null}),s}catch(e){const t=e instanceof Error?e.message:"Unknown error occurred";return a({data:null,loading:!1,error:t}),{success:!1,data:{results:[],summary:{totalVotes:0,totalOptions:0,groupBy:""}}}}},[r,null==t?void 0:t.collectionName]),s=e.useCallback(()=>o(),[o]),c=e.useCallback(()=>{a({data:null,loading:!1,error:null})},[]);return e.useEffect(()=>{!1!==(null==t?void 0:t.autoFetch)&&r&&o()},[o,null==t?void 0:t.autoFetch,r]),e.useEffect(()=>{if((null==t?void 0:t.refetchInterval)&&t.refetchInterval>0&&r){const e=setInterval(()=>{o()},t.refetchInterval);return()=>clearInterval(e)}},[o,null==t?void 0:t.refetchInterval,r]),{...n,fetch:o,refetch:s,reset:c}};
|
|
@@ -34,13 +34,18 @@ interface PaymentResponse {
|
|
|
34
34
|
data?: PaymentResponseData;
|
|
35
35
|
metadata?: PaymentResponseMetadata;
|
|
36
36
|
}
|
|
37
|
+
interface PaymentCallbackPayload {
|
|
38
|
+
[key: string]: any;
|
|
39
|
+
}
|
|
37
40
|
interface UsePaymentOptions {
|
|
38
41
|
capabilityId?: string;
|
|
39
42
|
integrationKey?: string;
|
|
43
|
+
onSuccess?: (payload: PaymentCallbackPayload) => void;
|
|
44
|
+
onFailure?: (payload: PaymentCallbackPayload) => void;
|
|
40
45
|
}
|
|
41
46
|
/**
|
|
42
47
|
* React hook for handling Stripe checkout payments with loading, error states
|
|
43
|
-
* @param options - Configuration including capability ID
|
|
48
|
+
* @param options - Configuration including capability ID, integration key, and callbacks
|
|
44
49
|
* @returns Object with payment function and state management
|
|
45
50
|
*/
|
|
46
51
|
export declare function usePayment(options?: UsePaymentOptions): {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usePayment.d.ts","sourceRoot":"","sources":["../../src/hooks/usePayment.ts"],"names":[],"mappings":"AAIA,KAAK,WAAW,GAAG,SAAS,GAAG,cAAc,GAAG,OAAO,CAAC;AAExD,UAAU,aAAa;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,WAAW,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAChC;AAQD,UAAU,mBAAmB;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,EAAE,MAAM,CAAC;IACZ,aAAa,EAAE,GAAG,CAAC;CACpB;AAED,UAAU,uBAAuB;IAC/B,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,EAAE,MAAM,CAAC;IACvB,IAAI,EAAE,WAAW,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED,UAAU,eAAe;IACvB,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,mBAAmB,CAAC;IAC3B,QAAQ,CAAC,EAAE,uBAAuB,CAAC;CACpC;AAED,UAAU,iBAAiB;IACzB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"usePayment.d.ts","sourceRoot":"","sources":["../../src/hooks/usePayment.ts"],"names":[],"mappings":"AAIA,KAAK,WAAW,GAAG,SAAS,GAAG,cAAc,GAAG,OAAO,CAAC;AAExD,UAAU,aAAa;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,WAAW,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAChC;AAQD,UAAU,mBAAmB;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,EAAE,MAAM,CAAC;IACZ,aAAa,EAAE,GAAG,CAAC;CACpB;AAED,UAAU,uBAAuB;IAC/B,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,EAAE,MAAM,CAAC;IACvB,IAAI,EAAE,WAAW,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED,UAAU,eAAe;IACvB,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,mBAAmB,CAAC;IAC3B,QAAQ,CAAC,EAAE,uBAAuB,CAAC;CACpC;AAED,UAAU,sBAAsB;IAC9B,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED,UAAU,iBAAiB;IACzB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,sBAAsB,KAAK,IAAI,CAAC;IACtD,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,sBAAsB,KAAK,IAAI,CAAC;CACvD;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,OAAO,GAAE,iBAAsB;6BA4FvC,aAAa,KAAG,OAAO,CAAC,eAAe,CAAC;;aA1IhD,OAAO;WACT,MAAM,GAAG,IAAI;aACX,OAAO;EA4NjB"}
|
package/dist/hooks.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./EmbeddableProvider-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./EmbeddableProvider-CT_fGWcI.cjs");exports.useAI=e.useAI,exports.useDebounce=e.useDebounce,exports.useEmbeddableConfig=e.useEmbeddableConfig,exports.useEmbeddableData=e.useEmbeddableData,exports.useEventTracking=e.useEventTracking,exports.useFormSubmission=e.useFormSubmission,exports.useLocalStorage=e.useLocalStorage,exports.usePayment=e.usePayment,exports.usePublicSubmissions=e.usePublicSubmissions,exports.useVote=e.useVote,exports.useVoteAggregations=e.useVoteAggregations;
|
package/dist/hooks.js
CHANGED
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./EmbeddableProvider-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./EmbeddableProvider-CT_fGWcI.cjs"),s=require("./utils.cjs"),o=require("./storage-BtXo3gya.cjs");exports.EmbeddableProvider=e.EmbeddableProvider,exports.useAI=e.useAI,exports.useDebounce=e.useDebounce,exports.useEmbeddableConfig=e.useEmbeddableConfig,exports.useEmbeddableContext=e.useEmbeddableContext,exports.useEmbeddableData=e.useEmbeddableData,exports.useEventTracking=e.useEventTracking,exports.useFormSubmission=e.useFormSubmission,exports.useLocalStorage=e.useLocalStorage,exports.usePayment=e.usePayment,exports.usePublicSubmissions=e.usePublicSubmissions,exports.useVote=e.useVote,exports.useVoteAggregations=e.useVoteAggregations,exports.createApiClient=s.createApiClient,exports.debounce=s.debounce,exports.storage=o.storage;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { E, a, b, c, u, d, e, f, g, h, i, j, k } from "./EmbeddableProvider-
|
|
1
|
+
import { E, a, b, c, u, d, e, f, g, h, i, j, k } from "./EmbeddableProvider-BiwCAPla.js";
|
|
2
2
|
import { createApiClient, debounce } from "./utils.js";
|
|
3
3
|
import { s } from "./storage-B4eeCFyo.js";
|
|
4
4
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const t={get(t,e={}){try{const{prefix:r="",deserialize:o=JSON.parse}=e,a=r+t,l=localStorage.getItem(a);return null===l?null:o(l)}catch(r){return null}},set(t,e,r={}){try{const{prefix:o="",serialize:a=JSON.stringify}=r,l=o+t,c=a(e);localStorage.setItem(l,c)}catch(o){}},remove(t,e={}){try{const{prefix:r=""}=e,o=r+t;localStorage.removeItem(o)}catch(r){}},clear(t={}){try{const{prefix:e=""}=t;if(!e)return void localStorage.clear();const r=[];for(let t=0;t<localStorage.length;t++){const o=localStorage.key(t);o&&o.startsWith(e)&&r.push(o)}r.forEach(
|
|
1
|
+
"use strict";const t={get(t,e={}){try{const{prefix:r="",deserialize:o=JSON.parse}=e,a=r+t,l=localStorage.getItem(a);return null===l?null:o(l)}catch(r){return null}},set(t,e,r={}){try{const{prefix:o="",serialize:a=JSON.stringify}=r,l=o+t,c=a(e);localStorage.setItem(l,c)}catch(o){}},remove(t,e={}){try{const{prefix:r=""}=e,o=r+t;localStorage.removeItem(o)}catch(r){}},clear(t={}){try{const{prefix:e=""}=t;if(!e)return void localStorage.clear();const r=[];for(let t=0;t<localStorage.length;t++){const o=localStorage.key(t);o&&o.startsWith(e)&&r.push(o)}r.forEach(t=>localStorage.removeItem(t))}catch(e){}},isAvailable(){try{const t="__storage_test__";return localStorage.setItem(t,"test"),localStorage.removeItem(t),!0}catch{return!1}}};exports.storage=t;
|
package/dist/utils.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./storage-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./storage-BtXo3gya.cjs");exports.storage=e.storage,exports.createApiClient=function(e){const t=e.baseUrl||"https://api.embeddable.com",o={"Content-Type":"application/json"};e.apiKey&&(o.Authorization=`Bearer ${e.apiKey}`);const r=async(r,s={})=>{try{const e=`${t}${r}`,a=await fetch(e,{...s,headers:{...o,...s.headers}}),n=await a.json();return a.ok?{data:n,success:!0}:{data:null,success:!1,error:n.message||`HTTP ${a.status}`}}catch(a){return e.debug,{data:null,success:!1,error:a instanceof Error?a.message:"Unknown error"}}};return{get:e=>r(e,{method:"GET"}),post:(e,t)=>r(e,{method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t)=>r(e,{method:"PUT",body:t?JSON.stringify(t):void 0}),delete:e=>r(e,{method:"DELETE"})}},exports.debounce=function(e,t){let o;return function(...r){void 0!==o&&clearTimeout(o),o=setTimeout(()=>{o=void 0,e(...r)},t)}};
|
package/package.json
CHANGED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
"use strict";const e=require("react"),t=require("./storage-EjA7Lhbb.cjs");var r,n={exports:{}},a={};var o,s={};
|
|
2
|
-
/**
|
|
3
|
-
* @license React
|
|
4
|
-
* react-jsx-runtime.development.js
|
|
5
|
-
*
|
|
6
|
-
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
7
|
-
*
|
|
8
|
-
* This source code is licensed under the MIT license found in the
|
|
9
|
-
* LICENSE file in the root directory of this source tree.
|
|
10
|
-
*/"production"===process.env.NODE_ENV?n.exports=function(){if(r)return a;r=1;var t=e,n=Symbol.for("react.element"),o=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,c=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function l(e,t,r){var a,o={},l=null,u=null;for(a in void 0!==r&&(l=""+r),void 0!==t.key&&(l=""+t.key),void 0!==t.ref&&(u=t.ref),t)s.call(t,a)&&!i.hasOwnProperty(a)&&(o[a]=t[a]);if(e&&e.defaultProps)for(a in t=e.defaultProps)void 0===o[a]&&(o[a]=t[a]);return{$$typeof:n,type:e,key:l,ref:u,props:o,_owner:c.current}}return a.Fragment=o,a.jsx=l,a.jsxs=l,a}():n.exports=(o||(o=1,"production"!==process.env.NODE_ENV&&function(){var t,r=e,n=Symbol.for("react.element"),a=Symbol.for("react.portal"),o=Symbol.for("react.fragment"),c=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),u=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),p=Symbol.for("react.suspense_list"),m=Symbol.for("react.memo"),g=Symbol.for("react.lazy"),y=Symbol.for("react.offscreen"),v=Symbol.iterator,b=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function h(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];!function(e,t,r){var n=b.ReactDebugCurrentFrame.getStackAddendum();""!==n&&(t+="%s",r=r.concat([n]));var a=r.map((function(e){return String(e)}));a.unshift("Warning: "+t),Function.prototype.apply.call(console[e],console,a)}("error",e,r)}function k(e){return e.displayName||"Context"}function w(e){if(null==e)return null;if("number"==typeof e.tag&&h("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),"function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case o:return"Fragment";case a:return"Portal";case i:return"Profiler";case c:return"StrictMode";case f:return"Suspense";case p:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case u:return k(e)+".Consumer";case l:return k(e._context)+".Provider";case d:return function(e,t,r){var n=e.displayName;if(n)return n;var a=t.displayName||t.name||"";return""!==a?r+"("+a+")":r}(e,e.render,"ForwardRef");case m:var t=e.displayName||null;return null!==t?t:w(e.type)||"Memo";case g:var r=e,n=r._payload,s=r._init;try{return w(s(n))}catch(y){return null}}return null}t=Symbol.for("react.module.reference");var _,S,E,C,O,j,T,P=Object.assign,x=0;function I(){}I.__reactDisabledLog=!0;var R,$=b.ReactCurrentDispatcher;function N(e,t,r){if(void 0===R)try{throw Error()}catch(a){var n=a.stack.trim().match(/\n( *(at )?)/);R=n&&n[1]||""}return"\n"+R+e}var D,F=!1,L="function"==typeof WeakMap?WeakMap:Map;function U(e,t){if(!e||F)return"";var r,n=D.get(e);if(void 0!==n)return n;F=!0;var a,o=Error.prepareStackTrace;Error.prepareStackTrace=void 0,a=$.current,$.current=null,function(){if(0===x){_=console.log,S=console.info,E=console.warn,C=console.error,O=console.group,j=console.groupCollapsed,T=console.groupEnd;var e={configurable:!0,enumerable:!0,value:I,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}x++}();try{if(t){var s=function(){throw Error()};if(Object.defineProperty(s.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(s,[])}catch(m){r=m}Reflect.construct(e,[],s)}else{try{s.call()}catch(m){r=m}e.call(s.prototype)}}else{try{throw Error()}catch(m){r=m}e()}}catch(g){if(g&&r&&"string"==typeof g.stack){for(var c=g.stack.split("\n"),i=r.stack.split("\n"),l=c.length-1,u=i.length-1;l>=1&&u>=0&&c[l]!==i[u];)u--;for(;l>=1&&u>=0;l--,u--)if(c[l]!==i[u]){if(1!==l||1!==u)do{if(l--,--u<0||c[l]!==i[u]){var d="\n"+c[l].replace(" at new "," at ");return e.displayName&&d.includes("<anonymous>")&&(d=d.replace("<anonymous>",e.displayName)),"function"==typeof e&&D.set(e,d),d}}while(l>=1&&u>=0);break}}}finally{F=!1,$.current=a,function(){if(0===--x){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:P({},e,{value:_}),info:P({},e,{value:S}),warn:P({},e,{value:E}),error:P({},e,{value:C}),group:P({},e,{value:O}),groupCollapsed:P({},e,{value:j}),groupEnd:P({},e,{value:T})})}x<0&&h("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}(),Error.prepareStackTrace=o}var f=e?e.displayName||e.name:"",p=f?N(f):"";return"function"==typeof e&&D.set(e,p),p}function A(e,t,r){if(null==e)return"";if("function"==typeof e)return U(e,!(!(n=e.prototype)||!n.isReactComponent));var n;if("string"==typeof e)return N(e);switch(e){case f:return N("Suspense");case p:return N("SuspenseList")}if("object"==typeof e)switch(e.$$typeof){case d:return U(e.render,!1);case m:return A(e.type,t,r);case g:var a=e,o=a._payload,s=a._init;try{return A(s(o),t,r)}catch(c){}}return""}D=new L;var V=Object.prototype.hasOwnProperty,W={},z=b.ReactDebugCurrentFrame;function B(e){if(e){var t=e._owner,r=A(e.type,e._source,t?t.type:null);z.setExtraStackFrame(r)}else z.setExtraStackFrame(null)}var J=Array.isArray;function K(e){return J(e)}function M(e){return""+e}function H(e){if(function(e){try{return M(e),!1}catch(t){return!0}}(e))return h("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",function(e){return"function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object"}(e)),M(e)}var Y,q,X=b.ReactCurrentOwner,G={key:!0,ref:!0,__self:!0,__source:!0};function Q(e,t,r,a,o){var s,c={},i=null,l=null;for(s in void 0!==r&&(H(r),i=""+r),function(e){if(V.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(t)&&(H(t.key),i=""+t.key),function(e){if(V.call(e,"ref")){var t=Object.getOwnPropertyDescriptor(e,"ref").get;if(t&&t.isReactWarning)return!1}return void 0!==e.ref}(t)&&(l=t.ref,function(e){"string"==typeof e.ref&&X.current}(t)),t)V.call(t,s)&&!G.hasOwnProperty(s)&&(c[s]=t[s]);if(e&&e.defaultProps){var u=e.defaultProps;for(s in u)void 0===c[s]&&(c[s]=u[s])}if(i||l){var d="function"==typeof e?e.displayName||e.name||"Unknown":e;i&&function(e,t){var r=function(){Y||(Y=!0,h("%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))};r.isReactWarning=!0,Object.defineProperty(e,"key",{get:r,configurable:!0})}(c,d),l&&function(e,t){var r=function(){q||(q=!0,h("%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))};r.isReactWarning=!0,Object.defineProperty(e,"ref",{get:r,configurable:!0})}(c,d)}return function(e,t,r,a,o,s,c){var i={$$typeof:n,type:e,key:t,ref:r,props:c,_owner:s,_store:{}};return Object.defineProperty(i._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(i,"_self",{configurable:!1,enumerable:!1,writable:!1,value:a}),Object.defineProperty(i,"_source",{configurable:!1,enumerable:!1,writable:!1,value:o}),Object.freeze&&(Object.freeze(i.props),Object.freeze(i)),i}(e,i,l,o,a,X.current,c)}var Z,ee=b.ReactCurrentOwner,te=b.ReactDebugCurrentFrame;function re(e){if(e){var t=e._owner,r=A(e.type,e._source,t?t.type:null);te.setExtraStackFrame(r)}else te.setExtraStackFrame(null)}function ne(e){return"object"==typeof e&&null!==e&&e.$$typeof===n}function ae(){if(ee.current){var e=w(ee.current.type);if(e)return"\n\nCheck the render method of `"+e+"`."}return""}Z=!1;var oe={};function se(e,t){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;var r=function(e){var t=ae();if(!t){var r="string"==typeof e?e:e.displayName||e.name;r&&(t="\n\nCheck the top-level render call using <"+r+">.")}return t}(t);if(!oe[r]){oe[r]=!0;var n="";e&&e._owner&&e._owner!==ee.current&&(n=" It was passed a child from "+w(e._owner.type)+"."),re(e),h('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',r,n),re(null)}}}function ce(e,t){if("object"==typeof e)if(K(e))for(var r=0;r<e.length;r++){var n=e[r];ne(n)&&se(n,t)}else if(ne(e))e._store&&(e._store.validated=!0);else if(e){var a=function(e){if(null===e||"object"!=typeof e)return null;var t=v&&e[v]||e["@@iterator"];return"function"==typeof t?t:null}(e);if("function"==typeof a&&a!==e.entries)for(var o,s=a.call(e);!(o=s.next()).done;)ne(o.value)&&se(o.value,t)}}function ie(e){var t,r=e.type;if(null!=r&&"string"!=typeof r){if("function"==typeof r)t=r.propTypes;else{if("object"!=typeof r||r.$$typeof!==d&&r.$$typeof!==m)return;t=r.propTypes}if(t){var n=w(r);!function(e,t,r,n,a){var o=Function.call.bind(V);for(var s in e)if(o(e,s)){var c=void 0;try{if("function"!=typeof e[s]){var i=Error((n||"React class")+": "+r+" type `"+s+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[s]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw i.name="Invariant Violation",i}c=e[s](t,s,n,r,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(l){c=l}!c||c instanceof Error||(B(a),h("%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).",n||"React class",r,s,typeof c),B(null)),c instanceof Error&&!(c.message in W)&&(W[c.message]=!0,B(a),h("Failed %s type: %s",r,c.message),B(null))}}(t,e.props,"prop",n,e)}else void 0===r.PropTypes||Z||(Z=!0,h("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",w(r)||"Unknown"));"function"!=typeof r.getDefaultProps||r.getDefaultProps.isReactClassApproved||h("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}var le={};function ue(e,r,a,s,v,b){var k=function(e){return"string"==typeof e||"function"==typeof e||e===o||e===i||e===c||e===f||e===p||e===y||"object"==typeof e&&null!==e&&(e.$$typeof===g||e.$$typeof===m||e.$$typeof===l||e.$$typeof===u||e.$$typeof===d||e.$$typeof===t||void 0!==e.getModuleId)}(e);if(!k){var _,S="";(void 0===e||"object"==typeof e&&null!==e&&0===Object.keys(e).length)&&(S+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."),S+=ae(),null===e?_="null":K(e)?_="array":void 0!==e&&e.$$typeof===n?(_="<"+(w(e.type)||"Unknown")+" />",S=" Did you accidentally export a JSX literal instead of a component?"):_=typeof e,h("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",_,S)}var E=Q(e,r,a,v,b);if(null==E)return E;if(k){var C=r.children;if(void 0!==C)if(s)if(K(C)){for(var O=0;O<C.length;O++)ce(C[O],e);Object.freeze&&Object.freeze(C)}else h("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 ce(C,e)}if(V.call(r,"key")){var j=w(e),T=Object.keys(r).filter((function(e){return"key"!==e})),P=T.length>0?"{key: someKey, "+T.join(": ..., ")+": ...}":"{key: someKey}";le[j+P]||(h('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',P,j,T.length>0?"{"+T.join(": ..., ")+": ...}":"{}",j),le[j+P]=!0)}return e===o?function(e){for(var t=Object.keys(e.props),r=0;r<t.length;r++){var n=t[r];if("children"!==n&&"key"!==n){re(e),h("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",n),re(null);break}}null!==e.ref&&(re(e),h("Invalid attribute `ref` supplied to `React.Fragment`."),re(null))}(E):ie(E),E}var de=function(e,t,r){return ue(e,t,r,!1)},fe=function(e,t,r){return ue(e,t,r,!0)};s.Fragment=o,s.jsx=de,s.jsxs=fe}()),s);var c=n.exports;const i="https://events.embeddable.co";function l(){const{config:e}=m();if(!e)throw new Error("No Embeddable configuration found. Make sure to wrap your app with EmbeddableProvider and provide a valid config.");return e}const u=()=>{const{widgetId:t}=l(),r=`${i}/api`,[n,a]=e.useState(!1),o=e.useCallback((async e=>{if(!t)return[];const n=[];try{a(!0);const o=await fetch(`${r}/marketing/track`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify({widgetId:t,capabilityId:"trackEvent",inputs:e})}),s=await o.json();s.success?s.results?s.results.forEach((e=>{n.push({success:e.success,integrationKey:e.integrationKey,data:e.data,error:e.error})})):n.push({success:!0,data:s.data}):n.push({success:!1,error:s.error||"Unknown error"})}catch(o){n.push({success:!1,error:o instanceof Error?o.message:"Network error"})}finally{a(!1)}return n}),[t,r]),s=e.useCallback((async(e={})=>o({event_name:"page_view",event_category:"engagement",custom_parameters:{page_url:window.location.href,page_title:document.title,referrer:document.referrer,...e}})),[o]),c=e.useCallback((async(e,t={})=>o({event_name:"form_submit",event_category:"conversion",custom_parameters:{form_data:e,...t}})),[o]),u=e.useCallback((async(e,t={})=>{let r={};return r="string"==typeof e?{element_selector:e}:{element_id:e.id,element_class:e.className,element_text:e.textContent||e.innerText,element_tag:e.tagName.toLowerCase()},o({event_name:"button_click",event_category:"interaction",custom_parameters:{...r,...t}})}),[o]),d=e.useCallback((async(e,t,r={})=>o({event_name:"conversion",event_category:"conversion",value:t,custom_parameters:{conversion_type:e,currency:r.currency||"USD",...r}})),[o]),f=e.useCallback((async(e,t={})=>o({event_name:"signup",event_category:"conversion",user_data:e,custom_parameters:t})),[o]),p=e.useCallback((async(e,t={})=>o({event_name:"purchase",event_category:"ecommerce",value:e.amount,custom_parameters:{transaction_id:e.id,currency:e.currency||"USD",items:e.items||[],...t}})),[o]),m=e.useCallback((()=>{s()}),[s]),g=e.useCallback((()=>{const e=async e=>{try{const t=e.target,r=new FormData(t),n=Object.fromEntries(r.entries());await c(n,{form_id:t.id,form_class:t.className,form_action:t.action,form_method:t.method})}catch(t){}};return document.addEventListener("submit",e),()=>{document.removeEventListener("submit",e)}}),[c]),y=e.useCallback(((e='button, .btn, [role="button"], a, input[type="submit"]')=>{const t=async t=>{const r=t.target.closest(e);if(r)try{await u(r)}catch(n){}};return document.addEventListener("click",t),()=>{document.removeEventListener("click",t)}}),[u]);return{isLoading:n,track:o,trackPageView:s,trackFormSubmit:c,trackClick:u,trackConversion:d,trackSignup:f,trackPurchase:p,enableAutoPageView:m,enableAutoFormTracking:g,enableAutoClickTracking:y}};const d={version:"latest",mode:"embeddable",ignoreCache:!1,lazyLoad:!1,loader:!0,widgetId:"",_containerId:"",_shadowRoot:void 0},f=e.createContext({config:{...d},setConfig:()=>{},data:{},setData:()=>{}});function p(){const{trackPageView:t}=u(),{config:r}=m();return e.useEffect((()=>{(null==r?void 0:r.widgetId)&&"preview"!==(null==r?void 0:r.mode)&&t()}),[null==r?void 0:r.widgetId,null==r?void 0:r.mode,t]),null}function m(){const t=e.useContext(f);if(!t)throw new Error("useEmbeddableContext must be used within an EmbeddableProvider");return t}exports.EmbeddableProvider=function({config:t,data:r,children:n}){const[a,o]=e.useState(d),[s,i]=e.useState(r||{});return e.useEffect((()=>{const e={...d,...t};o(e)}),[t]),e.useEffect((()=>{const e=e=>{("https://embeddable.co"===e.origin||e.origin.includes("localhost"))&&e.data&&"object"==typeof e.data&&"embeddable-update-data"===e.data.type&&i(e.data.data||{})};return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}}),[]),c.jsxs(f.Provider,{value:{config:a,setConfig:o,data:s,setData:i},children:[c.jsx(p,{}),n]})},exports.useAI=function(t){const{widgetId:r}=l(),[n,a]=e.useState({loading:!1,error:null,success:!1});return{...n,callAI:e.useCallback((async(e,n)=>{var o;a({loading:!0,error:null,success:!1});try{const s={widgetId:r,capabilityId:"ai_call",integrationKey:t.platform,prompt:e,history:n||[]},c=await fetch(`${i}/api/execute/ai`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify(s)}),l=await c.json();if(!c.ok){const e=l.message||l.error||`HTTP ${c.status}`;return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}if(l.success)return a({loading:!1,error:null,success:!0}),{success:!0,message:(null==(o=l.data)?void 0:o.response)||"AI call completed successfully",data:l.data,metadata:l.metadata};{const e=l.message||l.error||"AI call failed";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}}catch(s){const e=s instanceof Error?s.message:"Unknown error occurred";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}}),[t.platform,r]),reset:e.useCallback((()=>{a({loading:!1,error:null,success:!1})}),[])}},exports.useDebounce=function(t,r){const[n,a]=e.useState(t);return e.useEffect((()=>{const e=setTimeout((()=>{a(t)}),r);return()=>{clearTimeout(e)}}),[t,r]),n},exports.useEmbeddableConfig=l,exports.useEmbeddableContext=m,exports.useEmbeddableData=function(){const{data:e}=m();return{data:e}},exports.useEventTracking=u,exports.useFormSubmission=function(t){const{widgetId:r}=l(),[n,a]=e.useState({loading:!1,error:null,success:!1});return{...n,submit:e.useCallback((async e=>{var n,o,s;a({loading:!0,error:null,success:!1});try{if(null==t?void 0:t.validatePayload){const r=t.validatePayload(e);if(r)return a({loading:!1,error:r,success:!1}),{success:!1,message:r}}const c={payload:e,widgetId:r,collectionName:(null==t?void 0:t.collectionName)||"submissions"},l=await fetch(`${i}/api/submissions`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify(c)}),u=await l.json();if(!l.ok){const e=u.message||u.error||`HTTP ${l.status}`;return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}if(u.success)return a({loading:!1,error:null,success:!0}),{id:(null==(n=u.data)?void 0:n.id)||(null==(o=u.data)?void 0:o._id),success:!0,message:(null==(s=u.data)?void 0:s.message)||"Submission successful"};{const e=u.message||u.error||"Submission failed";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}}catch(c){const e=c instanceof Error?c.message:"Unknown error occurred";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}}),[t,r]),reset:e.useCallback((()=>{a({loading:!1,error:null,success:!1})}),[])}},exports.useLocalStorage=function(r,n,a={}){const{widgetId:o}=l(),s=e.useMemo((()=>({...a,prefix:`embd-${o}-${a.prefix||""}`})),[o,a]),[c,i]=e.useState((()=>{const e=t.storage.get(r,s);return null!==e?e:n})),u=e.useCallback((e=>{try{const n=e instanceof Function?e(c):e;i(n),t.storage.set(r,n,s)}catch(n){}}),[r,c,s]),d=e.useCallback((()=>{try{i(n),t.storage.remove(r,s)}catch(e){}}),[r,n,s]);return e.useEffect((()=>{const e=e=>{const t=s.prefix+r;if(e.key===t&&null!==e.newValue)try{const{deserialize:t=JSON.parse}=s,r=t(e.newValue);i(r)}catch(n){}};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)}),[r,s]),[c,u,d]},exports.usePayment=function(t={}){const{widgetId:r}=l(),[n,a]=e.useState({loading:!1,error:null,success:!1});return{...n,createCheckout:e.useCallback((async e=>{a({loading:!0,error:null,success:!1});try{const n={widgetId:r,capabilityId:t.capabilityId||"getCheckout",integrationKey:t.integrationKey||"stripe",inputs:e},o=await fetch(`${i}/api/execute/payments`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify(n)}),s=await o.json();if(!o.ok){const e=s.message||s.error||`HTTP ${o.status}`;return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}if(s.success)return a({loading:!1,error:null,success:!0}),{success:!0,message:"Checkout session created successfully",data:s.data,metadata:s.metadata};{const e=s.message||s.error||"Payment checkout failed";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}}catch(n){const e=n instanceof Error?n.message:"Unknown error occurred";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}}),[t.capabilityId,t.integrationKey,r]),reset:e.useCallback((()=>{a({loading:!1,error:null,success:!1})}),[])}},exports.usePublicSubmissions=function(t){const{widgetId:r}=l(),[n,a]=e.useState({loading:!1,error:null,data:null,pagination:null}),o=e.useCallback((async e=>{a((e=>({...e,loading:!0,error:null})));try{const n={...t,...e},o=new URLSearchParams;o.append("widgetId",r),(null==n?void 0:n.collectionName)&&o.append("collectionName",n.collectionName),o.append("page",String((null==n?void 0:n.page)||1)),o.append("limit",String((null==n?void 0:n.limit)||10)),o.append("sortBy",(null==n?void 0:n.sortBy)||"createdAt"),o.append("sortOrder",(null==n?void 0:n.sortOrder)||"desc"),(null==n?void 0:n.fromDate)&&o.append("fromDate",n.fromDate),(null==n?void 0:n.toDate)&&o.append("toDate",n.toDate);const s=await fetch(`${i}/api/submissions/public?${o.toString()}`,{method:"GET",headers:{"Content-Type":"application/json"},credentials:"omit"}),c=await s.json();if(!s.ok){const e=c.message||c.error||`HTTP ${s.status}`;return a((t=>({...t,loading:!1,error:e}))),{success:!1,data:[],pagination:{page:1,limit:10,total:0,pages:0},message:e}}if(c.success)return a((e=>({...e,loading:!1,error:null,data:c.data||[],pagination:c.pagination||{page:1,limit:10,total:0,pages:0}}))),{success:!0,data:c.data||[],pagination:c.pagination||{page:1,limit:10,total:0,pages:0}};{const e=c.message||c.error||"Failed to fetch submissions";return a((t=>({...t,loading:!1,error:e}))),{success:!1,data:[],pagination:{page:1,limit:10,total:0,pages:0},message:e}}}catch(n){const e=n instanceof Error?n.message:"Unknown error occurred";return a((t=>({...t,loading:!1,error:e}))),{success:!1,data:[],pagination:{page:1,limit:10,total:0,pages:0},message:e}}}),[t,r]),s=e.useCallback((()=>{a({loading:!1,error:null,data:null,pagination:null})}),[]);return e.useEffect((()=>{t&&void 0===t.page&&void 0===t.limit||o()}),[o,t]),{...n,fetchSubmissions:o,reset:s}},exports.useVote=function(t){const{widgetId:r}=l(),[n,a]=e.useState({loading:!1,error:null,success:!1});return{...n,vote:e.useCallback((async e=>{var n,o,s;a({loading:!0,error:null,success:!1});try{const c={voteFor:e,widgetId:r,collectionName:(null==t?void 0:t.collectionName)||"votes"},l=await fetch(`${i}/api/votes`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify(c)}),u=await l.json();if(!l.ok){const e=u.message||u.error||`HTTP ${l.status}`;return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}if(u.success)return a({loading:!1,error:null,success:!0}),{id:(null==(n=u.data)?void 0:n.id)||(null==(o=u.data)?void 0:o._id),success:!0,message:(null==(s=u.data)?void 0:s.message)||"Vote submitted successfully"};{const e=u.message||u.error||"Vote submission failed";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}}catch(c){const e=c instanceof Error?c.message:"Unknown error occurred";return a({loading:!1,error:e,success:!1}),{success:!1,message:e}}}),[t,r]),reset:e.useCallback((()=>{a({loading:!1,error:null,success:!1})}),[])}},exports.useVoteAggregations=function(t){const{widgetId:r}=l(),[n,a]=e.useState({data:null,loading:!1,error:null}),o=e.useCallback((async()=>{if(!r)return a({data:null,loading:!1,error:"Widget ID is required"}),{success:!1,data:{results:[],summary:{totalVotes:0,totalOptions:0,groupBy:""}}};a((e=>({...e,loading:!0,error:null})));try{const e=(null==t?void 0:t.collectionName)||"votes",n=new URL(`${i}/api/votes/aggregations`);n.searchParams.append("widgetId",r),n.searchParams.append("collectionName",e);const o=await fetch(n.toString(),{method:"GET",headers:{"Content-Type":"application/json"},credentials:"omit"}),s=await o.json();if(!o.ok){const e=s.message||s.error||`HTTP ${o.status}`;return a({data:null,loading:!1,error:e}),{success:!1,data:{results:[],summary:{totalVotes:0,totalOptions:0,groupBy:""}}}}return a({data:s.data,loading:!1,error:null}),s}catch(e){const t=e instanceof Error?e.message:"Unknown error occurred";return a({data:null,loading:!1,error:t}),{success:!1,data:{results:[],summary:{totalVotes:0,totalOptions:0,groupBy:""}}}}}),[r,null==t?void 0:t.collectionName]),s=e.useCallback((()=>o()),[o]),c=e.useCallback((()=>{a({data:null,loading:!1,error:null})}),[]);return e.useEffect((()=>{!1!==(null==t?void 0:t.autoFetch)&&r&&o()}),[o,null==t?void 0:t.autoFetch,r]),e.useEffect((()=>{if((null==t?void 0:t.refetchInterval)&&t.refetchInterval>0&&r){const e=setInterval((()=>{o()}),t.refetchInterval);return()=>clearInterval(e)}}),[o,null==t?void 0:t.refetchInterval,r]),{...n,fetch:o,refetch:s,reset:c}};
|