@flopay/vue 1.20.15 → 2.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.
Files changed (39) hide show
  1. package/README.md +56 -57
  2. package/dist/card-setup-entry.cjs +184 -569
  3. package/dist/card-setup-entry.d.ts +2 -2
  4. package/dist/card-setup-entry.mjs +3 -7
  5. package/dist/chunk-2VPPDVV7.mjs +218 -0
  6. package/dist/chunk-OCVTEXQA.mjs +20 -0
  7. package/dist/flopay-runtime-checkout.d.ts +11 -0
  8. package/dist/hosted-runtime-components.d.ts +587 -0
  9. package/dist/index.cjs +298 -5402
  10. package/dist/index.d.ts +3 -21
  11. package/dist/index.mjs +250 -3728
  12. package/dist/payment-method-setup-entry.cjs +194 -1852
  13. package/dist/payment-method-setup-entry.d.ts +2 -2
  14. package/dist/payment-method-setup-entry.mjs +4 -4
  15. package/dist/runtime-context.d.ts +11 -0
  16. package/package.json +3 -5
  17. package/dist/automatic-payment-button.d.ts +0 -296
  18. package/dist/buyer-identity-fallback.d.ts +0 -82
  19. package/dist/chunk-2USKULEH.mjs +0 -530
  20. package/dist/chunk-HH25IC76.mjs +0 -98
  21. package/dist/chunk-IJKGJSHH.mjs +0 -333
  22. package/dist/chunk-RAGPQWRA.mjs +0 -923
  23. package/dist/context.d.ts +0 -56
  24. package/dist/direct-paypal-button.d.ts +0 -325
  25. package/dist/flopay-card-setup.d.ts +0 -158
  26. package/dist/flopay-checkout.d.ts +0 -517
  27. package/dist/flopay-payment-method-setup-main.d.ts +0 -152
  28. package/dist/hooks.d.ts +0 -22
  29. package/dist/hosted-setup.d.ts +0 -116
  30. package/dist/payment-method-setup-paypal-D6FEQQJY.mjs +0 -151
  31. package/dist/payment-method-setup-paypal.d.ts +0 -108
  32. package/dist/processing-overlay.d.ts +0 -82
  33. package/dist/provider.d.ts +0 -76
  34. package/dist/saved-payment.d.ts +0 -44
  35. package/dist/split-card-form.d.ts +0 -777
  36. package/dist/stripe-elements-SI2PI6EO.mjs +0 -6
  37. package/dist/stripe-elements.d.ts +0 -280
  38. package/dist/stripe-paypal-continuation.d.ts +0 -28
  39. package/dist/vault-card-fields.d.ts +0 -129
@@ -1,18 +1,8 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res, err) => function __init() {
9
- if (err) throw err[0];
10
- try {
11
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
- } catch (e) {
13
- throw err = [e], e;
14
- }
15
- };
16
6
  var __export = (target, all) => {
17
7
  for (var name in all)
18
8
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -25,1877 +15,229 @@ var __copyProps = (to, from, except, desc) => {
25
15
  }
26
16
  return to;
27
17
  };
28
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
- // If the importer is in node compatibility mode or this is not an ESM
30
- // file that has been converted to a CommonJS file using a Babel-
31
- // compatible transform (i.e. "__esModule" has not been set), then set
32
- // "default" to the CommonJS "module.exports" for node compatibility.
33
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
- mod
35
- ));
36
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
19
 
