@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/README.md +287 -2
- package/dist/element-BbJGrJ33.js +610 -0
- package/dist/element-CZKsfyCs.cjs +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.js +169 -0
- package/dist/react.cjs +1 -0
- package/dist/react.js +97 -0
- package/dist/strabl-elements.js +1 -0
- package/dist/types/cdn.d.ts +20 -0
- package/dist/types/controller.d.ts +77 -0
- package/dist/types/element.d.ts +42 -0
- package/dist/types/elements.d.ts +86 -0
- package/dist/types/index.d.ts +7 -0
- package/dist/types/mount.d.ts +16 -0
- package/dist/types/options.d.ts +85 -0
- package/dist/types/protocol/currency.d.ts +6 -0
- package/dist/types/protocol/element-style.d.ts +29 -0
- package/dist/types/protocol/environments.d.ts +23 -0
- package/dist/types/protocol/fonts.d.ts +41 -0
- package/dist/types/protocol/index.d.ts +7 -0
- package/dist/types/protocol/styles.d.ts +6 -0
- package/dist/types/protocol/types.d.ts +276 -0
- package/dist/types/protocol/validate.d.ts +4 -0
- package/dist/types/provider-return.d.ts +32 -0
- package/dist/types/react/index.d.ts +14 -0
- package/package.json +49 -4
|
@@ -0,0 +1,610 @@
|
|
|
1
|
+
var N = Object.defineProperty;
|
|
2
|
+
var x = (e, t, s) => t in e ? N(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s;
|
|
3
|
+
var o = (e, t, s) => x(e, typeof t != "symbol" ? t + "" : t, s);
|
|
4
|
+
const L = "strabl-elements";
|
|
5
|
+
function g(e, t) {
|
|
6
|
+
return { source: L, v: 1, type: e, payload: t };
|
|
7
|
+
}
|
|
8
|
+
const a = (e) => typeof e == "object" && e !== null && !Array.isArray(e), l = (e, t = 2048) => typeof e == "string" && e.length <= t, d = (e) => typeof e == "boolean", u = (e, t = 2048) => e === void 0 || l(e, t), k = [
|
|
9
|
+
"cardHolderName",
|
|
10
|
+
"cardNumber",
|
|
11
|
+
"expiry",
|
|
12
|
+
"cvc"
|
|
13
|
+
], W = [
|
|
14
|
+
"card",
|
|
15
|
+
"applepay",
|
|
16
|
+
"googlepay",
|
|
17
|
+
"tabby",
|
|
18
|
+
"tamara"
|
|
19
|
+
], m = (e) => k.includes(e), y = (e) => l(e, 64) && /^[\w-]+$/.test(e), B = /^[\w-]{1,128}$/, H = /^[!-~]{1,512}$/;
|
|
20
|
+
function q(e) {
|
|
21
|
+
return a(e) && typeof e.sessionId == "string" && B.test(e.sessionId) && typeof e.clientSecret == "string" && H.test(e.clientSecret);
|
|
22
|
+
}
|
|
23
|
+
const $ = (e) => e === "TABBY" || e === "TAMARA", z = (e) => e === void 0 || y(e), f = (e) => a(e) && l(e.status, 40) && u(e.orderShortCode, 64) && u(e.paymentReference, 128) && u(e.threeDsUrl, 4096) && (e.amount === void 0 || typeof e.amount == "number" && Number.isFinite(e.amount)) && u(e.currency, 3);
|
|
24
|
+
function D(e) {
|
|
25
|
+
if (!z(e.requestId)) return !1;
|
|
26
|
+
switch (e.status) {
|
|
27
|
+
case "success":
|
|
28
|
+
return l(e.orderShortCode, 64) && f(e.transaction);
|
|
29
|
+
case "requires_action":
|
|
30
|
+
return l(e.url, 4096) && f(e.transaction) && (e.provider === void 0 || $(e.provider));
|
|
31
|
+
case "failed":
|
|
32
|
+
return l(e.code, 64) && l(e.message, 500) && (e.transaction === void 0 || f(e.transaction));
|
|
33
|
+
default:
|
|
34
|
+
return !1;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const V = {
|
|
38
|
+
hello: (e) => a(e) && y(e.instanceId),
|
|
39
|
+
ready: (e) => a(e) && Array.isArray(e.paymentMethods),
|
|
40
|
+
change: (e) => a(e) && (e.brand === null || l(e.brand, 32)) && d(e.empty) && d(e.complete) && a(e.errors) && Object.keys(e.errors).every(m) && (e.paymentMethod === void 0 || W.includes(e.paymentMethod)),
|
|
41
|
+
focus: (e) => a(e) && m(e.field),
|
|
42
|
+
blur: (e) => a(e) && m(e.field),
|
|
43
|
+
resize: (e) => a(e) && typeof e.height == "number" && e.height >= 0 && e.height < 1e4,
|
|
44
|
+
processing: (e) => a(e) && d(e.active),
|
|
45
|
+
beforeSubmit: (e) => a(e) && y(e.requestId),
|
|
46
|
+
overlay: (e) => a(e) && d(e.open),
|
|
47
|
+
result: (e) => a(e) && D(e),
|
|
48
|
+
error: (e) => a(e) && l(e.code, 64) && l(e.message, 500)
|
|
49
|
+
};
|
|
50
|
+
function j(e, t) {
|
|
51
|
+
return !a(e) || e.source !== L || e.v !== 1 || typeof e.type != "string" || !Object.hasOwn(t, e.type) ? null : t[e.type](e.payload) ? e : null;
|
|
52
|
+
}
|
|
53
|
+
const v = (e) => j(e, V), G = {
|
|
54
|
+
sandbox: "https://sandbox.payments.strabl.io",
|
|
55
|
+
prod: "https://payments.strabl.io"
|
|
56
|
+
}, K = "/v1/card-form/index.html";
|
|
57
|
+
function Y(e) {
|
|
58
|
+
return e.startsWith("pk_live_") ? "prod" : "sandbox";
|
|
59
|
+
}
|
|
60
|
+
const J = [
|
|
61
|
+
"paymentStatus",
|
|
62
|
+
"orderId",
|
|
63
|
+
"payment_id"
|
|
64
|
+
], Z = /* @__PURE__ */ new Set([
|
|
65
|
+
"approved",
|
|
66
|
+
"authorised",
|
|
67
|
+
"authorized",
|
|
68
|
+
"captured",
|
|
69
|
+
"fully_captured",
|
|
70
|
+
"success",
|
|
71
|
+
"succeeded",
|
|
72
|
+
"paid",
|
|
73
|
+
"closed"
|
|
74
|
+
]), Q = /* @__PURE__ */ new Set([
|
|
75
|
+
"declined",
|
|
76
|
+
"rejected",
|
|
77
|
+
"failed",
|
|
78
|
+
"failure",
|
|
79
|
+
"error",
|
|
80
|
+
"expired"
|
|
81
|
+
]), X = /* @__PURE__ */ new Set(["canceled", "cancelled", "cancel"]);
|
|
82
|
+
function ee(e) {
|
|
83
|
+
for (const t of ["paymentStatus", "status"]) {
|
|
84
|
+
const s = e.get(t)?.trim().toLowerCase();
|
|
85
|
+
if (s) {
|
|
86
|
+
if (Z.has(s)) return "success";
|
|
87
|
+
if (Q.has(s)) return "failed";
|
|
88
|
+
if (X.has(s)) return "cancelled";
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return "unknown";
|
|
92
|
+
}
|
|
93
|
+
function te(e) {
|
|
94
|
+
return e.has("paymentStatus") || e.has("payment_id");
|
|
95
|
+
}
|
|
96
|
+
function se(e) {
|
|
97
|
+
if (!e) return null;
|
|
98
|
+
try {
|
|
99
|
+
const t = JSON.parse(e);
|
|
100
|
+
if (typeof t == "object" && t !== null) {
|
|
101
|
+
const s = t;
|
|
102
|
+
return typeof s.sessionId != "string" ? null : {
|
|
103
|
+
sessionId: s.sessionId,
|
|
104
|
+
provider: s.provider === "TABBY" || s.provider === "TAMARA" ? s.provider : void 0,
|
|
105
|
+
orderShortCode: typeof s.orderShortCode == "string" && s.orderShortCode.length <= 64 ? s.orderShortCode : void 0
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
} catch {
|
|
109
|
+
}
|
|
110
|
+
return { sessionId: e };
|
|
111
|
+
}
|
|
112
|
+
function E(e, t, s) {
|
|
113
|
+
const r = e?.sessionId === t ? e : null;
|
|
114
|
+
if (te(s) || r?.provider && s.has("status"))
|
|
115
|
+
return {
|
|
116
|
+
provider: r?.provider,
|
|
117
|
+
status: ee(s),
|
|
118
|
+
orderShortCode: r?.orderShortCode
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
function w(e) {
|
|
122
|
+
const t = {
|
|
123
|
+
sessionId: e.sessionId ?? "",
|
|
124
|
+
clientSecret: e.clientSecret ?? ""
|
|
125
|
+
};
|
|
126
|
+
return q(t) ? t : null;
|
|
127
|
+
}
|
|
128
|
+
function I(e) {
|
|
129
|
+
return {
|
|
130
|
+
language: e.language === "ar" ? "ar" : "en",
|
|
131
|
+
fieldInputStyle: e.fieldInputStyle === "floating-label" ? "floating-label" : "outlined",
|
|
132
|
+
paymentMethods: e.paymentMethods?.length ? e.paymentMethods : ["card"],
|
|
133
|
+
customstyles: e.customstyles ?? {},
|
|
134
|
+
style: e.inputStyle ?? {},
|
|
135
|
+
fonts: e.fonts ?? [],
|
|
136
|
+
applePay: oe(e),
|
|
137
|
+
enableEmailCollection: e.enableEmailCollection ?? !0,
|
|
138
|
+
enableSaveCard: e.enableSaveCard ?? !0
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
const re = 64;
|
|
142
|
+
function oe(e) {
|
|
143
|
+
const t = e.merchantName?.trim(), s = e.countryCode?.trim().toUpperCase();
|
|
144
|
+
return s && !/^[A-Z]{2}$/.test(s) && console.warn(
|
|
145
|
+
`[strabl] ignored countryCode "${e.countryCode}": use a two-letter ISO 3166 code such as "SA"`
|
|
146
|
+
), {
|
|
147
|
+
label: t ? t.slice(0, re) : void 0,
|
|
148
|
+
countryCode: s && /^[A-Z]{2}$/.test(s) ? s : void 0
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
const ne = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
152
|
+
function ie(e) {
|
|
153
|
+
const t = e?.trim();
|
|
154
|
+
return t ? ne.test(t) ? t : (console.warn(
|
|
155
|
+
`[strabl] ignored platformUuid "${e}": expected a uuid such as 4038344c-6f04-4fce-bff9-780853587386`
|
|
156
|
+
), null) : null;
|
|
157
|
+
}
|
|
158
|
+
function ae(e) {
|
|
159
|
+
return e.apiKey ? w(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";
|
|
160
|
+
}
|
|
161
|
+
const le = ["amount", "currencyCode", "sessionToken", "amountSignature"];
|
|
162
|
+
function ce(e) {
|
|
163
|
+
const t = le.filter((s) => s in e);
|
|
164
|
+
t.length && console.warn(
|
|
165
|
+
`[strabl] ignored ${t.join(", ")}: the amount now comes from the session your server creates`
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
const S = "strabl-elements:awaiting-payer", de = [
|
|
169
|
+
"key",
|
|
170
|
+
"isStrablAuth",
|
|
171
|
+
"status",
|
|
172
|
+
"orderShortCode",
|
|
173
|
+
"reason",
|
|
174
|
+
...J
|
|
175
|
+
], ue = 2e4, he = 12e4, me = 120, fe = 440, pe = 540, ye = 770, R = () => typeof crypto < "u" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
176
|
+
class we {
|
|
177
|
+
constructor(t, s, r, n) {
|
|
178
|
+
o(this, "events");
|
|
179
|
+
o(this, "options");
|
|
180
|
+
o(this, "mode");
|
|
181
|
+
o(this, "iframe");
|
|
182
|
+
o(this, "elementsOrigin");
|
|
183
|
+
o(this, "instanceId", R());
|
|
184
|
+
o(this, "port", null);
|
|
185
|
+
o(this, "helloTimer");
|
|
186
|
+
o(this, "pendingSubmit", !1);
|
|
187
|
+
o(this, "viewportWidth", 0);
|
|
188
|
+
o(this, "resizeFrame", 0);
|
|
189
|
+
o(this, "savedFrameStyle", null);
|
|
190
|
+
/** This page load is the return from 3DS, so its URL carries return parameters. */
|
|
191
|
+
o(this, "resuming", !1);
|
|
192
|
+
o(this, "savedRootOverflow", "");
|
|
193
|
+
/** Holds the iframe's place in the page while it covers the viewport. */
|
|
194
|
+
o(this, "overlayPlaceholder", null);
|
|
195
|
+
/** The session the last payment ran under, remembered for the 3DS return. */
|
|
196
|
+
o(this, "session");
|
|
197
|
+
o(this, "connected");
|
|
198
|
+
o(this, "ready", new Promise((t) => this.connected = t));
|
|
199
|
+
o(this, "waiters", /* @__PURE__ */ new Map());
|
|
200
|
+
/**
|
|
201
|
+
* Back from 3DS or a provider's page with the browser's Back button, the
|
|
202
|
+
* page is restored as it was left: still "redirecting". Reopen the form.
|
|
203
|
+
*/
|
|
204
|
+
o(this, "onPageShow", (t) => {
|
|
205
|
+
t.persisted && (p(), this.post("clear", {}));
|
|
206
|
+
});
|
|
207
|
+
/** Keeps the form's breakpoints tied to the merchant's window width. */
|
|
208
|
+
o(this, "onWindowResize", () => {
|
|
209
|
+
cancelAnimationFrame(this.resizeFrame), this.resizeFrame = requestAnimationFrame(() => {
|
|
210
|
+
const t = window.innerWidth;
|
|
211
|
+
t !== this.viewportWidth && (this.viewportWidth = t, this.post("viewport", { width: t }));
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
o(this, "onWindowMessage", (t) => {
|
|
215
|
+
if (t.origin !== this.elementsOrigin || t.source !== this.iframe.contentWindow) return;
|
|
216
|
+
const s = v(t.data);
|
|
217
|
+
s?.type !== "hello" || s.payload.instanceId !== this.instanceId || this.connect();
|
|
218
|
+
});
|
|
219
|
+
this.events = s, this.options = r, this.mode = n;
|
|
220
|
+
const i = Y(r.apiKey);
|
|
221
|
+
this.elementsOrigin = new URL(
|
|
222
|
+
r.elementsUrl ?? G[i]
|
|
223
|
+
).origin, this.session = w(r), 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(() => {
|
|
224
|
+
this.emitError("frame_load_timeout", "The payment form did not load.");
|
|
225
|
+
}, ue);
|
|
226
|
+
}
|
|
227
|
+
update(t) {
|
|
228
|
+
this.options = t;
|
|
229
|
+
const s = w(t);
|
|
230
|
+
s && (this.session = s), this.post("update", {
|
|
231
|
+
...I(t),
|
|
232
|
+
session: s ?? void 0,
|
|
233
|
+
hasBeforeSubmit: !!t.onPaymentSubmission
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
/** Same as the pay button: invalid input is shown in the form, no result is sent. */
|
|
237
|
+
submit() {
|
|
238
|
+
if (!this.port) {
|
|
239
|
+
this.pendingSubmit = !0;
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
this.post("submit", {});
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Confirms or resumes a session and resolves with the outcome. Card or
|
|
246
|
+
* session problems resolve as `failed`; only SDK misuse rejects.
|
|
247
|
+
*/
|
|
248
|
+
async request(t, s) {
|
|
249
|
+
if (await this.ready, this.waiters.size) throw new Error("A payment is already in progress.");
|
|
250
|
+
s && (this.session = s);
|
|
251
|
+
const r = R(), n = t === "resume" && this.session ? E(
|
|
252
|
+
C(),
|
|
253
|
+
this.session.sessionId,
|
|
254
|
+
O()
|
|
255
|
+
) : void 0;
|
|
256
|
+
return new Promise((i, c) => {
|
|
257
|
+
const h = setTimeout(() => {
|
|
258
|
+
this.waiters.delete(r), c(new Error("The payment timed out."));
|
|
259
|
+
}, he);
|
|
260
|
+
this.waiters.set(r, { resolve: i, reject: c, timer: h }), t === "resume" ? this.post("resume", { requestId: r, session: s, providerReturn: n }) : this.post("submit", { requestId: r, session: s });
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
focus(t) {
|
|
264
|
+
this.iframe.focus(), this.post("focus", { field: t });
|
|
265
|
+
}
|
|
266
|
+
/** Makes the frame read the session's summary again. */
|
|
267
|
+
refresh() {
|
|
268
|
+
this.post("refresh", {});
|
|
269
|
+
}
|
|
270
|
+
clear() {
|
|
271
|
+
this.post("clear", {});
|
|
272
|
+
}
|
|
273
|
+
destroy() {
|
|
274
|
+
clearTimeout(this.helloTimer), window.removeEventListener("message", this.onWindowMessage), window.removeEventListener("resize", this.onWindowResize), window.removeEventListener("pageshow", this.onPageShow), cancelAnimationFrame(this.resizeFrame), this.setOverlay(!1);
|
|
275
|
+
for (const t of this.waiters.values())
|
|
276
|
+
clearTimeout(t.timer), t.reject(new Error("The card form was removed."));
|
|
277
|
+
this.waiters.clear(), this.port?.close(), this.port = null, this.iframe.remove();
|
|
278
|
+
}
|
|
279
|
+
createFrame() {
|
|
280
|
+
const t = new URL(K, this.elementsOrigin);
|
|
281
|
+
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));
|
|
282
|
+
const s = ie(this.options.platformUuid);
|
|
283
|
+
s && t.searchParams.set("platform", s);
|
|
284
|
+
const r = document.createElement("iframe");
|
|
285
|
+
r.src = t.toString(), r.title = "Secure card payment", r.allow = "payment", r.referrerPolicy = "origin", r.setAttribute(
|
|
286
|
+
"sandbox",
|
|
287
|
+
"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"
|
|
288
|
+
);
|
|
289
|
+
const n = window.innerWidth < ye ? pe : fe;
|
|
290
|
+
return r.style.cssText = `display:block;width:100%;height:${n}px;border:0;overflow:hidden;background:transparent;color-scheme:normal;`, r;
|
|
291
|
+
}
|
|
292
|
+
/** Runs on every `hello`, so a reloaded frame gets a fresh channel. */
|
|
293
|
+
connect() {
|
|
294
|
+
clearTimeout(this.helloTimer), this.port?.close();
|
|
295
|
+
const t = new MessageChannel();
|
|
296
|
+
this.port = t.port1, this.port.onmessage = (h) => {
|
|
297
|
+
const b = v(h.data);
|
|
298
|
+
b && this.handle(b);
|
|
299
|
+
};
|
|
300
|
+
const s = this.session ?? void 0, r = this.mode.autoRedirect ? C() : null;
|
|
301
|
+
let n = s !== void 0 && r?.sessionId === s.sessionId, i;
|
|
302
|
+
n && s && r?.provider && (i = E(
|
|
303
|
+
r,
|
|
304
|
+
s.sessionId,
|
|
305
|
+
O()
|
|
306
|
+
), i || (n = !1, p()));
|
|
307
|
+
const c = {
|
|
308
|
+
...I(this.options),
|
|
309
|
+
session: s,
|
|
310
|
+
hasBeforeSubmit: !!this.options.onPaymentSubmission,
|
|
311
|
+
viewportWidth: this.viewportWidth = window.innerWidth,
|
|
312
|
+
resume: n,
|
|
313
|
+
providerReturn: i,
|
|
314
|
+
page: Se()
|
|
315
|
+
};
|
|
316
|
+
this.resuming = c.resume, this.iframe.contentWindow?.postMessage(
|
|
317
|
+
g("init", c),
|
|
318
|
+
this.elementsOrigin,
|
|
319
|
+
[t.port2]
|
|
320
|
+
), this.connected(), this.pendingSubmit && (this.pendingSubmit = !1, this.submit());
|
|
321
|
+
}
|
|
322
|
+
async handle(t) {
|
|
323
|
+
const s = this.options;
|
|
324
|
+
switch (t.type) {
|
|
325
|
+
case "hello":
|
|
326
|
+
return;
|
|
327
|
+
case "ready":
|
|
328
|
+
s.onReady?.(t.payload.paymentMethods), this.emit("strablReady", t.payload.paymentMethods);
|
|
329
|
+
return;
|
|
330
|
+
case "change":
|
|
331
|
+
s.onChange?.(t.payload), this.emit("strablChange", t.payload);
|
|
332
|
+
return;
|
|
333
|
+
case "focus":
|
|
334
|
+
case "blur":
|
|
335
|
+
this.emit(
|
|
336
|
+
t.type === "focus" ? "strablFocus" : "strablBlur",
|
|
337
|
+
t.payload.field
|
|
338
|
+
);
|
|
339
|
+
return;
|
|
340
|
+
case "resize":
|
|
341
|
+
this.savedFrameStyle === null && (this.iframe.style.height = `${Math.max(me, Math.ceil(t.payload.height))}px`);
|
|
342
|
+
return;
|
|
343
|
+
case "overlay":
|
|
344
|
+
this.setOverlay(t.payload.open);
|
|
345
|
+
return;
|
|
346
|
+
case "processing":
|
|
347
|
+
this.emit("strablProcessing", t.payload.active);
|
|
348
|
+
return;
|
|
349
|
+
case "beforeSubmit": {
|
|
350
|
+
let r = !0;
|
|
351
|
+
if (s.onPaymentSubmission)
|
|
352
|
+
try {
|
|
353
|
+
r = !!await s.onPaymentSubmission();
|
|
354
|
+
} catch (n) {
|
|
355
|
+
console.error("[strabl] onPaymentSubmission threw:", n), r = !1;
|
|
356
|
+
}
|
|
357
|
+
this.post("beforeSubmitResult", {
|
|
358
|
+
requestId: t.payload.requestId,
|
|
359
|
+
proceed: r
|
|
360
|
+
});
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
case "result": {
|
|
364
|
+
const { requestId: r, ...n } = t.payload, i = r ? this.waiters.get(r) : void 0;
|
|
365
|
+
i && r && (clearTimeout(i.timer), this.waiters.delete(r), i.resolve(n)), this.dispatchResult(n);
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
case "error":
|
|
369
|
+
this.emitError(t.payload.code, t.payload.message);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
dispatchResult(t) {
|
|
374
|
+
const s = this.options;
|
|
375
|
+
switch (this.emit("strablResult", t), t.status) {
|
|
376
|
+
case "success":
|
|
377
|
+
this.finishReturn(), s.onPaymentSuccess?.(t.orderShortCode, t.transaction), this.emit("strablPaymentSuccess", t.orderShortCode);
|
|
378
|
+
return;
|
|
379
|
+
case "requires_action":
|
|
380
|
+
t.provider && T({
|
|
381
|
+
sessionId: this.session?.sessionId ?? "",
|
|
382
|
+
provider: t.provider,
|
|
383
|
+
orderShortCode: t.transaction.orderShortCode
|
|
384
|
+
}), (this.mode.autoRedirect || t.provider) && this.redirect(t.url, !t.provider);
|
|
385
|
+
return;
|
|
386
|
+
case "failed":
|
|
387
|
+
this.finishReturn(), s.onPaymentFailed?.(t.message, t.code), this.emit("strablPaymentFailed", t.message);
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
post(t, s) {
|
|
392
|
+
this.port?.postMessage(g(t, s));
|
|
393
|
+
}
|
|
394
|
+
/** Sends the payer to 3DS or the provider; the return page resumes the same session. */
|
|
395
|
+
redirect(t, s) {
|
|
396
|
+
let r;
|
|
397
|
+
try {
|
|
398
|
+
r = new URL(t);
|
|
399
|
+
} catch {
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
const n = this.elementsOrigin.startsWith("http://") || be(r.hostname);
|
|
403
|
+
if (r.protocol !== "https:" && !(n && r.protocol === "http:")) {
|
|
404
|
+
this.emitError(
|
|
405
|
+
"invalid_redirect",
|
|
406
|
+
"The verification page is not secure."
|
|
407
|
+
);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
this.session && s && T({ sessionId: this.session.sessionId }), window.location.assign(r.toString());
|
|
411
|
+
}
|
|
412
|
+
finishReturn() {
|
|
413
|
+
if (p(), !this.resuming) return;
|
|
414
|
+
this.resuming = !1;
|
|
415
|
+
const t = new URL(window.location.href);
|
|
416
|
+
de.forEach((s) => t.searchParams.delete(s)), window.history.replaceState(window.history.state, "", t.toString());
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Covers the viewport with the iframe while the frame shows a 3DS
|
|
420
|
+
* challenge or Apple's in-page Apple Pay sheet. A placeholder keeps the
|
|
421
|
+
* iframe's height in the page, so the page neither shrinks nor scrolls.
|
|
422
|
+
*/
|
|
423
|
+
setOverlay(t) {
|
|
424
|
+
const s = document.documentElement;
|
|
425
|
+
if (t && this.savedFrameStyle === null) {
|
|
426
|
+
const r = document.createElement("div");
|
|
427
|
+
r.style.cssText = `display:block;height:${this.iframe.offsetHeight}px;`, r.setAttribute("aria-hidden", "true"), this.iframe.before(r), this.overlayPlaceholder = r, this.savedFrameStyle = this.iframe.style.cssText, this.savedRootOverflow = s.style.overflow, this.iframe.style.cssText = "position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647;background:transparent;color-scheme:normal;", s.style.overflow = "hidden";
|
|
428
|
+
} else !t && this.savedFrameStyle !== null && (this.iframe.style.cssText = this.savedFrameStyle, s.style.overflow = this.savedRootOverflow, this.savedFrameStyle = null, this.overlayPlaceholder?.remove(), this.overlayPlaceholder = null);
|
|
429
|
+
}
|
|
430
|
+
emitError(t, s) {
|
|
431
|
+
this.options.onError?.(t, s), this.emit("strablError", { code: t, message: s });
|
|
432
|
+
}
|
|
433
|
+
emit(t, s) {
|
|
434
|
+
this.events.dispatchEvent(
|
|
435
|
+
new CustomEvent(t, { detail: s, bubbles: !0, composed: !0 })
|
|
436
|
+
);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
function C() {
|
|
440
|
+
try {
|
|
441
|
+
return se(sessionStorage.getItem(S));
|
|
442
|
+
} catch {
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
function T(e) {
|
|
447
|
+
if (e.sessionId)
|
|
448
|
+
try {
|
|
449
|
+
sessionStorage.setItem(S, JSON.stringify(e));
|
|
450
|
+
} catch {
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
function O() {
|
|
454
|
+
return new URL(window.location.href).searchParams;
|
|
455
|
+
}
|
|
456
|
+
function p() {
|
|
457
|
+
try {
|
|
458
|
+
sessionStorage.removeItem(S);
|
|
459
|
+
} catch {
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
function A(e) {
|
|
463
|
+
try {
|
|
464
|
+
const t = new URL(e);
|
|
465
|
+
return t.origin + t.pathname;
|
|
466
|
+
} catch {
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
function Se() {
|
|
471
|
+
return {
|
|
472
|
+
href: A(window.location.href),
|
|
473
|
+
referrer: document.referrer ? A(document.referrer) : void 0
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
function be(e) {
|
|
477
|
+
return e === "localhost" || e === "127.0.0.1" || e === "[::1]";
|
|
478
|
+
}
|
|
479
|
+
const P = "strabl-card-form", M = "strabl-submit-card-form", F = [
|
|
480
|
+
"apiKey",
|
|
481
|
+
"platformUuid",
|
|
482
|
+
"sessionId",
|
|
483
|
+
"clientSecret",
|
|
484
|
+
"language",
|
|
485
|
+
"fieldInputStyle",
|
|
486
|
+
"paymentMethods",
|
|
487
|
+
"customstyles",
|
|
488
|
+
"inputStyle",
|
|
489
|
+
"fonts",
|
|
490
|
+
"enableEmailCollection",
|
|
491
|
+
"enableSaveCard",
|
|
492
|
+
"merchantName",
|
|
493
|
+
"countryCode",
|
|
494
|
+
"elementsUrl",
|
|
495
|
+
"onPaymentSubmission",
|
|
496
|
+
"onPaymentSuccess",
|
|
497
|
+
"onPaymentFailed",
|
|
498
|
+
"onReady",
|
|
499
|
+
"onChange",
|
|
500
|
+
"onError"
|
|
501
|
+
], _ = {
|
|
502
|
+
apikey: "apiKey",
|
|
503
|
+
platformuuid: "platformUuid",
|
|
504
|
+
sessionid: "sessionId",
|
|
505
|
+
clientsecret: "clientSecret",
|
|
506
|
+
language: "language",
|
|
507
|
+
fieldinputstyle: "fieldInputStyle",
|
|
508
|
+
enableemailcollection: "enableEmailCollection",
|
|
509
|
+
enablesavecard: "enableSaveCard",
|
|
510
|
+
merchantname: "merchantName",
|
|
511
|
+
countrycode: "countryCode",
|
|
512
|
+
elementsurl: "elementsUrl"
|
|
513
|
+
}, ge = /* @__PURE__ */ new Set([
|
|
514
|
+
"enableEmailCollection",
|
|
515
|
+
"enableSaveCard"
|
|
516
|
+
]), ve = typeof HTMLElement > "u" ? class {
|
|
517
|
+
} : HTMLElement;
|
|
518
|
+
class U extends ve {
|
|
519
|
+
constructor() {
|
|
520
|
+
super();
|
|
521
|
+
o(this, "root");
|
|
522
|
+
o(this, "status");
|
|
523
|
+
o(this, "opts", {});
|
|
524
|
+
o(this, "controller", null);
|
|
525
|
+
o(this, "scheduled", !1);
|
|
526
|
+
o(this, "onLegacySubmit", () => {
|
|
527
|
+
this.submit();
|
|
528
|
+
});
|
|
529
|
+
this.root = this.attachShadow({ mode: "closed" });
|
|
530
|
+
const s = document.createElement("style");
|
|
531
|
+
s.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(s, this.status);
|
|
532
|
+
}
|
|
533
|
+
static get observedAttributes() {
|
|
534
|
+
return Object.keys(_);
|
|
535
|
+
}
|
|
536
|
+
connectedCallback() {
|
|
537
|
+
for (const s of F)
|
|
538
|
+
if (Object.hasOwn(this, s)) {
|
|
539
|
+
const r = this[s];
|
|
540
|
+
delete this[s], this.set(s, r);
|
|
541
|
+
}
|
|
542
|
+
ce(this), window.addEventListener(M, this.onLegacySubmit), this.schedule();
|
|
543
|
+
}
|
|
544
|
+
disconnectedCallback() {
|
|
545
|
+
window.removeEventListener(M, this.onLegacySubmit), this.controller?.destroy(), this.controller = null;
|
|
546
|
+
}
|
|
547
|
+
attributeChangedCallback(s, r, n) {
|
|
548
|
+
const i = _[s];
|
|
549
|
+
if (!i) return;
|
|
550
|
+
const c = ge.has(i) ? n !== "false" : n ?? void 0;
|
|
551
|
+
this.set(i, c);
|
|
552
|
+
}
|
|
553
|
+
/** Submits the payment, same as clicking the pay button. */
|
|
554
|
+
submit() {
|
|
555
|
+
this.controller?.submit();
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Reads the session again, e.g. after your server changed its amount with
|
|
559
|
+
* `POST /sessions/{id}/amount`. The form shows the new amount.
|
|
560
|
+
*/
|
|
561
|
+
refresh() {
|
|
562
|
+
this.controller?.refresh();
|
|
563
|
+
}
|
|
564
|
+
set(s, r) {
|
|
565
|
+
this.opts[s] !== r && (this.opts = { ...this.opts, [s]: r }, this.schedule());
|
|
566
|
+
}
|
|
567
|
+
/** Batches property changes made in the same task into one update. */
|
|
568
|
+
schedule() {
|
|
569
|
+
this.scheduled || (this.scheduled = !0, queueMicrotask(() => {
|
|
570
|
+
this.scheduled = !1, this.sync();
|
|
571
|
+
}));
|
|
572
|
+
}
|
|
573
|
+
sync() {
|
|
574
|
+
if (!this.isConnected) return;
|
|
575
|
+
const s = ae(this.opts);
|
|
576
|
+
if (s) {
|
|
577
|
+
this.controller || (this.status.textContent = "The payment form could not be loaded.", console.error(`[strabl] ${s}`));
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
this.status.textContent = "";
|
|
581
|
+
const r = this.opts;
|
|
582
|
+
this.controller ? this.controller.update(r) : this.controller = new we(this.root, this, r, {
|
|
583
|
+
autoRedirect: !0
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
for (const e of F)
|
|
588
|
+
Object.defineProperty(U.prototype, e, {
|
|
589
|
+
configurable: !0,
|
|
590
|
+
enumerable: !0,
|
|
591
|
+
get() {
|
|
592
|
+
return this.opts[e];
|
|
593
|
+
},
|
|
594
|
+
set(t) {
|
|
595
|
+
this.set(
|
|
596
|
+
e,
|
|
597
|
+
t
|
|
598
|
+
);
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
function Ie() {
|
|
602
|
+
typeof customElements < "u" && !customElements.get(P) && customElements.define(P, U);
|
|
603
|
+
}
|
|
604
|
+
export {
|
|
605
|
+
we as F,
|
|
606
|
+
U as S,
|
|
607
|
+
P as T,
|
|
608
|
+
Ie as d,
|
|
609
|
+
q as i
|
|
610
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var k=Object.defineProperty;var W=(e,t,s)=>t in e?k(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var o=(e,t,s)=>W(e,typeof t!="symbol"?t+"":t,s);const F="strabl-elements";function E(e,t){return{source:F,v:1,type:e,payload:t}}const a=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),l=(e,t=2048)=>typeof e=="string"&&e.length<=t,d=e=>typeof e=="boolean",u=(e,t=2048)=>e===void 0||l(e,t),B=["cardHolderName","cardNumber","expiry","cvc"],H=["card","applepay","googlepay","tabby","tamara"],m=e=>B.includes(e),y=e=>l(e,64)&&/^[\w-]+$/.test(e),q=/^[\w-]{1,128}$/,$=/^[!-~]{1,512}$/;function U(e){return a(e)&&typeof e.sessionId=="string"&&q.test(e.sessionId)&&typeof e.clientSecret=="string"&&$.test(e.clientSecret)}const z=e=>e==="TABBY"||e==="TAMARA",D=e=>e===void 0||y(e),f=e=>a(e)&&l(e.status,40)&&u(e.orderShortCode,64)&&u(e.paymentReference,128)&&u(e.threeDsUrl,4096)&&(e.amount===void 0||typeof e.amount=="number"&&Number.isFinite(e.amount))&&u(e.currency,3);function V(e){if(!D(e.requestId))return!1;switch(e.status){case"success":return l(e.orderShortCode,64)&&f(e.transaction);case"requires_action":return l(e.url,4096)&&f(e.transaction)&&(e.provider===void 0||z(e.provider));case"failed":return l(e.code,64)&&l(e.message,500)&&(e.transaction===void 0||f(e.transaction));default:return!1}}const j={hello:e=>a(e)&&y(e.instanceId),ready:e=>a(e)&&Array.isArray(e.paymentMethods),change:e=>a(e)&&(e.brand===null||l(e.brand,32))&&d(e.empty)&&d(e.complete)&&a(e.errors)&&Object.keys(e.errors).every(m)&&(e.paymentMethod===void 0||H.includes(e.paymentMethod)),focus:e=>a(e)&&m(e.field),blur:e=>a(e)&&m(e.field),resize:e=>a(e)&&typeof e.height=="number"&&e.height>=0&&e.height<1e4,processing:e=>a(e)&&d(e.active),beforeSubmit:e=>a(e)&&y(e.requestId),overlay:e=>a(e)&&d(e.open),result:e=>a(e)&&V(e),error:e=>a(e)&&l(e.code,64)&&l(e.message,500)};function G(e,t){return!a(e)||e.source!==F||e.v!==1||typeof e.type!="string"||!Object.hasOwn(t,e.type)?null:t[e.type](e.payload)?e:null}const I=e=>G(e,j),K={sandbox:"https://sandbox.payments.strabl.io",prod:"https://payments.strabl.io"},Y="/v1/card-form/index.html";function J(e){return e.startsWith("pk_live_")?"prod":"sandbox"}const Z=["paymentStatus","orderId","payment_id"],Q=new Set(["approved","authorised","authorized","captured","fully_captured","success","succeeded","paid","closed"]),X=new Set(["declined","rejected","failed","failure","error","expired"]),ee=new Set(["canceled","cancelled","cancel"]);function te(e){for(const t of["paymentStatus","status"]){const s=e.get(t)?.trim().toLowerCase();if(s){if(Q.has(s))return"success";if(X.has(s))return"failed";if(ee.has(s))return"cancelled"}}return"unknown"}function se(e){return e.has("paymentStatus")||e.has("payment_id")}function re(e){if(!e)return null;try{const t=JSON.parse(e);if(typeof t=="object"&&t!==null){const s=t;return typeof s.sessionId!="string"?null:{sessionId:s.sessionId,provider:s.provider==="TABBY"||s.provider==="TAMARA"?s.provider:void 0,orderShortCode:typeof s.orderShortCode=="string"&&s.orderShortCode.length<=64?s.orderShortCode:void 0}}}catch{}return{sessionId:e}}function R(e,t,s){const r=e?.sessionId===t?e:null;if(se(s)||r?.provider&&s.has("status"))return{provider:r?.provider,status:te(s),orderShortCode:r?.orderShortCode}}function w(e){const t={sessionId:e.sessionId??"",clientSecret:e.clientSecret??""};return U(t)?t:null}function C(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:ne(e),enableEmailCollection:e.enableEmailCollection??!0,enableSaveCard:e.enableSaveCard??!0}}const oe=64;function ne(e){const t=e.merchantName?.trim(),s=e.countryCode?.trim().toUpperCase();return s&&!/^[A-Z]{2}$/.test(s)&&console.warn(`[strabl] ignored countryCode "${e.countryCode}": use a two-letter ISO 3166 code such as "SA"`),{label:t?t.slice(0,oe):void 0,countryCode:s&&/^[A-Z]{2}$/.test(s)?s:void 0}}const ie=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ae(e){const t=e?.trim();return t?ie.test(t)?t:(console.warn(`[strabl] ignored platformUuid "${e}": expected a uuid such as 4038344c-6f04-4fce-bff9-780853587386`),null):null}function le(e){return e.apiKey?w(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 ce=["amount","currencyCode","sessionToken","amountSignature"];function de(e){const t=ce.filter(s=>s in e);t.length&&console.warn(`[strabl] ignored ${t.join(", ")}: the amount now comes from the session your server creates`)}const b="strabl-elements:awaiting-payer",ue=["key","isStrablAuth","status","orderShortCode","reason",...Z],he=2e4,me=12e4,fe=120,pe=440,ye=540,we=770,T=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;class N{constructor(t,s,r,n){o(this,"events");o(this,"options");o(this,"mode");o(this,"iframe");o(this,"elementsOrigin");o(this,"instanceId",T());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&&(p(),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 s=I(t.data);s?.type!=="hello"||s.payload.instanceId!==this.instanceId||this.connect()});this.events=s,this.options=r,this.mode=n;const i=J(r.apiKey);this.elementsOrigin=new URL(r.elementsUrl??K[i]).origin,this.session=w(r),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.")},he)}update(t){this.options=t;const s=w(t);s&&(this.session=s),this.post("update",{...C(t),session:s??void 0,hasBeforeSubmit:!!t.onPaymentSubmission})}submit(){if(!this.port){this.pendingSubmit=!0;return}this.post("submit",{})}async request(t,s){if(await this.ready,this.waiters.size)throw new Error("A payment is already in progress.");s&&(this.session=s);const r=T(),n=t==="resume"&&this.session?R(A(),this.session.sessionId,P()):void 0;return new Promise((i,c)=>{const h=setTimeout(()=>{this.waiters.delete(r),c(new Error("The payment timed out."))},me);this.waiters.set(r,{resolve:i,reject:c,timer:h}),t==="resume"?this.post("resume",{requestId:r,session:s,providerReturn:n}):this.post("submit",{requestId:r,session:s})})}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(Y,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 s=ae(this.options.platformUuid);s&&t.searchParams.set("platform",s);const r=document.createElement("iframe");r.src=t.toString(),r.title="Secure card payment",r.allow="payment",r.referrerPolicy="origin",r.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox");const n=window.innerWidth<we?ye:pe;return r.style.cssText=`display:block;width:100%;height:${n}px;border:0;overflow:hidden;background:transparent;color-scheme:normal;`,r}connect(){clearTimeout(this.helloTimer),this.port?.close();const t=new MessageChannel;this.port=t.port1,this.port.onmessage=h=>{const v=I(h.data);v&&this.handle(v)};const s=this.session??void 0,r=this.mode.autoRedirect?A():null;let n=s!==void 0&&r?.sessionId===s.sessionId,i;n&&s&&r?.provider&&(i=R(r,s.sessionId,P()),i||(n=!1,p()));const c={...C(this.options),session:s,hasBeforeSubmit:!!this.options.onPaymentSubmission,viewportWidth:this.viewportWidth=window.innerWidth,resume:n,providerReturn:i,page:Se()};this.resuming=c.resume,this.iframe.contentWindow?.postMessage(E("init",c),this.elementsOrigin,[t.port2]),this.connected(),this.pendingSubmit&&(this.pendingSubmit=!1,this.submit())}async handle(t){const s=this.options;switch(t.type){case"hello":return;case"ready":s.onReady?.(t.payload.paymentMethods),this.emit("strablReady",t.payload.paymentMethods);return;case"change":s.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(fe,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 r=!0;if(s.onPaymentSubmission)try{r=!!await s.onPaymentSubmission()}catch(n){console.error("[strabl] onPaymentSubmission threw:",n),r=!1}this.post("beforeSubmitResult",{requestId:t.payload.requestId,proceed:r});return}case"result":{const{requestId:r,...n}=t.payload,i=r?this.waiters.get(r):void 0;i&&r&&(clearTimeout(i.timer),this.waiters.delete(r),i.resolve(n)),this.dispatchResult(n);return}case"error":this.emitError(t.payload.code,t.payload.message);return}}dispatchResult(t){const s=this.options;switch(this.emit("strablResult",t),t.status){case"success":this.finishReturn(),s.onPaymentSuccess?.(t.orderShortCode,t.transaction),this.emit("strablPaymentSuccess",t.orderShortCode);return;case"requires_action":t.provider&&O({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(),s.onPaymentFailed?.(t.message,t.code),this.emit("strablPaymentFailed",t.message);return}}post(t,s){this.port?.postMessage(E(t,s))}redirect(t,s){let r;try{r=new URL(t)}catch{return}const n=this.elementsOrigin.startsWith("http://")||be(r.hostname);if(r.protocol!=="https:"&&!(n&&r.protocol==="http:")){this.emitError("invalid_redirect","The verification page is not secure.");return}this.session&&s&&O({sessionId:this.session.sessionId}),window.location.assign(r.toString())}finishReturn(){if(p(),!this.resuming)return;this.resuming=!1;const t=new URL(window.location.href);ue.forEach(s=>t.searchParams.delete(s)),window.history.replaceState(window.history.state,"",t.toString())}setOverlay(t){const s=document.documentElement;if(t&&this.savedFrameStyle===null){const r=document.createElement("div");r.style.cssText=`display:block;height:${this.iframe.offsetHeight}px;`,r.setAttribute("aria-hidden","true"),this.iframe.before(r),this.overlayPlaceholder=r,this.savedFrameStyle=this.iframe.style.cssText,this.savedRootOverflow=s.style.overflow,this.iframe.style.cssText="position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647;background:transparent;color-scheme:normal;",s.style.overflow="hidden"}else!t&&this.savedFrameStyle!==null&&(this.iframe.style.cssText=this.savedFrameStyle,s.style.overflow=this.savedRootOverflow,this.savedFrameStyle=null,this.overlayPlaceholder?.remove(),this.overlayPlaceholder=null)}emitError(t,s){this.options.onError?.(t,s),this.emit("strablError",{code:t,message:s})}emit(t,s){this.events.dispatchEvent(new CustomEvent(t,{detail:s,bubbles:!0,composed:!0}))}}function A(){try{return re(sessionStorage.getItem(b))}catch{return null}}function O(e){if(e.sessionId)try{sessionStorage.setItem(b,JSON.stringify(e))}catch{}}function P(){return new URL(window.location.href).searchParams}function p(){try{sessionStorage.removeItem(b)}catch{}}function M(e){try{const t=new URL(e);return t.origin+t.pathname}catch{return}}function Se(){return{href:M(window.location.href),referrer:document.referrer?M(document.referrer):void 0}}function be(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}const S="strabl-card-form",_="strabl-submit-card-form",x=["apiKey","platformUuid","sessionId","clientSecret","language","fieldInputStyle","paymentMethods","customstyles","inputStyle","fonts","enableEmailCollection","enableSaveCard","merchantName","countryCode","elementsUrl","onPaymentSubmission","onPaymentSuccess","onPaymentFailed","onReady","onChange","onError"],L={apikey:"apiKey",platformuuid:"platformUuid",sessionid:"sessionId",clientsecret:"clientSecret",language:"language",fieldinputstyle:"fieldInputStyle",enableemailcollection:"enableEmailCollection",enablesavecard:"enableSaveCard",merchantname:"merchantName",countrycode:"countryCode",elementsurl:"elementsUrl"},ge=new Set(["enableEmailCollection","enableSaveCard"]),ve=typeof HTMLElement>"u"?class{}:HTMLElement;class g extends ve{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 s=document.createElement("style");s.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(s,this.status)}static get observedAttributes(){return Object.keys(L)}connectedCallback(){for(const s of x)if(Object.hasOwn(this,s)){const r=this[s];delete this[s],this.set(s,r)}de(this),window.addEventListener(_,this.onLegacySubmit),this.schedule()}disconnectedCallback(){window.removeEventListener(_,this.onLegacySubmit),this.controller?.destroy(),this.controller=null}attributeChangedCallback(s,r,n){const i=L[s];if(!i)return;const c=ge.has(i)?n!=="false":n??void 0;this.set(i,c)}submit(){this.controller?.submit()}refresh(){this.controller?.refresh()}set(s,r){this.opts[s]!==r&&(this.opts={...this.opts,[s]:r},this.schedule())}schedule(){this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1,this.sync()}))}sync(){if(!this.isConnected)return;const s=le(this.opts);if(s){this.controller||(this.status.textContent="The payment form could not be loaded.",console.error(`[strabl] ${s}`));return}this.status.textContent="";const r=this.opts;this.controller?this.controller.update(r):this.controller=new N(this.root,this,r,{autoRedirect:!0})}}for(const e of x)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get(){return this.opts[e]},set(t){this.set(e,t)}});function Ee(){typeof customElements<"u"&&!customElements.get(S)&&customElements.define(S,g)}exports.FrameController=N;exports.StrablCardForm=g;exports.TAG_NAME=S;exports.defineStrablCardForm=Ee;exports.isSessionCredentials=U;
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var y=Object.defineProperty;var C=(s,t,e)=>t in s?y(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var u=(s,t,e)=>C(s,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./element-CZKsfyCs.cjs");function v(s){if(typeof document>"u")throw new Error("strablCardForm can only be called in a browser");i.defineStrablCardForm();const t=document.querySelector(s.selector);if(!t)throw new Error(`strablCardForm: no element matched selector "${s.selector}"`);const e=document.createElement(i.TAG_NAME),{selector:c,replace:d,...l}=s;return Object.assign(e,l),d?t.replaceChildren(e):t.appendChild(e),{element:e,update:n=>Object.assign(e,n),submit:()=>e.submit(),refresh:()=>e.refresh(),destroy:()=>e.remove()}}class f extends Error{constructor(e,c,d){super(c);u(this,"code");u(this,"transaction");this.code=e,this.transaction=d,this.name="StrablError"}}const g={name:"cardHolderName",number:"cardNumber",expiry:"expiry",cvv:"cvc",cardHolderName:"cardHolderName",cardNumber:"cardNumber",cvc:"cvc"},b={ready:"strablReady",change:"strablChange",focus:"strablFocus",blur:"strablBlur",result:"strablResult",error:"strablError"};function F(s,t={}){if(!/^pk_(live|test)_/.test(s??""))throw new Error("StrablElements: a publishable key (pk_…) is required");return{create(e,c={}){if(e!=="card")throw new Error(`StrablElements: unsupported element type "${e}"`);return N(s,t,c)}}}function N(s,t,e){const c=new EventTarget;let d=null,l=null,n=e;const E=()=>({apiKey:s,platformUuid:t.platformUuid,elementsUrl:t.elementsUrl,language:n.language??t.language,fieldInputStyle:n.fieldInputStyle,paymentMethods:n.paymentMethods,customstyles:n.customstyles,inputStyle:n.style,fonts:n.fonts,enableEmailCollection:n.enableEmailCollection,enableSaveCard:n.enableSaveCard,merchantName:n.merchantName,countryCode:n.countryCode,sessionId:n.session?.sessionId,clientSecret:n.session?.clientSecret});c.addEventListener(b.result,r=>{const a=r.detail;a.status==="failed"&&c.dispatchEvent(new CustomEvent(b.error,{detail:{code:a.code,message:a.message}}))});async function h(r,a){if(!l)throw new Error("StrablElements: mount the card element first");if(!i.isSessionCredentials(a))throw new Error("StrablElements: sessionId and clientSecret are required");const o=await l.request(r,{sessionId:a.sessionId,clientSecret:a.clientSecret});switch(o.status){case"success":return o.transaction;case"requires_action":return{...o.transaction,threeDsUrl:o.url,...o.provider?{provider:o.provider}:{}};case"failed":throw new f(o.code,o.message,o.transaction)}}return{mount(r){if(l)throw new Error("StrablElements: this card element is already mounted");const a=typeof r=="string"?document.querySelector(r):r;if(!a)throw new Error(`StrablElements: mount target "${r}" was not found`);d=document.createElement("div"),d.className="strabl-card-element";const o=d.attachShadow({mode:"closed"});a.appendChild(d),l=new i.FrameController(o,c,E(),{autoRedirect:!1})},on(r,a){const o=b[r];if(!o)throw new Error(`StrablElements: unknown event "${r}"`);const S=p=>{const m=p.detail;try{a(r==="error"?new f(m.code,m.message):m)}catch(w){console.error("[strabl] listener failed",w)}};return c.addEventListener(o,S),()=>c.removeEventListener(o,S)},confirm:r=>h("submit",r),resume:r=>h("resume",r),focus(r){const a=g[r];a&&l?.focus(a)},clear(){l?.clear()},update(r){n={...n,...r},l?.update(E())},refresh(){l?.refresh()},destroy(){l?.destroy(),l=null,d?.remove(),d=null}}}i.defineStrablCardForm();exports.StrablCardForm=i.StrablCardForm;exports.TAG_NAME=i.TAG_NAME;exports.defineStrablCardForm=i.defineStrablCardForm;exports.StrablElements=F;exports.StrablError=f;exports.strablCardForm=v;
|