@coras-io/embed 0.12.0 → 0.13.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 (43) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +18 -8
  3. package/dist/components/attraction-card/base/attraction-card.mixin.js +3 -3
  4. package/dist/components/attraction-card/base/attraction-card.styles.js +8 -0
  5. package/dist/components/button/button.component.d.ts +6 -0
  6. package/dist/components/button/button.component.js +31 -8
  7. package/dist/components/button/button.styles.js +8 -1
  8. package/dist/contexts/basket/basket.provider.js +1 -17
  9. package/dist/core/color-scheme.d.ts +0 -1
  10. package/dist/core/color-scheme.js +4 -6
  11. package/dist/core/utils/mount-root.d.ts +1 -0
  12. package/dist/core/utils/mount-root.js +15 -0
  13. package/dist/core/utils/redaction.js +5 -0
  14. package/dist/errors.js +2 -2
  15. package/dist/mixins/coinbase.mixin.d.ts +12 -2
  16. package/dist/mixins/coinbase.mixin.js +23 -20
  17. package/dist/sdk/mount.js +15 -13
  18. package/dist/sdk/redaction.d.ts +7 -1
  19. package/dist/sdk/redaction.js +32 -1
  20. package/dist/sdk/url.d.ts +44 -2
  21. package/dist/sdk/url.js +54 -6
  22. package/dist/sdk/validation.d.ts +1 -6
  23. package/dist/sdk/validation.js +7 -7
  24. package/dist/views/details-page/partials/location-categories/location-categories.component.d.ts +2 -1
  25. package/dist/views/details-page/partials/location-categories/location-categories.component.js +18 -5
  26. package/dist/views/payment-page/controllers/crypto-auth.controller.js +4 -4
  27. package/dist/views/payment-page/controllers/crypto-transfer.controller.d.ts +4 -4
  28. package/dist/views/payment-page/controllers/crypto-transfer.controller.js +9 -6
  29. package/dist/views/payment-page/controllers/stripe-payment.controller.d.ts +4 -1
  30. package/dist/views/payment-page/controllers/stripe-payment.controller.js +38 -10
  31. package/dist/views/payment-page/partials/activity-details/activity-details.component.js +1 -1
  32. package/dist/views/payment-page/partials/confirmation/confirmation.component.d.ts +2 -0
  33. package/dist/views/payment-page/partials/confirmation/confirmation.component.js +26 -6
  34. package/dist/views/payment-page/partials/confirmation/confirmation.styles.js +4 -0
  35. package/dist/views/payment-page/partials/hotel-pickup-field/hotel-pickup-field.component.js +3 -1
  36. package/dist/views/payment-page/partials/hotel-pickup-list/hotel-pickup-list.component.js +1 -1
  37. package/dist/views/payment-page/payment-page.component.d.ts +2 -1
  38. package/dist/views/payment-page/payment-page.component.js +45 -25
  39. package/dist/views/payment-page/payment-page.utils.d.ts +2 -0
  40. package/dist/views/payment-page/payment-page.utils.js +5 -0
  41. package/dist/views/suggestion-widget/suggestion-widget.component.d.ts +1 -1
  42. package/dist/views/suggestion-widget/suggestion-widget.component.js +11 -4
  43. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # @coras-io/embed
2
2
 
