@formspree/react
Advanced tools
Comparing version 2.4.1 to 2.4.2
@@ -7,6 +7,6 @@ import React from 'react'; | ||
declare type FromspreeContextType = { | ||
type FromspreeContextType = { | ||
client: Client; | ||
}; | ||
declare type FormspreeProviderProps = { | ||
type FormspreeProviderProps = { | ||
project?: string; | ||
@@ -16,7 +16,7 @@ children: React.ReactNode; | ||
}; | ||
declare const FormspreeProvider: (props: FormspreeProviderProps) => JSX.Element; | ||
declare const FormspreeProvider: (props: FormspreeProviderProps) => React.JSX.Element; | ||
declare function useFormspree(): FromspreeContextType; | ||
declare type FormError = Forms.FormError; | ||
declare type FieldError = Forms.FieldError; | ||
type FormError = Forms.FormError; | ||
type FieldError = Forms.FieldError; | ||
/** | ||
@@ -27,12 +27,12 @@ * ExtraData values can be strings or functions that return a string, or a | ||
*/ | ||
declare type ExtraDataValue = undefined | string | (() => string) | (() => Promise<string>) | (() => undefined) | (() => Promise<undefined>); | ||
declare type ExtraData = { | ||
type ExtraDataValue = undefined | string | (() => string) | (() => Promise<string>) | (() => undefined) | (() => Promise<undefined>); | ||
type ExtraData = { | ||
[key: string]: ExtraDataValue; | ||
}; | ||
declare type ErrorPayload = Forms.FormError; | ||
type ErrorPayload = Forms.FormError; | ||
declare type FormEvent = React.FormEvent<HTMLFormElement>; | ||
declare type SubmitHandler = (submissionData: FormEvent | SubmissionData) => Promise<SubmissionResponse>; | ||
declare type ResetFunction = () => void; | ||
declare type TUseForm = [ | ||
type FormEvent = React.FormEvent<HTMLFormElement>; | ||
type SubmitHandler = (submissionData: FormEvent | SubmissionData) => Promise<SubmissionResponse>; | ||
type ResetFunction = () => void; | ||
type TUseForm = [ | ||
{ | ||
@@ -54,3 +54,3 @@ result: SubmissionResponse | null; | ||
declare type ValidationErrorProps = { | ||
type ValidationErrorProps = { | ||
prefix?: string; | ||
@@ -57,0 +57,0 @@ field?: string; |
@@ -1,1 +0,678 @@ | ||
var X=Object.create;var P=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty;var se=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ne=(e,t)=>{for(var r in t)P(e,r,{get:t[r],enumerable:!0})},O=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of te(t))!oe.call(e,o)&&o!==r&&P(e,o,{get:()=>t[o],enumerable:!(s=ee(t,o))||s.enumerable});return e};var b=(e,t,r)=>(r=e!=null?X(re(e)):{},O(t||!e||!e.__esModule?P(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>O(P({},"__esModule",{value:!0}),e);var T=se((Ae,K)=>{"use strict";var j=Object.defineProperty,ae=Object.getOwnPropertyDescriptor,de=Object.getOwnPropertyNames,pe=Object.prototype.hasOwnProperty,me=(e,t)=>{for(var r in t)j(e,r,{get:t[r],enumerable:!0})},le=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of de(t))!pe.call(e,o)&&o!==r&&j(e,o,{get:()=>t[o],enumerable:!(s=ae(t,o))||s.enumerable});return e},ce=e=>le(j({},"__esModule",{value:!0}),e),U={};me(U,{Client:()=>Y,createClient:()=>k,getDefaultClient:()=>we,isFieldError:()=>Ee});K.exports=ce(U);var h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",ue=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;function fe(e){e=String(e);for(var t,r,s,o,i="",l=0,c=e.length%3;l<e.length;){if((r=e.charCodeAt(l++))>255||(s=e.charCodeAt(l++))>255||(o=e.charCodeAt(l++))>255)throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");t=r<<16|s<<8|o,i+=h.charAt(t>>18&63)+h.charAt(t>>12&63)+h.charAt(t>>6&63)+h.charAt(t&63)}return c?i.slice(0,c-3)+"===".substring(c):i}function ye(e){if(e=String(e).replace(/[\t\n\f\r ]+/g,""),!ue.test(e))throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");e+="==".slice(2-(e.length&3));for(var t,r="",s,o,i=0;i<e.length;)t=h.indexOf(e.charAt(i++))<<18|h.indexOf(e.charAt(i++))<<12|(s=h.indexOf(e.charAt(i++)))<<6|(o=h.indexOf(e.charAt(i++))),r+=s===64?String.fromCharCode(t>>16&255):o===64?String.fromCharCode(t>>16&255,t>>8&255):String.fromCharCode(t>>16&255,t>>8&255,t&255);return r}var he="2.8.1",L=(e=>(e.REQUIRED_FIELD_MISSING="REQUIRED_FIELD_MISSING",e.REQUIRED_FIELD_EMPTY="REQUIRED_FIELD_EMPTY",e.TYPE_EMAIL="TYPE_EMAIL",e.TYPE_NUMERIC="TYPE_NUMERIC",e.TYPE_TEXT="TYPE_TEXT",e))(L||{});function Ee(e){return e.code in L&&e.field!==void 0}function ge(e){return e.errors!==void 0}var be=e=>fe(JSON.stringify(e)),Fe=e=>{let t=`@formspree/core@${he}`;return e?`${e} ${t}`:t},xe=()=>1*new Date,S=(e,t,r)=>{e instanceof FormData?e.append(t,r):e=Object.assign(e,{[t]:r})},Pe=async({stripePromise:e,response:t,responseData:r,payload:s,data:o,fetchImpl:i,request:l,url:c})=>{let f=await e.handleCardAction(r.stripe.paymentIntentClientSecret);if(f.error)return{response:t,body:{errors:[{code:"STRIPE_CLIENT_ERROR",message:"Stripe SCA error",field:"paymentMethod"}]}};{s.paymentMethod.id||S(o,"paymentMethod",s.paymentMethod.id),S(o,"paymentIntent",f.paymentIntent.id),S(o,"resubmitKey",r.resubmitKey);let m=await i(c,{...l,body:JSON.stringify({paymentIntent:f.paymentIntent.id,resubmitKey:r.resubmitKey})}),u=await m.json();return{response:m,body:u}}};function N({body:e,response:t}){return!ge(e)&&(e==null?void 0:e.error)&&(e={errors:[{message:e.error}]}),{body:e,response:t}}var Se=()=>navigator.webdriver||!!document.documentElement.getAttribute(ye("d2ViZHJpdmVy"))||!!window.callPhantom||!!window._phantom,ve=class{constructor(){this.loadedAt=xe(),this.webdriver=Se()}teardown(){}data(){return{loadedAt:this.loadedAt,webdriver:this.webdriver}}},Y=class{constructor(e={}){this.project=e.project,this.stripePromise=e.stripePromise,typeof window<"u"&&this.startBrowserSession()}startBrowserSession(){this.session||(this.session=new ve)}teardown(){this.session&&this.session.teardown()}async submitForm(e,t,r={}){let s=r.endpoint||"https://formspree.io",o=r.fetchImpl||fetch,i=this.project?`${s}/p/${this.project}/f/${e}`:`${s}/f/${e}`,l=m=>m instanceof FormData?m:JSON.stringify(m),c={Accept:"application/json","Formspree-Client":Fe(r.clientName)};this.session&&(c["Formspree-Session-Data"]=be(this.session.data())),t instanceof FormData||(c["Content-Type"]="application/json");let f={method:"POST",mode:"cors",body:l(t),headers:c};if(this.stripePromise&&r.createPaymentMethod){let m=await r.createPaymentMethod();if(m.error)return{response:null,body:{errors:[{code:"STRIPE_CLIENT_ERROR",message:"Error creating payment method",field:"paymentMethod"}]}};S(t,"paymentMethod",m.paymentMethod.id);let u=await o(i,{...f,body:t}),y=await u.json();return y&&y.stripe&&y.stripe.requiresAction&&y.resubmitKey?await Pe({stripePromise:this.stripePromise,responseData:y,response:u,payload:m,data:t,fetchImpl:o,request:f,url:i}):N({response:u,body:y})}else return o(i,f).then(m=>m.json().then(u=>N({body:u,response:m}))).catch()}},k=e=>new Y(e),we=()=>(_||(_=k()),_),_});var Te={};ne(Te,{CardElement:()=>E.CardElement,FormspreeProvider:()=>z,ValidationError:()=>Q,isFieldError:()=>Z.isFieldError,useForm:()=>H,useFormspree:()=>w});module.exports=ie(Te);var n=b(require("react")),v=b(T()),$=require("@stripe/stripe-js/pure.js"),Ce=(0,n.lazy)(()=>import("@stripe/react-stripe-js").then(e=>({default:e.Elements}))),R=n.default.createContext({client:void 0});R.displayName="Formspree";var I,De=e=>(I||(I=(0,$.loadStripe)(e)),I),V=(e,t)=>{let r={};return e&&(r.stripePromise=e),t&&(r.project=t),(0,v.createClient)(r)},z=e=>{let[t,r]=(0,n.useState)(void 0),[s,o]=(0,n.useState)(V(t,e.project));return(0,n.useEffect)(()=>(s.startBrowserSession(),()=>{s.teardown()}),[]),(0,n.useEffect)(()=>{let i=async()=>{let l=await De(e.stripePK);r(l)};e.stripePK&&i()},[e.stripePK]),(0,n.useEffect)(()=>{t&&o(V(t,e.project))},[t]),n.default.createElement(R.Provider,{value:{client:s}},e.stripePK?n.default.createElement(n.default.Fragment,null,t&&n.default.createElement(n.Suspense,{fallback:n.default.createElement("p",null,"....")},n.default.createElement(Ce,{stripe:t},n.default.createElement(n.default.Fragment,null,e.children)))):n.default.createElement(n.default.Fragment,null,e.children))};function w(){let e=(0,n.useContext)(R);return e.client?e:{client:(0,v.getDefaultClient)()}}var F=require("react"),E=require("@stripe/react-stripe-js");var B="2.4.1";var je=e=>e.preventDefault!==void 0,H=(e,t={})=>{let[r,s]=(0,F.useState)(null),[o,i]=(0,F.useState)(!1),[l,c]=(0,F.useState)(!1),[f,m]=(0,F.useState)([]),u=w(),y=t.client||u,M,A;if(!y)throw new Error("You must provide a Formspree client");if(!e)throw new Error('You must provide a form key or hashid (e.g. useForm("myForm") or useForm("123xyz")');u.client&&u.client.stripePromise&&(M=(0,E.useStripe)(),A=(0,E.useElements)());let x=!!t.debug,g=t.data;return[{result:r,submitting:o,succeeded:l,errors:f},async C=>{let q=async a=>{a.preventDefault();let p=a.target;if(p.tagName!="FORM")throw new Error("submit was triggered for a non-form element");return new FormData(p)},d=je(C)?await q(C):C,G=(a,p)=>{d instanceof FormData?d.append(a,p):d=Object.assign(d,{[a]:p})};if(typeof g=="object")for(let a in g){let p;typeof g[a]=="function"?(p=g[a].call(null),typeof(p==null?void 0:p.then)=="function"&&(p=await p)):p=g[a],p!==void 0&&G(a,p)}let W=async()=>{let a={...d.address_line1&&{line1:d.address_line1},...d.address_line2&&{line2:d.address_line2},...d.address_city&&{city:d.address_city},...d.address_country&&{country:d.address_country},...d.address_state&&{state:d.address_state},...d.address_postal_code&&{postal_code:d.address_postal_code}};return await M.createPaymentMethod({type:"card",card:A.getElement(E.CardElement),billing_details:{...d.name&&{name:d.name},...d.email&&{email:d.email},...d.phone&&{phone:d.phone},...a&&{address:a}}})};return i(!0),u.client.submitForm(e,d,{endpoint:t.endpoint,clientName:`@formspree/react@${B}`,createPaymentMethod:u.client&&u.client.stripePromise?W:void 0}).then(a=>{let p=a.response.status,D;return p===200?(x&&console.log("Form submitted",a),c(!0),s(a),m([])):p>=400&&(D=a.body,D.errors?(m(D.errors),x&&console.log("Error",a)):(m([{message:"Unexpected error"}]),x&&console.log("Unexpected error",a)),c(!1)),a}).catch(a=>{throw x&&console.log("Unexpected error",a),c(!1),a}).finally(()=>{i(!1)})},()=>{i(!1),c(!1),m([])}]};var J=b(require("react")),Q=e=>{let{prefix:t,field:r,errors:s,...o}=e,i=(s||[]).find(l=>l.field===r);return i?J.default.createElement("div",{...o},t," ",i.message):null};var Z=b(T());0&&(module.exports={CardElement,FormspreeProvider,ValidationError,isFieldError,useForm,useFormspree}); | ||
function _array_like_to_array(arr, len) { | ||
if (len == null || len > arr.length) len = arr.length; | ||
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i]; | ||
return arr2; | ||
} | ||
function _array_with_holes(arr) { | ||
if (Array.isArray(arr)) return arr; | ||
} | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { | ||
try { | ||
var info = gen[key](arg); | ||
var value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
Promise.resolve(value).then(_next, _throw); | ||
} | ||
} | ||
function _async_to_generator(fn) { | ||
return function() { | ||
var self = this, args = arguments; | ||
return new Promise(function(resolve, reject) { | ||
var gen = fn.apply(self, args); | ||
function _next(value) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); | ||
} | ||
function _throw(err) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); | ||
} | ||
_next(undefined); | ||
}); | ||
}; | ||
} | ||
function _define_property(obj, key, value) { | ||
if (key in obj) { | ||
Object.defineProperty(obj, key, { | ||
value: value, | ||
enumerable: true, | ||
configurable: true, | ||
writable: true | ||
}); | ||
} else { | ||
obj[key] = value; | ||
} | ||
return obj; | ||
} | ||
function _instanceof(left, right) { | ||
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { | ||
return !!right[Symbol.hasInstance](left); | ||
} else { | ||
return left instanceof right; | ||
} | ||
} | ||
function _iterable_to_array_limit(arr, i) { | ||
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; | ||
if (_i == null) return; | ||
var _arr = []; | ||
var _n = true; | ||
var _d = false; | ||
var _s, _e; | ||
try { | ||
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){ | ||
_arr.push(_s.value); | ||
if (i && _arr.length === i) break; | ||
} | ||
} catch (err) { | ||
_d = true; | ||
_e = err; | ||
} finally{ | ||
try { | ||
if (!_n && _i["return"] != null) _i["return"](); | ||
} finally{ | ||
if (_d) throw _e; | ||
} | ||
} | ||
return _arr; | ||
} | ||
function _non_iterable_rest() { | ||
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); | ||
} | ||
function _object_spread(target) { | ||
for(var i = 1; i < arguments.length; i++){ | ||
var source = arguments[i] != null ? arguments[i] : {}; | ||
var ownKeys = Object.keys(source); | ||
if (typeof Object.getOwnPropertySymbols === "function") { | ||
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) { | ||
return Object.getOwnPropertyDescriptor(source, sym).enumerable; | ||
})); | ||
} | ||
ownKeys.forEach(function(key) { | ||
_define_property(target, key, source[key]); | ||
}); | ||
} | ||
return target; | ||
} | ||
function _object_without_properties(source, excluded) { | ||
if (source == null) return {}; | ||
var target = _object_without_properties_loose(source, excluded); | ||
var key, i; | ||
if (Object.getOwnPropertySymbols) { | ||
var sourceSymbolKeys = Object.getOwnPropertySymbols(source); | ||
for(i = 0; i < sourceSymbolKeys.length; i++){ | ||
key = sourceSymbolKeys[i]; | ||
if (excluded.indexOf(key) >= 0) continue; | ||
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; | ||
target[key] = source[key]; | ||
} | ||
} | ||
return target; | ||
} | ||
function _object_without_properties_loose(source, excluded) { | ||
if (source == null) return {}; | ||
var target = {}; | ||
var sourceKeys = Object.keys(source); | ||
var key, i; | ||
for(i = 0; i < sourceKeys.length; i++){ | ||
key = sourceKeys[i]; | ||
if (excluded.indexOf(key) >= 0) continue; | ||
target[key] = source[key]; | ||
} | ||
return target; | ||
} | ||
function _sliced_to_array(arr, i) { | ||
return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest(); | ||
} | ||
function _unsupported_iterable_to_array(o, minLen) { | ||
if (!o) return; | ||
if (typeof o === "string") return _array_like_to_array(o, minLen); | ||
var n = Object.prototype.toString.call(o).slice(8, -1); | ||
if (n === "Object" && o.constructor) n = o.constructor.name; | ||
if (n === "Map" || n === "Set") return Array.from(n); | ||
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen); | ||
} | ||
function _ts_generator(thisArg, body) { | ||
var f, y, t, g, _ = { | ||
label: 0, | ||
sent: function() { | ||
if (t[0] & 1) throw t[1]; | ||
return t[1]; | ||
}, | ||
trys: [], | ||
ops: [] | ||
}; | ||
return(g = { | ||
next: verb(0), | ||
"throw": verb(1), | ||
"return": verb(2) | ||
}, typeof Symbol === "function" && (g[Symbol.iterator] = function() { | ||
return this; | ||
}), g); | ||
function verb(n) { | ||
return function(v) { | ||
return step([ | ||
n, | ||
v | ||
]); | ||
}; | ||
} | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while(_)try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [ | ||
op[0] & 2, | ||
t.value | ||
]; | ||
switch(op[0]){ | ||
case 0: | ||
case 1: | ||
t = op; | ||
break; | ||
case 4: | ||
_.label++; | ||
return { | ||
value: op[1], | ||
done: false | ||
}; | ||
case 5: | ||
_.label++; | ||
y = op[1]; | ||
op = [ | ||
0 | ||
]; | ||
continue; | ||
case 7: | ||
op = _.ops.pop(); | ||
_.trys.pop(); | ||
continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { | ||
_ = 0; | ||
continue; | ||
} | ||
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { | ||
_.label = op[1]; | ||
break; | ||
} | ||
if (op[0] === 6 && _.label < t[1]) { | ||
_.label = t[1]; | ||
t = op; | ||
break; | ||
} | ||
if (t && _.label < t[2]) { | ||
_.label = t[2]; | ||
_.ops.push(op); | ||
break; | ||
} | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); | ||
continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { | ||
op = [ | ||
6, | ||
e | ||
]; | ||
y = 0; | ||
} finally{ | ||
f = t = 0; | ||
} | ||
if (op[0] & 5) throw op[1]; | ||
return { | ||
value: op[0] ? op[1] : void 0, | ||
done: true | ||
}; | ||
} | ||
} | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = function(target, all) { | ||
for(var name in all)__defProp(target, name, { | ||
get: all[name], | ||
enumerable: true | ||
}); | ||
}; | ||
var __copyProps = function(to, from, except, desc) { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined; | ||
try { | ||
var _loop = function() { | ||
var key = _step.value; | ||
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { | ||
get: function() { | ||
return from[key]; | ||
}, | ||
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable | ||
}); | ||
}; | ||
for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop(); | ||
} catch (err) { | ||
_didIteratorError = true; | ||
_iteratorError = err; | ||
} finally{ | ||
try { | ||
if (!_iteratorNormalCompletion && _iterator.return != null) { | ||
_iterator.return(); | ||
} | ||
} finally{ | ||
if (_didIteratorError) { | ||
throw _iteratorError; | ||
} | ||
} | ||
} | ||
} | ||
return to; | ||
}; | ||
var __toESM = function(mod, isNodeMode, target) { | ||
return target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(// If the importer is in node compatibility mode or this is not an ESM | ||
// file that has been converted to a CommonJS file using a Babel- | ||
// compatible transform (i.e. "__esModule" has not been set), then set | ||
// "default" to the CommonJS "module.exports" for node compatibility. | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { | ||
value: mod, | ||
enumerable: true | ||
}) : target, mod); | ||
}; | ||
var __toCommonJS = function(mod) { | ||
return __copyProps(__defProp({}, "__esModule", { | ||
value: true | ||
}), mod); | ||
}; | ||
// src/index.ts | ||
var src_exports = {}; | ||
__export(src_exports, { | ||
CardElement: function() { | ||
return import_react_stripe_js.CardElement; | ||
}, | ||
FormspreeProvider: function() { | ||
return FormspreeProvider; | ||
}, | ||
ValidationError: function() { | ||
return ValidationError; | ||
}, | ||
isFieldError: function() { | ||
return import_core2.isFieldError; | ||
}, | ||
useForm: function() { | ||
return useForm; | ||
}, | ||
useFormspree: function() { | ||
return useFormspree; | ||
} | ||
}); | ||
module.exports = __toCommonJS(src_exports); | ||
// src/context.tsx | ||
var import_react = __toESM(require("react")); | ||
var import_core = require("@formspree/core"); | ||
var import_pure = require("@stripe/stripe-js/pure.js"); | ||
var Elements = (0, import_react.lazy)(function() { | ||
return import("@stripe/react-stripe-js").then(function(module2) { | ||
return { | ||
default: module2.Elements | ||
}; | ||
}); | ||
}); | ||
var FormspreeContext = import_react.default.createContext({ | ||
client: void 0 | ||
}); | ||
FormspreeContext.displayName = "Formspree"; | ||
var stripePromise; | ||
var getStripe = function(stripeKey) { | ||
if (!stripePromise) { | ||
stripePromise = (0, import_pure.loadStripe)(stripeKey); | ||
} | ||
return stripePromise; | ||
}; | ||
var handleCreateClient = function(promise, project) { | ||
var config = {}; | ||
if (promise) { | ||
config.stripePromise = promise; | ||
} | ||
if (project) { | ||
config.project = project; | ||
} | ||
return (0, import_core.createClient)(config); | ||
}; | ||
var FormspreeProvider = function(props) { | ||
var _ref = _sliced_to_array((0, import_react.useState)(void 0), 2), stateStripePromise = _ref[0], setStateStripePromise = _ref[1]; | ||
var _ref1 = _sliced_to_array((0, import_react.useState)(handleCreateClient(stateStripePromise, props.project)), 2), client = _ref1[0], setClient = _ref1[1]; | ||
(0, import_react.useEffect)(function() { | ||
client.startBrowserSession(); | ||
return function() { | ||
client.teardown(); | ||
}; | ||
}, []); | ||
(0, import_react.useEffect)(function() { | ||
var getStripePromise = function() { | ||
var _ref = _async_to_generator(function() { | ||
var promiseStripe; | ||
return _ts_generator(this, function(_state) { | ||
switch(_state.label){ | ||
case 0: | ||
return [ | ||
4, | ||
getStripe(props.stripePK) | ||
]; | ||
case 1: | ||
promiseStripe = _state.sent(); | ||
setStateStripePromise(promiseStripe); | ||
return [ | ||
2 | ||
]; | ||
} | ||
}); | ||
}); | ||
return function getStripePromise() { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}(); | ||
if (props.stripePK) { | ||
getStripePromise(); | ||
} | ||
}, [ | ||
props.stripePK | ||
]); | ||
(0, import_react.useEffect)(function() { | ||
if (stateStripePromise) { | ||
setClient(handleCreateClient(stateStripePromise, props.project)); | ||
} | ||
}, [ | ||
stateStripePromise | ||
]); | ||
return /* @__PURE__ */ import_react.default.createElement(FormspreeContext.Provider, { | ||
value: { | ||
client: client | ||
} | ||
}, props.stripePK ? /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, stateStripePromise && /* @__PURE__ */ import_react.default.createElement(import_react.Suspense, { | ||
fallback: /* @__PURE__ */ import_react.default.createElement("p", null, "....") | ||
}, /* @__PURE__ */ import_react.default.createElement(Elements, { | ||
stripe: stateStripePromise | ||
}, /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, props.children)))) : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, props.children)); | ||
}; | ||
function useFormspree() { | ||
var context = (0, import_react.useContext)(FormspreeContext); | ||
return context.client ? context : { | ||
client: (0, import_core.getDefaultClient)() | ||
}; | ||
} | ||
// src/useForm.ts | ||
var import_react2 = require("react"); | ||
var import_react_stripe_js = require("@stripe/react-stripe-js"); | ||
// package.json | ||
var version = "2.4.2"; | ||
// src/useForm.ts | ||
var isEvent = function(data) { | ||
return data.preventDefault !== void 0; | ||
}; | ||
var useForm = function(formKey) { | ||
var args = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; | ||
var _ref = _sliced_to_array((0, import_react2.useState)(null), 2), result = _ref[0], setResult = _ref[1]; | ||
var _ref1 = _sliced_to_array((0, import_react2.useState)(false), 2), submitting = _ref1[0], setSubmitting = _ref1[1]; | ||
var _ref2 = _sliced_to_array((0, import_react2.useState)(false), 2), succeeded = _ref2[0], setSucceeded = _ref2[1]; | ||
var _ref3 = _sliced_to_array((0, import_react2.useState)([]), 2), errors = _ref3[0], setErrors = _ref3[1]; | ||
var formspreeContext = useFormspree(); | ||
var client = args.client || formspreeContext; | ||
var stripe; | ||
var elements; | ||
if (!client) { | ||
throw new Error("You must provide a Formspree client"); | ||
} | ||
if (!formKey) { | ||
throw new Error('You must provide a form key or hashid (e.g. useForm("myForm") or useForm("123xyz")'); | ||
} | ||
if (formspreeContext.client && formspreeContext.client.stripePromise) { | ||
stripe = (0, import_react_stripe_js.useStripe)(); | ||
elements = (0, import_react_stripe_js.useElements)(); | ||
} | ||
var debug = !!args.debug; | ||
var extraData = args.data; | ||
var reset = function() { | ||
setSubmitting(false); | ||
setSucceeded(false); | ||
setErrors([]); | ||
}; | ||
var handleSubmit = function() { | ||
var _ref = _async_to_generator(function(submissionData) { | ||
var getFormData, formData, _tmp, appendExtraData, _tmp1, _tmp2, _i, prop, extraDataValue, createPaymentMethod; | ||
return _ts_generator(this, function(_state) { | ||
switch(_state.label){ | ||
case 0: | ||
getFormData = function() { | ||
var _ref = _async_to_generator(function(event) { | ||
var form; | ||
return _ts_generator(this, function(_state) { | ||
event.preventDefault(); | ||
form = event.target; | ||
if (form.tagName != "FORM") { | ||
throw new Error("submit was triggered for a non-form element"); | ||
} | ||
return [ | ||
2, | ||
new FormData(form) | ||
]; | ||
}); | ||
}); | ||
return function getFormData(event) { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}(); | ||
if (!isEvent(submissionData)) return [ | ||
3, | ||
2 | ||
]; | ||
return [ | ||
4, | ||
getFormData(submissionData) | ||
]; | ||
case 1: | ||
_tmp = _state.sent(); | ||
return [ | ||
3, | ||
3 | ||
]; | ||
case 2: | ||
_tmp = submissionData; | ||
_state.label = 3; | ||
case 3: | ||
formData = _tmp; | ||
appendExtraData = function(prop, value) { | ||
if (_instanceof(formData, FormData)) { | ||
formData.append(prop, value); | ||
} else { | ||
formData = Object.assign(formData, _define_property({}, prop, value)); | ||
} | ||
}; | ||
if (!(typeof extraData === "object")) return [ | ||
3, | ||
10 | ||
]; | ||
_tmp1 = []; | ||
for(_tmp2 in extraData)_tmp1.push(_tmp2); | ||
_i = 0; | ||
_state.label = 4; | ||
case 4: | ||
if (!(_i < _tmp1.length)) return [ | ||
3, | ||
10 | ||
]; | ||
prop = _tmp1[_i]; | ||
extraDataValue = void 0; | ||
if (!(typeof extraData[prop] === "function")) return [ | ||
3, | ||
7 | ||
]; | ||
extraDataValue = extraData[prop].call(null); | ||
if (!(typeof (extraDataValue === null || extraDataValue === void 0 ? void 0 : extraDataValue.then) === "function")) return [ | ||
3, | ||
6 | ||
]; | ||
return [ | ||
4, | ||
extraDataValue | ||
]; | ||
case 5: | ||
extraDataValue = _state.sent(); | ||
_state.label = 6; | ||
case 6: | ||
return [ | ||
3, | ||
8 | ||
]; | ||
case 7: | ||
extraDataValue = extraData[prop]; | ||
_state.label = 8; | ||
case 8: | ||
if (extraDataValue !== void 0) { | ||
appendExtraData(prop, extraDataValue); | ||
} | ||
_state.label = 9; | ||
case 9: | ||
_i++; | ||
return [ | ||
3, | ||
4 | ||
]; | ||
case 10: | ||
createPaymentMethod = function() { | ||
var _ref = _async_to_generator(function() { | ||
var address, payload; | ||
return _ts_generator(this, function(_state) { | ||
switch(_state.label){ | ||
case 0: | ||
address = _object_spread({}, formData.address_line1 && { | ||
line1: formData.address_line1 | ||
}, formData.address_line2 && { | ||
line2: formData.address_line2 | ||
}, formData.address_city && { | ||
city: formData.address_city | ||
}, formData.address_country && { | ||
country: formData.address_country | ||
}, formData.address_state && { | ||
state: formData.address_state | ||
}, formData.address_postal_code && { | ||
postal_code: formData.address_postal_code | ||
}); | ||
return [ | ||
4, | ||
stripe.createPaymentMethod({ | ||
type: "card", | ||
card: elements.getElement(import_react_stripe_js.CardElement), | ||
billing_details: _object_spread({}, formData.name && { | ||
name: formData.name | ||
}, formData.email && { | ||
email: formData.email | ||
}, formData.phone && { | ||
phone: formData.phone | ||
}, address && { | ||
address: address | ||
}) | ||
}) | ||
]; | ||
case 1: | ||
payload = _state.sent(); | ||
return [ | ||
2, | ||
payload | ||
]; | ||
} | ||
}); | ||
}); | ||
return function createPaymentMethod() { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}(); | ||
setSubmitting(true); | ||
return [ | ||
2, | ||
formspreeContext.client.submitForm(formKey, formData, { | ||
endpoint: args.endpoint, | ||
clientName: "@formspree/react@".concat(version), | ||
createPaymentMethod: formspreeContext.client && formspreeContext.client.stripePromise ? createPaymentMethod : void 0 | ||
}).then(function(result2) { | ||
var status = result2.response.status; | ||
var body; | ||
if (status === 200) { | ||
if (debug) console.log("Form submitted", result2); | ||
setSucceeded(true); | ||
setResult(result2); | ||
setErrors([]); | ||
} else if (status >= 400) { | ||
body = result2.body; | ||
if (body.errors) { | ||
setErrors(body.errors); | ||
if (debug) console.log("Error", result2); | ||
} else { | ||
setErrors([ | ||
{ | ||
message: "Unexpected error" | ||
} | ||
]); | ||
if (debug) console.log("Unexpected error", result2); | ||
} | ||
setSucceeded(false); | ||
} | ||
return result2; | ||
}).catch(function(error) { | ||
if (debug) console.log("Unexpected error", error); | ||
setSucceeded(false); | ||
throw error; | ||
}).finally(function() { | ||
setSubmitting(false); | ||
}) | ||
]; | ||
} | ||
}); | ||
}); | ||
return function handleSubmit(submissionData) { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}(); | ||
return [ | ||
{ | ||
result: result, | ||
submitting: submitting, | ||
succeeded: succeeded, | ||
errors: errors | ||
}, | ||
handleSubmit, | ||
reset | ||
]; | ||
}; | ||
// src/ValidationError.tsx | ||
var import_react3 = __toESM(require("react")); | ||
var ValidationError = function(props) { | ||
var prefix = props.prefix, field = props.field, errors = props.errors, attrs = _object_without_properties(props, [ | ||
"prefix", | ||
"field", | ||
"errors" | ||
]); | ||
var error = (errors || []).find(function(error2) { | ||
return error2.field === field; | ||
}); | ||
if (!error) { | ||
return null; | ||
} | ||
return /* @__PURE__ */ import_react3.default.createElement("div", _object_spread({}, attrs), prefix, " ", error.message); | ||
}; | ||
// src/types.ts | ||
var import_core2 = require("@formspree/core"); | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
CardElement: CardElement, | ||
FormspreeProvider: FormspreeProvider, | ||
ValidationError: ValidationError, | ||
isFieldError: isFieldError, | ||
useForm: useForm, | ||
useFormspree: useFormspree | ||
}); | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@formspree/react", | ||
"version": "2.4.1", | ||
"version": "2.4.2", | ||
"description": "The React component library for Formspree", | ||
@@ -49,2 +49,3 @@ "private": false, | ||
"dependencies": { | ||
"@formspree/core": "^2.8.1", | ||
"@stripe/react-stripe-js": "^1.7.1", | ||
@@ -54,3 +55,7 @@ "@stripe/stripe-js": "^1.35.0" | ||
"devDependencies": { | ||
"@formspree/core": "*", | ||
"@babel/core": "^7.22.1", | ||
"@swc/core": "^1.3.61", | ||
"@testing-library/dom": "^9.3.0", | ||
"@testing-library/react": "^14.0.0", | ||
"@testing-library/user-event": "^14.4.3", | ||
"@types/jest": "^24.0.25", | ||
@@ -67,3 +72,2 @@ "@types/react": "^18.0.15", | ||
"react-dom": "^18.2.0", | ||
"react-test-renderer": "^17.0.2", | ||
"sort-package-json": "^1.22.1", | ||
@@ -73,2 +77,6 @@ "tsup": "^6.2.2", | ||
}, | ||
"peerDependencies": { | ||
"react": "^16.8 || ^17.0 || ^18.0", | ||
"react-dom": "^16.8 || ^17.0 || ^18.0" | ||
}, | ||
"publishConfig": { | ||
@@ -75,0 +83,0 @@ "access": "public", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
964
1
1
75179
5
19
+ Added@formspree/core@^2.8.1
+ Added@formspree/core@2.8.3(transitive)