Skip to content

feat(vault): createDetachedCardForm from the root, with CardForm's settings and update() - #79

Open
Pradeep-kumar1202 wants to merge 4 commits into
mainfrom
feat/vault-detached-card-form
Open

Pradeep-kumar1202 wants to merge 4 commits into
mainfrom
feat/vault-detached-card-form

Conversation

@Pradeep-kumar1202

@Pradeep-kumar1202 Pradeep-kumar1202 commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What

Adds createDetachedCardForm(config) to @juspay-tech/react-native-hyperswitch-vault, exported from the package root. It builds a card form whose fields are not its children: each field can sit in its own React root, and together they still collect and tokenize one card.

import { createDetachedCardForm, CardNumberField } from '@juspay-tech/react-native-hyperswitch-vault';

const form = createDetachedCardForm({ vaultDetails, environment: 'sandbox', onChange });

<form.Host />                                   // once per form
<form.Field><CardNumberField /></form.Field>    // in any root (same for expiry / CVC / name)

const result = await form.tokenize();
form.update({ appearance });                    // every root re-renders; the typed card is kept

JavaScript only. Nothing in this pull request calls the new function, and no existing export changes.

Why

This is the first of four pull requests that make the vault's card fields natively wrapped: each field becomes a native view whose content runs in a JavaScript engine the vault starts itself, so the card number and CVC never sit in the merchant's engine (as hyperswitch-web keeps each field in an iframe).

Each native view holds its own React root. Separate roots cannot share a card through <CardForm>'s React context. This function gives them one form that needs no common parent. The next pull request uses it inside the vault's own engine: a hidden form root renders form.Host, and each field root renders its field inside form.Field.

Pull request What it adds
#79 (this) createDetachedCardForm: one card across separate React roots
#103 the JavaScript the vault's own engine runs, and the bundle toolchain
#104 the Android host, and the choice between native and plain fields
#105 the iOS host

Each is based on the one before it. Merge order: #79, #103, #104, #105, then the release pull request (README, release notes, version 2.0.0). Labelled DO NOT MERGE until the stack is ready.

How it works

  • Three objects per form, created outside React:
    • the existing VaultCardStore, which holds the card;
    • DetachedCardLink, which holds the Host's tokenizer, a "submitting" flag and the form's logger. No card data;
    • the settings (detachedSettings.mjs). No card data.
  • Host (DetachedCardHost.res) renders nothing. It owns the tokenizer and reports ready and change. Render exactly one Host per form. Unmounting it ends the form: the card is cleared, tokenize() returns a refusal, no final change is sent, and getState() returns null.
  • Field (DetachedCardField.res) gives its children the context a <CardForm> would, and disables them while the Host is submitting or the form is disabled.
  • Settings: every setting a merchant can pass to <CardForm>, with the same defaults: vaultDetails, sdkAuthorization, session, environment, customEndpoints, locale, localisation, appearance, disabled, accessible, enabledCardSchemes, cardholderName, unstyled. (eligibility, which only the checkout SDK passes, is not one of them.)
  • update() cannot lose the card. Settings and card are separate objects, and update() only touches the settings. Each root reads them with useSyncExternalStore. The snapshot stays the same object until a setting really changes, so an equal value rebuilt by the caller re-renders nothing.
  • onReady / onChange are not settings. They are read when an event fires, so replacing one re-renders nothing.
  • One log stream per form. Every root runs VaultFormHost.useHost over the shared store, and that hook creates a logger. Without care, one form would log under one session id per root. The link hands every root the same logger, only the Host logs what belongs to the form as a whole, and the Host's settings log waits 500 ms after the last field arrived. useHost gets three optional parameters for this (loggerFor, ownsFormLogs, fieldsSettleMs); <CardForm> and HyperswitchVaultForm pass none of them.
  • The handle (tokenize, reset, focus, update, getState, on) exposes no store and no card values. tokenize() without a mounted Host resolves to {status: "validation_error", error: {code: "incomplete_field_set"}}; it never throws.

Files

File Change
src/createDetachedCardForm.mjs new: the factory and its handle
src/detachedSettings.mjs new: the form's settings, outside React
src/commitGate.mjs new: tokenize() waits until the Host has drawn the settings it was called with, and refuses if newer ones replace them
src/DetachedCardHost.res, src/DetachedCardField.res, src/DetachedCardLink.res new: the Host, the per-root Field, and what the Host shares with the Fields
src/VaultFormHost.res three optional parameters: loggerFor, ownsFormLogs, fieldsSettleMs
src/standalone-entry.mjs, src/public.ts the root export and its types
test/detached.test.mjs, package.json 11 unit tests; the test script runs them

Impact on existing merchants

  • Every existing export is unchanged. The root gains createDetachedCardForm. No new entry point.
  • <CardForm> and HyperswitchVaultForm call useHost exactly as before: with the new parameters left out, every branch behaves as on main.
  • @juspay-tech/react-native-hyperswitch-payment-methods needs no change.

Testing

