@formspree/core
Advanced tools
Comparing version 2.8.3 to 3.0.0
import { PaymentMethodResult, Stripe } from '@stripe/stripe-js'; | ||
type SubmissionData = FormData | any; | ||
interface SubmissionOptions { | ||
endpoint?: string; | ||
declare function appendExtraData(formData: SubmissionData, prop: string, value: string): void; | ||
type SubmissionData<T extends FieldValues = FieldValues> = FormData | T; | ||
type FieldValues = Record<string, string | number | boolean | null | undefined>; | ||
type SubmissionOptions = { | ||
clientName?: string; | ||
fetchImpl?: typeof fetch; | ||
createPaymentMethod?: () => Promise<PaymentMethodResult>; | ||
endpoint?: string; | ||
}; | ||
type SubmissionResult<T extends FieldValues> = SubmissionSuccess | SubmissionError<T>; | ||
declare class SubmissionSuccess { | ||
readonly kind = "success"; | ||
readonly next: string; | ||
constructor(serverResponse: ServerSuccessResponse); | ||
} | ||
declare enum FormErrorCodeEnum { | ||
INACTIVE = "INACTIVE", | ||
BLOCKED = "BLOCKED", | ||
EMPTY = "EMPTY", | ||
PROJECT_NOT_FOUND = "PROJECT_NOT_FOUND", | ||
FORM_NOT_FOUND = "FORM_NOT_FOUND", | ||
NO_FILE_UPLOADS = "NO_FILE_UPLOADS", | ||
TOO_MANY_FILES = "TOO_MANY_FILES", | ||
FILES_TOO_BIG = "FILES_TOO_BIG", | ||
STRIPE_CLIENT_ERROR = "STRIPE_CLIENT_ERROR", | ||
STRIPE_SCA_ERROR = "STRIPE_SCA_ERROR" | ||
type ServerSuccessResponse = { | ||
next: string; | ||
}; | ||
declare function isSubmissionError<T extends FieldValues>(result: SubmissionResult<T>): result is SubmissionError<T>; | ||
declare class SubmissionError<T extends FieldValues> { | ||
readonly kind = "error"; | ||
private readonly formErrors; | ||
private readonly fieldErrors; | ||
constructor(...serverErrors: ServerError[]); | ||
getFormErrors(): readonly FormError[]; | ||
getFieldErrors<K extends keyof T>(field: K): readonly FieldError[]; | ||
getAllFieldErrors(): readonly [keyof T, readonly FieldError[]][]; | ||
} | ||
declare enum FieldErrorCodeEnum { | ||
REQUIRED_FIELD_MISSING = "REQUIRED_FIELD_MISSING", | ||
REQUIRED_FIELD_EMPTY = "REQUIRED_FIELD_EMPTY", | ||
TYPE_EMAIL = "TYPE_EMAIL", | ||
TYPE_NUMERIC = "TYPE_NUMERIC", | ||
TYPE_TEXT = "TYPE_TEXT" | ||
} | ||
type FormErrorCode = keyof typeof FormErrorCodeEnum; | ||
type FieldErrorCode = keyof typeof FieldErrorCodeEnum; | ||
interface FormError { | ||
type FormError = { | ||
readonly code: FormErrorCode | 'UNSPECIFIED'; | ||
readonly message: string; | ||
}; | ||
type FormErrorCode = ValueOf<typeof FormErrorCodeEnum>; | ||
declare const FormErrorCodeEnum: { | ||
readonly BLOCKED: "BLOCKED"; | ||
readonly EMPTY: "EMPTY"; | ||
readonly FILES_TOO_BIG: "FILES_TOO_BIG"; | ||
readonly FORM_NOT_FOUND: "FORM_NOT_FOUND"; | ||
readonly INACTIVE: "INACTIVE"; | ||
readonly NO_FILE_UPLOADS: "NO_FILE_UPLOADS"; | ||
readonly PROJECT_NOT_FOUND: "PROJECT_NOT_FOUND"; | ||
readonly TOO_MANY_FILES: "TOO_MANY_FILES"; | ||
}; | ||
type FieldError = { | ||
readonly code: FieldErrorCode | 'UNSPECIFIED'; | ||
readonly message: string; | ||
}; | ||
type FieldErrorCode = ValueOf<typeof FieldErrorCodeEnum>; | ||
declare const FieldErrorCodeEnum: { | ||
readonly REQUIRED_FIELD_EMPTY: "REQUIRED_FIELD_EMPTY"; | ||
readonly REQUIRED_FIELD_MISSING: "REQUIRED_FIELD_MISSING"; | ||
readonly STRIPE_CLIENT_ERROR: "STRIPE_CLIENT_ERROR"; | ||
readonly STRIPE_SCA_ERROR: "STRIPE_SCA_ERROR"; | ||
readonly TYPE_EMAIL: "TYPE_EMAIL"; | ||
readonly TYPE_NUMERIC: "TYPE_NUMERIC"; | ||
readonly TYPE_TEXT: "TYPE_TEXT"; | ||
}; | ||
type ServerError = { | ||
code?: string; | ||
details?: Record<string, string>; | ||
field?: string; | ||
code?: FormErrorCode | FieldErrorCode; | ||
message: string; | ||
details?: { | ||
stripeCode?: string; | ||
}; | ||
} | ||
interface FieldError extends FormError { | ||
field: string; | ||
code: FieldErrorCode; | ||
} | ||
declare function isFieldError(error: FormError): error is FieldError; | ||
interface SuccessBody { | ||
id: string; | ||
data: object; | ||
} | ||
interface ErrorBody { | ||
errors: FormError[]; | ||
} | ||
type SubmissionBody = SuccessBody | ErrorBody; | ||
interface SubmissionResponse { | ||
body: SubmissionBody; | ||
response: Response | null; | ||
} | ||
}; | ||
type ValueOf<T> = T[keyof T]; | ||
interface Config { | ||
project?: string; | ||
stripePromise?: Stripe; | ||
stripe?: Stripe; | ||
} | ||
declare class Client { | ||
project: string | undefined; | ||
stripePromise: Stripe | undefined; | ||
private session; | ||
stripe: Stripe | undefined; | ||
private readonly session?; | ||
constructor(config?: Config); | ||
/** | ||
* Starts a browser session. | ||
*/ | ||
startBrowserSession(): void; | ||
/** | ||
* Teardown the client session. | ||
*/ | ||
teardown(): void; | ||
/** | ||
* Submit a form. | ||
@@ -81,3 +84,3 @@ * | ||
*/ | ||
submitForm(formKey: string, data: SubmissionData, opts?: SubmissionOptions): Promise<SubmissionResponse>; | ||
submitForm<T extends FieldValues>(formKey: string, data: SubmissionData<T>, opts?: SubmissionOptions): Promise<SubmissionResult<T>>; | ||
} | ||
@@ -93,13 +96,2 @@ /** | ||
declare class Session { | ||
loadedAt: number; | ||
webdriver: boolean; | ||
constructor(); | ||
teardown(): void; | ||
data(): { | ||
loadedAt: number; | ||
webdriver: boolean; | ||
}; | ||
} | ||
export { Client, Config, ErrorBody, FieldError, FormError, Session, SubmissionData, SubmissionResponse, createClient, getDefaultClient, isFieldError }; | ||
export { Client, Config, FieldErrorCode, FieldValues, FormErrorCode, SubmissionData, SubmissionError, SubmissionOptions, SubmissionResult, SubmissionSuccess, appendExtraData, createClient, getDefaultClient, isSubmissionError }; |
@@ -1,1 +0,1 @@ | ||
var E=Object.defineProperty,Y=Object.defineProperties,k=Object.getOwnPropertyDescriptor,K=Object.getOwnPropertyDescriptors,$=Object.getOwnPropertyNames,O=Object.getOwnPropertySymbols;var P=Object.prototype.hasOwnProperty,z=Object.prototype.propertyIsEnumerable;var C=(e,t,r)=>t in e?E(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,S=(e,t)=>{for(var r in t||(t={}))P.call(t,r)&&C(e,r,t[r]);if(O)for(var r of O(t))z.call(t,r)&&C(e,r,t[r]);return e},g=(e,t)=>Y(e,K(t));var J=(e,t)=>{for(var r in t)E(e,r,{get:t[r],enumerable:!0})},q=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $(t))!P.call(e,i)&&i!==r&&E(e,i,{get:()=>t[i],enumerable:!(o=k(t,i))||o.enumerable});return e};var G=e=>q(E({},"__esModule",{value:!0}),e);var R=(e,t,r)=>new Promise((o,i)=>{var s=p=>{try{n(r.next(p))}catch(c){i(c)}},a=p=>{try{n(r.throw(p))}catch(c){i(c)}},n=p=>p.done?o(p.value):Promise.resolve(p.value).then(s,a);n((r=r.apply(e,t)).next())});var Z={};J(Z,{Client:()=>b,createClient:()=>x,getDefaultClient:()=>U,isFieldError:()=>M});module.exports=G(Z);var m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",H=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;function w(e){e=String(e);for(var t,r,o,i,s="",a=0,n=e.length%3;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(i=e.charCodeAt(a++))>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|o<<8|i,s+=m.charAt(t>>18&63)+m.charAt(t>>12&63)+m.charAt(t>>6&63)+m.charAt(t&63)}return n?s.slice(0,n-3)+"===".substring(n):s}function F(e){if(e=String(e).replace(/[\t\n\f\r ]+/g,""),!H.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="",o,i,s=0;s<e.length;)t=m.indexOf(e.charAt(s++))<<18|m.indexOf(e.charAt(s++))<<12|(o=m.indexOf(e.charAt(s++)))<<6|(i=m.indexOf(e.charAt(s++))),r+=o===64?String.fromCharCode(t>>16&255):i===64?String.fromCharCode(t>>16&255,t>>8&255):String.fromCharCode(t>>16&255,t>>8&255,t&255);return r}var A="2.8.3";var D=(s=>(s.REQUIRED_FIELD_MISSING="REQUIRED_FIELD_MISSING",s.REQUIRED_FIELD_EMPTY="REQUIRED_FIELD_EMPTY",s.TYPE_EMAIL="TYPE_EMAIL",s.TYPE_NUMERIC="TYPE_NUMERIC",s.TYPE_TEXT="TYPE_TEXT",s))(D||{});function M(e){return e.code in D&&e.field!==void 0}function N(e){return e.errors!==void 0}var j=e=>w(JSON.stringify(e));var L=e=>{let t=`@formspree/core@${A}`;return e?`${e} ${t}`:t},v=()=>1*new Date,h=(e,t,r)=>{e instanceof FormData?e.append(t,r):e=Object.assign(e,{[t]:r})},B=p=>R(void 0,[p],function*({stripePromise:e,response:t,responseData:r,payload:o,data:i,fetchImpl:s,request:a,url:n}){let c=yield e.handleCardAction(r.stripe.paymentIntentClientSecret);if(c.error)return{response:t,body:{errors:[{code:"STRIPE_CLIENT_ERROR",message:"Stripe SCA error",field:"paymentMethod"}]}};{o.paymentMethod.id||h(i,"paymentMethod",o.paymentMethod.id),h(i,"paymentIntent",c.paymentIntent.id),h(i,"resubmitKey",r.resubmitKey);let l=yield s(n,g(S({},a),{body:JSON.stringify({paymentIntent:c.paymentIntent.id,resubmitKey:r.resubmitKey})})),u=yield l.json();return{response:l,body:u}}});function _({body:e,response:t}){return!N(e)&&(e!=null&&e.error)&&(e={errors:[{message:e.error}]}),{body:e,response:t}}var V=()=>navigator.webdriver||!!document.documentElement.getAttribute(F("d2ViZHJpdmVy"))||!!window.callPhantom||!!window._phantom,I=class{constructor(){this.loadedAt=v(),this.webdriver=V()}teardown(){}data(){return{loadedAt:this.loadedAt,webdriver:this.webdriver}}};var b=class{constructor(t={}){this.project=t.project,this.stripePromise=t.stripePromise,typeof window!="undefined"&&this.startBrowserSession()}startBrowserSession(){this.session||(this.session=new I)}teardown(){this.session&&this.session.teardown()}submitForm(i,s){return R(this,arguments,function*(t,r,o={}){let a=o.endpoint||"https://formspree.io",n=o.fetchImpl||fetch,p=this.project?`${a}/p/${this.project}/f/${t}`:`${a}/f/${t}`,c=d=>d instanceof FormData?d:JSON.stringify(d),l={Accept:"application/json","Formspree-Client":L(o.clientName)};this.session&&(l["Formspree-Session-Data"]=j(this.session.data())),r instanceof FormData||(l["Content-Type"]="application/json");let u={method:"POST",mode:"cors",body:c(r),headers:l};if(this.stripePromise&&o.createPaymentMethod){let d=yield o.createPaymentMethod();if(d.error)return{response:null,body:{errors:[{code:"STRIPE_CLIENT_ERROR",message:"Error creating payment method",field:"paymentMethod"}]}};h(r,"paymentMethod",d.paymentMethod.id);let y=yield n(p,g(S({},u),{body:r})),f=yield y.json();return f&&f.stripe&&f.stripe.requiresAction&&f.resubmitKey?yield B({stripePromise:this.stripePromise,responseData:f,response:y,payload:d,data:r,fetchImpl:n,request:u,url:p}):_({response:y,body:f})}else return n(p,u).then(d=>d.json().then(y=>_({body:y,response:d}))).catch()})}},x=e=>new b(e),U=()=>(T||(T=x()),T),T;0&&(module.exports={Client,createClient,getDefaultClient,isFieldError}); | ||
var g=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var Y=(e,r)=>{for(var t in r)g(e,t,{get:r[t],enumerable:!0})},K=(e,r,t,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of L(r))!V.call(e,s)&&s!==t&&g(e,s,{get:()=>r[s],enumerable:!(o=j(r,s))||o.enumerable});return e};var $=e=>K(g({},"__esModule",{value:!0}),e);var h=(e,r,t)=>new Promise((o,s)=>{var i=a=>{try{l(t.next(a))}catch(m){s(m)}},c=a=>{try{l(t.throw(a))}catch(m){s(m)}},l=a=>a.done?o(a.value):Promise.resolve(a.value).then(i,c);l((t=t.apply(e,r)).next())});var W={};Y(W,{SubmissionError:()=>p,appendExtraData:()=>E,createClient:()=>F,getDefaultClient:()=>U,isSubmissionError:()=>A});module.exports=$(W);var u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",J=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;function I(e){e=String(e);for(var r,t,o,s,i="",c=0,l=e.length%3;c<e.length;){if((t=e.charCodeAt(c++))>255||(o=e.charCodeAt(c++))>255||(s=e.charCodeAt(c++))>255)throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");r=t<<16|o<<8|s,i+=u.charAt(r>>18&63)+u.charAt(r>>12&63)+u.charAt(r>>6&63)+u.charAt(r&63)}return l?i.slice(0,l-3)+"===".substring(l):i}function O(e){if(e=String(e).replace(/[\t\n\f\r ]+/g,""),!J.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 r,t="",o,s,i=0;i<e.length;)r=u.indexOf(e.charAt(i++))<<18|u.indexOf(e.charAt(i++))<<12|(o=u.indexOf(e.charAt(i++)))<<6|(s=u.indexOf(e.charAt(i++))),t+=o===64?String.fromCharCode(r>>16&255):s===64?String.fromCharCode(r>>16&255,r>>8&255):String.fromCharCode(r>>16&255,r>>8&255,r&255);return t}var G=()=>navigator.webdriver||!!document.documentElement.getAttribute(O("d2ViZHJpdmVy"))||!!window.callPhantom||!!window._phantom,y=class{constructor(){this.loadedAt=Date.now(),this.webdriver=G()}data(){return{loadedAt:this.loadedAt,webdriver:this.webdriver}}};var S=class{constructor(r){this.kind="success";this.next=r.next}};function w(e){return"next"in e&&typeof e.next=="string"}var b=class{constructor(r,t){this.paymentIntentClientSecret=r;this.resubmitKey=t;this.kind="stripePluginPending"}};function _(e){if("stripe"in e&&"resubmitKey"in e&&typeof e.resubmitKey=="string"){let{stripe:r}=e;return typeof r=="object"&&r!=null&&"paymentIntentClientSecret"in r&&typeof r.paymentIntentClientSecret=="string"}return!1}function A(e){return e.kind==="error"}var p=class{constructor(...r){this.kind="error";this.formErrors=[];this.fieldErrors=new Map;var t;for(let o of r){if(!o.field){this.formErrors.push({code:o.code&&z(o.code)?o.code:"UNSPECIFIED",message:o.message});continue}let s=(t=this.fieldErrors.get(o.field))!=null?t:[];s.push({code:o.code&&Q(o.code)?o.code:"UNSPECIFIED",message:o.message}),this.fieldErrors.set(o.field,s)}}getFormErrors(){return[...this.formErrors]}getFieldErrors(r){var t;return(t=this.fieldErrors.get(r))!=null?t:[]}getAllFieldErrors(){return Array.from(this.fieldErrors)}};function z(e){return e in B}var B={BLOCKED:"BLOCKED",EMPTY:"EMPTY",FILES_TOO_BIG:"FILES_TOO_BIG",FORM_NOT_FOUND:"FORM_NOT_FOUND",INACTIVE:"INACTIVE",NO_FILE_UPLOADS:"NO_FILE_UPLOADS",PROJECT_NOT_FOUND:"PROJECT_NOT_FOUND",TOO_MANY_FILES:"TOO_MANY_FILES"};function Q(e){return e in Z}var Z={REQUIRED_FIELD_EMPTY:"REQUIRED_FIELD_EMPTY",REQUIRED_FIELD_MISSING:"REQUIRED_FIELD_MISSING",STRIPE_CLIENT_ERROR:"STRIPE_CLIENT_ERROR",STRIPE_SCA_ERROR:"STRIPE_SCA_ERROR",TYPE_EMAIL:"TYPE_EMAIL",TYPE_NUMERIC:"TYPE_NUMERIC",TYPE_TEXT:"TYPE_TEXT"};function P(e){return"errors"in e&&Array.isArray(e.errors)&&e.errors.every(r=>typeof r.message=="string")||"error"in e&&typeof e.error=="string"}var D="3.0.0";var v=e=>I(JSON.stringify(e)),N=e=>{let r=`@formspree/core@${D}`;return e?`${e} ${r}`:r};function E(e,r,t){e instanceof FormData?e.append(r,t):e[r]=t}function M(e){return e!==null&&typeof e=="object"}var R=class{constructor(r={}){this.project=r.project,this.stripe=r.stripe,typeof window!="undefined"&&(this.session=new y)}submitForm(s,i){return h(this,arguments,function*(r,t,o={}){let c=o.endpoint||"https://formspree.io",l=this.project?`${c}/p/${this.project}/f/${r}`:`${c}/f/${r}`,a={Accept:"application/json","Formspree-Client":N(o.clientName)};this.session&&(a["Formspree-Session-Data"]=v(this.session.data())),t instanceof FormData||(a["Content-Type"]="application/json");function m(f){return h(this,null,function*(){try{let n=yield(yield fetch(l,{method:"POST",mode:"cors",body:f instanceof FormData?f:JSON.stringify(f),headers:a})).json();if(M(n)){if(P(n))return Array.isArray(n.errors)?new p(...n.errors):new p({message:n.error});if(_(n))return new b(n.stripe.paymentIntentClientSecret,n.resubmitKey);if(w(n))return new S({next:n.next})}return new p({message:"Unexpected response format"})}catch(d){let n=d instanceof Error?d.message:`Unknown error while posting to Formspree: ${JSON.stringify(d)}`;return new p({message:n})}})}if(this.stripe&&o.createPaymentMethod){let f=yield o.createPaymentMethod();if(f.error)return new p({code:"STRIPE_CLIENT_ERROR",field:"paymentMethod",message:"Error creating payment method"});E(t,"paymentMethod",f.paymentMethod.id);let d=yield m(t);if(d.kind==="error")return d;if(d.kind==="stripePluginPending"){let n=yield this.stripe.handleCardAction(d.paymentIntentClientSecret);if(n.error)return new p({code:"STRIPE_CLIENT_ERROR",field:"paymentMethod",message:"Stripe SCA error"});t instanceof FormData?t.delete("paymentMethod"):delete t.paymentMethod,E(t,"paymentIntent",n.paymentIntent.id),E(t,"resubmitKey",d.resubmitKey);let x=yield m(t);return k(x),x}return d}let T=yield m(t);return k(T),T})}};function k(e){let{kind:r}=e;if(r!=="success"&&r!=="error")throw new Error(`Unexpected submission result (kind: ${r})`)}var F=e=>new R(e),U=()=>(C||(C=F()),C),C;0&&(module.exports={SubmissionError,appendExtraData,createClient,getDefaultClient,isSubmissionError}); |
{ | ||
"name": "@formspree/core", | ||
"version": "2.8.3", | ||
"version": "3.0.0", | ||
"private": false, | ||
@@ -30,4 +30,4 @@ "description": "The core library for Formspree", | ||
"clean": "rm -rf dist && rm -rf node_modules", | ||
"dev": "tsup src/index.ts --format esm,cjs --dts --sourcemap", | ||
"lint": "eslint src/*.ts*", | ||
"dev": "tsup src/index.ts --format esm,cjs --dts --sourcemap --watch", | ||
"lint": "eslint ./src ./test", | ||
"test": "jest", | ||
@@ -39,13 +39,6 @@ "typecheck": "tsc --noEmit" | ||
}, | ||
"devDependencies": { | ||
"np": "^3.0.4", | ||
"tsup": "^6.2.2" | ||
}, | ||
"publishConfig": { | ||
"access": "public", | ||
"registry": "https://registry.npmjs.org" | ||
}, | ||
"np": { | ||
"yarn": false | ||
} | ||
} |
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
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
17339
0
135