3
+ ## 0.13.1
4
+
5
+ ### Patch Changes
6
+
7
+ - dede3fc: Apply config and params updates that arrive while the chrome is still loading
8
+ - 590c9b1: Accept a trailing slash on `assetsUrl`: it is now removed, so icons, payment logos and the riyal font no longer request `//` paths that 404 on S3 and most CDNs.
9
+ - bd61a1c: Propagate a live colorScheme change to components inside shadow roots
10
+ - 6a63ce8: Transfer the exact FIDA amount shown when a basket has several reservations with decimal amounts, instead of a slightly larger amount from floating-point rounding
11
+ - c32851a: Fix the payment page so a chosen hotel pickup point is saved; tours with hotel pickup no longer fail with "This is a required field" on submit.
12
+ - 03b96ad: Redact personal data from everything passed to the host `logger`, so error reporters no longer receive end-user emails, phone numbers or SDK error details
13
+ - 07089d3: Redact phone numbers from API error payloads
14
+ - bb61396: Confirm the order instead of showing a failure when Stripe reports an error for a card or wallet payment that already succeeded, so charged customers are not told to book again, and show a failure when Stripe returns a payment that was not completed.
15
+
16
+ ## 0.13.0
17
+
18
+ ### Minor Changes
19
+
20
+ - b792a0b: Finish the embed's crawlable navigation. With an `href`, `coras-attraction-short-card` and `coras-attraction-long-card` stretch the title link's hit area over the whole card, so a click on the photo or the card body behaves like a click on the title; the title text stays the only link. With `hrefFor`, the details page's category "Explore" buttons, the suggestion widget's "See all activities" button and the order confirmation's Help Centre link render as real links too, and `coras-button` takes an `href` attribute that renders it as a link with the button's look. New in `@coras-io/embed/url`: `createCorasRouting({ url, navigate, replace })` returns the `hrefFor`, `onNavigate` and `onStateChange` mount options from one URL helper or strategy, so a host wires its router in one call and its links always match its routes; and two opt-in URL strategy options, `localeCase: "lower"` to write a lower-case locale segment and `defaultCurrency` to leave a default currency out of built URLs. The default strategy is unchanged. For every link a plain click still emits `onNavigate` without a page load, and a modified or middle click opens the page in a new tab. Without `href` or `hrefFor` nothing changes.
21
+
3
22
  ## 0.12.0
4
23
 
5
24
  ### Minor Changes
package/README.md CHANGED
@@ -31,17 +31,27 @@ copy instead of two; `@coinbase/cdp-core` is the only exact pin.
31
31
 
32
32
  ```ts
33
33
  import { mount } from "@coras-io/embed";
34
+ import { createCorasRouting, createCorasUrlState } from "@coras-io/embed/url";
35
+
36
+ const coras = createCorasUrlState({
37
+ localeCase: "lower",
38
+ currencyInPath: false,
39
+ defaultCurrency: "EUR",
40
+ });
34
41
 
35
42
  const app = mount({
36
43
  container,
37
44
  page: "landing",
38
45
  config: { apiUrl, distributorId, assetsUrl, locale, currency },
39
- onNavigate: (intent) => router.go(intent),
40
- onStateChange: (state) => router.replace(state),
46
+ ...createCorasRouting({
47
+ url: coras,
48
+ navigate: (href) => router.push(href),
49
+ replace: (href) => router.replace(href),
50
+ }),
41
51
  });
42
52
  ```
43
53
 
44
- `mount()` owns the container, chrome (navbar and footer), page swapping, and the host-routing contract (`coras:navigate` and `coras:state-change`). It returns an app handle with `ready`, `state`, `update()`, `navigate()`, `prefetch()`, and `unmount()`.
54
+ `mount()` owns the container, chrome (navbar and footer), page swapping, and the host-routing contract (`coras:navigate`, `coras:state-change` and the `hrefFor` option that renders the embed's navigation as real links). `createCorasRouting` returns those three options from one URL helper; the strategy above is the shape the Coras sites use, and the SDK default (`/en-IE/EUR/...`) stays available. It returns an app handle with `ready`, `state`, `update()`, `navigate()`, `prefetch()`, and `unmount()`.
45
55
 
46
56
  Page custom elements are internal. You never import them directly.
47
57
 
@@ -56,10 +66,10 @@ For the full guide and event reference, see the Coras docs at https://docs.coras
56
66
 
57
67
  ## Other entry points
58
68
 
59
- | Entry point | Purpose |
60
- | ------------------------- | ------------------------------------------------------------------------------- |
61
- | `@coras-io/embed/url` | URL and state helpers: `parseCorasUrl`, `buildCorasUrl`, `createCorasUrlState`. |
62
- | `@coras-io/embed/errors` | Typed error classes for host integration code. |
63
- | `@coras-io/embed/helpers` | Locale and currency helpers: `getLocale`, `getCurrency`. |
69
+ | Entry point | Purpose |
70
+ | ------------------------- | ----------------------------------------------------------------------------------------------------- |
71
+ | `@coras-io/embed/url` | URL and state helpers: `parseCorasUrl`, `buildCorasUrl`, `createCorasUrlState`, `createCorasRouting`. |
72
+ | `@coras-io/embed/errors` | Typed error classes for host integration code. |
73
+ | `@coras-io/embed/helpers` | Locale and currency helpers: `getLocale`, `getCurrency`. |
64
74
 
65
75
  Public TypeScript types come from the package root alongside `mount()`.
@@ -35,9 +35,9 @@ export const AttractionCardMixin = (superClass) => {
35
35
  this.timezone = "";
36
36
  this.locale = "en-GB";
37
37
  /**
38
- * The attraction page's URL. Set, the title becomes a link crawlers follow;
39
- * a plain click on it still reaches the card's click listener, which
40
- * navigates in the app.
38
+ * The attraction page's URL. Set, the title becomes a link crawlers follow
39
+ * whose hit area covers the whole card; a plain click anywhere on the card
40
+ * still reaches the card's click listener, which navigates in the app.
41
41
  */
42
42
  this.href = "";
43
43
  }
@@ -44,6 +44,7 @@ export default css `
44
44
  }
45
45
 
46
46
  .wrapper {
47
+ position: relative;
47
48
  container-type: inline-size;
48
49
  height: 100%;
49
50
  width: 100%;
@@ -68,6 +69,13 @@ export default css `
68
69
  text-overflow: ellipsis;
69
70
  }
