@vaam-apps/vpay-stripe-js 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js ADDED
@@ -0,0 +1,551 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _VpayStripe_instances, _VpayStripe_publishableKey, _VpayStripe_baseUrl, _VpayStripe_checkoutBaseUrl, _VpayStripe_fetchImpl, _VpayStripe_intentUrl, _VpayStripe_request, _VpayStripe_fetchJson, _VpayStripe_followRedirect;
13
+ /**
14
+ * The browser client: `loadStripe` and the `Stripe` object it resolves to.
15
+ *
16
+ * Speaks vpay's browser surface
17
+ * (`docs/plans/2026-09-03-step5c-stripejs.md` §1):
18
+ *
19
+ * - `GET /v1/browser/payment_intents/{id}?key=…&client_secret=…`
20
+ * - `POST /v1/browser/payment_intents/{id}/confirm` — form-encoded `key`,
21
+ * `client_secret`, `payment_method_data[…]`, `return_url`
22
+ *
23
+ * There is no `create`, no `list` and no `cancel` on that surface, and no
24
+ * `Idempotency-Key` header: a browser `POST` carrying one would be
25
+ * CORS-preflighted, and one-charge-per-intent is enforced by a unique index
26
+ * server-side instead. Nothing here mints, stores or derives a credential —
27
+ * the `client_secret` arrives from the merchant's own page and is passed
28
+ * straight back on each call.
29
+ */
30
+ import { CLIENT_ERROR_CODES, connectionError, parseErrorEnvelope, stripeError, unexpectedResponseError, } from "./errors.js";
31
+ import { createEmbeddedCheckout } from "./embedded.js";
32
+ import { openCheckoutPopup, } from "./popup.js";
33
+ import { encodeForm, FormEncodingError } from "./form.js";
34
+ /** The separator `vpay_core::ids::client_secret` joins an id and its suffix with. */
35
+ const SECRET_SEPARATOR = "_secret_";
36
+ /** A payment-intent id. */
37
+ const INTENT_ID_PREFIX = "pi_";
38
+ /** A checkout-session id (Step 9, D1) — a second credential, same shape. */
39
+ const SESSION_ID_PREFIX = "cs_";
40
+ /** `"/".charCodeAt(0)`, spelled out once for {@link stripTrailingSlashes}. */
41
+ const SLASH_CHAR_CODE = 47;
42
+ const DEFAULT_TIMEOUT_MS = 180000;
43
+ const DEFAULT_INTERVAL_MS = 2000;
44
+ /** Poll delays are drawn from `[0.75, 1.25] × intervalMs`, so a page of payers does not poll in lockstep. */
45
+ const JITTER_SPREAD = 0.5;
46
+ const INSPECT_CUSTOM = Symbol.for("nodejs.util.inspect.custom");
47
+ /** A `{ error }` result, built once so every failure path reads the same. */
48
+ function errorResult(error) {
49
+ return { error };
50
+ }
51
+ /**
52
+ * Splits `{prefix}abc_secret_xyz` into the object's id.
53
+ *
54
+ * Deliberately not a regex over the suffix alphabet: the suffix's shape is
55
+ * the server's business (32–128 characters, per migration `0023`'s CHECK),
56
+ * and a client-side pattern that disagreed with it would refuse a valid
57
+ * secret after a server change. What *is* checked is only what this package
58
+ * needs to build a URL — that there is a separator, that something precedes
59
+ * it, that it carries the expected id prefix, and that something follows it.
60
+ *
61
+ * Parameterised over the prefix because Step 9's Checkout Session is a
62
+ * **second** credential of exactly this shape (`cs_…_secret_…`, D1), and
63
+ * two near-identical parsers would drift the first time either object's id
64
+ * rules moved. `shape` names the object in the refusal message; the
65
+ * offending value itself is never quoted.
66
+ */
67
+ function parseClientSecret(clientSecret, prefix, shape) {
68
+ if (typeof clientSecret !== "string" || clientSecret.length === 0) {
69
+ return {
70
+ error: stripeError("invalid_request_error", "invalid_request", "clientSecret must be a non-empty string.", "clientSecret"),
71
+ };
72
+ }
73
+ const separator = clientSecret.indexOf(SECRET_SEPARATOR);
74
+ const id = separator === -1 ? "" : clientSecret.slice(0, separator);
75
+ const suffix = separator === -1
76
+ ? ""
77
+ : clientSecret.slice(separator + SECRET_SEPARATOR.length);
78
+ if (separator === -1 ||
79
+ !id.startsWith(prefix) ||
80
+ id.length <= prefix.length ||
81
+ suffix.length === 0) {
82
+ // The malformed value is **not** echoed. It is a credential the payer's
83
+ // page just handed us; a message quoting it would put it in whatever
84
+ // renders `error.message`.
85
+ return {
86
+ error: stripeError("invalid_request_error", "invalid_request", `clientSecret is not a vpay ${shape} client secret.`, "clientSecret"),
87
+ };
88
+ }
89
+ return { id };
90
+ }
91
+ /** {@link parseClientSecret} for a `pi_…_secret_…`. */
92
+ function parseIntentSecret(clientSecret) {
93
+ return parseClientSecret(clientSecret, INTENT_ID_PREFIX, "payment-intent");
94
+ }
95
+ /** {@link parseClientSecret} for a `cs_…_secret_…` (Step 9, D1). */
96
+ function parseSessionSecret(clientSecret) {
97
+ return parseClientSecret(clientSecret, SESSION_ID_PREFIX, "checkout-session");
98
+ }
99
+ /** The URL a `next_action` asks the browser to visit, if this intent has one. */
100
+ function redirectTarget(intent) {
101
+ const nextAction = intent.next_action;
102
+ if (nextAction === null || nextAction.type !== "redirect_to_url") {
103
+ return undefined;
104
+ }
105
+ const url = nextAction.redirect_to_url.url;
106
+ return typeof url === "string" && url.length > 0 ? url : undefined;
107
+ }
108
+ /**
109
+ * True only for an absolute `http:`/`https:` URL — the one shape it is safe
110
+ * to hand to `location.assign`.
111
+ *
112
+ * `next_action.redirect_to_url.url` is the rail's own value, echoed back
113
+ * through the server; it is not something this package minted. A
114
+ * `javascript:` URL would execute in the merchant's origin, `data:` and
115
+ * every other scheme are no better, and a relative path — `new URL` throws
116
+ * without a base — would resolve against whatever document happens to be
117
+ * open rather than the rail this intent named. `#followRedirect` refuses
118
+ * every shape but an absolute `http`/`https` URL instead of navigating to it.
119
+ */
120
+ function isSafeRedirectUrl(url) {
121
+ let parsed;
122
+ try {
123
+ parsed = new URL(url);
124
+ }
125
+ catch {
126
+ return false;
127
+ }
128
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
129
+ }
130
+ /** Narrows a decoded 2xx body to something that is actually a payment intent. */
131
+ function isPaymentIntent(body) {
132
+ return (typeof body === "object" &&
133
+ body !== null &&
134
+ body.object === "payment_intent" &&
135
+ typeof body.id === "string");
136
+ }
137
+ /** Narrows a decoded 2xx body to something that is actually a checkout session. */
138
+ function isCheckoutSession(body) {
139
+ return (typeof body === "object" &&
140
+ body !== null &&
141
+ body.object === "checkout.session" &&
142
+ typeof body.id === "string");
143
+ }
144
+ /**
145
+ * `window`, or `undefined` when there is none.
146
+ *
147
+ * This package is typed against `lib.dom`, where `window` is declared as
148
+ * always present; it nonetheless runs under Node in this repo's own tests,
149
+ * in SSR frameworks, and in workers. The `typeof` guard is the only form
150
+ * that does not throw a `ReferenceError` where the binding is absent
151
+ * entirely.
152
+ */
153
+ function browserWindow() {
154
+ return typeof window === "undefined" ? undefined : window;
155
+ }
156
+ /**
157
+ * Strips every trailing `/` from `value`, with no regex.
158
+ *
159
+ * `options.baseUrl` is caller-supplied — a merchant's own configuration, not
160
+ * something vpay generated — so a backtracking pattern here (`/\/+$/`) is a
161
+ * regular expression running over library input, and a caller who passed a
162
+ * pathological run of slashes could cost more than the O(n) this loop always
163
+ * costs.
164
+ */
165
+ function stripTrailingSlashes(value) {
166
+ let end = value.length;
167
+ while (end > 0 && value.charCodeAt(end - 1) === SLASH_CHAR_CODE) {
168
+ end -= 1;
169
+ }
170
+ return value.slice(0, end);
171
+ }
172
+ /** `Promise<never>` that never settles — see {@link ConfirmPaymentOptions.redirect}. */
173
+ function neverSettles() {
174
+ return new Promise(() => {
175
+ // Intentionally empty: the browser is unloading this document. Resolving
176
+ // here is what would let a caller's `.then` run a "payment failed" branch
177
+ // during the navigation, which is the bug this shape exists to prevent.
178
+ });
179
+ }
180
+ /**
181
+ * vpay's `Stripe` object. Constructed only by {@link loadStripe}.
182
+ *
183
+ * Holds a publishable key and a base URL and nothing else — in particular it
184
+ * never retains a `client_secret`, which is why the redacted representations
185
+ * below can be exhaustive rather than a filter.
186
+ */
187
+ export class VpayStripe {
188
+ constructor(publishableKey, baseUrl, checkoutBaseUrl, fetchImpl) {
189
+ _VpayStripe_instances.add(this);
190
+ _VpayStripe_publishableKey.set(this, void 0);
191
+ _VpayStripe_baseUrl.set(this, void 0);
192
+ _VpayStripe_checkoutBaseUrl.set(this, void 0);
193
+ _VpayStripe_fetchImpl.set(this, void 0);
194
+ __classPrivateFieldSet(this, _VpayStripe_publishableKey, publishableKey, "f");
195
+ __classPrivateFieldSet(this, _VpayStripe_baseUrl, baseUrl, "f");
196
+ __classPrivateFieldSet(this, _VpayStripe_checkoutBaseUrl, checkoutBaseUrl, "f");
197
+ __classPrivateFieldSet(this, _VpayStripe_fetchImpl, fetchImpl, "f");
198
+ }
199
+ async retrievePaymentIntent(clientSecret) {
200
+ const parsed = parseIntentSecret(clientSecret);
201
+ if ("error" in parsed) {
202
+ return errorResult(parsed.error);
203
+ }
204
+ const query = encodeForm({
205
+ key: __classPrivateFieldGet(this, _VpayStripe_publishableKey, "f"),
206
+ client_secret: clientSecret,
207
+ });
208
+ return __classPrivateFieldGet(this, _VpayStripe_instances, "m", _VpayStripe_request).call(this, "GET", `${__classPrivateFieldGet(this, _VpayStripe_instances, "m", _VpayStripe_intentUrl).call(this, parsed.id)}?${query}`, undefined);
209
+ }
210
+ async confirmPayment(options) {
211
+ const parsed = parseIntentSecret(options.clientSecret);
212
+ if ("error" in parsed) {
213
+ return errorResult(parsed.error);
214
+ }
215
+ const params = {
216
+ key: __classPrivateFieldGet(this, _VpayStripe_publishableKey, "f"),
217
+ client_secret: options.clientSecret,
218
+ };
219
+ const paymentMethodData = options.confirmParams?.payment_method_data;
220
+ if (paymentMethodData !== undefined) {
221
+ params["payment_method_data"] = paymentMethodData;
222
+ }
223
+ const returnUrl = options.confirmParams?.return_url;
224
+ if (returnUrl !== undefined) {
225
+ params["return_url"] = returnUrl;
226
+ }
227
+ let body;
228
+ try {
229
+ body = encodeForm(params);
230
+ }
231
+ catch (err) {
232
+ // The only values this package adds are strings it was handed; every
233
+ // encodable-value rule can therefore only be broken by
234
+ // `payment_method_data`, which is why `param` is a constant.
235
+ if (err instanceof FormEncodingError) {
236
+ return errorResult(stripeError("invalid_request_error", "invalid_request", err.message, "payment_method_data"));
237
+ }
238
+ throw err;
239
+ }
240
+ const result = await __classPrivateFieldGet(this, _VpayStripe_instances, "m", _VpayStripe_request).call(this, "POST", `${__classPrivateFieldGet(this, _VpayStripe_instances, "m", _VpayStripe_intentUrl).call(this, parsed.id)}/confirm`, body);
241
+ return __classPrivateFieldGet(this, _VpayStripe_instances, "m", _VpayStripe_followRedirect).call(this, result, options.redirect);
242
+ }
243
+ async handleNextAction(options) {
244
+ const result = await this.retrievePaymentIntent(options.clientSecret);
245
+ // No `redirect` knob: a caller reaching for `handleNextAction` has
246
+ // already decided to perform the action. `redirect: 'if_required'` on
247
+ // `confirmPayment` is how a caller opts out.
248
+ return __classPrivateFieldGet(this, _VpayStripe_instances, "m", _VpayStripe_followRedirect).call(this, result, undefined);
249
+ }
250
+ async confirmMobileMoneyPayment(clientSecret, data) {
251
+ // `{ type: 'mtn_momo', mtn_momo: { msisdn } }` — Stripe's shape, and what
252
+ // `/v1`'s `confirm` already accepts. The rail code appears twice on the
253
+ // wire (as `[type]` and as the nested key) because that is the contract;
254
+ // it is not duplicated here as a convenience.
255
+ return this.confirmPayment({
256
+ clientSecret,
257
+ confirmParams: {
258
+ payment_method_data: {
259
+ type: data.type,
260
+ [data.type]: { msisdn: data.msisdn },
261
+ },
262
+ },
263
+ });
264
+ }
265
+ async waitForPaymentIntent(clientSecret, options) {
266
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
267
+ const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
268
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
269
+ return errorResult(stripeError("invalid_request_error", "invalid_request", "timeoutMs must be a non-negative, finite number of milliseconds.", "timeoutMs"));
270
+ }
271
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
272
+ return errorResult(stripeError("invalid_request_error", "invalid_request", "intervalMs must be a positive, finite number of milliseconds.", "intervalMs"));
273
+ }
274
+ const deadline = Date.now() + timeoutMs;
275
+ for (;;) {
276
+ const result = await this.retrievePaymentIntent(clientSecret);
277
+ // An `{ error }` ends the poll rather than being retried until the
278
+ // deadline. A 404 or a malformed `clientSecret` would never come good,
279
+ // and an `api_connection_error` is something the *caller* must decide
280
+ // about — swallowing three minutes of connection failures and then
281
+ // reporting `polling_timeout` would describe the wrong fault.
282
+ if (result.error !== undefined) {
283
+ return result;
284
+ }
285
+ if (hasStoppedMoving(result.paymentIntent)) {
286
+ return result;
287
+ }
288
+ const remaining = deadline - Date.now();
289
+ if (remaining <= 0) {
290
+ return errorResult(stripeError("api_error", CLIENT_ERROR_CODES.pollingTimeout, "Timed out waiting for the payment intent to reach a final state."));
291
+ }
292
+ await sleep(Math.min(jitter(intervalMs), remaining));
293
+ }
294
+ }
295
+ async retrieveCheckoutSession(clientSecret) {
296
+ const parsed = parseSessionSecret(clientSecret);
297
+ if ("error" in parsed) {
298
+ return { error: parsed.error };
299
+ }
300
+ const query = encodeForm({
301
+ key: __classPrivateFieldGet(this, _VpayStripe_publishableKey, "f"),
302
+ client_secret: clientSecret,
303
+ });
304
+ const answer = await __classPrivateFieldGet(this, _VpayStripe_instances, "m", _VpayStripe_fetchJson).call(this, "GET", `${__classPrivateFieldGet(this, _VpayStripe_baseUrl, "f")}/v1/browser/checkout/sessions/${encodeURIComponent(parsed.id)}?${query}`, undefined);
305
+ if ("error" in answer) {
306
+ return { error: answer.error };
307
+ }
308
+ if (!answer.ok) {
309
+ return {
310
+ error: parseErrorEnvelope(answer.parsed) ??
311
+ unexpectedResponseError(answer.status),
312
+ };
313
+ }
314
+ return isCheckoutSession(answer.parsed)
315
+ ? { checkoutSession: answer.parsed }
316
+ : { error: unexpectedResponseError(answer.status) };
317
+ }
318
+ async initEmbeddedCheckout(options) {
319
+ const checkoutBaseUrl = __classPrivateFieldGet(this, _VpayStripe_checkoutBaseUrl, "f");
320
+ if (checkoutBaseUrl === undefined) {
321
+ throw new TypeError("initEmbeddedCheckout: loadStripe was not given options.checkoutBaseUrl, so there is no page to frame");
322
+ }
323
+ if (typeof options?.fetchClientSecret !== "function") {
324
+ throw new TypeError("initEmbeddedCheckout: options.fetchClientSecret must be a function returning a Promise<string>");
325
+ }
326
+ // Awaited before anything is built, and its rejection is *not* wrapped:
327
+ // this is the merchant's own call to its own server, and a message this
328
+ // package invented on top of it would hide the fault the merchant needs
329
+ // to see.
330
+ const clientSecret = await options.fetchClientSecret();
331
+ const parsed = parseSessionSecret(clientSecret);
332
+ if ("error" in parsed) {
333
+ // The offending value is a live credential; `parseSessionSecret`'s
334
+ // message never quotes it, and neither does this.
335
+ throw new TypeError("initEmbeddedCheckout: fetchClientSecret did not return a vpay checkout-session client secret");
336
+ }
337
+ return createEmbeddedCheckout({
338
+ publishableKey: __classPrivateFieldGet(this, _VpayStripe_publishableKey, "f"),
339
+ checkoutBaseUrl,
340
+ sessionId: parsed.id,
341
+ clientSecret,
342
+ onComplete: options.onComplete,
343
+ });
344
+ }
345
+ async openCheckoutPopup(options) {
346
+ const win = browserWindow();
347
+ if (win === undefined) {
348
+ throw new TypeError("openCheckoutPopup: there is no browser window to open one from");
349
+ }
350
+ // No `checkoutBaseUrl` is consulted, and that is not an oversight: a
351
+ // popup loads the **hosted** session's own `url`, which vpay minted and
352
+ // the merchant's server just handed back. `checkoutBaseUrl` exists to
353
+ // build an embedded frame `src` and to pin the origin a framed page
354
+ // posts from; neither applies here (see `popup.ts`).
355
+ return openCheckoutPopup({ win, options });
356
+ }
357
+ /** A safe, redacted representation. This object holds no secret to redact. */
358
+ [(_VpayStripe_publishableKey = new WeakMap(), _VpayStripe_baseUrl = new WeakMap(), _VpayStripe_checkoutBaseUrl = new WeakMap(), _VpayStripe_fetchImpl = new WeakMap(), _VpayStripe_instances = new WeakSet(), INSPECT_CUSTOM)]() {
359
+ const checkout = __classPrivateFieldGet(this, _VpayStripe_checkoutBaseUrl, "f") === undefined
360
+ ? ""
361
+ : `, checkoutBaseUrl: '${__classPrivateFieldGet(this, _VpayStripe_checkoutBaseUrl, "f")}'`;
362
+ return `VpayStripe { publishableKey: '${__classPrivateFieldGet(this, _VpayStripe_publishableKey, "f")}', baseUrl: '${__classPrivateFieldGet(this, _VpayStripe_baseUrl, "f")}'${checkout} }`;
363
+ }
364
+ /** A safe, redacted representation. This object holds no secret to redact. */
365
+ toJSON() {
366
+ const rendered = {
367
+ object: "vpay_stripe",
368
+ publishableKey: __classPrivateFieldGet(this, _VpayStripe_publishableKey, "f"),
369
+ baseUrl: __classPrivateFieldGet(this, _VpayStripe_baseUrl, "f"),
370
+ };
371
+ if (__classPrivateFieldGet(this, _VpayStripe_checkoutBaseUrl, "f") !== undefined) {
372
+ rendered.checkoutBaseUrl = __classPrivateFieldGet(this, _VpayStripe_checkoutBaseUrl, "f");
373
+ }
374
+ return rendered;
375
+ }
376
+ }
377
+ _VpayStripe_intentUrl = function _VpayStripe_intentUrl(id) {
378
+ return `${__classPrivateFieldGet(this, _VpayStripe_baseUrl, "f")}/v1/browser/payment_intents/${encodeURIComponent(id)}`;
379
+ }, _VpayStripe_request =
380
+ /**
381
+ * One request, one `PaymentIntentResult`. Never throws and never rejects.
382
+ *
383
+ * Neither `url` nor the thrown value reaches a message: the query string
384
+ * holds the `client_secret`.
385
+ */
386
+ async function _VpayStripe_request(method, url, body) {
387
+ const answer = await __classPrivateFieldGet(this, _VpayStripe_instances, "m", _VpayStripe_fetchJson).call(this, method, url, body);
388
+ if ("error" in answer) {
389
+ return errorResult(answer.error);
390
+ }
391
+ if (answer.ok) {
392
+ return isPaymentIntent(answer.parsed)
393
+ ? { paymentIntent: answer.parsed }
394
+ : errorResult(unexpectedResponseError(answer.status));
395
+ }
396
+ return errorResult(parseErrorEnvelope(answer.parsed) ??
397
+ unexpectedResponseError(answer.status));
398
+ }, _VpayStripe_fetchJson =
399
+ /**
400
+ * The transport, shared by every route this package speaks.
401
+ *
402
+ * Returns the decoded body rather than an object, because the two
403
+ * surfaces decode to different objects (a payment intent, a checkout
404
+ * session) and the *transport* rules — `credentials: 'omit'`, the one
405
+ * header, the body read inside the same `try`, and above all that no
406
+ * thrown value ever reaches a message — must be written once. A second
407
+ * copy of this method for sessions is exactly how one of the two would
408
+ * quietly stop omitting credentials.
409
+ */
410
+ async function _VpayStripe_fetchJson(method, url, body) {
411
+ let status;
412
+ let ok;
413
+ let text;
414
+ try {
415
+ // `credentials: 'omit'` and `mode: 'cors'` are set on every request,
416
+ // not left to the fetch implementation's default: this package never
417
+ // wants a cookie or an `Authorization` header attached on the
418
+ // merchant's behalf (the publishable key and client secret in the URL
419
+ // are the only credential this surface uses), and a same-origin
420
+ // default would silently start sending them if vpay's API and the
421
+ // merchant's page ever shared an origin.
422
+ const init = { method, credentials: "omit", mode: "cors" };
423
+ if (body !== undefined) {
424
+ init.body = body;
425
+ // The only header this package sets. Anything beyond
426
+ // `Content-Type: application/x-www-form-urlencoded` (a `Idempotency-Key`,
427
+ // an `Authorization`) would turn a CORS simple request into a
428
+ // preflighted one — see §0 S4 of the design.
429
+ init.headers = {
430
+ "Content-Type": "application/x-www-form-urlencoded",
431
+ };
432
+ }
433
+ const response = await __classPrivateFieldGet(this, _VpayStripe_fetchImpl, "f").call(this, url, init);
434
+ status = response.status;
435
+ ok = response.ok;
436
+ // Read inside the same `try`: `fetch` resolves once the headers
437
+ // arrive, so a truncated or stalled body rejects here.
438
+ text = await response.text();
439
+ }
440
+ catch {
441
+ return { error: connectionError() };
442
+ }
443
+ let parsed;
444
+ try {
445
+ parsed = text.length > 0 ? JSON.parse(text) : undefined;
446
+ }
447
+ catch {
448
+ parsed = undefined;
449
+ }
450
+ return { status, ok, parsed };
451
+ }, _VpayStripe_followRedirect = function _VpayStripe_followRedirect(result, redirect) {
452
+ if (result.error !== undefined) {
453
+ return Promise.resolve(result);
454
+ }
455
+ const url = redirectTarget(result.paymentIntent);
456
+ if (url === undefined || redirect === "if_required") {
457
+ return Promise.resolve(result);
458
+ }
459
+ if (!isSafeRedirectUrl(url)) {
460
+ // Refused, not navigated: this string reached us from the rail via
461
+ // the server, and a `javascript:`/`data:`/relative value is refused
462
+ // rather than handed to `location.assign`.
463
+ return Promise.resolve(errorResult(stripeError("api_error", CLIENT_ERROR_CODES.invalidRedirect, "The rail requested a redirect to a URL vpay will not navigate to.")));
464
+ }
465
+ const location = browserWindow()?.location;
466
+ if (location === undefined || typeof location.assign !== "function") {
467
+ return Promise.resolve(errorResult(stripeError("api_error", CLIENT_ERROR_CODES.redirectUnavailable, "This payment requires a redirect, but there is no browser window to navigate. Pass `redirect: 'if_required'` and handle `next_action.redirect_to_url` yourself.")));
468
+ }
469
+ location.assign(url);
470
+ return neverSettles();
471
+ };
472
+ /**
473
+ * True once the intent will not change again without a new request.
474
+ *
475
+ * `requires_payment_method` is terminal **only** with a
476
+ * `last_payment_error`: it is also the status of an intent nobody has
477
+ * confirmed yet, and treating that as final would make
478
+ * `waitForPaymentIntent` return the instant it was called.
479
+ */
480
+ function hasStoppedMoving(intent) {
481
+ if (intent.status === "succeeded" || intent.status === "canceled") {
482
+ return true;
483
+ }
484
+ return (intent.status === "requires_payment_method" &&
485
+ intent.last_payment_error !== null);
486
+ }
487
+ /** `[0.75, 1.25] × base`, rounded to whole milliseconds. */
488
+ function jitter(base) {
489
+ return Math.round(base * (1 - JITTER_SPREAD / 2 + Math.random() * JITTER_SPREAD));
490
+ }
491
+ function sleep(ms) {
492
+ return new Promise((resolve) => {
493
+ setTimeout(resolve, ms);
494
+ });
495
+ }
496
+ /**
497
+ * Builds a {@link Stripe} bound to one vpay deployment and one publishable
498
+ * key.
499
+ *
500
+ * Asynchronous purely for source compatibility with `@stripe/stripe-js`'s
501
+ * `loadStripe`, whose promise covers a `<script>` download. This one has
502
+ * nothing to download — the whole point of the package is that
503
+ * `js.stripe.com` is not in the picture — so it resolves immediately.
504
+ *
505
+ * **This is the one function here that rejects.** A blank publishable key or
506
+ * base URL is an integration mistake visible on the merchant's first page
507
+ * load, not a payer-facing failure, and the `Stripe` object's methods keep
508
+ * their never-rejects contract precisely because the arguments were checked
509
+ * once, here.
510
+ */
511
+ // async purely for source compatibility with `@stripe/stripe-js`'s
512
+ // `loadStripe`; see the doc comment above.
513
+ // eslint-disable-next-line @typescript-eslint/require-await
514
+ export async function loadStripe(publishableKey, options) {
515
+ if (typeof publishableKey !== "string" ||
516
+ publishableKey.trim().length === 0) {
517
+ throw new TypeError("loadStripe: publishableKey must be a non-empty string");
518
+ }
519
+ if (typeof options?.baseUrl !== "string" ||
520
+ options.baseUrl.trim().length === 0) {
521
+ throw new TypeError("loadStripe: options.baseUrl must be a non-empty string");
522
+ }
523
+ const fetchImpl = options.fetch ??
524
+ (typeof globalThis.fetch === "function"
525
+ ? // Bound: an unbound native `fetch` called as a method of anything
526
+ // other than the global throws `Illegal invocation` in browsers.
527
+ globalThis.fetch.bind(globalThis)
528
+ : undefined);
529
+ if (fetchImpl === undefined) {
530
+ throw new TypeError("loadStripe: no global fetch is available; pass options.fetch");
531
+ }
532
+ // Trailing slashes stripped once, so `${baseUrl}/v1/browser/...` cannot
533
+ // produce a `//` that some ingresses redirect and others 404.
534
+ const baseUrl = stripTrailingSlashes(options.baseUrl.trim());
535
+ // Checked here rather than at `initEmbeddedCheckout`, for the same reason
536
+ // the two above are: a misconfigured checkout origin is an integration
537
+ // mistake, and `event.origin` is compared against this value — a bad one
538
+ // does not fail loudly at message time, it silently accepts nothing.
539
+ let checkoutBaseUrl;
540
+ if (options.checkoutBaseUrl !== undefined) {
541
+ if (typeof options.checkoutBaseUrl !== "string" ||
542
+ options.checkoutBaseUrl.trim().length === 0) {
543
+ throw new TypeError("loadStripe: options.checkoutBaseUrl must be a non-empty string");
544
+ }
545
+ checkoutBaseUrl = stripTrailingSlashes(options.checkoutBaseUrl.trim());
546
+ if (!isSafeRedirectUrl(checkoutBaseUrl)) {
547
+ throw new TypeError("loadStripe: options.checkoutBaseUrl must be an absolute http(s) URL");
548
+ }
549
+ }
550
+ return new VpayStripe(publishableKey, baseUrl, checkoutBaseUrl, fetchImpl);
551
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Embedded Checkout: vpay's own checkout page, framed on the merchant's
3
+ * page, and the `postMessage` protocol between the two
4
+ * (`docs/plans/2026-09-04-step9-hosted-checkout.md`, D6 and D8).
5
+ *
6
+ * Three rules hold in this file, and each one is a test:
7
+ *
8
+ * 1. **The secret rides in the fragment, never the query string** (D6). A
9
+ * query string reaches the checkout app's server logs, its access log,
10
+ * and every proxy in between; a fragment is never sent to a server at
11
+ * all. The publishable key *is* in the query, because the page's own
12
+ * server needs it to look the tenant's `frame-ancestors` up before any
13
+ * script runs, and a publishable key is public by name.
14
+ * 2. **`event.origin` is compared against one pinned value**, derived from
15
+ * `checkoutBaseUrl`. `message` is a global event: without this check any
16
+ * page the merchant frames — an ad, an analytics pixel, an attacker's
17
+ * popup holding a reference to `window.opener` — can post
18
+ * `{type:'vpay:redirect', url}` and steer the merchant's top-level
19
+ * navigation. The check is the whole security boundary of this file.
20
+ * 3. **This side posts nothing.** There is therefore no target origin to
21
+ * get wrong, and in particular no `postMessage(…, '*')` — the mistake
22
+ * D8 names. The child learns the parent's origin from the CSP
23
+ * `frame-ancestors` vpay served it, not from a handshake.
24
+ */
25
+ import type { EmbeddedCheckout, EmbeddedCheckoutCompleteEvent } from "./types.js";
26
+ /**
27
+ * Everything {@link createEmbeddedCheckout} needs, resolved by the caller.
28
+ *
29
+ * A plain record rather than a reference back to the `Stripe` object: this
30
+ * module must not be able to reach a `client_secret` for a *payment intent*,
31
+ * and taking only what it needs is how that stays true by construction.
32
+ */
33
+ export interface EmbeddedCheckoutConfig {
34
+ /** `pk_…`, encoded into the frame's query string. */
35
+ publishableKey: string;
36
+ /** The checkout app's origin, trailing slashes already stripped. */
37
+ checkoutBaseUrl: string;
38
+ /** `cs_…`, parsed out of the session's client secret. */
39
+ sessionId: string;
40
+ /** `cs_…_secret_…`, placed in the frame's URL fragment. */
41
+ clientSecret: string;
42
+ /** The merchant's completion callback, if any. */
43
+ onComplete: ((event: EmbeddedCheckoutCompleteEvent) => void) | undefined;
44
+ }
45
+ /** The `origin` half of a URL — what `event.origin` is compared against. */
46
+ export declare function originOf(url: string): string;
47
+ /**
48
+ * Builds the frame's `src`: `{checkoutBaseUrl}/e/{cs_id}?key={pk}#{secret}`.
49
+ *
50
+ * The id is percent-encoded (it is interpolated into a path, and
51
+ * `client.ts` encodes an intent id for the same reason); the key is
52
+ * percent-encoded; the fragment is **verbatim**, because it is the exact
53
+ * byte string the page hands back to `/v1/browser` and an encoding this
54
+ * package applied would have to be undone by an agreement nobody wrote
55
+ * down.
56
+ */
57
+ export declare function embeddedFrameSrc(config: EmbeddedCheckoutConfig): string;
58
+ /**
59
+ * Builds one embedded-checkout handle: an `<iframe>`, a `message`
60
+ * listener pinned to the checkout origin, and the three-verb lifecycle
61
+ * `@stripe/stripe-js`'s `StripeEmbeddedCheckout` defines.
62
+ *
63
+ * The listener is attached here rather than in `mount`, so a page that
64
+ * posts a `vpay:complete` between two `mount` calls is not lost, and it is
65
+ * detached in `destroy` and nowhere else — `unmount` leaves the handle
66
+ * usable, which is Stripe's own semantics.
67
+ */
68
+ export declare function createEmbeddedCheckout(config: EmbeddedCheckoutConfig): EmbeddedCheckout;