At this commit (440500d):

  • The vault builds: ReScript, TypeScript and rollup.
  • yarn test in the vault: 59 pass (48 existing; 11 new: the settings, the shared logger, and the commit gate).
  • Rendered outside the repository in a React test renderer, with the Host and three fields in four separate roots: the fields edit one card; update() re-themes every root and keeps the typed number; tokenize() makes exactly one call; one form logs under one session id, with its settings once; no log contains the card number. A plain <CardForm> still collects a card. These tests are not in this pull request, because the vault has no React test harness.

Through the rest of the stack: the native path in #103 to #105 runs this function inside the vault's engine. It was run on the Android emulator and the iOS simulator on React Native 0.82 to 0.88 (main flow, keyboard, dark mode, the form's API): every check passes, and the merchant's engine sees no card text.

Not run: the example app with this pull request alone; hyperswitch-client-core's payment-methods tests.

Not in this PR

  • Version and release: in the release pull request after feat(vault): iOS host for the native card fields #105.
  • hyperswitch-client-core: it still requires …-vault/detached (src/payment-methods/hosted/hyperswitchDetached.tsx), inside a try, and pins vault 1.0.1. No published vault has had that subpath, so nothing changes there. To use this function it must import the root and bump its pin; that is a follow-up.
  • README.

Note for the reviewer

  • Render form.Host once per form. A second Host for the same form is not guarded here: both would emit change, and the first to unmount would clear the card under the other. feat(vault): hosted entry and bundle for the vault's own engine #103's form root refuses a second Host per form id. A guard on the link itself is a possible follow-up.
  • A form that lives for less than half a second logs no settings, because of the 500 ms wait. A <CardForm> with no fields already behaves this way for one second.
  • createDetachedCardForm is visible to merchants in the root's types. It needs a vault session to do anything and carries no card data.

@Pradeep-kumar1202
Pradeep-kumar1202 force-pushed the feat/vault-detached-card-form branch from 287df1b to 3a598fa Compare November 19, 2026 23:03
@Pradeep-kumar1202 Pradeep-kumar1202 changed the title feat(vault): add ./detached entry with createDetachedCardForm feat(vault): createDetachedCardForm from the root, with every CardForm setting and update() Nov 24, 2026
@Pradeep-kumar1202 Pradeep-kumar1202 changed the title feat(vault): createDetachedCardForm from the root, with every CardForm setting and update() feat(vault): createDetachedCardForm from the root, with CardForm's settings and update() Nov 25, 2026
…t the previous session

update() changes a detached form's settings at once, but the Host reads them when React next draws
it, and its session (from sdkAuthorization / vaultDetails) is worked out while it draws. So
update({sdkAuthorization: fresh}) followed straight away by tokenize() ran with the previous
session: an old-session request, or a wrong session_consumed refusal after the session had been
replaced. (Found in review.)

tokenize() now waits until the Host has committed the settings that are current when it is called
(commitGate.mjs), then runs. It never waits forever: if the Host unmounts it refuses as before (no
Host mounted), and if no commit comes within 5 seconds it refuses with tokenization_failed and
"did not apply its new settings in time". With nothing pending it runs at once, as before.

Tests: the gate on its own (waits for the current settings, follows the newest update, ends on
unmount, times out instead of hanging).
Pradeep-kumar1202 added a commit that referenced this pull request Dec 2, 2026
… command can see the old ones