38
- // src/context.ts
39
- var FLOPAY_CONTEXT;
40
- var init_context = __esm({
41
- "src/context.ts"() {
42
- "use strict";
43
- FLOPAY_CONTEXT = /* @__PURE__ */ Symbol("flopay.vue.provider");
44
- }
45
- });
46
-
47
- // src/provider.ts
48
- function telemetryBridge(flopay) {
49
- return flopay[FLOPAY_TELEMETRY_BRIDGE];
50
- }
51
- function isPromiseLike(value) {
52
- return typeof value?.then === "function";
53
- }
54
- function createInstrumentEmitter(notify) {
55
- const emittedOnce = /* @__PURE__ */ new Set();
56
- return (source) => {
57
- const event = (0, import_shared3.projectFloInstrument)(source);
58
- if (!event) return;
59
- if (import_shared3.FLO_INSTRUMENT_ONCE_NAMES.has(event.name)) {
60
- if (emittedOnce.has(event.name)) return;
61
- emittedOnce.add(event.name);
62
- }
63
- (0, import_shared3.invokeMerchantCallback)(() => notify(event));
64
- };
65
- }
66
- var import_shared3, import_vue4, FLOPAY_TELEMETRY_BRIDGE, FloPayProvider;
67
- var init_provider = __esm({
68
- "src/provider.ts"() {
69
- "use strict";
70
- import_shared3 = require("@flopay/shared");
71
- import_vue4 = require("vue");
72
- init_context();
73
- FLOPAY_TELEMETRY_BRIDGE = /* @__PURE__ */ Symbol.for("@flopay/js.telemetry.bridge.v1");
74
- FloPayProvider = (0, import_vue4.defineComponent)({
75
- name: "FloPayProvider",
76
- props: {
77
- flopay: {
78
- type: [Object, Promise],
79
- default: null
80
- },
81
- paypalFlopay: {
82
- type: [Object, Promise],
83
- default: null
84
- },
85
- options: { type: Object, default: void 0 }
86
- },
87
- emits: { instrument: (_event) => true },
88
- setup(props, { emit, slots }) {
89
- const initial = (source) => isPromiseLike(source) ? null : source ?? null;
90
- const flopay = (0, import_vue4.shallowRef)(initial(props.flopay));
91
- const paypalFlopay = (0, import_vue4.shallowRef)(initial(props.paypalFlopay));
92
- const component = (0, import_vue4.getCurrentInstance)();
93
- const emitInstrument = createInstrumentEmitter((event) => {
94
- const listener = component?.vnode.props?.onInstrument;
95
- if (!listener) return emit("instrument", event);
96
- for (const handler of [listener].flat()) handler(event);
97
- });
98
- const emitTelemetryInstrument = (source) => {
99
- if (!(0, import_shared3.isCardFieldsInstrumentSource)(source)) emitInstrument(source);
100
- };
101
- (0, import_vue4.provide)(FLOPAY_CONTEXT, {
102
- flopay,
103
- paypalFlopay,
104
- billingApiUrl: () => (0, import_shared3.resolveBillingApiUrl)(props.options?.billingApiUrl),
105
- emitInstrument
106
- });
107
- const follow = (read, target, provider) => (0, import_vue4.watch)(
108
- read,
109
- (source, _previous, onCleanup) => {
110
- let active = true;
111
- onCleanup(() => {
112
- active = false;
113
- });
114
- if (!isPromiseLike(source)) {
115
- target.value = source ?? null;
116
- return;
117
- }
118
- if (provider === "paypal") target.value = null;
119
- source.then(
120
- (instance) => {
121
- if (active) target.value = instance;
122
- },
123
- () => {
124
- if (!active) return;
125
- emitInstrument({
126
- class: "technical_error",
127
- errorCode: "SDK_INITIALIZATION_FAILED",
128
- ...provider ? { provider } : {}
129
- });
130
- }
131
- );
132
- },
133
- { immediate: true }
134
- );
135
- (0, import_vue4.onMounted)(() => {
136
- emitInstrument({ class: "lifecycle", name: "checkout.mount" });
137
- follow(() => props.flopay, flopay);
138
- follow(() => props.paypalFlopay, paypalFlopay, "paypal");
139
- (0, import_vue4.watch)(
140
- flopay,
141
- (instance, _previous, onCleanup) => {
142
- if (!instance) return;
143
- emitInstrument({ class: "lifecycle", name: "sdk.initialize.ready" });
144
- const unsubscribe = telemetryBridge(instance)?.subscribe?.(emitTelemetryInstrument);
145
- onCleanup(() => unsubscribe?.());
146
- void (0, import_vue4.nextTick)(() => emitInstrument({ class: "lifecycle", name: "checkout.rendered" }));
147
- },
148
- { immediate: true }
149
- );
150
- (0, import_vue4.watch)(paypalFlopay, (instance, _previous, onCleanup) => {
151
- if (!instance || instance === flopay.value) return;
152
- const unsubscribe = telemetryBridge(instance)?.subscribe?.(emitTelemetryInstrument);
153
- onCleanup(() => unsubscribe?.());
154
- });
155
- });
156
- return () => slots.default?.();
157
- }
158
- });
159
- }
160
- });
161
-
162
- // src/stripe-paypal-continuation.ts
163
- function sessionStore() {
164
- if (typeof window === "undefined") return null;
165
- try {
166
- return window.sessionStorage;
167
- } catch {
168
- return null;
169
- }
170
- }
171
- function createStripePayPalAttempt() {
172
- const random = globalThis.crypto?.randomUUID?.();
173
- if (random) return random;
174
- return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`;
175
- }
176
- function saveStripePayPalContinuation(continuation) {
177
- const store = sessionStore();
178
- if (!store) return false;
179
- try {
180
- store.setItem(
181
- STRIPE_PAYPAL_CONTINUATION_KEY,
182
- JSON.stringify({
183
- attempt: continuation.attempt,
184
- sessionId: continuation.sessionId,
185
- ...continuation.nonce ? { nonce: continuation.nonce } : {}
186
- })
187
- );
188
- return true;
189
- } catch {
190
- return false;
191
- }
192
- }
193
- function clearStripePayPalContinuation() {
194
- try {
195
- sessionStore()?.removeItem(STRIPE_PAYPAL_CONTINUATION_KEY);
196
- } catch {
197
- }
198
- }
199
- function stripePayPalReturnUrl(attempt) {
200
- const url = new URL((0, import_shared4.stripeRedirectReturnUrl)());
201
- url.searchParams.delete(STRIPE_PAYPAL_ATTEMPT_PARAM);
202
- if (attempt) url.searchParams.set(STRIPE_PAYPAL_ATTEMPT_PARAM, attempt);
203
- return url.toString();
204
- }
205
- function readStripePayPalReturnContinuation() {
206
- if (typeof window === "undefined") return null;
207
- const [paymentIntentId] = (0, import_shared4.readStripeRedirectParams)();
208
- if (!paymentIntentId) return null;
209
- const attempt = new URLSearchParams(window.location.search).get(STRIPE_PAYPAL_ATTEMPT_PARAM);
210
- if (!attempt) return null;
211
- try {
212
- const raw = sessionStore()?.getItem(STRIPE_PAYPAL_CONTINUATION_KEY);
213
- if (!raw) return null;
214
- const parsed = JSON.parse(raw);
215
- if (!parsed || parsed.attempt !== attempt || typeof parsed.sessionId !== "string") return null;
216
- return {
217
- attempt,
218
- sessionId: parsed.sessionId,
219
- ...typeof parsed.nonce === "string" ? { nonce: parsed.nonce } : {}
220
- };
221
- } catch {
222
- return null;
223
- }
224
- }
225
- function consumeStripePayPalReturn() {
226
- clearStripePayPalContinuation();
227
- window.history.replaceState({}, "", stripePayPalReturnUrl());
228
- }
229
- var import_shared4, STRIPE_PAYPAL_CONTINUATION_KEY, STRIPE_PAYPAL_ATTEMPT_PARAM;
230
- var init_stripe_paypal_continuation = __esm({
231
- "src/stripe-paypal-continuation.ts"() {
232
- "use strict";
233
- import_shared4 = require("@flopay/shared");
234
- STRIPE_PAYPAL_CONTINUATION_KEY = "flopay_vue_paypal_resume";
235
- STRIPE_PAYPAL_ATTEMPT_PARAM = "flopay_paypal_attempt";
236
- }
237
- });
238
-
239
- // src/stripe-elements.ts
240
- var stripe_elements_exports = {};
241
- __export(stripe_elements_exports, {
242
- StripePaymentMethods: () => StripePaymentMethods
243
- });
244
- function buildExpressMethodMap(wallets) {
245
- const enabledKeys = new Set(wallets.map(import_shared5.stripeExpressMethodToOptionKey));
246
- return Object.fromEntries(
247
- ["applePay", "googlePay", "paypal", "link", "amazonPay", "klarna"].map((key) => [
248
- key,
249
- enabledKeys.has(key) ? "auto" : "never"
250
- ])
251
- );
252
- }
253
- function checkoutButtonMethodFromProviderMethod(method) {
254
- if (method === "paypal") return "paypal";
255
- if (method === "apple_pay") return "apple_pay";
256
- return "google_pay";
257
- }
258
- function walletClockNow() {
259
- return globalThis.performance?.now() ?? Date.now();
260
- }
261
- function stripeMethodCategory(method) {
262
- return WALLET_METHODS.has(method) ? "wallet" : "apm";
263
- }
264
- function declineReason(error) {
265
- return error.decline_code ?? error.code ?? "provider_declined";
266
- }
267
- async function reportSettledIntentVerdict(response, method, sessionId, session, outcomes) {
268
- const json = response.status === 204 ? null : await response.json().catch(() => null);
269
- if (response.ok) {
270
- const authorized = session?.captureMethod === "manual" || json?.status === "authorized";
271
- const paymentId = typeof json?.paymentId === "string" ? json.paymentId : session?.paymentId;
272
- const authorizationExpiresAt = typeof json?.authorizationExpiresAt === "string" ? json.authorizationExpiresAt : session?.authorizationExpiresAt;
273
- outcomes.complete(
274
- authorized ? {
275
- status: "authorized",
276
- ...paymentId ? { paymentId } : {},
277
- sessionId: typeof json?.sessionId === "string" ? json.sessionId : sessionId,
278
- ...authorizationExpiresAt ? { authorizationExpiresAt } : {},
279
- checkoutMethod: method
280
- } : { status: "succeeded", checkoutMethod: method }
281
- );
282
- return;
283
- }
284
- const type = typeof json?.type === "string" ? json.type : void 0;
285
- const message = typeof json?.message === "string" ? json.message : void 0;
286
- const code = typeof json?.code === "string" ? json.code : void 0;
287
- const actionCode = type === void 0 ? void 0 : SETTLED_ACTION_REQUIRED_CODES.get(type);
288
- if (actionCode === void 0 && (0, import_shared5.classifyPaymentRejection)(response.status, json) === "payment_declined") {
289
- outcomes.decline({
290
- method,
291
- message: message ?? "Your payment was declined.",
292
- code,
293
- declineCode: typeof json?.declineCode === "string" ? json.declineCode : code,
294
- sessionId
295
- });
296
- return;
297
- }
298
- outcomes.error(
299
- new import_shared5.FloPayError(message ?? "Payment could not be completed. Please try again.", "api_error", {
300
- code: actionCode ?? code ?? "payment_processing_error",
301
- statusCode: response.status,
302
- sessionId
303
- })
304
- );
305
- }
306
- var import_card_setup2, import_shared5, import_vue5, WALLET_METHODS, EXPRESS_CHECKOUT_CLICK_BUDGET_MS, PAYPAL_REDIRECT_TILE_HEIGHT, stripePayPalResumeAttempts, SETTLED_ACTION_REQUIRED_CODES, StripePaymentMethods;
307
- var init_stripe_elements = __esm({
308
- "src/stripe-elements.ts"() {
309
- "use strict";
310
- import_card_setup2 = require("@flopay/js/card-setup");
311
- import_shared5 = require("@flopay/shared");
312
- import_vue5 = require("vue");
313
- init_context();
314
- init_provider();
315
- init_stripe_paypal_continuation();
316
- WALLET_METHODS = /* @__PURE__ */ new Set(["apple_pay", "google_pay", "link", "paypal", "amazon_pay"]);
317
- EXPRESS_CHECKOUT_CLICK_BUDGET_MS = 900;
318
- PAYPAL_REDIRECT_TILE_HEIGHT = 44;
319
- stripePayPalResumeAttempts = /* @__PURE__ */ new Map();
320
- SETTLED_ACTION_REQUIRED_CODES = /* @__PURE__ */ new Map([
321
- ["3ds_required", "authentication_required"],
322
- ["paypal_direct_required", "paypal_direct_required"]
323
- ]);
324
- StripePaymentMethods = (0, import_vue5.defineComponent)({
325
- name: "FloPayStripePaymentMethods",
326
- props: {
327
- session: { type: Object, default: null },
328
- sessionId: { type: String, required: true },
329
- nonce: { type: String, default: void 0 },
330
- billingApiUrl: { type: String, required: true },
331
- publishableKey: { type: String, required: true },
332
- methods: { type: Array, required: true },
333
- /** `payment` for checkout, `setup` for payment-method setup. */
334
- intentKind: { type: String, default: "payment" },
335
- currency: { type: String, default: void 0 },
336
- amount: { type: Number, default: 0 },
337
- /**
338
- * React's `totalAmount`: the cart total due today, in minor units. When it
339
- * is given on a checkout (`intentKind: 'payment'`), the wallet row follows
340
- * React's wallet group: its Elements mode, amount and capture method come
341
- * from the shared `resolveWalletModeOptions` (setup mode for a $0 total),
342
- * and its intent is `totalAmount > 0 ? 'payment' : 'setup'`.
343
- */
344
- totalAmount: { type: Number, default: void 0 },
345
- returnUrl: { type: String, default: void 0 },
346
- /** The theme's appearance, normalized for Stripe Elements (React's setup branch does the same). */
347
- appearance: { type: Object, default: void 0 },
348
- /**
349
- * React's `stripePayPalPresentation`, which the form resolves from its
350
- * `walletPresentation` prop through the shared
351
- * `resolveStripePayPalPresentation`. With `redirect`, Stripe-routed PayPal
352
- * leaves the wallet row and renders as React's full-page "Pay with PayPal"
353
- * redirect tile, which resumes the payment when the buyer returns.
354
- */
355
- paypalPresentation: { type: String, default: "popup" },
356
- /**
357
- * The form's click gate (React's `runBeforeButtonClick`), run by the
358
- * redirect tile and by the wallet row's Express Checkout click.
359
- */
360
- runBeforeButtonClick: {
361
- type: Function,
362
- default: void 0
363
- },
364
- /**
365
- * React's `onTokenizedBody={dispatchTokenizedBody}` for the redirect tile:
366
- * the form posts `/process` with the approved payment. Without it, the
367
- * tile reports `complete` itself, as this component's wallet row does.
368
- */
369
- onTokenizedBody: {
370
- type: Function,
371
- default: void 0
372
- },
373
- /**
374
- * React's `isProcessing={isSubmitting}`: while the form is processing, the
375
- * PayPal redirect tile and the APM button are disabled and ignore clicks.
376
- */
377
- isProcessing: { type: Boolean, default: false },
378
- /**
379
- * The form's storage-free stand-in for the click-time account patch React
380
- * restores from its `localStorage` continuation (issue #410, triage AC 4:
381
- * Vue never stores it). On an authorized redirect return it is asked once
382
- * for the account, with the returned session id; what it answers goes to
383
- * `onTokenizedBody` as the attempt's `accountPatch`. A throw or no answer
384
- * continues without one, because the payment is already authorized.
385
- */
386
- recoverAccountPatch: {
387
- type: Function,
388
- default: void 0
389
- }
390
- },
391
- emits: {
392
- /** The buyer confirmed a wallet or APM and its element validated: the attempt starts. */
393
- submitting: () => true,
394
- complete: (_result) => true,
395
- decline: (_decline) => true,
396
- error: (_error) => true
397
- },
398
- setup(props, { emit }) {
399
- const walletContainer = (0, import_vue5.ref)(null);
400
- const apmContainer = (0, import_vue5.ref)(null);
401
- const processing = (0, import_vue5.ref)(false);
402
- const busy = () => processing.value || props.isProcessing;
403
- const cleanups = [];
404
- let apmElements = null;
405
- let stripe = null;
406
- const elementsOptions = (methods, surface) => {
407
- const setupFutureUsage = (0, import_shared5.resolveSetupFutureUsage)(props.session, methods, surface);
408
- const currency = (props.currency ?? props.session?.currency ?? "usd").toLowerCase();
409
- const appearance = props.appearance ? { appearance: (0, import_shared5.toStripeAppearance)(props.appearance) } : {};
410
- return props.intentKind === "setup" ? { mode: "setup", currency, allowedPaymentMethodTypes: methods, ...appearance } : {
411
- mode: props.session?.mode === "subscription" ? "subscription" : "payment",
412
- amount: props.amount,
413
- currency,
414
- // Stripe.js Endive (@stripe/stripe-js 10) removed the Elements
415
- // `paymentMethodTypes` option; `allowedPaymentMethodTypes` replaces it.
416
- allowedPaymentMethodTypes: methods,
417
- ...setupFutureUsage ? { setupFutureUsage } : {},
418
- ...appearance
419
- };
420
- };
421
- const walletFollowsTotal = () => props.intentKind === "payment" && typeof props.totalAmount === "number";
422
- const walletIntentKind = () => {
423
- if (!walletFollowsTotal()) return props.intentKind;
424
- return (props.totalAmount ?? 0) > 0 ? "payment" : "setup";
425
- };
426
- const walletElementsOptions = (methods) => {
427
- if (!walletFollowsTotal()) return elementsOptions(methods, "wallet");
428
- const setupFutureUsage = (0, import_shared5.resolveSetupFutureUsage)(props.session, methods, "wallet");
429
- const currency = (props.currency ?? props.session?.currency ?? "usd").toLowerCase();
430
- return {
431
- ...(0, import_shared5.resolveWalletModeOptions)(props.totalAmount, props.session?.captureMethod),
432
- currency,
433
- allowedPaymentMethodTypes: methods,
434
- ...setupFutureUsage ? { setupFutureUsage } : {},
435
- ...props.appearance ? { appearance: (0, import_shared5.toStripeAppearance)(props.appearance) } : {}
436
- };
437
- };
438
- let walletAttempt = null;
439
- const floPayContext = (0, import_vue5.inject)(FLOPAY_CONTEXT, null);
440
- const walletTelemetry = () => {
441
- const instance = floPayContext?.flopay.value;
442
- return instance ? telemetryBridge(instance) : void 0;
443
- };
444
- let walletSheetClick = null;
445
- let walletSheetAttempts = 0;
446
- const endWalletSheetClick = () => {
447
- walletSheetClick?.stopObserving();
448
- walletSheetClick = null;
449
- };
450
- const observeWalletSheetClick = (method, startedAt) => {
451
- endWalletSheetClick();
452
- walletSheetAttempts += 1;
453
- const click = {
454
- attempt: walletSheetAttempts,
455
- method,
456
- startedAt,
457
- handoffObserved: false,
458
- stopObserving: () => {
459
- }
460
- };
461
- const onBlur = () => {
462
- click.handoffObserved = true;
463
- };
464
- const onVisibilityChange = () => {
465
- if (document.visibilityState === "hidden") click.handoffObserved = true;
466
- };
467
- window.addEventListener("blur", onBlur);
468
- document.addEventListener("visibilitychange", onVisibilityChange);
469
- click.stopObserving = () => {
470
- window.removeEventListener("blur", onBlur);
471
- document.removeEventListener("visibilitychange", onVisibilityChange);
472
- };
473
- walletSheetClick = click;
474
- };
475
- cleanups.push(endWalletSheetClick);
476
- const reportWalletSheetRefusal = (click) => {
477
- const environment = (0, import_shared5.detectPayPalEnvironment)();
478
- walletTelemetry()?.error?.({
479
- errorCode: "PROVIDER_RUNTIME_FAILED",
480
- failureCategory: "provider_runtime",
481
- stage: "overlay_open",
482
- provider: "stripe",
483
- paymentMethodCategory: "wallet",
484
- requestCategory: "provider_sdk",
485
- terminalReason: "provider_error",
486
- attempt: click.attempt,
487
- walletType: "google_pay",
488
- ...environment,
489
- presentationMode: "popup"
490
- });
491
- const failure = new import_shared5.FloPayError((0, import_shared5.buildWalletSheetWindowMessage)("Google Pay"), "api_error", {
492
- code: "external_payment_method_failed",
493
- param: click.method,
494
- details: {
495
- providerCode: import_shared5.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,
496
- popupBlocked: false,
497
- ...environment,
498
- presentationMode: "popup"
499
- }
500
- });
501
- (0, import_shared5.invokeMerchantCallback)(() => emit("error", failure));
502
- };
503
- const gateWalletClick = async (event) => {
504
- const clickStartedAt = walletClockNow();
505
- walletAttempt = null;
506
- endWalletSheetClick();
507
- const gate = props.runBeforeButtonClick;
508
- if (!gate) {
509
- observeWalletSheetClick(event.expressPaymentType, clickStartedAt);
510
- event.resolve();
511
- return;
512
- }
513
- let clickActive = true;
514
- const clickTimer = setTimeout(() => {
515
- clickActive = false;
516
- event.reject();
517
- }, EXPRESS_CHECKOUT_CLICK_BUDGET_MS);
518
- let beforeClick;
519
- try {
520
- beforeClick = await gate(checkoutButtonMethodFromProviderMethod(event.expressPaymentType));
521
- } catch {
522
- beforeClick = { proceed: false };
523
- } finally {
524
- clearTimeout(clickTimer);
525
- }
526
- if (!clickActive) return;
527
- if (!beforeClick.proceed) {
528
- event.reject();
529
- return;
530
- }
531
- walletAttempt = {
532
- method: event.expressPaymentType,
533
- ...beforeClick.sessionId ? { sessionId: beforeClick.sessionId } : {},
534
- ...beforeClick.nonce ? { nonce: beforeClick.nonce } : {}
535
- };
536
- observeWalletSheetClick(event.expressPaymentType, clickStartedAt);
537
- event.resolve();
538
- };
539
- const settledVerdictOutcomes = {
540
- complete: (result) => (0, import_shared5.invokeMerchantCallback)(() => emit("complete", result)),
541
- decline: (decline) => (0, import_shared5.invokeMerchantCallback)(() => emit("decline", decline)),
542
- error: (failure) => (0, import_shared5.invokeMerchantCallback)(() => emit("error", failure))
543
- };
544
- const confirm = async (elements, method, intentKind = props.intentKind, attempt = null) => {
545
- if (!stripe || processing.value) return;
546
- processing.value = true;
547
- const api = new import_card_setup2.PaymentAPI(props.billingApiUrl, { telemetry: false });
548
- const category = stripeMethodCategory(method);
549
- const sessionId = attempt?.sessionId ?? props.sessionId;
550
- const nonce = attempt?.nonce ?? props.nonce;
551
- try {
552
- const submitted = await elements.submit();
553
- if (submitted.error) return;
554
- (0, import_shared5.invokeMerchantCallback)(() => emit("submitting"));
555
- const intent = await api.createSessionIntent(sessionId, nonce ?? "", {
556
- provider: "stripe",
557
- paymentMethodCategory: category,
558
- paymentMethodType: method,
559
- paymentMethodId: null,
560
- intentKind
561
- });
562
- if ((0, import_shared5.isSettledSessionIntent)(intent)) {
563
- if (intentKind === "setup") throw (0, import_shared5.settledSessionIntentError)(sessionId);
564
- await reportSettledIntentVerdict(
565
- intent.response,
566
- method,
567
- sessionId,
568
- props.session,
569
- settledVerdictOutcomes
570
- );
571
- return;
572
- }
573
- const clientSecret = intent.clientSecret ?? "";
574
- const returnUrl = props.returnUrl ?? window.location.href;
575
- const { error } = intentKind === "setup" ? await stripe.confirmSetup({
576
- elements,
577
- clientSecret,
578
- confirmParams: { return_url: returnUrl },
579
- redirect: "if_required"
580
- }) : await stripe.confirmPayment({
581
- elements,
582
- clientSecret,
583
- confirmParams: { return_url: returnUrl },
584
- redirect: "if_required"
585
- });
586
- if (error) {
587
- if (intentKind === "payment") {
588
- void api.reportSessionIntentDecline(sessionId, nonce ?? "", {
589
- provider: "stripe",
590
- paymentMethodCategory: category,
591
- paymentMethodType: method,
592
- providerDeclineReason: declineReason(error),
593
- providerIntentId: intent.providerObjectId
594
- }).catch(() => {
595
- });
596
- }
597
- const decline = {
598
- method,
599
- message: error.message ?? "Your payment was declined.",
600
- code: error.code,
601
- declineCode: error.decline_code ?? error.code,
602
- sessionId
603
- };
604
- (0, import_shared5.invokeMerchantCallback)(() => emit("decline", decline));
605
- return;
606
- }
607
- const result = {
608
- status: "succeeded",
609
- paymentIntentId: intent.providerObjectId,
610
- checkoutMethod: method
611
- };
612
- (0, import_shared5.invokeMerchantCallback)(() => emit("complete", result));
613
- } catch (error) {
614
- const failure = error instanceof import_shared5.FloPayError ? error : new import_shared5.FloPayError(
615
- error instanceof Error ? error.message : "Payment failed.",
616
- "api_error"
617
- );
618
- (0, import_shared5.invokeMerchantCallback)(() => emit("error", failure));
619
- } finally {
620
- processing.value = false;
621
- }
622
- };
623
- const paypalRedirect = () => props.paypalPresentation === "redirect" && props.intentKind === "payment" && props.methods.includes("paypal");
624
- let active = true;
625
- const emitPayPalDecline = (message, sessionId, error) => {
626
- const decline = {
627
- method: "paypal",
628
- message,
629
- ...error ? { code: error.code, declineCode: error.decline_code ?? error.code } : {},
630
- sessionId
631
- };
632
- (0, import_shared5.invokeMerchantCallback)(() => emit("decline", decline));
633
- };
634
- const emitPayPalFailure = (message, code) => {
635
- const failure = new import_shared5.FloPayError(message, "api_error", code ? { code } : void 0);
636
- (0, import_shared5.invokeMerchantCallback)(() => emit("error", failure));
637
- };
638
- const handOffPayPal = (body, overrides) => {
639
- if (props.onTokenizedBody) {
640
- props.onTokenizedBody(body, overrides);
641
- return;
642
- }
643
- const result = {
644
- status: "succeeded",
645
- paymentIntentId: body.threeDSecureActionResultTokenId,
646
- checkoutMethod: "paypal"
647
- };
648
- (0, import_shared5.invokeMerchantCallback)(() => emit("complete", result));
649
- };
650
- const redirectToPayPal = async () => {
651
- if (!stripe || busy()) return;
652
- processing.value = true;
653
- const api = new import_card_setup2.PaymentAPI(props.billingApiUrl, { telemetry: false });
654
- let sessionId = props.sessionId;
655
- try {
656
- const beforeClick = props.runBeforeButtonClick ? await props.runBeforeButtonClick("paypal") : { proceed: true };
657
- if (!beforeClick.proceed) return;
658
- sessionId = beforeClick.sessionId ?? props.sessionId;
659
- const nonce = beforeClick.nonce ?? props.nonce;
660
- const createPaymentMethod = stripe.createPaymentMethod;
661
- const { error: pmError, paymentMethod } = await createPaymentMethod.call(stripe, {
662
- type: "paypal"
663
- });
664
- if (pmError) {
665
- emitPayPalFailure(
666
- pmError.message ?? "PayPal could not be started.",
667
- "stripe_paypal_create_payment_method_failed"
668
- );
669
- return;
670
- }
671
- const intent = await api.createSessionIntent(sessionId, nonce ?? "", {
672
- provider: "stripe",
673
- paymentMethodCategory: "wallet",
674
- paymentMethodType: "paypal",
675
- paymentMethodId: paymentMethod?.id ?? null,
676
- intentKind: "payment"
677
- });
678
- if ((0, import_shared5.isSettledSessionIntent)(intent)) {
679
- await reportSettledIntentVerdict(
680
- intent.response,
681
- "paypal",
682
- sessionId,
683
- props.session,
684
- settledVerdictOutcomes
685
- );
686
- return;
687
- }
688
- if (intent.provider !== "stripe") {
689
- throw new Error("Invalid provider returned for PayPal intent");
690
- }
691
- const clientSecret = intent.clientSecret ?? "";
692
- const attempt = createStripePayPalAttempt();
693
- const continuationSaved = saveStripePayPalContinuation({ attempt, sessionId, nonce });
694
- if (!continuationSaved) {
695
- throw new Error("Unable to save PayPal checkout progress. Please try again.");
696
- }
697
- const { error, paymentIntent } = await stripe.confirmPayment({
698
- clientSecret,
699
- confirmParams: {
700
- return_url: stripePayPalReturnUrl(attempt),
701
- ...paymentMethod?.id ? { payment_method: paymentMethod.id } : {}
702
- },
703
- redirect: "if_required"
704
- });
705
- clearStripePayPalContinuation();
706
- if (error) {
707
- if ((0, import_shared5.isProviderDecline)(error)) {
708
- void api.reportSessionIntentDecline(sessionId, nonce ?? "", {
709
- provider: "stripe",
710
- paymentMethodCategory: "wallet",
711
- paymentMethodType: "paypal",
712
- providerDeclineReason: error.code ?? "provider_declined",
713
- providerIntentId: intent.providerObjectId
714
- }).catch(() => {
715
- });
716
- emitPayPalDecline(error.message ?? "Your payment was declined.", sessionId, error);
717
- return;
718
- }
719
- emitPayPalFailure(
720
- error.message ?? "PayPal payment failed.",
721
- "stripe_paypal_confirm_failed"
722
- );
723
- return;
724
- }
725
- const paymentMethodId = typeof paymentIntent?.payment_method === "string" ? paymentIntent.payment_method : paymentIntent?.payment_method?.id;
726
- handOffPayPal(
727
- {
728
- id: paymentMethodId ?? paymentIntent?.id,
729
- type: "card",
730
- threeDSecureActionResultTokenId: paymentIntent?.id,
731
- isPaypal: true
732
- },
733
- {
734
- accountPatch: beforeClick.accountPatch,
735
- paymentMethodCategory: "paypal",
736
- presentationMode: "redirect",
737
- sessionId,
738
- nonce
739
- }
740
- );
741
- } catch (error) {
742
- emitPayPalFailure(
743
- error instanceof Error ? error.message : "PayPal payment failed.",
744
- "stripe_paypal_failed"
745
- );
746
- } finally {
747
- processing.value = false;
748
- }
749
- };
750
- const recoverReturnAccount = async (sessionId) => {
751
- const recover = props.recoverAccountPatch;
752
- if (!recover) return void 0;
753
- try {
754
- return await recover(sessionId) ?? void 0;
755
- } catch {
756
- return void 0;
757
- }
758
- };
759
- const continueAuthorizedReturn = async (paymentIntent, continuation) => {
760
- const paymentMethodId = typeof paymentIntent.payment_method === "string" ? paymentIntent.payment_method : paymentIntent.payment_method?.id;
761
- const accountPatch = await recoverReturnAccount(continuation.sessionId);
762
- if (!active) return;
763
- handOffPayPal(
764
- {
765
- id: paymentMethodId ?? paymentIntent.id,
766
- type: "card",
767
- threeDSecureActionResultTokenId: paymentIntent.id,
768
- isPaypal: true
769
- },
770
- {
771
- ...accountPatch ? { accountPatch } : {},
772
- sessionId: continuation.sessionId,
773
- nonce: continuation.nonce,
774
- presentationMode: "redirect"
775
- }
776
- );
777
- };
778
- const resumeStripePayPal = async (provider) => {
779
- const [paymentIntentId, clientSecret, redirectStatus] = (0, import_shared5.readStripeRedirectParams)();
780
- if (!paymentIntentId || !clientSecret) return;
781
- const continuation = readStripePayPalReturnContinuation();
782
- if (!continuation) return;
783
- const sessionId = continuation.sessionId;
784
- const retrievalKey = continuation.attempt;
785
- let retrieval = stripePayPalResumeAttempts.get(retrievalKey);
786
- if (!retrieval) {
787
- retrieval = redirectStatus === "failed" ? Promise.resolve(null) : Promise.resolve().then(() => provider.retrievePaymentIntent(clientSecret));
788
- stripePayPalResumeAttempts.set(retrievalKey, retrieval);
789
- }
790
- processing.value = true;
791
- try {
792
- const result = await retrieval;
793
- if (!active) return;
794
- if (result?.error) {
795
- stripePayPalResumeAttempts.delete(retrievalKey);
796
- emitPayPalFailure(
797
- result.error.message ?? "Failed to retrieve PayPal payment status.",
798
- "REDIRECT_RESUME_FAILED"
799
- );
800
- return;
801
- }
802
- consumeStripePayPalReturn();
803
- stripePayPalResumeAttempts.delete(retrievalKey);
804
- if (redirectStatus === "failed") {
805
- emitPayPalDecline("PayPal payment was declined. Please try again.", sessionId);
806
- return;
807
- }
808
- const paymentIntent = result?.paymentIntent;
809
- if (paymentIntent && paymentIntent.id !== paymentIntentId) {
810
- emitPayPalFailure(
811
- "Failed to match the returned PayPal payment.",
812
- "REDIRECT_RESUME_FAILED"
813
- );
814
- return;
815
- }
816
- if (paymentIntent && (paymentIntent.status === "requires_capture" || paymentIntent.status === "succeeded")) {
817
- await continueAuthorizedReturn(paymentIntent, continuation);
818
- return;
819
- }
820
- emitPayPalDecline("PayPal payment was not completed. Please try again.", sessionId);
821
- } catch (error) {
822
- if (!active) return;
823
- stripePayPalResumeAttempts.delete(retrievalKey);
824
- emitPayPalFailure(
825
- error instanceof Error ? error.message : "Failed to complete PayPal payment.",
826
- "REDIRECT_RESUME_FAILED"
827
- );
828
- } finally {
829
- if (active) processing.value = false;
830
- }
831
- };
832
- (0, import_vue5.onMounted)(async () => {
833
- const wallets = props.methods.filter(
834
- (method) => WALLET_METHODS.has(method) && !(method === "paypal" && paypalRedirect())
835
- );
836
- const apms = props.methods.filter((method) => !WALLET_METHODS.has(method));
837
- try {
838
- const { loadStripe } = await import("@stripe/stripe-js");
839
- stripe = await loadStripe(props.publishableKey);
840
- if (!stripe) throw new Error("Stripe.js did not initialize.");
841
- if (paypalRedirect()) void resumeStripePayPal(stripe);
842
- if (wallets.length > 0 && walletContainer.value) {
843
- if ((0, import_shared5.shouldPreferWalletPopup)()) cleanups.push((0, import_shared5.denyPaymentPermissionToNewFrames)(document));
844
- const elements = stripe.elements(walletElementsOptions(wallets));
845
- const express = elements.create("expressCheckout", {
846
- paymentMethods: buildExpressMethodMap(wallets)
847
- });
848
- express.on("click", (event) => gateWalletClick(event));
849
- express.on("confirm", (event) => {
850
- const attempt = walletAttempt;
851
- walletAttempt = null;
852
- endWalletSheetClick();
853
- void confirm(elements, event.expressPaymentType, walletIntentKind(), attempt);
854
- });
855
- express.on("cancel", () => {
856
- walletAttempt = null;
857
- const click = walletSheetClick;
858
- endWalletSheetClick();
859
- if (click && (0, import_shared5.isWalletSheetRefusedForWindowSize)({
860
- method: click.method,
861
- elapsedMs: walletClockNow() - click.startedAt,
862
- handoffObserved: click.handoffObserved
863
- })) {
864
- reportWalletSheetRefusal(click);
865
- }
866
- });
867
- express.mount(walletContainer.value);
868
- cleanups.push(() => express.destroy());
869
- }
870
- if (apms.length > 0 && apmContainer.value) {
871
- apmElements = stripe.elements(elementsOptions(apms, "inline_apm"));
872
- const payment = apmElements.create("payment", { layout: "accordion" });
873
- payment.mount(apmContainer.value);
874
- cleanups.push(() => payment.destroy());
875
- }
876
- } catch (error) {
877
- const failure = new import_shared5.FloPayError(
878
- error instanceof Error ? error.message : "Payment methods failed to load.",
879
- "api_error",
880
- { code: "PROVIDER_LOAD_FAILED" }
881
- );
882
- (0, import_shared5.invokeMerchantCallback)(() => emit("error", failure));
883
- }
884
- });
885
- (0, import_vue5.onBeforeUnmount)(() => {
886
- active = false;
887
- for (const cleanup of cleanups.splice(0)) cleanup();
888
- });
889
- return () => (0, import_vue5.h)("div", { "data-testid": "flopay-stripe-methods" }, [
890
- // React renders the Stripe PayPal group above the wallet row.
891
- paypalRedirect() ? (0, import_vue5.h)(
892
- "div",
893
- {
894
- role: "group",
895
- "aria-label": "PayPal payment method",
896
- "data-testid": "flopay-paypal-focus-target",
897
- style: { borderRadius: "8px" }
898
- },
899
- [
900
- (0, import_vue5.h)(
901
- "button",
902
- {
903
- type: "button",
904
- "data-testid": "flopay-stripe-paypal-redirect",
905
- disabled: busy(),
906
- onClick: () => void redirectToPayPal(),
907
- style: {
908
- width: "100%",
909
- minHeight: `${PAYPAL_REDIRECT_TILE_HEIGHT}px`,
910
- border: "1px solid #d1d5db",
911
- borderRadius: "8px",
912
- background: "#ffc439",
913
- color: "#111827",
914
- cursor: busy() ? "not-allowed" : "pointer",
915
- fontSize: "1rem",
916
- fontWeight: 700
917
- }
918
- },
919
- "Pay with PayPal"
920
- )
921
- ]
922
- ) : null,
923
- (0, import_vue5.h)("div", { ref: walletContainer, "data-testid": "flopay-express-checkout" }),
924
- (0, import_vue5.h)("div", { ref: apmContainer, "data-testid": "flopay-payment-element" }),
925
- props.methods.some((method) => !WALLET_METHODS.has(method)) ? (0, import_vue5.h)(
926
- "button",
927
- {
928
- type: "button",
929
- disabled: busy(),
930
- onClick: () => {
931
- if (props.isProcessing) return;
932
- const method = props.methods.find((candidate) => !WALLET_METHODS.has(candidate));
933
- if (apmElements && method) void confirm(apmElements, method);
934
- }
935
- },
936
- processing.value ? "Processing\u2026" : "Continue"
937
- ) : null
938
- ]);
939
- }
940
- });
941
- }
942
- });
943
-
944
- // src/payment-method-setup-paypal.ts
945
- var payment_method_setup_paypal_exports = {};
946
- __export(payment_method_setup_paypal_exports, {
947
- PayPalSetupMethod: () => PayPalSetupMethod
948
- });
949
- var import_card_setup3, import_shared6, import_paypal_js, import_vue6, PayPalSetupMethod;
950
- var init_payment_method_setup_paypal = __esm({
951
- "src/payment-method-setup-paypal.ts"() {
952
- "use strict";
953
- import_card_setup3 = require("@flopay/js/card-setup");
954
- import_shared6 = require("@flopay/shared");
955
- import_paypal_js = require("@paypal/paypal-js");
956
- import_vue6 = require("vue");
957
- PayPalSetupMethod = (0, import_vue6.defineComponent)({
958
- name: "FloPayPayPalSetupMethod",
959
- props: {
960
- clientId: { type: String, required: true },
961
- environment: { type: String, default: void 0 },
962
- /** The setup session's own currency, when the read carries one. A vault flow needs none. */
963
- currency: { type: String, default: void 0 },
964
- sessionId: { type: String, required: true },
965
- nonce: { type: String, required: true },
966
- billingApiUrl: { type: String, required: true },
967
- telemetry: { type: Boolean, default: void 0 },
968
- customer: { type: Object, required: true }
969
- },
970
- emits: {
971
- /** The buyer started saving PayPal. */
972
- submitting: () => true,
973
- /** PayPal accepted the account and the billing API took the token. */
974
- confirmed: () => true,
975
- /** A technical failure; `retryable` says whether trying again can help. */
976
- failed: (_error, _options) => true,
977
- /** The buyer closed PayPal's window without an outcome (not a cancel). */
978
- abandoned: () => true
979
- },
980
- setup(props, { emit }) {
981
- const container = (0, import_vue6.ref)(null);
982
- let active = true;
983
- let close;
984
- let api = null;
985
- (0, import_vue6.onMounted)(() => {
986
- const { inAppBrowser } = (0, import_shared6.detectPayPalEnvironment)();
987
- const client = new import_card_setup3.PaymentAPI(props.billingApiUrl, { telemetry: props.telemetry });
988
- api = client;
989
- const { sessionId, nonce } = props;
990
- const customer = {
991
- userId: props.customer.userId,
992
- email: props.customer.email
993
- };
994
- const environment = props.environment;
995
- void (async () => {
996
- try {
997
- const paypal = await (0, import_paypal_js.loadScript)({
998
- clientId: props.clientId,
999
- ...props.currency ? { currency: props.currency.toUpperCase() } : {},
1000
- components: "buttons",
1001
- ...environment === "sandbox" || environment === "production" ? { environment } : {}
1002
- });
1003
- const target = container.value;
1004
- if (!active || !target) return;
1005
- if (!paypal?.Buttons) {
1006
- throw new import_shared6.FloPayError("PayPal could not be loaded.", "api_error", {
1007
- code: "paypal_unavailable"
1008
- });
1009
- }
1010
- const buttons = paypal.Buttons({
1011
- createVaultSetupToken: async () => {
1012
- emit("submitting");
1013
- const intent = await client.createSessionIntent(sessionId, nonce, {
1014
- provider: "paypal",
1015
- paymentMethodCategory: "wallet",
1016
- paymentMethodType: import_shared6.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,
1017
- paymentMethodId: null,
1018
- intentKind: "setup"
1019
- });
1020
- if ((0, import_shared6.isSettledSessionIntent)(intent)) throw (0, import_shared6.settledSessionIntentError)(sessionId);
1021
- if (intent.provider !== "paypal" || intent.providerObjectType !== "setup_token") {
1022
- throw new import_shared6.FloPayError(
1023
- "The billing API did not return a PayPal setup token.",
1024
- "api_error",
1025
- { code: "InvalidSessionIntentResponse" }
1026
- );
1027
- }
1028
- return intent.providerObjectId;
1029
- },
1030
- onApprove: async (data) => {
1031
- const token = data.vaultSetupToken;
1032
- if (!token) {
1033
- throw new import_shared6.FloPayError("PayPal approved without a setup token.", "api_error", {
1034
- code: "paypal_setup_token_missing"
1035
- });
1036
- }
1037
- const response = await client.processPayment(customer.userId, {
1038
- sessionId,
1039
- nonce,
1040
- paymentMethodCategory: "paypal",
1041
- tokenizedData: {
1042
- id: token,
1043
- type: "paypal_setup_token",
1044
- isPaypal: true,
1045
- gateway: "paypal",
1046
- paymentMethodType: import_shared6.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE
1047
- },
1048
- accountData: customer
1049
- });
1050
- if (!response.ok) {
1051
- throw new import_shared6.FloPayError("PayPal could not be saved.", "api_error", {
1052
- code: "paypal_setup_failed",
1053
- statusCode: response.status
1054
- });
1055
- }
1056
- if (active) emit("confirmed");
1057
- },
1058
- onCancel: () => {
1059
- if (active) emit("abandoned");
1060
- },
1061
- onError: (error) => {
1062
- if (!active) return;
1063
- const { popupBlocked } = (0, import_shared6.classifyExternalMethodFailure)(error, {
1064
- inAppBrowser,
1065
- handoffObserved: false
1066
- });
1067
- emit(
1068
- "failed",
1069
- popupBlocked ? new Error((0, import_shared6.buildExternalMethodRecoveryMessage)("PayPal", true, inAppBrowser)) : error,
1070
- { code: popupBlocked ? "popup_blocked" : "paypal_setup_failed", retryable: true }
1071
- );
1072
- }
1073
- });
1074
- close = () => buttons.close();
1075
- await buttons.render(target);
1076
- } catch (error) {
1077
- if (!active) return;
1078
- emit("failed", error, { code: "paypal_unavailable", retryable: true });
1079
- }
1080
- })();
1081
- });
1082
- (0, import_vue6.onBeforeUnmount)(() => {
1083
- active = false;
1084
- void close?.().catch(() => {
1085
- });
1086
- api?.destroy();
1087
- api = null;
1088
- });
1089
- return () => (0, import_vue6.h)("div", { ref: container, "data-flopay-paypal-setup": "" });
1090
- }
1091
- });
1092
- }
1093
- });
1094
-
1095
20
  // src/payment-method-setup-entry.ts
1096
21
  var payment_method_setup_entry_exports = {};
1097
22
  __export(payment_method_setup_entry_exports, {
1098
- FloPayPaymentMethodSetup: () => FloPayPaymentMethodSetup
23
+ FloPayPaymentMethodSetup: () => FloPayRuntimePaymentMethodSetup
1099
24
  });
1100
25
  module.exports = __toCommonJS(payment_method_setup_entry_exports);
1101
26
 
1102
- // src/flopay-payment-method-setup-main.ts
1103
- var import_card_setup4 = require("@flopay/js/card-setup");
1104
- var import_shared7 = require("@flopay/shared");
1105
- var import_vue7 = require("vue");
1106
-
1107
- // src/hosted-setup.ts
1108
- var import_card_setup = require("@flopay/js/card-setup");
1109
- var import_shared = require("@flopay/shared");
27
+ // src/flopay-runtime-payment-method-setup.ts
1110
28
  var import_vue2 = require("vue");
1111
29
 
1112
- // src/processing-overlay.ts
30
+ // src/flopay-runtime-card-setup.ts
31
+ var import_js = require("@flopay/js");
32
+ var import_shared = require("@flopay/shared");
1113
33
  var import_vue = require("vue");
1114
- var PROCESSING_OVERLAY_SUCCESS_DELAY_MS = 600;
1115
- var PROCESSING_OVERLAY_ERROR_DELAY_MS = 400;
1116
- var NEUTRAL_THEME = {
1117
- panel: { background: "white" },
1118
- spinnerTrackColor: "#e5e7eb",
1119
- spinnerAccentColor: "#4A49FF",
1120
- labelColors: { processing: "#374151", success: "#16a34a", error: "#dc2626" },
1121
- noteColor: "#6b7280"
1122
- };
1123
- var KEYFRAMES_ID = "flopay-processing-overlay-keyframes";
1124
- var KEYFRAMES = [
1125
- "@keyframes flopay-spin { to { transform: rotate(360deg); } }",
1126
- "@keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }",
1127
- "@keyframes flopay-draw { to { stroke-dashoffset: 0; } }",
1128
- "@keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }"
1129
- ].join("\n");
1130
- function ensureKeyframes() {
1131
- if (typeof document === "undefined" || document.getElementById(KEYFRAMES_ID)) return;
1132
- const style = document.createElement("style");
1133
- style.id = KEYFRAMES_ID;
1134
- style.textContent = KEYFRAMES;
1135
- document.head.appendChild(style);
1136
- }
1137
- var SVG = {
1138
- "aria-hidden": "true",
1139
- width: "48",
1140
- height: "48",
1141
- viewBox: "0 0 24 24",
1142
- fill: "none"
1143
- };
1144
- function statusIcon(status, theme) {
1145
- if (status === "processing") {
1146
- return (0, import_vue.h)("svg", { ...SVG, style: { animation: "flopay-spin 0.8s linear infinite" } }, [
1147
- (0, import_vue.h)("circle", {
1148
- cx: "12",
1149
- cy: "12",
1150
- r: "10",
1151
- stroke: theme.spinnerTrackColor,
1152
- "stroke-width": "3"
1153
- }),
1154
- (0, import_vue.h)("path", { d: "M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z", fill: theme.spinnerAccentColor })
1155
- ]);
1156
- }
1157
- if (status === "success") {
1158
- return (0, import_vue.h)("div", { style: { animation: "flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)" } }, [
1159
- (0, import_vue.h)("svg", SVG, [
1160
- (0, import_vue.h)("circle", { cx: "12", cy: "12", r: "11", fill: "#22c55e" }),
1161
- (0, import_vue.h)("path", {
1162
- d: "M7 12.5l3 3 7-7",
1163
- stroke: "white",
1164
- "stroke-width": "2.5",
1165
- "stroke-linecap": "round",
1166
- "stroke-linejoin": "round",
1167
- style: {
1168
- strokeDasharray: 20,
1169
- strokeDashoffset: 20,
1170
- animation: "flopay-draw 0.4s 0.15s ease forwards"
1171
- }
1172
- })
1173
- ])
1174
- ]);
1175
- }
1176
- return (0, import_vue.h)("div", { style: { animation: "flopay-shake 0.4s ease" } }, [
1177
- (0, import_vue.h)("svg", SVG, [
1178
- (0, import_vue.h)("circle", { cx: "12", cy: "12", r: "11", fill: "#ef4444" }),
1179
- (0, import_vue.h)("path", {
1180
- d: "M8 8l8 8M16 8l-8 8",
1181
- stroke: "white",
1182
- "stroke-width": "2.5",
1183
- "stroke-linecap": "round",
1184
- style: {
1185
- strokeDasharray: 12,
1186
- strokeDashoffset: 12,
1187
- animation: "flopay-draw 0.3s 0.1s ease forwards"
1188
- }
1189
- })
1190
- ])
1191
- ]);
1192
- }
1193
- var ProcessingOverlay = (0, import_vue.defineComponent)({
1194
- name: "FloPayProcessingOverlay",
1195
- props: {
1196
- status: { type: String, required: true },
1197
- errorMessage: { type: String, default: null },
1198
- processingLabel: { type: String, default: "PROCESSING..." },
1199
- successLabel: { type: String, default: "PAYMENT SUCCESSFUL" },
1200
- errorLabel: { type: String, default: "PAYMENT FAILED" },
1201
- /** Success sub-note; `null` omits it (surfaces that do not redirect). */
1202
- successNote: {
1203
- type: String,
1204
- default: "You will be automatically redirected, do not close or navigate away from this window."
1205
- },
1206
- theme: { type: Object, default: void 0 }
1207
- },
1208
- setup(props) {
1209
- (0, import_vue.onMounted)(ensureKeyframes);
1210
- return () => {
1211
- const theme = props.theme ?? NEUTRAL_THEME;
1212
- const noteStyle = {
1213
- fontSize: "13px",
1214
- color: theme.noteColor,
1215
- fontWeight: 400,
1216
- maxWidth: "260px",
1217
- lineHeight: 1.4,
1218
- margin: 0
1219
- };
1220
- const label = {
1221
- processing: props.processingLabel,
1222
- success: props.successLabel,
1223
- error: props.errorLabel
1224
- }[props.status];
1225
- const note = { processing: null, success: props.successNote, error: props.errorMessage }[props.status];
1226
- return (0, import_vue.h)(
1227
- "div",
1228
- {
1229
- "data-testid": "flopay-processing-overlay",
1230
- "data-status": props.status,
1231
- // The attribute the Vue setup surfaces' overlay already carried.
1232
- "data-state": props.status,
1233
- role: "dialog",
1234
- "aria-modal": "true",
1235
- style: {
1236
- position: "fixed",
1237
- inset: 0,
1238
- background: "rgba(0,0,0,0.35)",
1239
- display: "flex",
1240
- alignItems: "center",
1241
- justifyContent: "center",
1242
- zIndex: 1e3,
1243
- backdropFilter: "blur(2px)"
1244
- }
1245
- },
1246
- [
1247
- (0, import_vue.h)(
1248
- "div",
1249
- {
1250
- "data-testid": "flopay-processing-overlay-panel",
1251
- style: {
1252
- borderRadius: "12px",
1253
- boxShadow: "0 8px 32px rgba(0,0,0,0.18)",
1254
- ...theme.panel,
1255
- padding: "2rem 2.5rem",
1256
- textAlign: "center",
1257
- minWidth: "240px",
1258
- display: "flex",
1259
- flexDirection: "column",
1260
- alignItems: "center",
1261
- gap: "16px"
1262
- }
1263
- },
1264
- [
1265
- (0, import_vue.h)("div", { style: { width: "48px", height: "48px", position: "relative" } }, [
1266
- statusIcon(props.status, theme)
1267
- ]),
1268
- (0, import_vue.h)(
1269
- "span",
1270
- {
1271
- "data-testid": "flopay-processing-overlay-label",
1272
- style: {
1273
- fontSize: "14px",
1274
- fontWeight: 600,
1275
- letterSpacing: "0.05em",
1276
- color: theme.labelColors[props.status]
1277
- }
1278
- },
1279
- label
1280
- ),
1281
- note ? (0, import_vue.h)("p", { style: noteStyle }, note) : null
1282
- ]
1283
- )
1284
- ]
1285
- );
1286
- };
1287
- }
1288
- });
1289
-
1290
- // src/hosted-setup.ts
1291
- var FloPayCardSetupError = class extends import_shared.FloPayError {
1292
- constructor(message, type, options) {
1293
- super(message, type, options);
1294
- this.name = "FloPayCardSetupError";
1295
- this.retryable = options.retryable;
1296
- }
1297
- };
1298
- function asCardSetupError(error, overrides = {}) {
1299
- const source = error instanceof import_shared.FloPayError ? error : void 0;
1300
- const statusCode = source?.statusCode;
1301
- const retryable = overrides.retryable ?? (source?.type === "network_error" || source?.type === "rate_limit_error" || typeof statusCode === "number" && statusCode >= 500 || source?.code === "vault_capture_timeout" || !source);
1302
- return new FloPayCardSetupError(
1303
- source?.message ?? (error instanceof Error ? error.message : "Failed to load the secure card form."),
1304
- source?.type ?? "api_error",
34
+ var SETUP_CONTRACT_VERSION = "2.4.0";
35
+ function isRecord(value) {
36
+ return typeof value === "object" && value !== null && !Array.isArray(value);
37
+ }
38
+ var ERROR_TYPES = /* @__PURE__ */ new Set([
39
+ "validation_error",
40
+ "api_error",
41
+ "authentication_error",
42
+ "rate_limit_error",
43
+ "network_error"
44
+ ]);
45
+ function setupError(message, type, retryable, options = {}) {
46
+ return Object.assign(new import_shared.FloPayError(message, type, options), { retryable });
47
+ }
48
+ function errorFromPayload(payload) {
49
+ const record = isRecord(payload) ? payload : {};
50
+ const type = typeof record.type === "string" && ERROR_TYPES.has(record.type) ? record.type : "";
51
+ return setupError(
52
+ typeof record.message === "string" ? record.message : "The setup failed.",
53
+ type || "api_error",
54
+ record.retryable === true,
1305
55
  {
1306
- code: overrides.code ?? source?.code ?? "card_setup_load_failed",
1307
- retryable,
1308
- ...source?.param ? { param: source.param } : {},
1309
- ...statusCode === void 0 ? {} : { statusCode }
56
+ ...typeof record.code === "string" ? { code: record.code } : {},
57
+ ...typeof record.param === "string" ? { param: record.param } : {},
58
+ ...typeof record.statusCode === "number" ? { statusCode: record.statusCode } : {}
1310
59
  }
1311
60
  );
1312
61
  }
1313
- function useCardSetupTheme(source) {
1314
- const resolved = (0, import_vue2.computed)(
1315
- () => (0, import_shared.resolveCardSetupTheme)({
1316
- theme: source.theme ?? "modern-light",
1317
- appearance: source.appearance,
1318
- buttonsStyles: source.buttonsStyles
1319
- })
1320
- );
1321
- const vaultTheme = (0, import_vue2.computed)(() => resolved.value.vaultTheme);
1322
- const surfaceStyle = (0, import_vue2.computed)(
1323
- () => (0, import_shared.mergeCardSetupSurface)(resolved.value.surface, source.containerStyle)
1324
- );
1325
- const overlayTheme = (0, import_vue2.computed)(() => resolved.value.overlayTheme);
1326
- const appearance = (0, import_vue2.computed)(() => resolved.value.appearance);
1327
- return { vaultTheme, surfaceStyle, overlayTheme, appearance };
62
+ function loadError(caught) {
63
+ if (caught instanceof import_shared.FloPayError) {
64
+ return setupError(caught.message, caught.type, true, {
65
+ code: caught.code ?? "runtime_load_failed",
66
+ cause: caught
67
+ });
68
+ }
69
+ return setupError("The checkout runtime failed to load.", "network_error", true, {
70
+ code: "runtime_load_failed",
71
+ cause: caught
72
+ });
1328
73
  }
1329
- function useHostedSetup(props, emitters, options) {
1330
- const capture = (0, import_vue2.shallowRef)(null);
1331
- const vault = (0, import_vue2.shallowRef)(null);
1332
- const session = (0, import_vue2.shallowRef)(null);
1333
- const loadError = (0, import_vue2.ref)(null);
1334
- let active = true;
1335
- let terminal = false;
1336
- let completed = false;
1337
- let submissionInFlight = false;
1338
- let clearTimer = null;
1339
- const offs = [];
1340
- const sessionId = () => props.sessionId ?? "";
1341
- const showOverlay = (state) => {
1342
- if (clearTimer) clearTimeout(clearTimer);
1343
- clearTimer = null;
1344
- emitters.overlay(state);
74
+ function setupConfig(props) {
75
+ return {
76
+ ...props.theme === void 0 ? {} : { theme: props.theme },
77
+ ...props.appearance === void 0 ? {} : { appearance: props.appearance },
78
+ ...props.buttonsStyles === void 0 ? {} : { buttonsStyles: props.buttonsStyles },
79
+ ...props.containerStyle === void 0 ? {} : { containerStyle: props.containerStyle },
80
+ ...props.strings === void 0 ? {} : { strings: props.strings }
1345
81
  };
1346
- const holdFailure = (message) => {
1347
- showOverlay({ status: "error", message });
1348
- clearTimer = setTimeout(() => {
1349
- clearTimer = null;
1350
- if (active) emitters.overlay(null);
1351
- }, PROCESSING_OVERLAY_ERROR_DELAY_MS);
82
+ }
83
+ var setupProps = {
84
+ sessionId: { type: String, required: true },
85
+ nonce: { type: String, required: true },
86
+ theme: {
87
+ type: [String, Object],
88
+ default: void 0
89
+ },
90
+ appearance: { type: Object, default: void 0 },
91
+ buttonsStyles: { type: Object, default: void 0 },
92
+ containerStyle: {
93
+ type: Object,
94
+ default: void 0
95
+ },
96
+ strings: { type: Object, default: void 0 },
97
+ runtimeUrl: { type: String, required: true },
98
+ runtimeTimeoutMs: { type: Number, default: void 0 }
99
+ };
100
+ var setupEmits = {
101
+ ready: () => true,
102
+ validation: (_message) => true,
103
+ complete: (_event) => true,
104
+ decline: (_event) => true,
105
+ cancel: (_event) => true,
106
+ error: (_error) => true
107
+ };
108
+ var LISTENERS = {
109
+ ready: "onReady",
110
+ validation: "onValidation",
111
+ complete: "onComplete",
112
+ decline: "onDecline",
113
+ cancel: "onCancel",
114
+ error: "onError"
115
+ };
116
+ function setupRuntimeSetup(kind, props, emit) {
117
+ const instance = (0, import_vue.getCurrentInstance)();
118
+ const container = (0, import_vue.ref)(null);
119
+ let handle = null;
120
+ let generation = 0;
121
+ const deliver = (name, argument) => {
122
+ try {
123
+ if (instance?.isUnmounted) {
124
+ const listener = instance.vnode.props?.[LISTENERS[name]];
125
+ if (typeof listener === "function") listener(argument);
126
+ return;
127
+ }
128
+ emit(
129
+ name,
130
+ ...argument === void 0 ? [] : [argument]
131
+ );
132
+ } catch {
133
+ }
1352
134
  };
1353
- const bind = (adapter) => {
1354
- submissionInFlight = false;
1355
- offs.push(
1356
- adapter.on("submitting", () => {
1357
- submissionInFlight = true;
1358
- showOverlay({ status: "processing", message: null });
1359
- }),
1360
- adapter.on("complete", (event) => {
1361
- terminal = true;
1362
- submissionInFlight = false;
1363
- showOverlay({ status: "success", message: null });
1364
- setTimeout(() => {
1365
- if (completed) return;
1366
- completed = true;
1367
- (0, import_shared.invokeMerchantCallback)(
1368
- () => emitters.complete({
1369
- status: "succeeded",
1370
- sessionId: sessionId(),
1371
- ...event.paymentMethod ? { paymentMethod: event.paymentMethod } : {}
1372
- })
1373
- );
1374
- if (active) emitters.overlay(null);
1375
- }, PROCESSING_OVERLAY_SUCCESS_DELAY_MS);
1376
- }),
1377
- adapter.on("decline", (event) => {
1378
- terminal = true;
1379
- submissionInFlight = false;
1380
- holdFailure(event.message ?? null);
1381
- (0, import_shared.invokeMerchantCallback)(
1382
- () => emitters.decline({
1383
- status: "declined",
1384
- sessionId: sessionId(),
1385
- ...event.declineReason ? { reason: event.declineReason } : {},
1386
- ...event.message ? { message: event.message } : {}
1387
- })
135
+ const onEvent = (event) => {
136
+ const payload = event.payload;
137
+ switch (event.name) {
138
+ case "setupReady":
139
+ deliver("ready");
140
+ return;
141
+ case "setupValidation":
142
+ deliver(
143
+ "validation",
144
+ isRecord(payload) && typeof payload.message === "string" ? payload.message : null
1388
145
  );
1389
- }),
1390
- // Closing the bank's authentication window is not an outcome: the hosted
1391
- // form keeps polling and may still report one. Drop the overlay but keep
1392
- // the submission in flight, so a late failure still shows "CARD NOT SAVED".
1393
- adapter.on("challenge_dismissed", () => {
1394
- showOverlay(null);
1395
- })
1396
- );
146
+ return;
147
+ case "complete":
148
+ case "decline":
149
+ case "cancel":
150
+ deliver(event.name, payload);
151
+ return;
152
+ case "error":
153
+ deliver("error", errorFromPayload(payload));
154
+ return;
155
+ default:
156
+ return;
157
+ }
1397
158
  };
1398
- (0, import_vue2.onMounted)(async () => {
1399
- const billingApiUrl = (0, import_shared.resolveBillingApiUrl)(props.billingApiUrl);
1400
- const api = new import_card_setup.PaymentAPI(billingApiUrl, { telemetry: props.telemetry });
1401
- try {
1402
- if (!sessionId().trim()) {
1403
- throw new import_shared.FloPayError("A setup surface requires a sessionId.", "validation_error", {
1404
- code: "MissingCheckoutSessionId",
1405
- param: "sessionId"
1406
- });
1407
- }
1408
- if (!props.nonce?.trim()) {
1409
- throw new import_shared.FloPayError("A setup surface requires a session nonce.", "validation_error", {
1410
- code: "MissingCheckoutSessionToken",
1411
- param: "nonce"
159
+ const stop = () => {
160
+ generation += 1;
161
+ const current = handle;
162
+ handle = null;
163
+ current?.unmount();
164
+ };
165
+ const start = () => {
166
+ const element = container.value;
167
+ if (!element) return;
168
+ generation += 1;
169
+ const current = generation;
170
+ (0, import_js.loadCheckoutRuntime)({
171
+ runtimeUrl: props.runtimeUrl,
172
+ ...props.runtimeTimeoutMs === void 0 ? {} : { timeoutMs: props.runtimeTimeoutMs }
173
+ }).then(
174
+ (runtime) => {
175
+ if (current !== generation) return;
176
+ if (typeof runtime.mountSetup !== "function") {
177
+ deliver(
178
+ "error",
179
+ setupError(
180
+ "The checkout runtime on this page is too old to run setup.",
181
+ "api_error",
182
+ false,
183
+ { code: "runtime_setup_unsupported" }
184
+ )
185
+ );
186
+ return;
187
+ }
188
+ handle = runtime.mountSetup(element, {
189
+ setup: kind,
190
+ sessionId: props.sessionId,
191
+ nonce: props.nonce,
192
+ contractVersion: SETUP_CONTRACT_VERSION,
193
+ ...setupConfig(props),
194
+ onEvent
1412
195
  });
196
+ },
197
+ (caught) => {
198
+ if (current === generation) deliver("error", loadError(caught));
1413
199
  }
1414
- const result = await api.getUnifiedCheckoutSession(sessionId(), props.nonce);
1415
- const read = result.data.session;
1416
- if (!read || !(0, import_shared.isCardSetupCheckoutSession)(read)) {
1417
- throw new import_shared.FloPayError(
1418
- "Only a zero-amount, productless setup session is accepted.",
1419
- "validation_error",
1420
- { code: "InvalidCardSetupSession", param: "sessionId" }
1421
- );
1422
- }
1423
- if (!active) return;
1424
- session.value = result;
1425
- if (!options.requireVault(result)) return;
1426
- let block = read.vault;
1427
- if (!(0, import_shared.isMountableVaultBlock)(block))
1428
- block = await api.getVaultCapture(sessionId(), props.nonce);
1429
- const mount = (0, import_shared.resolveVaultMountOptions)(block, {
1430
- billingApiUrl,
1431
- sessionId: sessionId(),
1432
- nonce: props.nonce
1433
- });
1434
- if (!mount) {
1435
- throw new import_shared.FloPayError(
1436
- "FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.",
1437
- "api_error",
1438
- { code: "UnsupportedBackendVaultCapability" }
1439
- );
1440
- }
1441
- if (!active) return;
1442
- const adapter = new import_card_setup.PciVaultCardCapture({
1443
- sessionId: sessionId(),
1444
- operation: "card_setup",
1445
- telemetry: props.telemetry
1446
- });
1447
- bind(adapter);
1448
- vault.value = mount;
1449
- capture.value = adapter;
1450
- } catch (error) {
1451
- if (!active) return;
1452
- terminal = true;
1453
- const failure = asCardSetupError(error);
1454
- loadError.value = failure;
1455
- (0, import_shared.invokeMerchantCallback)(() => emitters.error(failure));
1456
- } finally {
1457
- api.destroy();
1458
- }
1459
- });
1460
- (0, import_vue2.onBeforeUnmount)(() => {
1461
- active = false;
1462
- if (clearTimer) clearTimeout(clearTimer);
1463
- clearTimer = null;
1464
- for (const off of offs.splice(0)) off();
1465
- if (!terminal && sessionId()) {
1466
- (0, import_shared.invokeMerchantCallback)(
1467
- () => emitters.cancel({ status: "cancelled", sessionId: sessionId() })
1468
- );
200
+ );
201
+ };
202
+ (0, import_vue.onMounted)(start);
203
+ (0, import_vue.watch)(
204
+ () => [props.sessionId, props.nonce, props.runtimeUrl, props.runtimeTimeoutMs],
205
+ () => {
206
+ stop();
207
+ start();
1469
208
  }
1470
- });
1471
- return {
1472
- capture,
1473
- vault,
1474
- session,
1475
- loadError,
1476
- settle: () => {
1477
- terminal = true;
1478
- },
1479
- widgetFailed: (message) => {
1480
- if (!submissionInFlight) return;
1481
- submissionInFlight = false;
1482
- holdFailure(message);
209
+ );
210
+ (0, import_vue.watch)(
211
+ () => JSON.stringify(setupConfig(props)),
212
+ () => {
213
+ handle?.update({
214
+ theme: props.theme,
215
+ appearance: props.appearance,
216
+ buttonsStyles: props.buttonsStyles,
217
+ containerStyle: props.containerStyle,
218
+ strings: props.strings
219
+ });
1483
220
  }
1484
- };
221
+ );
222
+ (0, import_vue.onBeforeUnmount)(stop);
223
+ return () => (0, import_vue.h)("div", { ref: container });
1485
224
  }
1486
-
1487
- // src/vault-card-fields.ts
1488
- var import_shared2 = require("@flopay/shared");
1489
- var import_vue3 = require("vue");
1490
- var labelledCaptures = /* @__PURE__ */ new WeakSet();
1491
- var VaultCardFields = (0, import_vue3.defineComponent)({
1492
- name: "VaultCardFields",
1493
- props: {
1494
- capture: { type: Object, default: void 0 },
1495
- html: { type: String, default: void 0 },
1496
- messageToken: { type: String, default: void 0 },
1497
- expectedOrigin: { type: String, default: void 0 },
1498
- expiresAt: { type: String, default: void 0 },
1499
- verificationRequired: { type: Boolean, default: void 0 },
1500
- theme: { type: Object, default: void 0 },
1501
- submitLabel: { type: String, default: void 0 },
1502
- containerStyle: { type: Object, default: void 0 }
1503
- },
1504
- emits: {
1505
- ready: () => true,
1506
- error: (_message) => true,
1507
- validation: (_message) => true
1508
- },
225
+ var FloPayRuntimeCardSetup = (0, import_vue.defineComponent)({
226
+ name: "FloPayRuntimeCardSetup",
227
+ props: setupProps,
228
+ emits: setupEmits,
1509
229
  setup(props, { emit }) {
1510
- const container = (0, import_vue3.ref)(null);
1511
- let teardown = null;
1512
- let appliedLabel;
1513
- let appliedTheme = null;
1514
- const mountWidget = () => {
1515
- teardown?.();
1516
- teardown = null;
1517
- const el = container.value;
1518
- const { capture, html } = props;
1519
- if (!el || !capture || !html) return;
1520
- let active = true;
1521
- let readyEmitted = false;
1522
- const emitReadyOnce = () => {
1523
- if (!active || readyEmitted) return;
1524
- readyEmitted = true;
1525
- (0, import_shared2.invokeMerchantCallback)(() => emit("ready"));
1526
- };
1527
- const offReady = capture.on("ready", emitReadyOnce);
1528
- const offError = capture.on("error", (event) => {
1529
- const message = (0, import_shared2.buyerEmailRequiredPrompt)(event.vaultOutcome) ?? event.message ?? "There was a problem loading the secure card form.";
1530
- (0, import_shared2.invokeMerchantCallback)(() => emit("error", message));
1531
- });
1532
- const offValidation = capture.on("validation", (event) => {
1533
- (0, import_shared2.invokeMerchantCallback)(() => emit("validation", event.message ?? null));
1534
- });
1535
- const label = props.submitLabel ?? void 0;
1536
- const labelDirective = label ?? (labelledCaptures.has(capture) ? null : void 0);
1537
- appliedLabel = label;
1538
- appliedTheme = props.theme ?? null;
1539
- if (label !== void 0) labelledCaptures.add(capture);
1540
- capture.mount(el, {
1541
- html,
1542
- ...props.messageToken ? { messageToken: props.messageToken } : {},
1543
- ...props.expectedOrigin ? { expectedOrigin: props.expectedOrigin } : {},
1544
- ...typeof props.expiresAt === "string" ? { expiresAt: props.expiresAt } : {},
1545
- ...props.verificationRequired ? { verificationRequired: true } : {},
1546
- ...props.theme ? { theme: props.theme } : {},
1547
- ...labelDirective === void 0 ? {} : { submitLabel: labelDirective }
1548
- }).then(emitReadyOnce).catch((error) => {
1549
- if (!active) return;
1550
- const message = error instanceof Error ? error.message : "Failed to load the secure card form.";
1551
- (0, import_shared2.invokeMerchantCallback)(() => emit("error", message));
1552
- });
1553
- teardown = () => {
1554
- active = false;
1555
- offReady();
1556
- offError();
1557
- offValidation();
1558
- capture.unmount();
1559
- };
1560
- };
1561
- (0, import_vue3.onMounted)(() => {
1562
- mountWidget();
1563
- (0, import_vue3.watch)(
1564
- () => [
1565
- props.capture,
1566
- props.html,
1567
- props.messageToken,
1568
- props.expectedOrigin,
1569
- props.expiresAt,
1570
- props.verificationRequired
1571
- ],
1572
- mountWidget
1573
- );
1574
- (0, import_vue3.watch)(
1575
- () => props.theme,
1576
- (theme) => {
1577
- if (theme === void 0) return;
1578
- if (theme === null && appliedTheme === null) return;
1579
- appliedTheme = theme;
1580
- props.capture?.applyTheme?.(theme);
1581
- }
1582
- );
1583
- (0, import_vue3.watch)(
1584
- () => props.submitLabel ?? void 0,
1585
- (label) => {
1586
- if (!props.capture || label === appliedLabel) return;
1587
- appliedLabel = label;
1588
- if (label !== void 0) labelledCaptures.add(props.capture);
1589
- props.capture.setSubmitLabel?.(label ?? null);
1590
- }
1591
- );
1592
- });
1593
- (0, import_vue3.onBeforeUnmount)(() => {
1594
- teardown?.();
1595
- teardown = null;
1596
- });
1597
- return () => (0, import_vue3.h)("div", {
1598
- ref: container,
1599
- "data-testid": "flopay-vault-card-fields",
1600
- style: props.containerStyle
1601
- });
230
+ return setupRuntimeSetup("card", props, emit);
1602
231
  }
1603
232
  });
1604
233
 
1605
- // src/flopay-payment-method-setup-main.ts
1606
- var VERIFY_ATTEMPTS = 15;
1607
- var VERIFY_INTERVAL_MS = 2e3;
1608
- function delay(ms) {
1609
- return new Promise((resolve) => setTimeout(resolve, ms));
1610
- }
1611
- var StripeSetupMethods = (0, import_vue7.defineAsyncComponent)(
1612
- () => Promise.resolve().then(() => (init_stripe_elements(), stripe_elements_exports)).then((module2) => module2.StripePaymentMethods)
1613
- );
1614
- var PayPalSetupMethods = (0, import_vue7.defineAsyncComponent)(
1615
- () => Promise.resolve().then(() => (init_payment_method_setup_paypal(), payment_method_setup_paypal_exports)).then((module2) => module2.PayPalSetupMethod)
1616
- );
1617
- var FloPayPaymentMethodSetup = (0, import_vue7.defineComponent)({
1618
- name: "FloPayPaymentMethodSetup",
1619
- props: {
1620
- sessionId: { type: String, default: void 0 },
1621
- nonce: { type: String, default: void 0 },
1622
- billingApiUrl: { type: String, default: void 0 },
1623
- telemetry: { type: Boolean, default: void 0 },
1624
- theme: {
1625
- type: [String, Object],
1626
- default: "modern-light"
1627
- },
1628
- containerStyle: {
1629
- type: Object,
1630
- default: void 0
1631
- },
1632
- appearance: { type: Object, default: void 0 },
1633
- buttonsStyles: { type: Object, default: void 0 }
1634
- },
1635
- emits: {
1636
- ready: () => true,
1637
- complete: (_event) => true,
1638
- cancel: (_event) => true,
1639
- decline: (_event) => true,
1640
- validation: (_message) => true,
1641
- error: (_error) => true
1642
- },
1643
- setup(props, { emit, slots }) {
1644
- const overlay = (0, import_vue7.shallowRef)(null);
1645
- const setup = useHostedSetup(
1646
- props,
1647
- {
1648
- complete: (event) => emit("complete", event),
1649
- decline: (event) => emit("decline", event),
1650
- cancel: (event) => emit("cancel", event),
1651
- error: (error) => emit("error", error),
1652
- // The hosted card's outcome overlay, in card wording (React's `'card'`).
1653
- overlay: (state) => {
1654
- showOverlay(state ? { ...state, wording: "card" } : null);
1655
- }
1656
- },
1657
- { requireVault: (session) => (0, import_shared7.readSetupAdvertisement)(session).card }
1658
- );
1659
- const theme = useCardSetupTheme(props);
1660
- const verified = (0, import_vue7.ref)(false);
1661
- let mounted = false;
1662
- let submissionInFlight = false;
1663
- let completionEmitted = false;
1664
- let verificationGeneration = 0;
1665
- let overlayTimer = null;
1666
- const sessionId = () => props.sessionId ?? "";
1667
- const showOverlay = (next) => {
1668
- if (overlayTimer) clearTimeout(overlayTimer);
1669
- overlayTimer = null;
1670
- overlay.value = next;
1671
- };
1672
- const clearOverlayLater = () => {
1673
- overlayTimer = setTimeout(() => {
1674
- overlayTimer = null;
1675
- if (mounted) overlay.value = null;
1676
- }, PROCESSING_OVERLAY_ERROR_DELAY_MS);
1677
- };
1678
- (0, import_vue7.onMounted)(() => {
1679
- mounted = true;
1680
- });
1681
- (0, import_vue7.onBeforeUnmount)(() => {
1682
- mounted = false;
1683
- verificationGeneration += 1;
1684
- if (overlayTimer) clearTimeout(overlayTimer);
1685
- overlayTimer = null;
1686
- });
1687
- const reportVerified = () => {
1688
- setup.settle();
1689
- submissionInFlight = false;
1690
- verified.value = true;
1691
- showOverlay({ status: "success", wording: "payment_method", message: null });
1692
- setTimeout(() => {
1693
- if (completionEmitted) return;
1694
- completionEmitted = true;
1695
- (0, import_shared7.invokeMerchantCallback)(
1696
- () => emit("complete", { status: "succeeded", sessionId: sessionId() })
1697
- );
1698
- if (mounted) overlay.value = null;
1699
- }, PROCESSING_OVERLAY_SUCCESS_DELAY_MS);
1700
- };
1701
- const reportDecline = (event) => {
1702
- setup.settle();
1703
- submissionInFlight = false;
1704
- showOverlay({ status: "error", wording: "payment_method", message: event.message ?? null });
1705
- (0, import_shared7.invokeMerchantCallback)(
1706
- () => emit("decline", {
1707
- status: "declined",
1708
- sessionId: sessionId(),
1709
- ...event.reason ? { reason: event.reason } : {},
1710
- ...event.message ? { message: event.message } : {}
1711
- })
1712
- );
1713
- clearOverlayLater();
1714
- };
1715
- const reportFailure = (error) => {
1716
- if (submissionInFlight) {
1717
- submissionInFlight = false;
1718
- showOverlay({ status: "error", wording: "payment_method", message: error.message });
1719
- clearOverlayLater();
1720
- } else {
1721
- showOverlay(null);
1722
- }
1723
- (0, import_shared7.invokeMerchantCallback)(() => emit("error", error));
1724
- };
1725
- const verifySetup = async (options = {}) => {
1726
- verificationGeneration += 1;
1727
- const generation = verificationGeneration;
1728
- const stale = () => !mounted || generation !== verificationGeneration;
1729
- submissionInFlight = true;
1730
- showOverlay({ status: "processing", wording: "payment_method", message: null });
1731
- const api = new import_card_setup4.PaymentAPI((0, import_shared7.resolveBillingApiUrl)(props.billingApiUrl), {
1732
- telemetry: props.telemetry
1733
- });
1734
- try {
1735
- for (let attempt = 0; attempt < VERIFY_ATTEMPTS; attempt += 1) {
1736
- if (attempt > 0 || options.waitFirst) await delay(VERIFY_INTERVAL_MS);
1737
- if (stale()) return;
1738
- const result = await api.getUnifiedCheckoutSession(sessionId(), props.nonce);
1739
- if (stale()) return;
1740
- const status = result.data.session?.status;
1741
- if (status === "complete") {
1742
- reportVerified();
1743
- return;
1744
- }
1745
- if (status === "expired") {
1746
- throw new import_shared7.FloPayError(
1747
- "This setup session expired before the payment method was saved.",
1748
- "validation_error",
1749
- { code: "payment_method_setup_expired" }
1750
- );
1751
- }
1752
- }
1753
- throw new import_shared7.FloPayError(
1754
- "The payment method could not be confirmed yet. Please try again.",
1755
- "api_error",
1756
- { code: "payment_method_setup_unverified" }
1757
- );
1758
- } catch (error) {
1759
- if (stale()) return;
1760
- const unverified = error instanceof import_shared7.FloPayError && error.code === "payment_method_setup_unverified";
1761
- reportFailure(asCardSetupError(error, unverified ? { retryable: true } : {}));
1762
- } finally {
1763
- api.destroy();
1764
- }
1765
- };
1766
- const redirectReturn = (0, import_card_setup4.readSetupRedirectReturn)();
1767
- if (redirectReturn) {
1768
- const stopRedirectWatch = (0, import_vue7.watch)(
1769
- () => setup.session.value,
1770
- (normalized) => {
1771
- if (!normalized) return;
1772
- stopRedirectWatch();
1773
- (0, import_card_setup4.clearSetupRedirectParams)();
1774
- if (normalized.data.session?.status === "complete") {
1775
- reportVerified();
1776
- return;
1777
- }
1778
- if (redirectReturn.failed) {
1779
- reportDecline({ reason: "redirect_failed" });
1780
- return;
1781
- }
1782
- void verifySetup({ waitFirst: true });
1783
- }
1784
- );
1785
- }
1786
- const overlayNode = () => {
1787
- const state = overlay.value;
1788
- if (!state) return null;
1789
- return (0, import_vue7.h)(ProcessingOverlay, {
1790
- status: state.status,
1791
- errorMessage: state.message,
1792
- ...(0, import_shared7.setupOverlayLabels)(state.wording),
1793
- successNote: null,
1794
- ...theme.overlayTheme.value ? { theme: theme.overlayTheme.value } : {}
1795
- });
1796
- };
1797
- return () => {
1798
- if (setup.loadError.value) {
1799
- return (0, import_vue7.h)("div", { role: "alert" }, setup.loadError.value.message);
1800
- }
1801
- const normalized = setup.session.value;
1802
- if (!normalized) return slots.loading?.() ?? null;
1803
- if (verified.value) {
1804
- return (0, import_vue7.h)("div", { "data-testid": "flopay-payment-method-setup" }, [overlayNode()]);
1805
- }
1806
- const advertisement = (0, import_shared7.readSetupAdvertisement)(normalized);
1807
- const session = normalized.data.session ?? null;
1808
- const billingApiUrl = (0, import_shared7.resolveBillingApiUrl)(props.billingApiUrl);
1809
- const stripeBranch = (entry) => (0, import_vue7.h)("div", { key: entry.method, "data-flopay-payment-method": entry.method }, [
1810
- (0, import_vue7.h)(StripeSetupMethods, {
1811
- session,
1812
- sessionId: sessionId(),
1813
- nonce: props.nonce,
1814
- billingApiUrl,
1815
- publishableKey: entry.publishableKey,
1816
- methods: [entry.method],
1817
- intentKind: "setup",
1818
- currency: entry.currency,
1819
- ...theme.appearance.value ? { appearance: theme.appearance.value } : {},
1820
- // The provider said yes; wait for the backend to agree.
1821
- onComplete: () => {
1822
- void verifySetup();
1823
- },
1824
- onDecline: (decline) => reportDecline({
1825
- ...decline.code ? { reason: decline.code } : {},
1826
- ...decline.message ? { message: decline.message } : {}
1827
- }),
1828
- onError: (error) => reportFailure(asCardSetupError(error))
1829
- })
1830
- ]);
1831
- const paypal = advertisement.paypal;
1832
- const paypalBranch = paypal ? (0, import_vue7.h)("div", { key: "paypal", "data-flopay-payment-method": "paypal" }, [
1833
- (0, import_vue7.h)(PayPalSetupMethods, {
1834
- clientId: paypal.clientId,
1835
- ...paypal.environment ? { environment: paypal.environment } : {},
1836
- ...advertisement.currency ? { currency: advertisement.currency } : {},
1837
- sessionId: sessionId(),
1838
- nonce: props.nonce ?? "",
1839
- billingApiUrl,
1840
- telemetry: props.telemetry,
1841
- customer: {
1842
- userId: session?.customer?.id ?? "",
1843
- email: session?.customer?.email ?? ""
1844
- },
1845
- onSubmitting: () => {
1846
- submissionInFlight = true;
1847
- showOverlay({ status: "processing", wording: "payment_method", message: null });
1848
- },
1849
- onConfirmed: () => {
1850
- void verifySetup();
1851
- },
1852
- onFailed: (error, options) => reportFailure(asCardSetupError(error, options)),
1853
- // Closing PayPal's window is not an outcome: no cancel, decline or error.
1854
- onAbandoned: () => {
1855
- submissionInFlight = false;
1856
- showOverlay(null);
1857
- }
1858
- })
1859
- ]) : null;
1860
- const capture = setup.capture.value;
1861
- const vault = setup.vault.value;
1862
- const card = advertisement.card && capture && vault?.html ? (0, import_vue7.h)("div", { key: "card", "data-flopay-payment-method": "card" }, [
1863
- (0, import_vue7.h)(VaultCardFields, {
1864
- capture,
1865
- html: vault.html,
1866
- messageToken: vault.messageToken,
1867
- expectedOrigin: vault.expectedOrigin,
1868
- expiresAt: vault.expiresAt,
1869
- verificationRequired: vault.verificationRequired,
1870
- theme: theme.vaultTheme.value,
1871
- containerStyle: theme.surfaceStyle.value,
1872
- onReady: () => (0, import_shared7.invokeMerchantCallback)(() => emit("ready")),
1873
- onValidation: (message) => (0, import_shared7.invokeMerchantCallback)(() => emit("validation", message)),
1874
- onError: (message) => {
1875
- if (!message) return;
1876
- setup.widgetFailed(message);
1877
- const error = asCardSetupError(new Error(message), {
1878
- code: "card_setup_widget_failed",
1879
- retryable: true
1880
- });
1881
- (0, import_shared7.invokeMerchantCallback)(() => emit("error", error));
1882
- }
1883
- })
1884
- ]) : null;
1885
- const wallets = advertisement.stripe.filter(
1886
- ({ method }) => (0, import_shared7.stripeMethodCategory)(method) === "wallet"
1887
- );
1888
- const tiles = advertisement.stripe.filter(
1889
- ({ method }) => (0, import_shared7.stripeMethodCategory)(method) !== "wallet"
1890
- );
1891
- return (0, import_vue7.h)("div", { "data-testid": "flopay-payment-method-setup" }, [
1892
- overlayNode(),
1893
- ...wallets.map(stripeBranch),
1894
- paypalBranch,
1895
- ...tiles.map(stripeBranch),
1896
- card
1897
- ]);
1898
- };
234
+ // src/flopay-runtime-payment-method-setup.ts
235
+ var FloPayRuntimePaymentMethodSetup = (0, import_vue2.defineComponent)({
236
+ name: "FloPayRuntimePaymentMethodSetup",
237
+ props: setupProps,
238
+ emits: setupEmits,
239
+ setup(props, { emit }) {
240
+ return setupRuntimeSetup("payment_method", props, emit);
1899
241
  }
1900
242
  });
1901
243
  // Annotate the CommonJS export names for ESM import in node: