@bestcheckout/dynamic-component-cli 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -314,40 +314,65 @@ Payment method IDs come from `snapshot.payment.methods`. Render only the methods
314
314
  | PayPal | `payment.mountAction` for the native authorization button; do not use `checkout.submit()` |
315
315
  | Express | `checkout.express.mount` for the native express controls |
316
316
 
317
- Check the result of `payment.selectMethod(method)` before mounting. Secure-element handles also expose `validate()`. Keep mount containers stable across input, address and quote updates. Catch mount failures and show an unavailable state without an automatic retry loop. Components must not read or persist card numbers, CVV or payment tokens. Use this wrapper as `src/SecurePaymentForm.tsx`, passing a currently supported secure-form method:
317
+ Check the result of `payment.selectMethod(method)` before mounting. Secure-element handles also expose `validate()`. Mount only a supported method using the integration in the table above; do not guess secure/action support from a regular expression over the method label. Keep mount containers stable across input, address and quote updates. Components must not read or persist card numbers, CVV or payment tokens.
318
+
319
+ ##### Payment mount lifecycle
320
+
321
+ Runtime capability objects and their methods may receive new references on ordinary Host updates. A new `checkout` reference is not a new checkout session. Do not make payment mount effects depend on `runtime`, `checkout`, `snapshot`, inline option objects or mount-function references: mounting/releasing can itself notify the Host, creating an update → cleanup → remount loop. Subscription effects may depend on the current API object; payment resource ownership must use a separate lifecycle.
322
+
323
+ The wrapper below updates a ref after commit and mounts by component instance, checkout presence, mount kind and payment method. The current Renderer remounts the enclosing dynamic component when its template/Section identity or Host session changes. Keep this wrapper inside that component; do not hoist it into a persistent global root. A custom Host must provide a session key that changes with the business session and remount the component on session replacement. `runtime.page` is not an order/session identifier; do not invent one from an email, amount or snapshot. Runtime refs are not a substitute for Host session isolation.
324
+
325
+ Use this wrapper as `src/NativePaymentControl.tsx`. `kind="secure"` mounts a secure form, `kind="action"` mounts a native authorization button, and `kind="express"` mounts native express controls (omit `method` for Express). Render one owner for each payment surface; do not mount a duplicate alongside an enabled built-in Payment/Express section.
318
326
 
319
327
  ```tsx
320
- import { useEffect, useRef, useState } from "react";
328
+ import { useEffect, useLayoutEffect, useRef, useState } from "react";
321
329
  import type { DynamicCheckoutRuntime } from "@bestcheckout/dynamic-component-cli/types";
322
330
 
323
- export function SecurePaymentForm({ checkout, method }: {
331
+ export function NativePaymentControl({ checkout, kind, method = "" }: {
324
332
  checkout?: DynamicCheckoutRuntime;
325
- method: string;
333
+ kind: "secure" | "action" | "express";
334
+ method?: string;
326
335
  }) {
327
336
  const container = useRef<HTMLDivElement>(null);
337
+ const latestCheckout = useRef(checkout);
328
338
  const [error, setError] = useState("");
339
+ const hasCheckout = Boolean(checkout);
340
+
341
+ // Keep the API current without making its reference a mount identity.
342
+ useLayoutEffect(() => {
343
+ latestCheckout.current = checkout;
344
+ }, [checkout]);
329
345
 
330
346
  useEffect(() => {
347
+ const api = latestCheckout.current;
331
348
  const element = container.current;
332
- if (!checkout || !element || !method) {
333
- setError("Payment form is unavailable.");
349
+ if (!hasCheckout || !api || !element || (kind !== "express" && !method)) {
350
+ setError("Payment controls are unavailable. Please refresh the page.");
334
351
  return;
335
352
  }
336
353
  let cancelled = false;
337
354
  let unmount: (() => void) | undefined;
338
355
  setError("");
339
- void checkout.payment.mountSecureElement({ element, method }).then(
340
- (handle) => {
356
+ const mount = async () => {
357
+ try {
358
+ const handle = await (kind === "express"
359
+ ? api.express.mount({ element })
360
+ : kind === "action"
361
+ ? api.payment.mountAction({ element, method })
362
+ : api.payment.mountSecureElement({ element, method }));
341
363
  if (cancelled) handle.unmount();
342
364
  else unmount = () => handle.unmount();
343
- },
344
- () => { if (!cancelled) setError("Payment form failed to load."); },
345
- );
365
+ } catch {
366
+ if (!cancelled) setError("Payment controls failed to load. Please refresh the page.");
367
+ }
368
+ };
369
+ // Run after React commits; cleanup of the previous owner is queued first.
370
+ queueMicrotask(() => { if (!cancelled) void mount(); });
346
371
  return () => {
347
372
  cancelled = true;
348
- unmount?.();
373
+ queueMicrotask(() => unmount?.());
349
374
  };
350
- }, [checkout, method]);
375
+ }, [hasCheckout, kind, method]);
351
376
 
352
377
  return (
353
378
  <div>
@@ -358,7 +383,33 @@ export function SecurePaymentForm({ checkout, method }: {
358
383
  }
359
384
  ```