70
71
 
72
+ /* The link's hit area is the whole card; the text stays the only link. */
73
+ a.title::after {
74
+ content: "";
75
+ position: absolute;
76
+ inset: 0;
77
+ }
78
+
71
79
  .date {
72
80
  font-size: var(--attraction-card-details-font-size);
73
81
  line-height: var(--attraction-card-details-line-height);
@@ -18,11 +18,17 @@ export declare class CorasButton extends LitElement {
18
18
  clickable: boolean;
19
19
  error: boolean;
20
20
  loading: boolean;
21
+ /**
22
+ * Renders the button as a link to this URL, with the button's look. A
23
+ * disabled or loading button stays a button, since a link cannot be disabled.
24
+ */
25
+ href: string;
21
26
  constructor();
22
27
  connectedCallback(): void;
23
28
  disconnectedCallback(): void;
24
29
  click(): void;
25
30
  private handleHostClick;
26
31
  private computeClasses;
32
+ private renderContent;
27
33
  render(): import("lit").TemplateResult<1>;
28
34
  }
@@ -27,6 +27,11 @@ export class CorasButton extends LitElement {
27
27
  this.clickable = true;
28
28
  this.error = false;
29
29
  this.loading = false;
30
+ /**
31
+ * Renders the button as a link to this URL, with the button's look. A
32
+ * disabled or loading button stays a button, since a link cannot be disabled.
33
+ */
34
+ this.href = "";
30
35
  this.internals = this.attachInternals();
31
36
  }
32
37
  connectedCallback() {
@@ -90,26 +95,41 @@ export class CorasButton extends LitElement {
90
95
  loading: this.loading,
91
96
  };
92
97
  }
98
+ renderContent() {
99
+ return when(this.loading, () => html `<coras-loading-spinner size="small"></coras-loading-spinner>`, () => html `
100
+ <slot name="prefix" part="prefix"></slot>
101
+ <slot part="label"></slot>
102
+ <slot name="suffix" part="suffix"></slot>
103
+ `);
104
+ }
93
105
  render() {
106
+ const inactive = this.disabled || this.loading;
107
+ if (this.href && !inactive) {
108
+ return html `
109
+ <a
110
+ part="base"
111
+ href=${this.href}
112
+ class="${classMap(this.computeClasses())}"
113
+ >
114
+ ${this.renderContent()}
115
+ </a>
116
+ `;
117
+ }
94
118
  return html `
95
119
  <button
96
120
  part="base"
97
121
  type="${this.type}"
98
- ?disabled="${this.disabled || this.loading}"
99
- aria-disabled="${this.disabled || this.loading ? "true" : "false"}"
122
+ ?disabled="${inactive}"
123
+ aria-disabled="${inactive ? "true" : "false"}"
100
124
  class="${classMap(this.computeClasses())}"
101
125
  >
102
- ${when(this.loading, () => html `<coras-loading-spinner size="small"></coras-loading-spinner>`, () => html `
103
- <slot name="prefix" part="prefix"></slot>
104
- <slot part="label"></slot>
105
- <slot name="suffix" part="suffix"></slot>
106
- `)}
126
+ ${this.renderContent()}
107
127
  </button>
108
128
  `;
109
129
  }
110
130
  }
111
131
  __decorate([
112
- query("button")
132
+ query("button, a")
113
133
  ], CorasButton.prototype, "button", void 0);
