Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
"build:clean": "rescript clean && rescript && tsc -p tsconfig.build.json && rollup -c",
"clean": "rescript clean",
"prepack": "rescript && tsc -p tsconfig.build.json && rollup -c",
"test": "rescript && node --no-warnings --test test/logging.test.mjs"
"test": "rescript && node --no-warnings --test test/logging.test.mjs test/detached.test.mjs"
},
"peerDependencies": {
"react": "*",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* One field of a detached card form, in a React root of its own. It gives its children the widget
* context a <CardForm> would, built over the form's shared store, so the fields of every root edit
* one card. While the Host is submitting, or the form is disabled, the fields are disabled as they
* would be in a <CardForm>.
*/
@react.component
let make = (
~store: VaultCardStore.t,
~link: DetachedCardLink.t,
~session: option<VaultFormOptions.vaultSession>=?,
~sdkAuthorization: option<string>=?,
~vaultDetails: option<VaultDetails.vaultDetails>=?,
~environment: VaultFormOptions.vaultEnvironment,
~appearance: option<VaultFormOptions.appearance>=?,
~locale: option<string>=?,
~localisation: option<VaultFormOptions.localisation>=?,
~customEndpoints: option<VaultEndpoint.customEndpoints>=?,
~disabled: option<bool>=?,
~accessible: option<bool>=?,
~enabledCardSchemes: option<array<string>>=?,
~cardholderName: option<CardFieldOptions.cardholderNameMode>=?,
~unstyled: option<bool>=?,
~children: React.element,
) => {
let submitting = React.useSyncExternalStore(
~subscribe=DetachedCardLink.subscribe(link, ...),
~getSnapshot=DetachedCardLink.isSubmitting(link, ...),
)

let host = DetachedCardHost.useShared(
~store,
~link,
~ownsFormLogs=false,
~session,
~sdkAuthorization,
~vaultDetails,
~environment,
~appearance,
~locale,
~localisation,
~customEndpoints,
~disabled=submitting || disabled->Option.getOr(false),
~accessible,
~enabledCardSchemes,
~cardholderName,
~unstyled,
~onReady=None,
~onChange=None,
)

<VaultWidgetContext.ContextProvider value={Some(host.contextValue)}>
children
</VaultWidgetContext.ContextProvider>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
* The non-visual root of a detached card form, rendered once by the screen that owns the form. It
* holds the form's tokenizer and reports the form's state; the fields render in roots of their own
* (DetachedCardField).
*
* ONE HOST PER FORM. Every render of a Host points the form's link at that Host's tokenizer, and
* its cleanup empties the link and resets the shared store. A second Host of the same form would
* point the link at its own tokenizer (with its own guard against a second submit), and whichever
* unmounted first would clear the card under the other. So a form has exactly one Host
* (createDetachedCardForm.mjs says the same to its callers).
*
* Unmounting the Host ends the form: the card is cleared, tokenize() refuses, and no final `change`
* is sent.
*/

/*
* How long the Host waits, after the last field registered, before it logs the form's settings.
* Each field is a root of its own and registers on its own, so without the wait the settings would
* be logged once per field, each time with one more field in the list.
*/
let fieldsSettleMs = 500

/*
* The <CardForm> provider's hook, over a store and a logger the form shares across roots. It takes
* every setting a <CardForm> takes, with the same defaults, so a detached form behaves as that form
* would. Only the Host root logs what belongs to the form as a whole (`ownsFormLogs`).
*/
let useShared = (
~store: VaultCardStore.t,
~link: DetachedCardLink.t,
~ownsFormLogs: bool,
~session: option<VaultFormOptions.vaultSession>,
~sdkAuthorization: option<string>,
~vaultDetails: option<VaultDetails.vaultDetails>,
~environment: VaultFormOptions.vaultEnvironment,
~appearance: option<VaultFormOptions.appearance>,
~locale: option<string>,
~localisation: option<VaultFormOptions.localisation>,
~customEndpoints: option<VaultEndpoint.customEndpoints>,
~disabled: bool,
~accessible: option<bool>,
~enabledCardSchemes: option<array<string>>,
~cardholderName: option<CardFieldOptions.cardholderNameMode>,
~unstyled: option<bool>,
~onReady: option<VaultPublicState.cardFormEvent => unit>,
~onChange: option<VaultPublicState.cardFormChange => unit>,
) =>
VaultFormHost.useHost(
~store,
~loggerFor=DetachedCardLink.loggerFor(link, ...),
~ownsFormLogs,
~fieldsSettleMs,
~session=session->Option.map(VaultFormOptions.sessionToJson),
~sdkAuthorization,
~vaultDetails,
~environment,
~appearance,
~locale,
~localisation,
~disabled,
~accessible,
~enabledCardSchemes=enabledCardSchemes->Option.getOr([]),
~eligibility=None,
~customEndpoints,
~cardholderNameMode=cardholderName->Option.getOr(#collect),
~onReady,
~onChange,
~unstyled=unstyled->Option.getOr(CardFieldOptions.defaultUnstyled),
~defaultErrorDisplay=CardFieldOptions.defaultErrorDisplayComposable,
)

@react.component
let make = (
~store: VaultCardStore.t,
~link: DetachedCardLink.t,
~session: option<VaultFormOptions.vaultSession>=?,
~sdkAuthorization: option<string>=?,
~vaultDetails: option<VaultDetails.vaultDetails>=?,
~environment: VaultFormOptions.vaultEnvironment,
~appearance: option<VaultFormOptions.appearance>=?,
~locale: option<string>=?,
~localisation: option<VaultFormOptions.localisation>=?,
~customEndpoints: option<VaultEndpoint.customEndpoints>=?,
~disabled: option<bool>=?,
~accessible: option<bool>=?,
~enabledCardSchemes: option<array<string>>=?,
~cardholderName: option<CardFieldOptions.cardholderNameMode>=?,
~unstyled: option<bool>=?,
~onReady: option<VaultPublicState.cardFormEvent => unit>=?,
~onChange: option<VaultPublicState.cardFormChange => unit>=?,
) => {
let host = useShared(
~store,
~link,
~ownsFormLogs=true,
~session,
~sdkAuthorization,
~vaultDetails,
~environment,
~appearance,
~locale,
~localisation,
~customEndpoints,
~disabled=disabled->Option.getOr(false),
~accessible,
~enabledCardSchemes,
~cardholderName,
~unstyled,
~onReady,
~onChange,
)

React.useEffectOnEveryRender(() => {
link.machinery = Some(host.machinery)
link.focusField = Some(host.focusField)
link->DetachedCardLink.setSubmitting(host.machinery.isSubmitting)
None
})

React.useEffect0(() => Some(
() => {
link.machinery = None
link.focusField = None
link->DetachedCardLink.setSubmitting(false)
store->VaultCardStore.dispatch(CardStateReducer.Reset)
},
))

React.null
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* What a detached card form's Host shares with its Fields. Each Field sits in a React root of its
* own, so it cannot read the Host's context; it reads this instead.
*
* The card is NOT here. It lives in the VaultCardStore that the Host and every Field subscribe to.
* This holds only the Host's machinery (so the form's handle can tokenize through it), whether a
* submit is in flight (so every Field disables itself, as it would inside a <CardForm>), and the
* form's one logger (so the logs of every root carry one session_id, as a <CardForm>'s do).
*/
type t = {
mutable machinery: option<VaultFormCoordinator.machinery>,
mutable focusField: option<VaultPublicState.elementType => unit>,
mutable submitting: bool,
mutable listeners: array<(int, unit => unit)>,
mutable nextListenerId: int,
// The form's logger and the URL it was made for ("" when the form logs nowhere).
mutable logger: option<(string, VaultLogger.t)>,
}

let make = (): t => {
machinery: None,
focusField: None,
submitting: false,
listeners: [],
nextListenerId: 0,
logger: None,
}

let subscribe = (link: t, listener: unit => unit) => {
link.nextListenerId = link.nextListenerId + 1
let id = link.nextListenerId
link.listeners = link.listeners->Array.concat([(id, listener)])
() => link.listeners = link.listeners->Array.filter(((other, _)) => other !== id)
}

let isSubmitting = (link: t, ()) => link.submitting

let setSubmitting = (link: t, submitting: bool) =>
if link.submitting !== submitting {
link.submitting = submitting
link.listeners->Array.forEach(((_, listener)) => listener())
}

/*
* The form's logger: made by whichever root asks first, then the same one for every root. A new
* logging URL (the form's endpoints or environment changed) gets a new logger, as it does in a
* <CardForm>; the roots flush the old one as they let go of it.
*/
let loggerFor = (link: t, ~url: option<string>, ~platform: string) => {
let key = url->Option.getOr("")
switch link.logger {
| Some((current, logger)) if current === key => logger
| _ =>
let logger = VaultLogger.make(~url, ~platform)
link.logger = Some((key, logger))
logger
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ type host = {

let useHost = (
~store: option<VaultCardStore.t>=?,
// A detached form's roots each run this hook over one store. These three keep its logs one form's:
// `loggerFor` hands every root the same logger; only the Host root (`ownsFormLogs`) logs what
// belongs to the form as a whole; and `fieldsSettleMs` is how long its settings log waits after
// the last field arrived, because its fields mount in roots of their own, one after another,
// where a <CardForm>'s arrive in one commit. A <CardForm> passes none of them.
~loggerFor: option<(~url: option<string>, ~platform: string) => VaultLogger.t>=?,
~ownsFormLogs: bool=true,
~fieldsSettleMs: int=0,
~session: option<JSON.t>,

~sdkAuthorization: option<string>,
Expand Down Expand Up @@ -71,17 +79,20 @@ let useHost = (
| Ready({authorization}) => authorization
| Unusable(_) => ""
}
let logger = React.useMemo1(
() => VaultLogger.make(~url=loggingUrl, ~platform=(ReactNative.Platform.os :> string)),
[loggingUrl],
)
let logger = React.useMemo1(() => {
let platform = (ReactNative.Platform.os :> string)
switch loggerFor {
| Some(shared) => shared(~url=loggingUrl, ~platform)
| None => VaultLogger.make(~url=loggingUrl, ~platform)
}
}, [loggingUrl])
// A session that replaces another starts the logger afresh, as web loads its frames afresh for
// each. The first session to arrive does not: what the customer did before it keeps its session_id.
let lastResolvedSdkAuthorizationRef = React.useRef("")
React.useEffect2(() => {
if resolvedSdkAuthorization !== "" {
let previous = lastResolvedSdkAuthorizationRef.current
if previous !== "" && previous !== resolvedSdkAuthorization {
if ownsFormLogs && previous !== "" && previous !== resolvedSdkAuthorization {
logger->VaultLogger.startNewSession
}
lastResolvedSdkAuthorizationRef.current = resolvedSdkAuthorization
Expand Down Expand Up @@ -332,13 +343,14 @@ let useHost = (
~paymentId,
)
}
if loggedSessionStatus === "consumed" || loggedSettingsRef.current === key {
if !ownsFormLogs || loggedSessionStatus === "consumed" || loggedSettingsRef.current === key {
None
} else if hasFields {
} else if hasFields && fieldsSettleMs <= 0 {
logSettings()
None
} else {
let timer = setTimeout(logSettings, 1000)
// Restarted by every change to `settings`, so a field that arrives resets the wait.
let timer = setTimeout(logSettings, hasFields ? fieldsSettleMs : 1000)
Some(() => clearTimeout(timer))
}
}, (settings, resolvedSdkAuthorization, logger, hasFields))
Expand Down Expand Up @@ -420,7 +432,9 @@ let useHost = (
// Once per logger session, as web logs it once per frame.
let coBadgedLoggedInRef = React.useRef("")
React.useEffect3(() => {
if controller.values.isCoBadged && coBadgedLoggedInRef.current !== logger.sessionId {
if (
ownsFormLogs && controller.values.isCoBadged && coBadgedLoggedInRef.current !== logger.sessionId
) {
coBadgedLoggedInRef.current = logger.sessionId
logUserEvent(~eventName=CARD_SCHEME_SELECTION, ~value="Card detected as co-badged")
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Which settings has the detached form's Host actually drawn with? tokenize() asks this before it
* runs.
*
* WHY. `update()` changes the settings at once, but the Host only reads them when React next draws
* it, a moment later. The Host's session (from `sdkAuthorization` / `vaultDetails`) is worked out
* while it draws, so a tokenize() called right after update({sdkAuthorization: fresh}) would still
* run with the previous session: an old-session request, or a wrong `session_consumed` refusal.
* So tokenize() waits until the Host has committed the settings that are current when it is called.
*
* A SAVE BELONGS TO THE SETTINGS IT WAS CALLED WITH. If newer settings replace them before the Host
* draws them (another update(), or, in the vault's own engine, the next props from native), the wait
* ends as `superseded` and the save is refused, unsent: it never runs with a session it was not
* called for. The merchant can save again.
*
* It never waits forever: if the Host goes away the wait ends as `closed`, and if no commit comes
* within `timeoutMs` it ends as `timeout`. Plain data and timers only, so it is tested without React.
*/

/* What a save refused as `superseded` says (here and for native's equivalent, native/out.mjs). */
export const settingsChangedMessage =
"The card form's settings changed before the save could run. Nothing was sent; try again.";

export function makeCommitGate({ timeoutMs = 5000, setTimer = setTimeout, clearTimer = clearTimeout } = {}) {
let mounted = false;
let drawn;
const waiters = new Set();

const settle = (waiter, outcome) => {
if (!waiters.delete(waiter)) return;
clearTimer(waiter.timer);
waiter.resolve(outcome);
};

return {
/* The Host committed a render made with `settings` (the settings object it read). */
committed(settings) {
mounted = true;
drawn = settings;
for (const waiter of [...waiters]) {
if (drawn === waiter.wanted) settle(waiter, 'current');
else if (waiter.current() !== waiter.wanted) settle(waiter, 'superseded');
}
},

/* The Host unmounted: nothing can be drawn any more. */
closed() {
mounted = false;
drawn = undefined;
for (const waiter of [...waiters]) settle(waiter, 'closed');
},

/* Whether the Host has drawn with exactly `settings`. */
isDrawn(settings) {
return mounted && drawn === settings;
},

/*
* Resolves 'current' once the Host has drawn with exactly `wanted`; 'superseded' if, at a commit,
* `current()` (the newest settings) is no longer `wanted`; 'closed' if the Host unmounts first
* (or none is mounted); 'timeout' after `timeoutMs`.
*/
whenDrawn(wanted, current = () => wanted) {
if (!mounted) return Promise.resolve('closed');
if (drawn === wanted) return Promise.resolve('current');
if (current() !== wanted) return Promise.resolve('superseded');
return new Promise((resolve) => {
const waiter = { wanted, current, resolve, timer: undefined };
waiter.timer = setTimer(() => settle(waiter, 'timeout'), timeoutMs);
waiters.add(waiter);
});
},
};
}
Loading
Loading