360
385
 
361
- This only manages the form lifecycle. It does not submit or indicate successful payment. If a mount resolves after cleanup, the returned handle is immediately released. Do not remount on each snapshot update.
386
+ This manages control ownership only; mounting does not submit or prove successful payment. Host updates refresh an existing mounted control through the runtime adapter. If a mount resolves after cleanup, its handle is immediately released. Failure remains an unavailable state across ordinary snapshot updates; do not automatically retry on errors or new Runtime references.
387
+
388
+ The recovery policy in this example is a visible instruction to refresh the page manually, with no automatic retry or reload. After a mounted control becomes unavailable or throws during rendering, the Adapter removes the provider subtree, releases its Host reservation once and keeps a refresh message inside its owned container until disposal. Ordinary Host updates do not recover that failed mount; a page refresh creates a new instance. `hasCheckout` only detects that the checkout API exists, not that the payment SDK is ready. Errors handled internally by a payment SDK, including asynchronous network failures, remain the responsibility of that SDK/Host UI; a React error boundary does not catch every asynchronous error.
389
+
390
+ Mount calls and cleanup are queued after the React commit so nested payment roots are not synchronously unmounted while React is rendering; cancelled setups are skipped. React StrictMode may run setup/cleanup again in development; cleanup must tolerate it. Do not keep the first Runtime forever in a ref, remove all effect dependencies, or suppress dependency lint rules as a workaround.
391
+
392
+ ##### Patterns to avoid in dynamic components
393
+
394
+ | Risky pattern | Failure mode | Supported approach |
395
+ | --- | --- | --- |
396
+ | Payment mount effect depends on an API/snapshot object; random, timestamp or serialized-snapshot React keys | Repeated SDK initialization, requests and lost input | Use the lifecycle wrapper above; stable component types, keys and container nodes within a session |
397
+ | `innerHTML`, `replaceChildren`, manual removal, or another `createRoot` inside a payment container | React/SDK DOM ownership conflicts and `removeChild` errors | Leave the empty ref container to the mount handle; release with `unmount()` |
398
+ | Calling setters, coupon actions, repricing or payment actions during render or in every subscription callback | Update/request feedback loops and duplicate writes | Render reads only; invoke writes from user intent or narrowly keyed, guarded effects |
399
+ | `getSnapshot: () => ({ ...checkout.getSnapshot() })`, allocating arrays with `map/filter`, or a new fallback object on every read | Unstable external-store snapshots and repeated renders | Return the existing snapshot; derive display values after reading it; always unsubscribe |
400
+ | Defining a component function inside another render, or keying the whole form by field values | React sees a new component identity; focus and payment state reset | Define components at module scope and use stable resource/instance keys |
401
+ | Applying an async result after its selection/session changed | Stale products, address options or quotes overwrite current state | Track request identity or cancellation; ignore stale completions and release late mount handles |
402
+ | Only using `setBusy(true)` to prevent same-tick duplicate actions; unbounded retry/polling | Duplicate submissions or request storms | Use an immediate ref lock plus visible busy state, unlock in `finally`; use bounded/manual recovery and existing payment status reads |
403
+ | Guessing payment capabilities by label, swallowing mount errors, or treating fulfilled Promises as payment success | Wrong control, silent failure or false success | Follow supported method integration and result contracts; show errors; keep unknown/processing explicit |
404
+ | Calling Hooks conditionally after an early return or inside a list/callback | Hook order changes when data or capabilities appear | Call Hooks unconditionally at component top level; put availability checks inside callbacks/effects or split a module-scope child component |
405
+ | Mutating settings/snapshots or computing authoritative totals, defaulting missing amount/currency to zero/USD | Corrupt shared data or show false prices/readiness | Keep snapshots/settings read-only; use local UI state and server amounts; render missing/unknown explicitly |
406
+ | Global DOM queries, duplicate hard-coded input IDs, global listeners/timers without cleanup | One instance changes another, leaked callbacks and duplicate actions | Use instance refs/IDs and scoped styles; remove listeners, clear timers, unsubscribe and release handles on cleanup |
407
+ | Automatically submitting/accepting/retrying a charge when data becomes ready or a request times out | Unintended or duplicate transactions | Require user intent; keep unknown/processing states; reconcile the existing attempt instead of creating another payment |
408
+ | Reading browser globals at module evaluation, storing business state in module globals/local storage, or private API/SDK fallbacks | Build failure, stale/cross-session data and bypassed Host controls | Browser work in cleaned-up effects; state per instance; use documented optional Runtime capabilities |
409
+
410
+ For asynchronous writes, acquire a ref lock before the first `await`; a disabled button/state update alone is not a synchronous lock. Release the lock in `finally` and discard stale UI results using the request/selection identity. A local lock does not replace the Host/server transaction guard or idempotency, and a timeout is not evidence that a payment failed. Avoid reporting a second global toast for errors the Host already displays; show a local unavailable/recovery state when needed.
411
+
412
+ For payment examples, validate ordinary Host reference changes, input/quote updates, method/kind switches, session remount, capability withdrawal, delayed resolution after cleanup, failed mounts and StrictMode. Assert both stable DOM/input and bounded mount/request counts. A successful build or Editor preview alone does not verify these properties or a real payment.
362
413
 
363
414
  #### Upsell and Downsell runtime
364
415
 
@@ -455,6 +506,8 @@ Before publishing, verify:
455
506
  - Manifest page support, schema and defaults match the target template.
456
507
  - Preview works on desktop and mobile; HMR does not lose settings or create duplicate subscriptions.
457
508
  - Loading, empty, unavailable, validation, network error and duplicate-action states are handled.
509
+ - Review the Runtime guide’s “Patterns to avoid in dynamic components”; test two instances, late/failed responses, session replacement and unmount cleanup.
510
+ - Payment mount/request counts settle after initialization and do not grow on ordinary API/snapshot updates; SDK containers and input values remain stable.
458
511
  - Runtime actions check `ok`/status and never assume a Promise means payment success.
459
512
  - Save and reopen preserve the component identity and settings.
460
513
  - Publish succeeds, the local server can stop, and a refreshed storefront renders the published artifact.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bestcheckout/dynamic-component-cli",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "CLI and starter project generator for BestCheckout dynamic components",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -48,6 +48,8 @@
48
48
  "pack:check": "npm pack --dry-run",
49
49
  "test:integration": "node tests/standalone.integration.mjs",
50
50
  "test:editor": "node scripts/test-editor.mjs",
51
+ "test:payment-example": "node tests/payment-example.integration.mjs",
52
+ "test:payment-host": "node tests/payment-host.integration.mjs",
51
53
  "sync:protocol": "node scripts/sync-protocol.mjs",
52
54
  "check:protocol": "node scripts/sync-protocol.mjs --check"
53
55
  }
@@ -15,7 +15,7 @@ export function componentSource(id, pageType) {
15
15
  const capability = ['upsell', 'downsell'].includes(pageType)
16
16
  ? ', capabilities: { offerRecommendation: true }'
17
17
  : '';
18
- return `import { useSyncExternalStore } from "react";
18
+ return `import { useCallback, useSyncExternalStore } from "react";
19
19
  import type { DynamicComponentDefinition, DynamicComponentProps } from "@bestcheckout/dynamic-component-cli/types";
20
20
 
21
21
  export const manifest = { componentId: ${JSON.stringify(id)}, name: ${JSON.stringify(id)}, supportedPageTypes: [${JSON.stringify(pageType)}] as const${capability} };
@@ -25,8 +25,14 @@ export const styles = ".example{padding:20px;border:1px solid #ddd;border-radius
25
25
  export function Component({ settings, runtime }: DynamicComponentProps) {
26
26
  // Host supplies business data. Missing capabilities remain unavailable.
27
27
  const account = runtime.account;
28
- const snapshot = useSyncExternalStore(account ? listener => account.subscribe(() => listener()) : () => () => {}, account ? () => account.getSnapshot() : () => undefined);
29
- return <section className="example"><h2>{String(settings.heading || "")}</h2><p>Page: {runtime.page.pageType}</p><p>Account: {snapshot?.status || "unavailable"}</p></section>;
28
+ const subscribe = useCallback(
29
+ (notify: () => void) => account?.subscribe(() => notify()) ?? (() => {}),
30
+ [account],
31
+ );
32
+ // This view needs only a primitive status, not a freshly projected object.
33
+ const getStatus = useCallback(() => account?.getSnapshot().status, [account]);
34
+ const status = useSyncExternalStore(subscribe, getStatus);
35
+ return <section className="example"><h2>{String(settings.heading || "")}</h2><p>Page: {runtime.page.pageType}</p><p>Account: {status || "unavailable"}</p></section>;
30
36
  }
31
37
  export default { manifest, schema, defaultSettings, styles, Component } satisfies DynamicComponentDefinition;
32
38
  `;
package/types/index.d.ts CHANGED
@@ -410,6 +410,8 @@ type CheckoutAddressSchema = Record<"state" | "city" | "zip", {
410
410
  }>;
411
411
  type CheckoutDeliveryState = {
412
412
  values: CheckoutDeliveryValues;
413
+ /** Actual load failure; Host presents this through Toast. */
414
+ locationError?: string;
413
415
  locationStatus?: string;
414
416
  retryLocations?: () => void;
415
417
  countryOptions: CheckoutDeliveryOption[];
@@ -440,6 +442,8 @@ type CheckoutDeliveryState = {
440
442
  };
441
443
  type CheckoutBillingState = {
442
444
  values: CheckoutDeliveryValues;
445
+ /** Actual load failure; Host presents this through Toast. */
446
+ locationError?: string;
443
447
  locationStatus?: string;
444
448
  retryLocations?: () => void;
445
449
  countryOptions: CheckoutDeliveryOption[];
@@ -881,6 +885,7 @@ declare function toCheckoutSnapshot(host: CheckoutRuntime, preview?: boolean): {
881
885
  useStateSelect: boolean;
882
886
  useCitySelect: boolean;
883
887
  phoneCode?: string;
888
+ locationError?: string | undefined;
884
889
  locationStatus?: string | undefined;
885
890
  lastNameFirst?: boolean | undefined;
886
891
  isAddressComplete?: boolean | undefined;
@@ -899,6 +904,7 @@ declare function toCheckoutSnapshot(host: CheckoutRuntime, preview?: boolean): {
899
904
  useStateSelect: boolean;
900
905
  useCitySelect: boolean;
901
906
  phoneCode?: string;
907
+ locationError?: string | undefined;
902
908
  locationStatus?: string | undefined;
903
909
  lastNameFirst?: boolean | undefined;
904
910
  isAddressComplete?: boolean | undefined;
@@ -952,6 +958,7 @@ declare function createDynamicCheckoutAdapter(context: DynamicComponentContext,
952
958
  useStateSelect: boolean;
953
959
  useCitySelect: boolean;
954
960
  phoneCode?: string;
961
+ locationError?: string | undefined;
955
962
  locationStatus?: string | undefined;
956
963
  lastNameFirst?: boolean | undefined;
957
964
  isAddressComplete?: boolean | undefined;
@@ -970,6 +977,7 @@ declare function createDynamicCheckoutAdapter(context: DynamicComponentContext,
970
977
  useStateSelect: boolean;
971
978
  useCitySelect: boolean;
972
979
  phoneCode?: string;
980
+ locationError?: string | undefined;
973
981
  locationStatus?: string | undefined;
974
982
  lastNameFirst?: boolean | undefined;
975
983
  isAddressComplete?: boolean | undefined;
@@ -1047,6 +1055,7 @@ declare function createDynamicCheckoutAdapter(context: DynamicComponentContext,
1047
1055
  useStateSelect: boolean;
1048
1056
  useCitySelect: boolean;
1049
1057
  phoneCode?: string;
1058
+ locationError?: string | undefined;
1050
1059
  locationStatus?: string | undefined;
1051
1060
  lastNameFirst?: boolean | undefined;
1052
1061
  isAddressComplete?: boolean | undefined;
@@ -1117,6 +1126,7 @@ declare function createDynamicCheckoutAdapter(context: DynamicComponentContext,
1117
1126
  useStateSelect: boolean;
1118
1127
  useCitySelect: boolean;
1119
1128
  phoneCode?: string;
1129
+ locationError?: string | undefined;
1120
1130
  locationStatus?: string | undefined;
1121
1131
  lastNameFirst?: boolean | undefined;
1122
1132
  isAddressComplete?: boolean | undefined;