@strabl-engineering/strabl-web-sdk 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,169 @@
1
+ var y = Object.defineProperty;
2
+ var v = (s, t, e) => t in s ? y(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
3
+ var m = (s, t, e) => v(s, typeof t != "symbol" ? t + "" : t, e);
4
+ import { d as p, T as C, F as g, i as N } from "./element-BbJGrJ33.js";
5
+ import { S as k } from "./element-BbJGrJ33.js";
6
+ function x(s) {
7
+ if (typeof document > "u")
8
+ throw new Error("strablCardForm can only be called in a browser");
9
+ p();
10
+ const t = document.querySelector(s.selector);
11
+ if (!t)
12
+ throw new Error(
13
+ `strablCardForm: no element matched selector "${s.selector}"`
14
+ );
15
+ const e = document.createElement(C), { selector: c, replace: d, ...l } = s;
16
+ return Object.assign(e, l), d ? t.replaceChildren(e) : t.appendChild(e), {
17
+ element: e,
18
+ update: (n) => Object.assign(e, n),
19
+ submit: () => e.submit(),
20
+ refresh: () => e.refresh(),
21
+ destroy: () => e.remove()
22
+ };
23
+ }
24
+ class E extends Error {
25
+ constructor(e, c, d) {
26
+ super(c);
27
+ m(this, "code");
28
+ m(this, "transaction");
29
+ this.code = e, this.transaction = d, this.name = "StrablError";
30
+ }
31
+ }
32
+ const F = {
33
+ name: "cardHolderName",
34
+ number: "cardNumber",
35
+ expiry: "expiry",
36
+ cvv: "cvc",
37
+ cardHolderName: "cardHolderName",
38
+ cardNumber: "cardNumber",
39
+ cvc: "cvc"
40
+ }, u = {
41
+ ready: "strablReady",
42
+ change: "strablChange",
43
+ focus: "strablFocus",
44
+ blur: "strablBlur",
45
+ result: "strablResult",
46
+ error: "strablError"
47
+ };
48
+ function L(s, t = {}) {
49
+ if (!/^pk_(live|test)_/.test(s ?? ""))
50
+ throw new Error("StrablElements: a publishable key (pk_…) is required");
51
+ return {
52
+ create(e, c = {}) {
53
+ if (e !== "card")
54
+ throw new Error(`StrablElements: unsupported element type "${e}"`);
55
+ return I(s, t, c);
56
+ }
57
+ };
58
+ }
59
+ function I(s, t, e) {
60
+ const c = new EventTarget();
61
+ let d = null, l = null, n = e;
62
+ const f = () => ({
63
+ apiKey: s,
64
+ platformUuid: t.platformUuid,
65
+ elementsUrl: t.elementsUrl,
66
+ language: n.language ?? t.language,
67
+ fieldInputStyle: n.fieldInputStyle,
68
+ paymentMethods: n.paymentMethods,
69
+ customstyles: n.customstyles,
70
+ inputStyle: n.style,
71
+ fonts: n.fonts,
72
+ enableEmailCollection: n.enableEmailCollection,
73
+ enableSaveCard: n.enableSaveCard,
74
+ merchantName: n.merchantName,
75
+ countryCode: n.countryCode,
76
+ sessionId: n.session?.sessionId,
77
+ clientSecret: n.session?.clientSecret
78
+ });
79
+ c.addEventListener(u.result, (r) => {
80
+ const a = r.detail;
81
+ a.status === "failed" && c.dispatchEvent(
82
+ new CustomEvent(u.error, {
83
+ detail: { code: a.code, message: a.message }
84
+ })
85
+ );
86
+ });
87
+ async function b(r, a) {
88
+ if (!l)
89
+ throw new Error("StrablElements: mount the card element first");
90
+ if (!N(a))
91
+ throw new Error(
92
+ "StrablElements: sessionId and clientSecret are required"
93
+ );
94
+ const o = await l.request(r, {
95
+ sessionId: a.sessionId,
96
+ clientSecret: a.clientSecret
97
+ });
98
+ switch (o.status) {
99
+ case "success":
100
+ return o.transaction;
101
+ case "requires_action":
102
+ return {
103
+ ...o.transaction,
104
+ threeDsUrl: o.url,
105
+ ...o.provider ? { provider: o.provider } : {}
106
+ };
107
+ case "failed":
108
+ throw new E(o.code, o.message, o.transaction);
109
+ }
110
+ }
111
+ return {
112
+ mount(r) {
113
+ if (l)
114
+ throw new Error("StrablElements: this card element is already mounted");
115
+ const a = typeof r == "string" ? document.querySelector(r) : r;
116
+ if (!a)
117
+ throw new Error(
118
+ `StrablElements: mount target "${r}" was not found`
119
+ );
120
+ d = document.createElement("div"), d.className = "strabl-card-element";
121
+ const o = d.attachShadow({ mode: "closed" });
122
+ a.appendChild(d), l = new g(o, c, f(), {
123
+ autoRedirect: !1
124
+ });
125
+ },
126
+ on(r, a) {
127
+ const o = u[r];
128
+ if (!o) throw new Error(`StrablElements: unknown event "${r}"`);
129
+ const h = (w) => {
130
+ const i = w.detail;
131
+ try {
132
+ a(
133
+ r === "error" ? new E(i.code, i.message) : i
134
+ );
135
+ } catch (S) {
136
+ console.error("[strabl] listener failed", S);
137
+ }
138
+ };
139
+ return c.addEventListener(o, h), () => c.removeEventListener(o, h);
140
+ },
141
+ confirm: (r) => b("submit", r),
142
+ resume: (r) => b("resume", r),
143
+ focus(r) {
144
+ const a = F[r];
145
+ a && l?.focus(a);
146
+ },
147
+ clear() {
148
+ l?.clear();
149
+ },
150
+ update(r) {
151
+ n = { ...n, ...r }, l?.update(f());
152
+ },
153
+ refresh() {
154
+ l?.refresh();
155
+ },
156
+ destroy() {
157
+ l?.destroy(), l = null, d?.remove(), d = null;
158
+ }
159
+ };
160
+ }
161
+ p();
162
+ export {
163
+ k as StrablCardForm,
164
+ L as StrablElements,
165
+ E as StrablError,
166
+ C as TAG_NAME,
167
+ p as defineStrablCardForm,
168
+ x as strablCardForm
169
+ };
package/dist/react.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("react"),h=require("./element-CZKsfyCs.cjs");function L(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const e in s)if(e!=="default"){const l=Object.getOwnPropertyDescriptor(s,e);Object.defineProperty(a,e,l.get?l:{enumerable:!0,get:()=>s[e]})}}return a.default=s,Object.freeze(a)}const o=L(_),T=["onPaymentSubmission","onPaymentSuccess","onPaymentFailed","onReady","onChange","onError"];h.defineStrablCardForm();const q=o.forwardRef(function(a,e){const{className:l,style:N,...c}=a,u=o.useRef(null),r=o.useRef(c);r.current=c;const n=o.useMemo(()=>{const t={};for(const O of T)t[O]=(...J)=>r.current[O]?.(...J);return t},[]),{apiKey:i,platformUuid:y,sessionId:m,clientSecret:f,language:S,fieldInputStyle:b,paymentMethods:E,customstyles:F,inputStyle:M,fonts:j,enableEmailCollection:d,enableSaveCard:p,merchantName:g,countryCode:P,elementsUrl:C}=c,K=JSON.stringify(E??null),R=JSON.stringify(F??null),k=JSON.stringify(j??null),v=JSON.stringify(M??null);o.useLayoutEffect(()=>{const t=u.current;t&&Object.assign(t,{apiKey:i,platformUuid:y,sessionId:m,clientSecret:f,language:S,fieldInputStyle:b,paymentMethods:r.current.paymentMethods,customstyles:r.current.customstyles,inputStyle:r.current.inputStyle,fonts:r.current.fonts,enableEmailCollection:d,enableSaveCard:p,merchantName:g,countryCode:P,elementsUrl:C,onPaymentSubmission:c.onPaymentSubmission?n.onPaymentSubmission:void 0,onPaymentSuccess:n.onPaymentSuccess,onPaymentFailed:n.onPaymentFailed,onReady:n.onReady,onChange:n.onChange,onError:n.onError})},[i,y,m,f,S,b,K,R,v,k,d,p,g,P,C,!!c.onPaymentSubmission,n]);const A=o.useCallback(t=>{u.current=t,typeof e=="function"?e(t):e&&(e.current=t)},[e]);return o.createElement(h.TAG_NAME,{ref:A,class:l,style:N})});exports.StrablCardPaymentForm=q;
package/dist/react.js ADDED
@@ -0,0 +1,97 @@
1
+ import * as t from "react";
2
+ import { d as L, T as v } from "./element-BbJGrJ33.js";
3
+ const B = [
4
+ "onPaymentSubmission",
5
+ "onPaymentSuccess",
6
+ "onPaymentFailed",
7
+ "onReady",
8
+ "onChange",
9
+ "onError"
10
+ ];
11
+ L();
12
+ const U = t.forwardRef(function(P, o) {
13
+ const { className: g, style: h, ...a } = P, r = t.useRef(null), s = t.useRef(a);
14
+ s.current = a;
15
+ const e = t.useMemo(() => {
16
+ const n = {};
17
+ for (const C of B)
18
+ n[C] = (...k) => s.current[C]?.(
19
+ ...k
20
+ );
21
+ return n;
22
+ }, []), {
23
+ apiKey: l,
24
+ platformUuid: c,
25
+ sessionId: u,
26
+ clientSecret: i,
27
+ language: y,
28
+ fieldInputStyle: m,
29
+ paymentMethods: E,
30
+ customstyles: N,
31
+ inputStyle: F,
32
+ fonts: K,
33
+ enableEmailCollection: S,
34
+ enableSaveCard: f,
35
+ merchantName: p,
36
+ countryCode: b,
37
+ elementsUrl: d
38
+ } = a, M = JSON.stringify(E ?? null), O = JSON.stringify(N ?? null), R = JSON.stringify(K ?? null), A = JSON.stringify(F ?? null);
39
+ t.useLayoutEffect(() => {
40
+ const n = r.current;
41
+ n && Object.assign(n, {
42
+ apiKey: l,
43
+ platformUuid: c,
44
+ sessionId: u,
45
+ clientSecret: i,
46
+ language: y,
47
+ fieldInputStyle: m,
48
+ paymentMethods: s.current.paymentMethods,
49
+ customstyles: s.current.customstyles,
50
+ inputStyle: s.current.inputStyle,
51
+ fonts: s.current.fonts,
52
+ enableEmailCollection: S,
53
+ enableSaveCard: f,
54
+ merchantName: p,
55
+ countryCode: b,
56
+ elementsUrl: d,
57
+ onPaymentSubmission: a.onPaymentSubmission ? e.onPaymentSubmission : void 0,
58
+ onPaymentSuccess: e.onPaymentSuccess,
59
+ onPaymentFailed: e.onPaymentFailed,
60
+ onReady: e.onReady,
61
+ onChange: e.onChange,
62
+ onError: e.onError
63
+ });
64
+ }, [
65
+ l,
66
+ c,
67
+ u,
68
+ i,
69
+ y,
70
+ m,
71
+ M,
72
+ O,
73
+ A,
74
+ R,
75
+ S,
76
+ f,
77
+ p,
78
+ b,
79
+ d,
80
+ !!a.onPaymentSubmission,
81
+ e
82
+ ]);
83
+ const J = t.useCallback(
84
+ (n) => {
85
+ r.current = n, typeof o == "function" ? o(n) : o && (o.current = n);
86
+ },
87
+ [o]
88
+ );
89
+ return t.createElement(v, {
90
+ ref: J,
91
+ class: g,
92
+ style: h
93
+ });
94
+ });
95
+ export {
96
+ U as StrablCardPaymentForm
97
+ };
@@ -0,0 +1 @@
1
+ var StrablElementsBundle=(function(){"use strict";var xe=Object.defineProperty;var ke=(p,h,f)=>h in p?xe(p,h,{enumerable:!0,configurable:!0,writable:!0,value:f}):p[h]=f;var o=(p,h,f)=>ke(p,typeof h!="symbol"?h+"":h,f);const h="strabl-elements";function f(e,t){return{source:h,v:1,type:e,payload:t}}const c=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),m=(e,t=2048)=>typeof e=="string"&&e.length<=t,b=e=>typeof e=="boolean",S=(e,t=2048)=>e===void 0||m(e,t),G=["cardHolderName","cardNumber","expiry","cvc"],K=["card","applepay","googlepay","tabby","tamara"],E=e=>G.includes(e),g=e=>m(e,64)&&/^[\w-]+$/.test(e),Y=/^[\w-]{1,128}$/,J=/^[!-~]{1,512}$/;function M(e){return c(e)&&typeof e.sessionId=="string"&&Y.test(e.sessionId)&&typeof e.clientSecret=="string"&&J.test(e.clientSecret)}const Z=e=>e==="TABBY"||e==="TAMARA",Q=e=>e===void 0||g(e),v=e=>c(e)&&m(e.status,40)&&S(e.orderShortCode,64)&&S(e.paymentReference,128)&&S(e.threeDsUrl,4096)&&(e.amount===void 0||typeof e.amount=="number"&&Number.isFinite(e.amount))&&S(e.currency,3);function X(e){if(!Q(e.requestId))return!1;switch(e.status){case"success":return m(e.orderShortCode,64)&&v(e.transaction);case"requires_action":return m(e.url,4096)&&v(e.transaction)&&(e.provider===void 0||Z(e.provider));case"failed":return m(e.code,64)&&m(e.message,500)&&(e.transaction===void 0||v(e.transaction));default:return!1}}const ee={hello:e=>c(e)&&g(e.instanceId),ready:e=>c(e)&&Array.isArray(e.paymentMethods),change:e=>c(e)&&(e.brand===null||m(e.brand,32))&&b(e.empty)&&b(e.complete)&&c(e.errors)&&Object.keys(e.errors).every(E)&&(e.paymentMethod===void 0||K.includes(e.paymentMethod)),focus:e=>c(e)&&E(e.field),blur:e=>c(e)&&E(e.field),resize:e=>c(e)&&typeof e.height=="number"&&e.height>=0&&e.height<1e4,processing:e=>c(e)&&b(e.active),beforeSubmit:e=>c(e)&&g(e.requestId),overlay:e=>c(e)&&b(e.open),result:e=>c(e)&&X(e),error:e=>c(e)&&m(e.code,64)&&m(e.message,500)};function te(e,t){return!c(e)||e.source!==h||e.v!==1||typeof e.type!="string"||!Object.hasOwn(t,e.type)?null:t[e.type](e.payload)?e:null}const L=e=>te(e,ee),re={sandbox:"https://sandbox.payments.strabl.io",prod:"https://payments.strabl.io"},se="/v1/card-form/index.html";function ne(e){return e.startsWith("pk_live_")?"prod":"sandbox"}const oe=["paymentStatus","orderId","payment_id"],ie=new Set(["approved","authorised","authorized","captured","fully_captured","success","succeeded","paid","closed"]),ae=new Set(["declined","rejected","failed","failure","error","expired"]),le=new Set(["canceled","cancelled","cancel"]);function ce(e){for(const t of["paymentStatus","status"]){const r=e.get(t)?.trim().toLowerCase();if(r){if(ie.has(r))return"success";if(ae.has(r))return"failed";if(le.has(r))return"cancelled"}}return"unknown"}function de(e){return e.has("paymentStatus")||e.has("payment_id")}function ue(e){if(!e)return null;try{const t=JSON.parse(e);if(typeof t=="object"&&t!==null){const r=t;return typeof r.sessionId!="string"?null:{sessionId:r.sessionId,provider:r.provider==="TABBY"||r.provider==="TAMARA"?r.provider:void 0,orderShortCode:typeof r.orderShortCode=="string"&&r.orderShortCode.length<=64?r.orderShortCode:void 0}}}catch{}return{sessionId:e}}function N(e,t,r){const s=e?.sessionId===t?e:null;if(de(r)||s?.provider&&r.has("status"))return{provider:s?.provider,status:ce(r),orderShortCode:s?.orderShortCode}}function I(e){const t={sessionId:e.sessionId??"",clientSecret:e.clientSecret??""};return M(t)?t:null}function F(e){return{language:e.language==="ar"?"ar":"en",fieldInputStyle:e.fieldInputStyle==="floating-label"?"floating-label":"outlined",paymentMethods:e.paymentMethods?.length?e.paymentMethods:["card"],customstyles:e.customstyles??{},style:e.inputStyle??{},fonts:e.fonts??[],applePay:me(e),enableEmailCollection:e.enableEmailCollection??!0,enableSaveCard:e.enableSaveCard??!0}}const he=64;function me(e){const t=e.merchantName?.trim(),r=e.countryCode?.trim().toUpperCase();return r&&!/^[A-Z]{2}$/.test(r)&&console.warn(`[strabl] ignored countryCode "${e.countryCode}": use a two-letter ISO 3166 code such as "SA"`),{label:t?t.slice(0,he):void 0,countryCode:r&&/^[A-Z]{2}$/.test(r)?r:void 0}}const fe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function pe(e){const t=e?.trim();return t?fe.test(t)?t:(console.warn(`[strabl] ignored platformUuid "${e}": expected a uuid such as 4038344c-6f04-4fce-bff9-780853587386`),null):null}function ye(e){return e.apiKey?I(e)?null:"sessionId and clientSecret are required: create the session on your server with your secret key, then pass both to the form":"apiKey is required"}const we=["amount","currencyCode","sessionToken","amountSignature"];function be(e){const t=we.filter(r=>r in e);t.length&&console.warn(`[strabl] ignored ${t.join(", ")}: the amount now comes from the session your server creates`)}const C="strabl-elements:awaiting-payer",Se=["key","isStrablAuth","status","orderShortCode","reason",...oe],Ee=2e4,ge=12e4,ve=120,Ie=440,Ce=540,Re=770,U=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;class x{constructor(t,r,s,n){o(this,"events");o(this,"options");o(this,"mode");o(this,"iframe");o(this,"elementsOrigin");o(this,"instanceId",U());o(this,"port",null);o(this,"helloTimer");o(this,"pendingSubmit",!1);o(this,"viewportWidth",0);o(this,"resizeFrame",0);o(this,"savedFrameStyle",null);o(this,"resuming",!1);o(this,"savedRootOverflow","");o(this,"overlayPlaceholder",null);o(this,"session");o(this,"connected");o(this,"ready",new Promise(t=>this.connected=t));o(this,"waiters",new Map);o(this,"onPageShow",t=>{t.persisted&&(R(),this.post("clear",{}))});o(this,"onWindowResize",()=>{cancelAnimationFrame(this.resizeFrame),this.resizeFrame=requestAnimationFrame(()=>{const t=window.innerWidth;t!==this.viewportWidth&&(this.viewportWidth=t,this.post("viewport",{width:t}))})});o(this,"onWindowMessage",t=>{if(t.origin!==this.elementsOrigin||t.source!==this.iframe.contentWindow)return;const r=L(t.data);r?.type!=="hello"||r.payload.instanceId!==this.instanceId||this.connect()});this.events=r,this.options=s,this.mode=n;const i=ne(s.apiKey);this.elementsOrigin=new URL(s.elementsUrl??re[i]).origin,this.session=I(s),this.iframe=this.createFrame(),window.addEventListener("message",this.onWindowMessage),window.addEventListener("resize",this.onWindowResize),window.addEventListener("pageshow",this.onPageShow),t.appendChild(this.iframe),this.helloTimer=setTimeout(()=>{this.emitError("frame_load_timeout","The payment form did not load.")},Ee)}update(t){this.options=t;const r=I(t);r&&(this.session=r),this.post("update",{...F(t),session:r??void 0,hasBeforeSubmit:!!t.onPaymentSubmission})}submit(){if(!this.port){this.pendingSubmit=!0;return}this.post("submit",{})}async request(t,r){if(await this.ready,this.waiters.size)throw new Error("A payment is already in progress.");r&&(this.session=r);const s=U(),n=t==="resume"&&this.session?N(k(),this.session.sessionId,q()):void 0;return new Promise((i,a)=>{const y=setTimeout(()=>{this.waiters.delete(s),a(new Error("The payment timed out."))},ge);this.waiters.set(s,{resolve:i,reject:a,timer:y}),t==="resume"?this.post("resume",{requestId:s,session:r,providerReturn:n}):this.post("submit",{requestId:s,session:r})})}focus(t){this.iframe.focus(),this.post("focus",{field:t})}refresh(){this.post("refresh",{})}clear(){this.post("clear",{})}destroy(){clearTimeout(this.helloTimer),window.removeEventListener("message",this.onWindowMessage),window.removeEventListener("resize",this.onWindowResize),window.removeEventListener("pageshow",this.onPageShow),cancelAnimationFrame(this.resizeFrame),this.setOverlay(!1);for(const t of this.waiters.values())clearTimeout(t.timer),t.reject(new Error("The card form was removed."));this.waiters.clear(),this.port?.close(),this.port=null,this.iframe.remove()}createFrame(){const t=new URL(se,this.elementsOrigin);t.searchParams.set("key",this.options.apiKey),t.searchParams.set("origin",window.location.origin),t.searchParams.set("id",this.instanceId),t.searchParams.set("v",String(1));const r=pe(this.options.platformUuid);r&&t.searchParams.set("platform",r);const s=document.createElement("iframe");s.src=t.toString(),s.title="Secure card payment",s.allow="payment",s.referrerPolicy="origin",s.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox");const n=window.innerWidth<Re?Ce:Ie;return s.style.cssText=`display:block;width:100%;height:${n}px;border:0;overflow:hidden;background:transparent;color-scheme:normal;`,s}connect(){clearTimeout(this.helloTimer),this.port?.close();const t=new MessageChannel;this.port=t.port1,this.port.onmessage=y=>{const w=L(y.data);w&&this.handle(w)};const r=this.session??void 0,s=this.mode.autoRedirect?k():null;let n=r!==void 0&&s?.sessionId===r.sessionId,i;n&&r&&s?.provider&&(i=N(s,r.sessionId,q()),i||(n=!1,R()));const a={...F(this.options),session:r,hasBeforeSubmit:!!this.options.onPaymentSubmission,viewportWidth:this.viewportWidth=window.innerWidth,resume:n,providerReturn:i,page:Oe()};this.resuming=a.resume,this.iframe.contentWindow?.postMessage(f("init",a),this.elementsOrigin,[t.port2]),this.connected(),this.pendingSubmit&&(this.pendingSubmit=!1,this.submit())}async handle(t){const r=this.options;switch(t.type){case"hello":return;case"ready":r.onReady?.(t.payload.paymentMethods),this.emit("strablReady",t.payload.paymentMethods);return;case"change":r.onChange?.(t.payload),this.emit("strablChange",t.payload);return;case"focus":case"blur":this.emit(t.type==="focus"?"strablFocus":"strablBlur",t.payload.field);return;case"resize":this.savedFrameStyle===null&&(this.iframe.style.height=`${Math.max(ve,Math.ceil(t.payload.height))}px`);return;case"overlay":this.setOverlay(t.payload.open);return;case"processing":this.emit("strablProcessing",t.payload.active);return;case"beforeSubmit":{let s=!0;if(r.onPaymentSubmission)try{s=!!await r.onPaymentSubmission()}catch(n){console.error("[strabl] onPaymentSubmission threw:",n),s=!1}this.post("beforeSubmitResult",{requestId:t.payload.requestId,proceed:s});return}case"result":{const{requestId:s,...n}=t.payload,i=s?this.waiters.get(s):void 0;i&&s&&(clearTimeout(i.timer),this.waiters.delete(s),i.resolve(n)),this.dispatchResult(n);return}case"error":this.emitError(t.payload.code,t.payload.message);return}}dispatchResult(t){const r=this.options;switch(this.emit("strablResult",t),t.status){case"success":this.finishReturn(),r.onPaymentSuccess?.(t.orderShortCode,t.transaction),this.emit("strablPaymentSuccess",t.orderShortCode);return;case"requires_action":t.provider&&W({sessionId:this.session?.sessionId??"",provider:t.provider,orderShortCode:t.transaction.orderShortCode}),(this.mode.autoRedirect||t.provider)&&this.redirect(t.url,!t.provider);return;case"failed":this.finishReturn(),r.onPaymentFailed?.(t.message,t.code),this.emit("strablPaymentFailed",t.message);return}}post(t,r){this.port?.postMessage(f(t,r))}redirect(t,r){let s;try{s=new URL(t)}catch{return}const n=this.elementsOrigin.startsWith("http://")||Te(s.hostname);if(s.protocol!=="https:"&&!(n&&s.protocol==="http:")){this.emitError("invalid_redirect","The verification page is not secure.");return}this.session&&r&&W({sessionId:this.session.sessionId}),window.location.assign(s.toString())}finishReturn(){if(R(),!this.resuming)return;this.resuming=!1;const t=new URL(window.location.href);Se.forEach(r=>t.searchParams.delete(r)),window.history.replaceState(window.history.state,"",t.toString())}setOverlay(t){const r=document.documentElement;if(t&&this.savedFrameStyle===null){const s=document.createElement("div");s.style.cssText=`display:block;height:${this.iframe.offsetHeight}px;`,s.setAttribute("aria-hidden","true"),this.iframe.before(s),this.overlayPlaceholder=s,this.savedFrameStyle=this.iframe.style.cssText,this.savedRootOverflow=r.style.overflow,this.iframe.style.cssText="position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647;background:transparent;color-scheme:normal;",r.style.overflow="hidden"}else!t&&this.savedFrameStyle!==null&&(this.iframe.style.cssText=this.savedFrameStyle,r.style.overflow=this.savedRootOverflow,this.savedFrameStyle=null,this.overlayPlaceholder?.remove(),this.overlayPlaceholder=null)}emitError(t,r){this.options.onError?.(t,r),this.emit("strablError",{code:t,message:r})}emit(t,r){this.events.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!0,composed:!0}))}}function k(){try{return ue(sessionStorage.getItem(C))}catch{return null}}function W(e){if(e.sessionId)try{sessionStorage.setItem(C,JSON.stringify(e))}catch{}}function q(){return new URL(window.location.href).searchParams}function R(){try{sessionStorage.removeItem(C)}catch{}}function B(e){try{const t=new URL(e);return t.origin+t.pathname}catch{return}}function Oe(){return{href:B(window.location.href),referrer:document.referrer?B(document.referrer):void 0}}function Te(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}const O="strabl-card-form",H="strabl-submit-card-form",$=["apiKey","platformUuid","sessionId","clientSecret","language","fieldInputStyle","paymentMethods","customstyles","inputStyle","fonts","enableEmailCollection","enableSaveCard","merchantName","countryCode","elementsUrl","onPaymentSubmission","onPaymentSuccess","onPaymentFailed","onReady","onChange","onError"],D={apikey:"apiKey",platformuuid:"platformUuid",sessionid:"sessionId",clientsecret:"clientSecret",language:"language",fieldinputstyle:"fieldInputStyle",enableemailcollection:"enableEmailCollection",enablesavecard:"enableSaveCard",merchantname:"merchantName",countrycode:"countryCode",elementsurl:"elementsUrl"},Ae=new Set(["enableEmailCollection","enableSaveCard"]),Pe=typeof HTMLElement>"u"?class{}:HTMLElement;class T extends Pe{constructor(){super();o(this,"root");o(this,"status");o(this,"opts",{});o(this,"controller",null);o(this,"scheduled",!1);o(this,"onLegacySubmit",()=>{this.submit()});this.root=this.attachShadow({mode:"closed"});const r=document.createElement("style");r.textContent=":host{display:block}p{margin:0;font:14px/1.4 system-ui,sans-serif;color:#b42318}p:empty{display:none}",this.status=document.createElement("p"),this.status.setAttribute("role","alert"),this.root.append(r,this.status)}static get observedAttributes(){return Object.keys(D)}connectedCallback(){for(const r of $)if(Object.hasOwn(this,r)){const s=this[r];delete this[r],this.set(r,s)}be(this),window.addEventListener(H,this.onLegacySubmit),this.schedule()}disconnectedCallback(){window.removeEventListener(H,this.onLegacySubmit),this.controller?.destroy(),this.controller=null}attributeChangedCallback(r,s,n){const i=D[r];if(!i)return;const a=Ae.has(i)?n!=="false":n??void 0;this.set(i,a)}submit(){this.controller?.submit()}refresh(){this.controller?.refresh()}set(r,s){this.opts[r]!==s&&(this.opts={...this.opts,[r]:s},this.schedule())}schedule(){this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1,this.sync()}))}sync(){if(!this.isConnected)return;const r=ye(this.opts);if(r){this.controller||(this.status.textContent="The payment form could not be loaded.",console.error(`[strabl] ${r}`));return}this.status.textContent="";const s=this.opts;this.controller?this.controller.update(s):this.controller=new x(this.root,this,s,{autoRedirect:!0})}}for(const e of $)Object.defineProperty(T.prototype,e,{configurable:!0,enumerable:!0,get(){return this.opts[e]},set(t){this.set(e,t)}});function z(){typeof customElements<"u"&&!customElements.get(O)&&customElements.define(O,T)}class A extends Error{constructor(r,s,n){super(s);o(this,"code");o(this,"transaction");this.code=r,this.transaction=n,this.name="StrablError"}}const _e={name:"cardHolderName",number:"cardNumber",expiry:"expiry",cvv:"cvc",cardHolderName:"cardHolderName",cardNumber:"cardNumber",cvc:"cvc"},P={ready:"strablReady",change:"strablChange",focus:"strablFocus",blur:"strablBlur",result:"strablResult",error:"strablError"};function Me(e,t={}){if(!/^pk_(live|test)_/.test(e??""))throw new Error("StrablElements: a publishable key (pk_…) is required");return{create(r,s={}){if(r!=="card")throw new Error(`StrablElements: unsupported element type "${r}"`);return Le(e,t,s)}}}function Le(e,t,r){const s=new EventTarget;let n=null,i=null,a=r;const y=()=>({apiKey:e,platformUuid:t.platformUuid,elementsUrl:t.elementsUrl,language:a.language??t.language,fieldInputStyle:a.fieldInputStyle,paymentMethods:a.paymentMethods,customstyles:a.customstyles,inputStyle:a.style,fonts:a.fonts,enableEmailCollection:a.enableEmailCollection,enableSaveCard:a.enableSaveCard,merchantName:a.merchantName,countryCode:a.countryCode,sessionId:a.session?.sessionId,clientSecret:a.session?.clientSecret});s.addEventListener(P.result,l=>{const d=l.detail;d.status==="failed"&&s.dispatchEvent(new CustomEvent(P.error,{detail:{code:d.code,message:d.message}}))});async function w(l,d){if(!i)throw new Error("StrablElements: mount the card element first");if(!M(d))throw new Error("StrablElements: sessionId and clientSecret are required");const u=await i.request(l,{sessionId:d.sessionId,clientSecret:d.clientSecret});switch(u.status){case"success":return u.transaction;case"requires_action":return{...u.transaction,threeDsUrl:u.url,...u.provider?{provider:u.provider}:{}};case"failed":throw new A(u.code,u.message,u.transaction)}}return{mount(l){if(i)throw new Error("StrablElements: this card element is already mounted");const d=typeof l=="string"?document.querySelector(l):l;if(!d)throw new Error(`StrablElements: mount target "${l}" was not found`);n=document.createElement("div"),n.className="strabl-card-element";const u=n.attachShadow({mode:"closed"});d.appendChild(n),i=new x(u,s,y(),{autoRedirect:!1})},on(l,d){const u=P[l];if(!u)throw new Error(`StrablElements: unknown event "${l}"`);const V=Fe=>{const _=Fe.detail;try{d(l==="error"?new A(_.code,_.message):_)}catch(Ue){console.error("[strabl] listener failed",Ue)}};return s.addEventListener(u,V),()=>s.removeEventListener(u,V)},confirm:l=>w("submit",l),resume:l=>w("resume",l),focus(l){const d=_e[l];d&&i?.focus(d)},clear(){i?.clear()},update(l){a={...a,...l},i?.update(y())},refresh(){i?.refresh()},destroy(){i?.destroy(),i=null,n?.remove(),n=null}}}function Ne(e){if(typeof document>"u")throw new Error("strablCardForm can only be called in a browser");z();const t=document.querySelector(e.selector);if(!t)throw new Error(`strablCardForm: no element matched selector "${e.selector}"`);const r=document.createElement(O),{selector:s,replace:n,...i}=e;return Object.assign(r,i),n?t.replaceChildren(r):t.appendChild(r),{element:r,update:a=>Object.assign(r,a),submit:()=>r.submit(),refresh:()=>r.refresh(),destroy:()=>r.remove()}}z();const j=Object.assign(Me,{strablCardForm:Ne,StrablCardForm:T,StrablError:A});return typeof window<"u"&&(window.StrablElements=j),j})();
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Script-tag build: `<script src="https://js.strabl.io/v1/strabl-elements.js">`
3
+ * defines `<strabl-card-form>` and exposes `window.StrablElements`, which is
4
+ * both the contract's factory (`StrablElements("pk_…")`) and, for v1-style
5
+ * pages, the holder of `strablCardForm` and `StrablCardForm`.
6
+ */
7
+ import { StrablCardForm } from "./element.js";
8
+ import { StrablElements, StrablError } from "./elements.js";
9
+ import { strablCardForm } from "./mount.js";
10
+ declare const api: typeof StrablElements & {
11
+ strablCardForm: typeof strablCardForm;
12
+ StrablCardForm: typeof StrablCardForm;
13
+ StrablError: typeof StrablError;
14
+ };
15
+ declare global {
16
+ interface Window {
17
+ StrablElements?: typeof api;
18
+ }
19
+ }
20
+ export default api;
@@ -0,0 +1,77 @@
1
+ import { type FieldName, type PaymentResult, type SessionCredentials } from "./protocol/index.js";
2
+ import { type CardFormOptions } from "./options.js";
3
+ export interface ControllerMode {
4
+ /**
5
+ * Element and React: follow the 3DS redirect and resume when the payer
6
+ * comes back. StrablElements: hand the URL to the merchant instead.
7
+ */
8
+ autoRedirect: boolean;
9
+ }
10
+ /**
11
+ * Owns one hosted-form iframe: creates it, performs the origin-checked
12
+ * handshake, and turns frame messages into callbacks and DOM events.
13
+ * It never sees card data; only the iframe does.
14
+ */
15
+ export declare class FrameController {
16
+ private readonly events;
17
+ private options;
18
+ private readonly mode;
19
+ readonly iframe: HTMLIFrameElement;
20
+ private readonly elementsOrigin;
21
+ private readonly instanceId;
22
+ private port;
23
+ private helloTimer;
24
+ private pendingSubmit;
25
+ private viewportWidth;
26
+ private resizeFrame;
27
+ private savedFrameStyle;
28
+ /** This page load is the return from 3DS, so its URL carries return parameters. */
29
+ private resuming;
30
+ private savedRootOverflow;
31
+ /** Holds the iframe's place in the page while it covers the viewport. */
32
+ private overlayPlaceholder;
33
+ /** The session the last payment ran under, remembered for the 3DS return. */
34
+ private session;
35
+ private connected;
36
+ private readonly ready;
37
+ private readonly waiters;
38
+ constructor(container: Node, events: EventTarget, options: CardFormOptions, mode: ControllerMode);
39
+ update(options: CardFormOptions): void;
40
+ /** Same as the pay button: invalid input is shown in the form, no result is sent. */
41
+ submit(): void;
42
+ /**
43
+ * Confirms or resumes a session and resolves with the outcome. Card or
44
+ * session problems resolve as `failed`; only SDK misuse rejects.
45
+ */
46
+ request(type: "submit" | "resume", session?: SessionCredentials): Promise<PaymentResult>;
47
+ focus(field: FieldName): void;
48
+ /** Makes the frame read the session's summary again. */
49
+ refresh(): void;
50
+ clear(): void;
51
+ destroy(): void;
52
+ private createFrame;
53
+ /**
54
+ * Back from 3DS or a provider's page with the browser's Back button, the
55
+ * page is restored as it was left: still "redirecting". Reopen the form.
56
+ */
57
+ private onPageShow;
58
+ /** Keeps the form's breakpoints tied to the merchant's window width. */
59
+ private onWindowResize;
60
+ private onWindowMessage;
61
+ /** Runs on every `hello`, so a reloaded frame gets a fresh channel. */
62
+ private connect;
63
+ private handle;
64
+ private dispatchResult;
65
+ private post;
66
+ /** Sends the payer to 3DS or the provider; the return page resumes the same session. */
67
+ private redirect;
68
+ private finishReturn;
69
+ /**
70
+ * Covers the viewport with the iframe while the frame shows a 3DS
71
+ * challenge or Apple's in-page Apple Pay sheet. A placeholder keeps the
72
+ * iframe's height in the page, so the page neither shrinks nor scrolls.
73
+ */
74
+ private setOverlay;
75
+ private emitError;
76
+ private emit;
77
+ }
@@ -0,0 +1,42 @@
1
+ import { type CardFormOptions } from "./options.js";
2
+ export declare const TAG_NAME = "strabl-card-form";
3
+ declare const BaseElement: typeof HTMLElement;
4
+ /**
5
+ * `<strabl-card-form>`: a thin host for the Strabl iframe. It holds no card
6
+ * data and sets no amount: it pays the session your server created
7
+ * (`sessionId` + `clientSecret`).
8
+ * After a 3DS redirect it resumes that session by itself.
9
+ */
10
+ export declare class StrablCardForm extends BaseElement {
11
+ static get observedAttributes(): string[];
12
+ private readonly root;
13
+ private readonly status;
14
+ private opts;
15
+ private controller;
16
+ private scheduled;
17
+ constructor();
18
+ connectedCallback(): void;
19
+ disconnectedCallback(): void;
20
+ attributeChangedCallback(name: string, _old: string | null, value: string | null): void;
21
+ /** Submits the payment, same as clicking the pay button. */
22
+ submit(): void;
23
+ /**
24
+ * Reads the session again, e.g. after your server changed its amount with
25
+ * `POST /sessions/{id}/amount`. The form shows the new amount.
26
+ */
27
+ refresh(): void;
28
+ private onLegacySubmit;
29
+ private set;
30
+ /** Batches property changes made in the same task into one update. */
31
+ private schedule;
32
+ private sync;
33
+ }
34
+ export interface StrablCardForm extends Partial<CardFormOptions> {
35
+ }
36
+ export declare function defineStrablCardForm(): void;
37
+ declare global {
38
+ interface HTMLElementTagNameMap {
39
+ [TAG_NAME]: StrablCardForm;
40
+ }
41
+ }
42
+ export {};
@@ -0,0 +1,86 @@
1
+ import type { CardFormChange } from "./options.js";
2
+ import { type ElementStyle, type FieldInputStyle, type FieldName, type FontSource, type Language, type PaymentMethod, type PaymentResult, type SessionCredentials, type StyleTokens, type Transaction } from "./protocol/index.js";
3
+ /**
4
+ * The Stripe-style API from the DirectPay Elements contract:
5
+ *
6
+ * ```js
7
+ * const elements = StrablElements("pk_live_…");
8
+ * const card = elements.create("card", { style: { base: { color: "#0f172a" } } });
9
+ * card.mount("#card");
10
+ * const tx = await card.confirm({ sessionId, clientSecret });
11
+ * ```
12
+ *
13
+ * The amount is not an argument anywhere: `confirm` pays the session that
14
+ * the merchant's backend created with its secret key.
15
+ */
16
+ export interface StrablElementsOptions {
17
+ /** Override the hosted page origin, e.g. `http://localhost:5173` in development. */
18
+ elementsUrl?: string;
19
+ /** Your platform uuid: the form reads its SDK styling sooner. Optional. */
20
+ platformUuid?: string;
21
+ language?: Language;
22
+ }
23
+ export interface CardElementOptions {
24
+ /** Per-state input styles: `{ base, focus, invalid, placeholder }`. */
25
+ style?: ElementStyle;
26
+ customstyles?: StyleTokens;
27
+ fonts?: FontSource[];
28
+ language?: Language;
29
+ fieldInputStyle?: FieldInputStyle;
30
+ paymentMethods?: PaymentMethod[];
31
+ /** Ask for the payer's email and offer saved cards. Defaults to true. */
32
+ enableEmailCollection?: boolean;
33
+ /** Offer to save a new card. Defaults to true. */
34
+ enableSaveCard?: boolean;
35
+ /**
36
+ * The session to show and pay. Needed up front for Apple Pay, whose sheet
37
+ * opens from a button inside the form and shows the session's amount;
38
+ * cards can also receive it with confirm().
39
+ */
40
+ session?: SessionCredentials;
41
+ /** Your business name on the Apple Pay sheet; defaults to your host name. */
42
+ merchantName?: string;
43
+ /** Your country, ISO 3166 alpha-2 ("SA"), for the Apple Pay sheet. */
44
+ countryCode?: string;
45
+ }
46
+ /** Rejection from confirm/resume, and the payload of the `error` event. */
47
+ export declare class StrablError extends Error {
48
+ readonly code: string;
49
+ readonly transaction?: Transaction | undefined;
50
+ constructor(code: string, message: string, transaction?: Transaction | undefined);
51
+ }
52
+ export interface CardElementEvents {
53
+ ready: PaymentMethod[];
54
+ change: CardFormChange;
55
+ focus: FieldName;
56
+ blur: FieldName;
57
+ result: PaymentResult;
58
+ error: StrablError;
59
+ }
60
+ export type CardElementEventName = keyof CardElementEvents;
61
+ /** The contract's field names, and the form's own. */
62
+ export type CardField = "name" | "number" | "expiry" | "cvv" | FieldName;
63
+ export interface CardElement {
64
+ mount(target: string | HTMLElement): void;
65
+ on<E extends CardElementEventName>(event: E, listener: (payload: CardElementEvents[E]) => void): () => void;
66
+ /**
67
+ * Charges the session. Resolves with the transaction; when it is
68
+ * `AUTHORIZED` with a `threeDsUrl`, send the payer there and call
69
+ * `resume` when they return. Tabby and Tamara buttons redirect by
70
+ * themselves; call `resume` on the return page for those too: it settles
71
+ * from the status the provider put on the URL. Rejects with a {@link StrablError}.
72
+ */
73
+ confirm(session: SessionCredentials): Promise<Transaction>;
74
+ /** Finishes the session after 3-D Secure. Needs no card data. */
75
+ resume(session: SessionCredentials): Promise<Transaction>;
76
+ focus(field: CardField): void;
77
+ clear(): void;
78
+ update(options: CardElementOptions): void;
79
+ /** Reads the session again, e.g. after your server changed its amount. */
80
+ refresh(): void;
81
+ destroy(): void;
82
+ }
83
+ export interface StrablElementsInstance {
84
+ create(type: "card", options?: CardElementOptions): CardElement;
85
+ }
86
+ export declare function StrablElements(publishableKey: string, options?: StrablElementsOptions): StrablElementsInstance;
@@ -0,0 +1,7 @@
1
+ export { StrablCardForm, defineStrablCardForm, TAG_NAME } from "./element.js";
2
+ export { strablCardForm } from "./mount.js";
3
+ export { StrablElements, StrablError } from "./elements.js";
4
+ export type { LoadCardFormOptions, LoadedCardForm } from "./mount.js";
5
+ export type { CardElement, CardElementEventName, CardElementEvents, CardElementOptions, CardField, StrablElementsInstance, StrablElementsOptions, } from "./elements.js";
6
+ export type { CardFormOptions, CardFormChange, PaymentSuccessDetails, } from "./options.js";
7
+ export type { ElementStyle, FieldInputStyle, FontSource, Language, PaymentMethod, PaymentResult, SessionCredentials, StyleTokens, Transaction, } from "./protocol/index.js";
@@ -0,0 +1,16 @@
1
+ import { StrablCardForm } from "./element.js";
2
+ import type { CardFormOptions } from "./options.js";
3
+ export interface LoadCardFormOptions extends CardFormOptions {
4
+ selector: string;
5
+ /** Replace the target's children instead of appending. */
6
+ replace?: boolean;
7
+ }
8
+ export interface LoadedCardForm {
9
+ element: StrablCardForm;
10
+ update: (options: Partial<CardFormOptions>) => void;
11
+ submit: () => void;
12
+ /** Reads the session again, e.g. after your server changed its amount. */
13
+ refresh: () => void;
14
+ destroy: () => void;
15
+ }
16
+ export declare function strablCardForm(options: LoadCardFormOptions): LoadedCardForm;
@@ -0,0 +1,85 @@
1
+ import { type DisplayOptions, type ElementStyle, type FieldInputStyle, type FontSource, type Language, type PaymentMethod, type SessionCredentials, type StyleTokens, type Transaction } from "./protocol/index.js";
2
+ /** The transaction behind a successful payment, as the API reported it. */
3
+ export type PaymentSuccessDetails = Transaction;
4
+ export interface CardFormChange {
5
+ brand: string | null;
6
+ empty: boolean;
7
+ /**
8
+ * Whether the selected method can be paid: the card fields (or the saved
9
+ * card's CVC) are valid, or Tabby / Tamara have the phone (and email) they need.
10
+ */
11
+ complete: boolean;
12
+ /** Card field errors; Tabby / Tamara show theirs in the form only. */
13
+ errors: Record<string, string>;
14
+ /** The method the payer selected: "card", "tabby" or "tamara". */
15
+ paymentMethod?: PaymentMethod;
16
+ }
17
+ /**
18
+ * Options shared by the custom element, strablCardForm and the React wrapper.
19
+ *
20
+ * The amount is not an option. Your backend creates a session with its secret
21
+ * key (`POST /v1/api/direct/sessions`) and passes `sessionId` and
22
+ * `clientSecret` to the page; the charge is whatever that session says.
23
+ */
24
+ export interface CardFormOptions {
25
+ /** Publishable key (`pk_live_…` or `pk_test_…`). */
26
+ apiKey: string;
27
+ /**
28
+ * Your platform uuid, from the dashboard. Optional: with it, the form reads
29
+ * your platform's SDK settings (`sdkCustomization`) while the session loads,
30
+ * instead of after. Payment methods and saving cards set there win over
31
+ * `paymentMethods`, `enableEmailCollection` and `enableSaveCard`; its
32
+ * language is the starting one, and a later change of `language` switches
33
+ * it. Tabby and Tamara are offered only when it lists them. Whatever it
34
+ * leaves unset comes from these options.
35
+ * Not a secret.
36
+ */
37
+ platformUuid?: string;
38
+ sessionId?: string;
39
+ /** Returned once by the session call. Never log it or put it in a URL. */
40
+ clientSecret?: string;
41
+ language?: Language;
42
+ fieldInputStyle?: FieldInputStyle;
43
+ paymentMethods?: PaymentMethod[];
44
+ customstyles?: StyleTokens;
45
+ /** Per-state input styles: `{ base, focus, invalid, placeholder }`. */
46
+ inputStyle?: ElementStyle;
47
+ /**
48
+ * Web fonts for `customstyles.fontFamily`. Fonts loaded by your page are not
49
+ * visible inside the iframe, so list them here: font files over HTTPS, or a
50
+ * Google Fonts stylesheet URL.
51
+ */
52
+ fonts?: FontSource[];
53
+ /**
54
+ * Ask for the payer's email (and find their saved cards with a one-time
55
+ * code). Defaults to true; false hides the email step.
56
+ */
57
+ enableEmailCollection?: boolean;
58
+ /**
59
+ * Offer to save a new card for faster checkout. Defaults to true; false
60
+ * never saves a new card, though saved cards are still offered.
61
+ */
62
+ enableSaveCard?: boolean;
63
+ /**
64
+ * Your business name, shown on the Apple Pay sheet's total line. Defaults
65
+ * to your page's host name. The amount is always the session's.
66
+ */
67
+ merchantName?: string;
68
+ /** Your country, ISO 3166 alpha-2 ("SA", "AE"), for the Apple Pay sheet. */
69
+ countryCode?: string;
70
+ onPaymentSubmission?: () => boolean | Promise<boolean>;
71
+ onPaymentSuccess?: (orderShortCode: string, details: PaymentSuccessDetails) => void;
72
+ onPaymentFailed?: (failureReason: string, code: string) => void;
73
+ onReady?: (paymentMethods: PaymentMethod[]) => void;
74
+ onChange?: (change: CardFormChange) => void;
75
+ onError?: (code: string, message: string) => void;
76
+ /** Override the hosted page origin, e.g. `http://localhost:5173` in development. */
77
+ elementsUrl?: string;
78
+ }
79
+ export declare function buildSession(opts: Pick<CardFormOptions, "sessionId" | "clientSecret">): SessionCredentials | null;
80
+ export declare function buildDisplayOptions(opts: Omit<CardFormOptions, "apiKey">): DisplayOptions;
81
+ /** The platform uuid if it is one; anything else is ignored with a warning. */
82
+ export declare function validPlatformUuid(value: string | undefined): string | null;
83
+ /** Explains why the options cannot start a payment, or returns null when they can. */
84
+ export declare function configError(opts: CardFormOptions): string | null;
85
+ export declare function warnRemovedOptions(opts: object): void;
@@ -0,0 +1,6 @@
1
+ export declare function isCurrencyCode(value: unknown): value is string;
2
+ export declare function currencyDecimals(currencyCode: string): number;
3
+ /** True when the amount is positive, finite and has no more decimals than the currency allows. */
4
+ export declare function isValidAmount(amount: unknown, currencyCode: string): boolean;
5
+ /** Amount as a fixed-decimal string in the currency's minor units, e.g. "12.500" for KWD. */
6
+ export declare function formatAmount(amount: number, currencyCode: string): string;