114
134
  __decorate([
115
135
  property({ type: String })
@@ -147,3 +167,6 @@ __decorate([
147
167
  __decorate([
148
168
  property({ type: Boolean })
149
169
  ], CorasButton.prototype, "loading", void 0);
170
+ __decorate([
171
+ property({ type: String })
172
+ ], CorasButton.prototype, "href", void 0);
@@ -105,7 +105,14 @@ export default css `
105
105
  pointer-events: none;
106
106
  }
107
107
 
108
- button {
108
+ /* Outranks the shared :host a default, so a linked button keeps the button's look. */
109
+ :host a {
110
+ font-weight: var(--button-font-weight);
111
+ text-decoration: none;
112
+ }
113
+
114
+ button,
115
+ a {
109
116
  align-items: center;
110
117
  background-color: transparent;
111
118
  border-radius: var(--button-border-radius);
@@ -13,24 +13,8 @@ import { getBookingSession } from "../../core/api/middlewares/booking-session/bo
13
13
  import { distributorIdContext, localeContext } from "../properties.context.js";
14
14
  import { clientContext } from "../client.context.js";
15
15
  import { apiGet, apiDelete } from "../../core/api/queries.js";
16
+ import { findMountRoot } from "../../core/utils/mount-root.js";
16
17
  import styles from "./basket.styles.js";
17
- // Walk up (crossing shadow boundaries) to the mount root the SDK marks with
18
- // `data-coras-root`. Null when rendered outside a mount (e.g. Storybook).
19
- function findMountRoot(start) {
20
- let node = start;
21
- while (node) {
22
- if (node instanceof HTMLElement && node.hasAttribute("data-coras-root")) {
23
- return node;
24
- }
25
- if (node.parentNode) {
26
- node = node.parentNode;
27
- continue;
28
- }
29
- const root = node.getRootNode();
30
- node = root instanceof ShadowRoot ? root.host : null;
31
- }
32
- return null;
33
- }
34
18
  export class CorasBasketProvider extends LitElement {
35
19
  static { this.styles = styles; }
36
20
  constructor() {
@@ -1,6 +1,5 @@
1
1
  import type { ReactiveController, ReactiveControllerHost } from "lit";
2
2
  export type ColorScheme = "light" | "dark";
3
- export declare function resolveColorScheme(element: Element): ColorScheme;
4
3
  export declare class ColorSchemeController implements ReactiveController {
5
4
  scheme: ColorScheme;
6
5
  private readonly host;
@@ -1,11 +1,9 @@
1
- function schemeRoot(el) {
2
- return el.closest("[data-coras-root]") ?? el.ownerDocument.documentElement;
3
- }
1
+ import { findMountRoot } from "./utils/mount-root.js";
4
2
  function prefersDark() {
5
3
  return (typeof matchMedia === "function" &&
6
4
  matchMedia("(prefers-color-scheme: dark)").matches);
7
5
  }
8
- export function resolveColorScheme(element) {
6
+ function resolveColorScheme(element) {
9
7
  const scheme = getComputedStyle(element).colorScheme.toLowerCase();
10
8
  const hasLight = scheme.includes("light");
11
9
  const hasDark = scheme.includes("dark");
@@ -28,9 +26,9 @@ export class ColorSchemeController {
28
26
  this.media.addEventListener("change", this.onChange);
29
27
  }
30
28
  this.observer = new MutationObserver(this.onChange);
31
- this.observer.observe(schemeRoot(this.host), {
29
+ this.observer.observe(findMountRoot(this.host) ?? this.host.ownerDocument.documentElement, {
32
30
  attributes: true,
33
- attributeFilter: ["style", "class", "data-coras-color-scheme"],
31
+ attributeFilter: ["style", "class"],
34
32
  });
35
33
  this.scheme = resolveColorScheme(this.host);
36
34
  }
@@ -0,0 +1 @@
1
+ export declare function findMountRoot(start: Node): HTMLElement | null;
@@ -0,0 +1,15 @@
1
+ export function findMountRoot(start) {
2
+ let node = start;
3
+ while (node) {
4
+ if (node instanceof HTMLElement && node.hasAttribute("data-coras-root")) {
5
+ return node;
6
+ }
7
+ if (node.parentNode) {
8
+ node = node.parentNode;
9
+ continue;
10
+ }
11
+ const root = node.getRootNode();
12
+ node = root instanceof ShadowRoot ? root.host : null;
13
+ }
14
+ return null;
15
+ }
@@ -13,6 +13,9 @@ const SENSITIVE_PATTERNS = [
13
13
  /client_secret["':=\s]+[a-z0-9_-]+/gi,
14
14
  // Bearer / access tokens.
15
15
  /\bBearer\s+[a-z0-9._-]+/gi,
16
+ // E.164 phone numbers. The leading "+" keeps ids and timestamps intact; see
17
+ // docs/SECURITY.md.
18
+ /\+\d(?:[\s().-]*\d){7,14}/g,
16
19
  ];
17
20
  // Card-like number runs (13-19 digits, optionally space/dash separated). A
18
21
  // millisecond timestamp is also 13 digits, so a run is only masked when it
@@ -47,6 +50,8 @@ export function redactValue(value) {
47
50
  return redactString(value);
48
51
  if (Array.isArray(value))
49
52
  return value.map(redactValue);
53
+ if (value instanceof Date)
54
+ return value;
50
55
  if (value && typeof value === "object") {
51
56
  const out = {};
52
57
  for (const [key, item] of Object.entries(value)) {
package/dist/errors.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { APIError } from "./core/api/api-error.js";
2
2
  export { setApiErrorReporter } from "./core/api/middlewares/error-handler/error-handler.js";
3
- // Recursive value redaction (emails, keys, tokens, card numbers) for callers
4
- // that forward an error body to logs or error tracking.
3
+ // Recursive value redaction (emails, phone numbers, keys, tokens, card
4
+ // numbers) for callers that forward an error body to logs or error tracking.
5
5
  export { redactValue } from "./sdk/redaction.js";
@@ -39,7 +39,7 @@ export interface CoinbaseMixinInterface {
39
39
  getUser(): Promise<CoinbaseSession | undefined>;
40
40
  getTokenBalance(address: `0x${string}`): Promise<bigint | null>;
41
41
  formatTokenBalance(balance: bigint): string;
42
- transferTokens(amount: string): Promise<TransferResult>;
42
+ transferTokens(amountWei: bigint): Promise<TransferResult>;
43
43
  coinbaseSession: CoinbaseSession | undefined;
44
44
  cdpProjectId: string;
45
45
  cryptoRpc?: string;
@@ -47,7 +47,7 @@ export interface CoinbaseMixinInterface {
47
47
  tokenContractAddress: `0x${string}`;
48
48
  recipientAddress: `0x${string}`;
49
49
  isTransferPending: boolean;
50
- pendingTransferAmount: string;
50
+ pendingTransferAmountWei: bigint;
51
51
  isMfaEnrolled: boolean;
52
52
  mfaEnrollmentCodeSent: boolean;
53
53
  mfaEnrollmentError: string;
@@ -61,6 +61,16 @@ export interface CoinbaseMixinInterface {
61
61
  resetMfaVerificationState(): void;
62
62
  getCoinbaseAccessToken(): Promise<string | null>;
63
63
  }
64
+ /**
65
+ * Token decimals for FIDA (standard ERC-20 is 18)
66
+ */
67
+ export declare const TOKEN_DECIMALS = 18;
68
+ /**
69
+ * Sums token amounts in base units so decimal amounts add up exactly.
70
+ * Throws when an amount is not a plain decimal, such as exponent form.
71
+ */
72
+ export declare function sumTokenAmountsInBaseUnits(amounts: ReadonlyArray<number | string>): bigint;
73
+ export declare function hasSufficientBalance(balanceWei: bigint, amountWei: bigint): boolean;
64
74
  export declare const CoinbaseMixin: <TBase extends Constructor<LitElement & {
65
75
  logger: Logger;
66
76
  }>>(Base: TBase) => Constructor<CoinbaseMixinInterface> & TBase;
@@ -52,12 +52,22 @@ const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12
52
52
  /**
53
53
  * Token decimals for FIDA (standard ERC-20 is 18)
54
54
  */
55
- const TOKEN_DECIMALS = 18;
55
+ export const TOKEN_DECIMALS = 18;
56
56
  /**
57
57
  * Maximum transfer amount in whole tokens (safety bound).
58
58
  */
59
59
  const MAX_TRANSFER_AMOUNT = 1_000_000;
60
60
  const MAX_TRANSFER_AMOUNT_WEI = parseUnits(String(MAX_TRANSFER_AMOUNT), TOKEN_DECIMALS);
61
+ /**
62
+ * Sums token amounts in base units so decimal amounts add up exactly.
63
+ * Throws when an amount is not a plain decimal, such as exponent form.
64
+ */
65
+ export function sumTokenAmountsInBaseUnits(amounts) {
66
+ return amounts.reduce((sum, amount) => sum + parseUnits(String(amount), TOKEN_DECIMALS), 0n);
67
+ }
68
+ export function hasSufficientBalance(balanceWei, amountWei) {
69
+ return balanceWei >= amountWei;
70
+ }
61
71
  /**
62
72
  * Maps a sendUserOperation rejection to a code. The SDK's MfaError carries
63
73
  * a `code` and names itself; anything else is opaque and reported as unknown.
@@ -93,7 +103,7 @@ export const CoinbaseMixin = (Base) => {
93
103
  this.walletEmail = "";
94
104
  this.walletEmailError = "";
95
105
  this.isTransferPending = false;
96
- this.pendingTransferAmount = "";
106
+ this.pendingTransferAmountWei = 0n;
97
107
  this.isMfaEnrolled = false;
98
108
  this.mfaEnrollmentCodeSent = false;
99
109
  this.mfaEnrollmentError = "";
@@ -363,7 +373,8 @@ export const CoinbaseMixin = (Base) => {
363
373
  this.logger.error("Failed to initiate MFA enrollment");
364
374
  this.mfaEnrollmentError =
365
375
  "Failed to send MFA verification code. Please try again.";
366
- throw new Error("Failed to send MFA verification code. Please try again.", { cause: error });
376
+ // eslint-disable-next-line preserve-caught-error -- the CDP error can echo the phone number, so it must not reach the host logger (docs/SECURITY.md)
377
+ throw new Error("Failed to send MFA verification code. Please try again.");
367
378
  }
368
379
  }
369
380
  /**
@@ -592,10 +603,10 @@ export const CoinbaseMixin = (Base) => {
592
603
  * The user will be prompted by CDP to confirm the transaction via SMS OTP.
593
604
  * Gas fees are sponsored by the CDP paymaster on Base Sepolia.
594
605
  *
595
- * @param amount - Amount of tokens to transfer (in human-readable format, e.g., "100")
606
+ * @param amountWei - Amount of tokens to transfer in base units
596
607
  * @returns Transfer result with transaction hash or error
597
608
  */
598
- async transferTokens(amount) {
609
+ async transferTokens(amountWei) {
599
610
  // Prevent concurrent transfers (double-click safety)
600
611
  if (this.isTransferPending) {
601
612
  return { success: false, error: "in_progress" };
@@ -614,16 +625,7 @@ export const CoinbaseMixin = (Base) => {
614
625
  catch {
615
626
  return { success: false, error: "invalid_address" };
616
627
  }
617
- // Exact decimal parsing: floats would drift (0.1 + 0.2) and stringify
618
- // tiny values in exponent form, which viem rejects.
619
- let amountInWei;
620
- try {
621
- amountInWei = parseUnits(amount, TOKEN_DECIMALS);
622
- }
623
- catch {
624
- return { success: false, error: "invalid_amount" };
625
- }
626
- if (amountInWei <= 0n || amountInWei > MAX_TRANSFER_AMOUNT_WEI) {
628
+ if (amountWei <= 0n || amountWei > MAX_TRANSFER_AMOUNT_WEI) {
627
629
  return { success: false, error: "invalid_amount" };
628
630
  }
629
631
  // Claimed synchronously, before the first await, so a second click
@@ -634,7 +636,7 @@ export const CoinbaseMixin = (Base) => {
634
636
  const abort = new AbortController();
635
637
  this._transferAbort = abort;
636
638
  this.isTransferPending = true;
637
- this.pendingTransferAmount = amount;
639
+ this.pendingTransferAmountWei = amountWei;
638
640
  try {
639
641
  // Gas sponsorship requires ERC-4337 smart accounts, not plain EOAs
640
642
  let smartAccountAddress = this.coinbaseSession.smartAccountAddress;
@@ -651,10 +653,11 @@ export const CoinbaseMixin = (Base) => {
651
653
  const data = encodeFunctionData({
652
654
  abi: ERC20_ABI,
653
655
  functionName: "transfer",
654
- args: [this.recipientAddress, amountInWei],
656
+ args: [this.recipientAddress, amountWei],
655
657
  });
656
658
  const smartAccountBalance = await this.getTokenBalance(smartAccountAddress);
657
- if (smartAccountBalance === null || smartAccountBalance < amountInWei) {
659
+ if (smartAccountBalance === null ||
660
+ !hasSufficientBalance(smartAccountBalance, amountWei)) {
658
661
  return { success: false, error: "insufficient_balance" };
659
662
  }
660
663
  const userOpResult = await this._cdpCore.sendUserOperation({
@@ -697,7 +700,7 @@ export const CoinbaseMixin = (Base) => {
697
700
  finally {
698
701
  if (attempt === this._transferSequence) {
699
702
  this.isTransferPending = false;
700
- this.pendingTransferAmount = "";
703
+ this.pendingTransferAmountWei = 0n;
701
704
  }
702
705
  if (this._transferAbort === abort) {
703
706
  this._transferAbort = null;
@@ -919,7 +922,7 @@ export const CoinbaseMixin = (Base) => {
919
922
  ], CoinbaseMixinClass.prototype, "isTransferPending", void 0);
920
923
  __decorate([
921
924
  state()
922
- ], CoinbaseMixinClass.prototype, "pendingTransferAmount", void 0);
925
+ ], CoinbaseMixinClass.prototype, "pendingTransferAmountWei", void 0);
923
926
  __decorate([
924
927
  state()
925
928
  ], CoinbaseMixinClass.prototype, "isMfaEnrolled", void 0);
package/dist/sdk/mount.js CHANGED
@@ -8,7 +8,7 @@ import { applyConfig, applyParams, captureConfigDefaults, captureParamDefaults,
8
8
  import { applyColorScheme, applyTheme, clearTheme } from "./theme.js";
9
9
  import { safeUrl, migrateBrandConfig, } from "@coras-io/brand-tokens";
10
10
  import { ensureTokensInjected } from "../styles/tokens.js";
11
- import { redactValue, toPublicErrorDetail } from "./redaction.js";
11
+ import { redactLogger, redactValue, toPublicErrorDetail } from "./redaction.js";
12
12
  import { assertValidPage, CorasValidationError, validateConfig, validateMountOptions, validatePageParams, } from "./validation.js";
13
13
  /**
14
14
  * Rejection reason of `ready` when `unmount()` runs before the first render
@@ -57,9 +57,10 @@ export function createMountWith(registry) {
57
57
  const strict = options.strict === true;
58
58
  const preview = options.preview === true;
59
59
  const container = options.container;
60
+ const logger = redactLogger(options.logger);
60
61
  // Dev-time diagnostics (see diagnostics.ts): active only when a logger is
61
62
  // wired or `strict` is on, so production stays silent.
62
- const diagnostics = createDiagnostics(options.logger, strict);
63
+ const diagnostics = createDiagnostics(logger, strict);
63
64
  // Mounting a second app into a container that already holds one silently
64
65
  // stacks two mounts - a common cause of "it renders twice" in effects that
65
66
  // forget to unmount.
@@ -129,13 +130,13 @@ export function createMountWith(registry) {
129
130
  });
130
131
  }
131
132
  catch (error) {
132
- options.logger?.error?.(error);
133
+ logger?.error?.(error);
133
134
  }
134
135
  }
135
136
  function reportError(error) {
136
137
  const detail = toPublicErrorDetail(error, currentPage);
137
138
  // Per-mount logging only; the SDK never writes unconditional console output.
138
- options.logger?.error?.(error);
139
+ logger?.error?.(error);
139
140
  // Deliver to `onError` via the `coras:error` event only: the callback
140
141
  // bridge routes it to `onError`, so calling `onError` here as well would
141
142
  // fire it twice for one error.
@@ -170,23 +171,24 @@ export function createMountWith(registry) {
170
171
  if (destroyed || generationToken !== generation)
171
172
  return;
172
173
  const element = document.createElement(entry.tagName);
173
- // Capture element defaults before applyConfig writes to them, so a later
174
- // update that clears an optional config value can restore the default.
175
- const configDefaults = captureConfigDefaults(element);
176
- applyConfig(element, currentConfig, configDefaults);
177
174
  // Preview is a mount-time rendering mode, not config or a param, so it is
178
175
  // set directly on the element; pages that honor it read their own property.
179
176
  element.preview = preview;
180
- element.logger = toLogger(options.logger);
177
+ element.logger = toLogger(logger);
181
178
  element.hrefFor = options.hrefFor ?? null;
182
- const paramDefaults = captureParamDefaults(element, entry);
183
- applyParams(element, entry, currentParams, paramDefaults);
184
179
  // Chrome is rebuilt per page rather than moved: the navbar/footer consume
185
180
  // the page's context (locale, dispatch, current page…) and re-parenting a
186
181
  // context consumer across providers leaves those bindings stale.
187
182
  const chrome = await createChrome(currentChrome, themeLogos());
188
183
  if (destroyed || generationToken !== generation)
189
184
  return;
185
+ // After the chrome await, so an update() made while it loads still lands.
186
+ // Capture element defaults before applyConfig writes to them, so a later
187
+ // update that clears an optional config value can restore the default.
188
+ const configDefaults = captureConfigDefaults(element);
189
+ applyConfig(element, currentConfig, configDefaults);
190
+ const paramDefaults = captureParamDefaults(element, entry);
191
+ applyParams(element, entry, currentParams, paramDefaults);
190
192
  for (const chromeElement of chrome) {
191
193
  element.appendChild(chromeElement);
192
194
  }
@@ -234,7 +236,7 @@ export function createMountWith(registry) {
234
236
  emitObservability("coras.page-loaded", { page: targetPage });
235
237
  }
236
238
  const bridge = attachCallbackBridge(root, options, {
237
- onListenerError: (error) => options.logger?.error?.(error),
239
+ onListenerError: (error) => logger?.error?.(error),
238
240
  });
239
241
  function startRender(targetPage, rollback) {
240
242
  const token = ++generation;
@@ -424,8 +426,8 @@ export function createMountWith(registry) {
424
426
  unmount() {
425
427
  if (destroyed)
426
428
  return;
427
- emitObservability("coras.unmounted");
428
429
  destroyed = true;
430
+ emitObservability("coras.unmounted");
429
431
  // Invalidate any in-flight render so late loads are ignored.
430
432
  generation += 1;
431
433
  bridge.dispose();
@@ -1,4 +1,4 @@
1
- import type { CorasPageName, CorasErrorDetail } from "./types.js";
1
+ import type { CorasErrorDetail, CorasLogger, CorasPageName } from "./types.js";
2
2
  export { redactString, redactValue } from "../core/utils/redaction.js";
3
3
  /**
4
4
  * Convert any thrown value into a safe, redacted public error. Validation
@@ -6,3 +6,9 @@ export { redactString, redactValue } from "../core/utils/redaction.js";
6
6
  * collapsed to a generic message so internal/provider details never leak.
7
7
  */
8
8
  export declare function toPublicErrorDetail(error: unknown, page?: CorasPageName): CorasErrorDetail;
9
+ /**
10
+ * Wrap a host logger so every argument is redacted before the host sees it.
11
+ * An `Error` is replaced by a copy with the same prototype, redacted message,
12
+ * stack, and own enumerable fields, and no `cause`.
13
+ */
14
+ export declare function redactLogger(logger: CorasLogger | undefined): CorasLogger | undefined;
@@ -1,4 +1,4 @@
1
- import { redactString } from "../core/utils/redaction.js";
1
+ import { redactString, redactValue } from "../core/utils/redaction.js";
2
2
  import { CorasValidationError } from "./validation.js";
3
3
  export { redactString, redactValue } from "../core/utils/redaction.js";
4
4
  /**
@@ -20,3 +20,34 @@ export function toPublicErrorDetail(error, page) {
20
20
  ...(page ? { page } : {}),
21
21
  };
22
22
  }
23
+ function redactLogArgument(value) {
24
+ if (!(value instanceof Error))
25
+ return redactValue(value);
26
+ const copy = new Error(redactString(value.message));
27
+ Object.setPrototypeOf(copy, Object.getPrototypeOf(value));
28
+ Object.assign(copy, redactValue(value));
29
+ copy.stack =
30
+ value.stack === undefined ? undefined : redactString(value.stack);
31
+ return copy;
32
+ }
33
+ /**
34
+ * Wrap a host logger so every argument is redacted before the host sees it.
35
+ * An `Error` is replaced by a copy with the same prototype, redacted message,
36
+ * stack, and own enumerable fields, and no `cause`.
37
+ */
38
+ export function redactLogger(logger) {
39
+ if (!logger)
40
+ return undefined;
41
+ return {
42
+ ...(logger.warn
43
+ ? {
44
+ warn: (message, data) => logger.warn?.(redactString(message), redactLogArgument(data)),
45
+ }
46
+ : {}),
47
+ ...(logger.error
48
+ ? {
49
+ error: (error, data) => logger.error?.(redactLogArgument(error), redactLogArgument(data)),
50
+ }
51
+ : {}),
52
+ };
53
+ }