The form room applied a settings update from native in a passive effect, which runs a moment after
the render commits. A tokenize command handled in that moment saw the previous settings, and so
the previous session, as current. The update now runs in a layout effect, while the render commits;
from then on form.tokenize() (#79's createDetachedCardForm) waits for the Host to draw the new
settings, so the command uses the new session.

Not covered here: a command that native code sends before the props update has reached the engine
at all. Keeping that order is the native hosts' part (#104, #105).
tokenize() waited for the Host to draw whichever settings were newest when it committed. So if
newer settings replaced the ones a save was called with before the Host drew them (update(A),
tokenize(), then update(B) at once; or, in the vault's own engine, a tokenize command carrying A
followed by B's props), the save ran with B's session, one it was not called for. (Found in review.)

tokenize() now keeps the settings it was called with and waits for exactly those. If newer settings
replace them first, it refuses without sending anything: tokenization_failed, "The card form's
settings changed before the save could run. Nothing was sent; try again." It checks once more just
before it runs. Everything else is as before: no wait when the settings are already drawn, a
refusal when the Host unmounts, tokenization_failed after 5 seconds with no commit.

Tests: the gate test that expected the wait to follow the newest settings now expects the save to
be refused when they are replaced, refused at once when already replaced, and to keep waiting
through a commit of older settings.
Pradeep-kumar1202 added a commit that referenced this pull request Dec 3, 2026
… command can see the old ones

The form room applied a settings update from native in a passive effect, which runs a moment after
the render commits. A tokenize command handled in that moment saw the previous settings, and so
the previous session, as current. The update now runs in a layout effect, while the render commits;
from then on form.tokenize() (#79's createDetachedCardForm) waits for the Host to draw the new
settings, so the command uses the new session.

Not covered here: a command that native code sends before the props update has reached the engine
at all. Keeping that order is the native hosts' part (#104, #105).

@manideepk90 manideepk90 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the design holds up. It builds (ReScript, tsc, rollup), and yarn test passes 59/59 at 1550bc8.

I checked the two edge cases I was worried about (a second form.Host, and the Host unmounting while its fields stay) against the native side in #104/#105. Neither can happen on the native path:

  • NativeCardForm creates one formId per instance, and VaultForms.open (Android) / HyperswitchVaultForms open: (iOS) keep one form root per formId. Each form root creates its own detached form, so even a re-opened id gets a separate link and store. #103's openForm also refuses a duplicate id.
  • The Host only unmounts when the whole form root does. That closes the registry entry, so the field roots render nothing and the merchant gets VAULT_FORM_ERROR.

But createDetachedCardForm is also exported from the package root, so direct callers (and the planned hyperswitch-client-core switch) don't get those guarantees. Two small changes before approval:

1. State the one-Host contract in the code (blocking, a comment is enough)

DetachedCardHost.res: every Host writes link.machinery / submitting on every render, and every Host's cleanup sets link.machinery = None and Resets the shared store. With two Hosts on one form, the single-submit guard (VaultFormCoordinator.res, inFlightRef) is per Host, so two tokenize() calls can reach two machineries. The first Host to unmount also clears the card under the other, and change fires twice.

Please put the contract where the code is, as createCardForm.mjs does for Form ("One instance drives ONE mounted form…"): one Host per form, and unmounting it ends the form. On that path the card is cleared and no final change is sent, so getState() keeps the last snapshot. A guard is welcome but not required. If you add one, mirror <CardForm>'s duplicate-field refusal (VaultFormHost.res, duplicateMessage). Clearing latest next to gate.closed() is a one-line improvement for direct callers.

2. Reuse existing code (can be a follow-up if you note it here)

  • DetachedCardLink.subscribe / setSubmitting copy VaultCardStore.subscribe / notify line for line. detachedSettings.mjs and #103's forms.mjs add two more copies. One small subscribe/notify helper would cover all of them.
  • EVENTS, announce and on() in createDetachedCardForm.mjs copy createCardForm.mjs. A shared helper keeps fixes to event fan-out in one place.

Nits: the description says 55 tests (it's 59) and leaves commitGate.mjs out of the Files table. The useShared doc comment sits above fieldsSettleMs = 500 in DetachedCardHost.res.

…it unmounts

Review follow-up. A detached form has exactly one Host: every Host points the form at its own
tokenizer, with its own guard against a second submit, and the first to unmount clears the card
under any other. The rule is now stated where the code is (createDetachedCardForm.mjs, as
createCardForm.mjs states its own, and DetachedCardHost.res), with what unmounting the Host means:
the card is cleared, tokenize() refuses, and no final change is sent.

getState() now returns null once the Host unmounts, instead of the last snapshot of a card that is
gone. The useShared comment in DetachedCardHost.res moves back above useShared.
Pradeep-kumar1202 added a commit that referenced this pull request Dec 3, 2026
… command can see the old ones

The form room applied a settings update from native in a passive effect, which runs a moment after
the render commits. A tokenize command handled in that moment saw the previous settings, and so
the previous session, as current. The update now runs in a layout effect, while the render commits;
from then on form.tokenize() (#79's createDetachedCardForm) waits for the Host to draw the new
settings, so the command uses the new session.

Not covered here: a command that native code sends before the props update has reached the engine
at all. Keeping that order is the native hosts' part (#104, #105).
@Pradeep-kumar1202

Copy link
Copy Markdown
Contributor Author

@manideepk90 Thanks. Done in 440500d:

  • The one-Host rule is now in createDetachedCardForm.mjs and DetachedCardHost.res: one Host per form; unmounting it ends the form (card cleared, tokenize() refuses, no final change).
  • getState() returns null once the Host unmounts (latest cleared next to gate.closed()).
  • Moved the useShared comment, and fixed the description (59 tests, commitGate.mjs in the Files table).

I'm not adding the guard for now, since the native path can't create a second Host. I'll add it when client-core moves to the root export.

Agreed on reuse: a shared subscribe/notify helper and the event fan-out helper will come as a follow-up.

#103 to #105 are rebased on this.

@manideepk90 manideepk90 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-checked at 440500d: the one-Host contract and "unmounting the Host ends the form" are now stated in createDetachedCardForm.mjs, and getState() returns null once the Host unmounts. Build passes and yarn test is 59/59. Approving.

Follow-ups as agreed, fine as separate PRs:

  • one shared subscribe/notify helper (DetachedCardLink, VaultCardStore, detachedSettings.mjs, #103's forms.mjs);
  • one shared event fan-out helper for createCardForm.mjs and createDetachedCardForm.mjs;
  • a second-Host guard once hyperswitch-client-core uses the root export directly.

Minor, no change needed: in dev StrictMode the effect cleanup runs once on mount, so getState() is null until the next change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants