@swell/apps-sdk 2.0.0-alpha.8 → 2.0.0

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
@@ -10,7 +10,7 @@ applications, use [`swell-js`](https://github.com/swellstores/swell-js).
10
10
  ## Installation
11
11
 
12
12
  ```sh
13
- npm install @swell/apps-sdk@next swell-js@^5.9.2
13
+ npm install @swell/apps-sdk swell-js@^5.9.4
14
14
  ```
15
15
 
16
16
  Supports Node.js 22.22.2+ and Cloudflare Workers, with no Node compatibility flags
@@ -121,6 +121,7 @@ import { verifySwellWebhook } from '@swell/apps-sdk';
121
121
 
122
122
  const webhook = await verifySwellWebhook(request.headers, await request.text(), {
123
123
  appId: 'my_app', // The id in your app's swell.json.
124
+ url: 'https://example.com/hooks/orders', // The address the webhook is set to in Swell.
124
125
  });
125
126
  // webhook.event is the event the body carries.
126
127
  ```
@@ -150,10 +151,11 @@ export default function ColorPicker({ value, setValue, readonly }: ComponentProp
150
151
  | `params` | Configuration from the place that uses the component |
151
152
  | `settings` | The app's public settings |
152
153
  | `locale`, `readonly` | Display locale and read-only state |
154
+ | `theme` | The host's color theme, `'light'` or `'dark'`, re-rendered when it changes. The frame sets it as `data-theme` and `color-scheme` on its root from its start, so CSS can follow it with `:root[data-theme="dark"]` |
153
155
  | `setValidity(error)` | Report a validation error, or `null` when valid |
154
156
  | `fetch` | Like `fetch`, but requests to the app's own origin (app functions, `/app-api`) carry a platform token when the host provides one, so they receive a verified `Swell-Context` with `surface` |
155
157
  | `call(name, data)` | Calls a host action and resolves with its result; payment components get `createIntent` and `getIntent` |
156
- | `on(event, handler)` | Handle a host event. Only the first handler registered for an event runs; its return value, or the error it throws, answers the host's `emit` |
158
+ | `on(event, handler)` | Handle a host event. Returns a function that removes the handler. Every handler of the event runs, in the order registered, each after the previous one settles; the first error thrown answers the host's `emit`, otherwise the last result other than `undefined` does. A handler registered again, as an effect does on a re-render, moves to the end, so keep steps that depend on each other in one handler. One removed while the event runs is skipped, and one registered meanwhile runs from the next event |
157
159
 
158
160
  ### Payment components
159
161
 
@@ -169,7 +171,7 @@ export const config = {
169
171
  };
170
172
 
171
173
  export default function Card({ call, on, context }: ComponentProps<never, PaymentContext>) {
172
- // Register in an effect: the frame runs only the first handler registered for an event, and `on` returns the unsubscribe
174
+ // Register in an effect, whose cleanup (the function `on` returns) removes the handler of the previous render
173
175
  useEffect(() => on('submit', async (): Promise<PaymentSubmitResult> => {
174
176
  const intent = await call<{ id: string }>('createIntent', { amount: context.cart.capture_total });
175
177
  return { billing: { intent } };
@@ -215,8 +217,8 @@ badge.unmount();
215
217
  | --- | --- |
216
218
  | `ready` | Resolves when the component has mounted in its frame. Rejects when the app or component cannot be loaded, when the frame page does not start within 10 seconds of loading, when the props cannot be sent, or when you unmount first |
217
219
  | `on(event, handler)` | Listen to `change` (new value), `validity` (error or `null`) and `error` (load, start, token and component failures, including the ones that reject `ready`). Returns a function that removes the listener; other event names are ignored |
218
- | `update(input)` | Re-render with new `value`, `context`, `params`, `readonly` or `locale`. Updates made before the component list loads are kept |
219
- | `emit(event, data)` | Waits for `ready`, then resolves with the result of the component's first `on` handler for the event, or rejects with its error |
220
+ | `update(input)` | Re-render with new `value`, `context`, `params`, `readonly`, `locale` or `theme`. Updates made before the component list loads are kept |
221
+ | `emit(event, data)` | Waits for `ready`, then resolves with the last result other than `undefined` of the component's `on` handlers for the event, or rejects with the first error one throws |
220
222
  | `focus()` | Moves keyboard focus to the component's first control, for example when your form focuses its first invalid field. During overlay, to the component's modal |
221
223
  | `unmount()` | Removes the frame. Before the component list loads, it cancels the mount; `ready` and pending `emit` calls reject |
222
224
 
@@ -226,7 +228,7 @@ Props and event data must be structured-cloneable. Props that cannot be cloned f
226
228
 
227
229
  Hosts that have their own session, like the Swell admin, pass `getToken: (app) => Promise<{ token, expires }>`. The token is refreshed a minute before it expires; if a refresh fails, the component keeps the current token and the host retries. Without `getToken` the frame gets no token, and `props.fetch` sends requests without a token header.
228
230
 
229
- The frame is an iframe inside the target element, so it behaves like any element of your page: it takes part in the layout, your popovers, sticky bars and dialogs stack over it, scrolling containers clip it, and Tab and Shift+Tab move into it and on to the neighbouring elements. Tab skips a component whose frame has not started yet, failed to start or reported an error before it rendered. The target's height follows the component's content. Do not move the target in the DOM while the component is mounted: browsers reload a moved iframe, so the component would start again with the current props.
231
+ The frame is an iframe inside the target element, so it behaves like any element of your page: it takes part in the layout, your popovers, sticky bars and dialogs stack over it, scrolling containers clip it, and Tab and Shift+Tab move into it and on to the neighbouring elements. Tab skips a component whose frame has not started yet, failed to start or reported an error before it rendered. The target's height follows the component's content from the frame's first report on, and is then at least 1px so that a modal opened from an empty component can still cover the viewport. Do not move the target in the DOM while the component is mounted: browsers reload a moved iframe, so the component would start again with the current props.
230
232
 
231
233
  When a component opens a modal (a payment SDK's 3D Secure challenge, a QR code), its frame covers the viewport until the modal closes. The frame enters the browser's top layer (the Popover API), so z-index, `transform`, `opacity` and `overflow` on the target's ancestors cannot confine it; in browsers without the Popover API it is a fixed box with the highest z-index, which a transformed or filtered ancestor still confines. Meanwhile the rest of your page is `inert` and does not scroll, and keyboard focus moves into the modal.
232
234
 
@@ -313,6 +315,10 @@ rotation during GET requests. A supplied writer may throw or skip a write; after
313
315
  its reader must still report the actual state. Writer return values are ignored.
314
316
  Persist cookies in writable route handlers or actions.
315
317
 
318
+ Let the reader return every Swell cookie, `swell-visitor` included: swell-js sends it
319
+ as `X-Visitor`, so a cart created on the server keeps its ad attribution. Record consent
320
+ with `swell.consent.set()` from the browser's swell-js; on the server it rejects.
321
+
316
322
  For API response caching, replace `storefront.request` before first use. The SDK
317
323
  leaves response caching to your application.
318
324
 
@@ -344,7 +350,7 @@ require an HTTP request or a store user.
344
350
 
345
351
  ### Webhook options
346
352
 
347
- `verifySwellWebhook(headers, body, { env?, appId?, storeId? })` returns the webhook or
353
+ `verifySwellWebhook(headers, body, { url, env?, appId?, storeId? })` returns the webhook or
348
354
  throws if verification fails. Pass `appId`, `storeId` or both from trusted configuration:
349
355
  `appId` accepts only webhooks of apps with that id, and `storeId` only the webhooks of
350
356
  that store. Without either it throws, since any Swell store can send a signed webhook to
@@ -352,6 +358,15 @@ any address. An app id is unique to its developer and store, so another develope
352
358
  private app can have yours: check `storeId` against the stores your app is installed in
353
359
  before acting for one.
354
360
 
361
+ `url` is the address the webhook is set to in Swell: a string, a `URL`, or an object
362
+ with its `href`, such as Next's `request.nextUrl`. The signature
363
+ names the endpoint Swell sent the request to, so a request that one endpoint of a store
364
+ received and sent on to another is refused there. Pass the address from your
365
+ configuration. The request URL serves only where the platform routes requests to your
366
+ endpoint strictly by its host; never build it from the `Host` or `X-Forwarded-*` headers,
367
+ which the sender sets. The same address written another way, with an upper-case host, a
368
+ default port or a fragment, matches; its path and query must be the same.
369
+
355
370
  It reads the same configuration as the request context. `SWELL_VERIFY_HEADERS=false`
356
371
  also turns off webhook verification, so while it is set anyone can send a webhook your
357
372
  endpoint accepts.
@@ -44,6 +44,20 @@ export function startComponentFrame(options = {}) {
44
44
  document.body.appendChild(root);
45
45
  }
46
46
  const target = root;
47
+ // The frame shows the theme from its start: the host puts it in the frame's URL, which keeps the current one
48
+ // for a reload
49
+ let rootTheme;
50
+ const showTheme = (theme) => {
51
+ if (theme === rootTheme)
52
+ return;
53
+ rootTheme = theme;
54
+ document.documentElement.dataset.theme = theme;
55
+ document.documentElement.style.colorScheme = theme;
56
+ const url = new URL(win.location.href);
57
+ url.searchParams.set('theme', theme);
58
+ win.history.replaceState(win.history.state, '', url.href);
59
+ };
60
+ showTheme(params.get('theme') === 'dark' ? 'dark' : 'light');
47
61
  const importModule = options.importModule ?? ((url) => import(/* webpackIgnore: true */ /* @vite-ignore */ url));
48
62
  let props = null;
49
63
  let token = null;
@@ -101,10 +115,19 @@ export function startComponentFrame(options = {}) {
101
115
  },
102
116
  };
103
117
  const componentProps = () => ({ ...props, ...callbacks });
118
+ // A host before themes sends none: its pages are light
119
+ const applyTheme = () => {
120
+ if (!props)
121
+ return;
122
+ props = { ...props, theme: props.theme === 'dark' ? 'dark' : 'light' };
123
+ showTheme(props.theme);
124
+ };
125
+ // At least 1px, so a modal opened from an empty component has an area: in a frame without height a modal has
126
+ // none either, and overlay could not tell it from an empty fixed container
104
127
  const reportHeight = () => {
105
128
  if (overlay)
106
129
  return;
107
- const height = Math.ceil(target.getBoundingClientRect().height);
130
+ const height = Math.max(1, Math.ceil(target.getBoundingClientRect().height));
108
131
  if (height !== lastHeight) {
109
132
  lastHeight = height;
110
133
  post({ type: 'resize', height });
@@ -189,6 +212,7 @@ export function startComponentFrame(options = {}) {
189
212
  case 'init':
190
213
  actions = Array.isArray(message.actions) ? message.actions.filter(name => typeof name === 'string') : [];
191
214
  props = message.props;
215
+ applyTheme();
192
216
  token = message.token;
193
217
  if (!mounting) {
194
218
  mounting = mount();
@@ -212,15 +236,25 @@ export function startComponentFrame(options = {}) {
212
236
  if (!props)
213
237
  return;
214
238
  props = { ...props, ...message.props };
239
+ applyTheme();
215
240
  await module?.update(target, componentProps());
216
241
  return;
217
242
  case 'token':
218
243
  token = message.token;
219
244
  return;
220
245
  case 'event': {
221
- const [handler] = handlers.get(message.name) ?? [];
246
+ // The handlers registered when the event arrived, in order, each after the previous one settles; one
247
+ // removed meanwhile, as a re-render's effect cleanup does, no longer runs
222
248
  try {
223
- post({ type: 'result', call: message.call, result: handler ? await handler(message.data) : undefined });
249
+ let result;
250
+ for (const handler of handlers.get(message.name) ?? []) {
251
+ if (!handlers.get(message.name)?.includes(handler))
252
+ continue;
253
+ const value = await handler(message.data);
254
+ if (value !== undefined)
255
+ result = value;
256
+ }
257
+ post({ type: 'result', call: message.call, result });
224
258
  }
225
259
  catch (error) {
226
260
  post({ type: 'result', call: message.call, error: errorMessage(error) });
@@ -247,5 +281,5 @@ export function startComponentFrame(options = {}) {
247
281
  if (message)
248
282
  handle(message).catch(fail);
249
283
  });
250
- post({ type: 'hello' });
284
+ post({ type: 'hello', themes: true });
251
285
  }
@@ -19,8 +19,9 @@ export interface ComponentHandle<TValue = unknown> {
19
19
  /** Re-renders the component with new data. */
20
20
  update(input: ComponentInput<TValue>): void;
21
21
  /**
22
- * Sends an event to the component and resolves with its handler's result. Rejects when the frame
23
- * does not start in time, reports an error (final) or is unmounted.
22
+ * Sends an event to the component and resolves with the last result other than `undefined` of its
23
+ * handlers for the event, or rejects with the first error one throws. Also rejects when the frame does
24
+ * not start in time, reports an error (final) or is unmounted.
24
25
  */
25
26
  emit<T = unknown>(event: string, data?: unknown): Promise<T>;
26
27
  /**
@@ -19,8 +19,9 @@ export interface ComponentHandle<TValue = unknown> {
19
19
  /** Re-renders the component with new data. */
20
20
  update(input: ComponentInput<TValue>): void;
21
21
  /**
22
- * Sends an event to the component and resolves with its handler's result. Rejects when the frame
23
- * does not start in time, reports an error (final) or is unmounted.
22
+ * Sends an event to the component and resolves with the last result other than `undefined` of its
23
+ * handlers for the event, or rejects with the first error one throws. Also rejects when the frame does
24
+ * not start in time, reports an error (final) or is unmounted.
24
25
  */
25
26
  emit<T = unknown>(event: string, data?: unknown): Promise<T>;
26
27
  /**
@@ -6,14 +6,16 @@ const RETRY_MS = 10_000;
6
6
  const MAX_RETRY_MS = 5 * 60_000;
7
7
  const MAX_TIMEOUT = 2 ** 31 - 1;
8
8
  const START_MS = 10_000;
9
- const INPUT_KEYS = ['value', 'context', 'params', 'readonly', 'locale'];
9
+ const INPUT_KEYS = ['value', 'context', 'params', 'readonly', 'locale', 'theme'];
10
10
  export const toError = (error) => (error instanceof Error ? error : new Error(String(error)));
11
+ /** The theme a host shows: dark, or light for anything else. */
12
+ const toTheme = (theme) => (theme === 'dark' ? 'dark' : 'light');
11
13
  /** The props a handle update changes: only the keys the host passed. */
12
14
  export function pickInput(input) {
13
15
  const changed = {};
14
16
  for (const key of INPUT_KEYS) {
15
17
  if (key in input)
16
- Object.assign(changed, { [key]: input[key] });
18
+ Object.assign(changed, { [key]: key === 'theme' ? toTheme(input.theme) : input[key] });
17
19
  }
18
20
  return changed;
19
21
  }
@@ -72,7 +74,10 @@ export function embedComponent(placeholder, options) {
72
74
  const props = {
73
75
  value: options.value, context: options.context ?? {}, params: options.params ?? {},
74
76
  settings: options.settings ?? {}, locale: options.locale ?? 'en', readonly: options.readonly ?? false,
77
+ theme: toTheme(options.theme),
75
78
  };
79
+ // The frame shows the theme from its start, before the host's init reaches it
80
+ url.searchParams.set('theme', props.theme);
76
81
  const { on, notify } = createListeners();
77
82
  const pending = new Map();
78
83
  let calls = 0;
@@ -105,6 +110,10 @@ export function embedComponent(placeholder, options) {
105
110
  pending.clear();
106
111
  };
107
112
  const placed = placeFrame(placeholder, url.href, options.title ?? 'App component', rect => send({ type: 'rect', rect }));
113
+ // A frame whose scheme differs from its element's gets an opaque background. A frame runtime that shows the theme
114
+ // sets it on its root and says so in its hello; until then, and for an older one, both keep the normal scheme
115
+ placed.iframe.style.colorScheme = 'normal';
116
+ let showsTheme = false;
108
117
  // A Tab stop only while the frame runs: from its first hello until it fails to start, or reports an error
109
118
  // before it rendered, so Tab skips a frame that shows an error page
110
119
  placed.iframe.tabIndex = -1;
@@ -185,6 +194,8 @@ export function embedComponent(placeholder, options) {
185
194
  switch (message.type) {
186
195
  case 'hello':
187
196
  clearTimeout(startTimer);
197
+ showsTheme = Boolean(message.themes);
198
+ placed.iframe.style.colorScheme = showsTheme ? props.theme : 'normal';
188
199
  if (greeted) {
189
200
  // The frame reloaded: its new runtime starts without overlay and cannot answer earlier events
190
201
  placed.setOverlay(false);
@@ -277,6 +288,8 @@ export function embedComponent(placeholder, options) {
277
288
  update(input) {
278
289
  const changed = pickInput(input);
279
290
  Object.assign(props, changed);
291
+ if (changed.theme && showsTheme)
292
+ placed.iframe.style.colorScheme = changed.theme;
280
293
  send({ type: 'update', props: changed });
281
294
  },
282
295
  async emit(name, data) {
@@ -3,7 +3,7 @@
3
3
  const IN_FLOW = {
4
4
  display: 'block', position: 'static', inset: 'auto', margin: '0', padding: '0', border: '0',
5
5
  width: '100%', height: '100%', 'max-width': 'none', 'max-height': 'none', overflow: 'visible',
6
- background: 'transparent', 'color-scheme': 'normal', 'z-index': 'auto',
6
+ background: 'transparent', 'z-index': 'auto',
7
7
  };
8
8
  // The z-index only matters without the Popover API: the top layer is above every z-index
9
9
  const COVER = { position: 'fixed', inset: '0px', width: '100vw', height: '100vh', 'z-index': '2147483647' };
@@ -20,6 +20,7 @@ export interface WireProps {
20
20
  settings: Record<string, unknown>;
21
21
  locale: string;
22
22
  readonly: boolean;
23
+ theme: 'light' | 'dark';
23
24
  }
24
25
  export type HostMessage = {
25
26
  type: 'init';
@@ -50,6 +51,7 @@ export type HostMessage = {
50
51
  };
51
52
  export type FrameMessage = {
52
53
  type: 'hello';
54
+ themes?: boolean;
53
55
  } | {
54
56
  type: 'ready';
55
57
  } | {
@@ -20,6 +20,7 @@ export interface WireProps {
20
20
  settings: Record<string, unknown>;
21
21
  locale: string;
22
22
  readonly: boolean;
23
+ theme: 'light' | 'dark';
23
24
  }
24
25
  export type HostMessage = {
25
26
  type: 'init';
@@ -50,6 +51,7 @@ export type HostMessage = {
50
51
  };
51
52
  export type FrameMessage = {
52
53
  type: 'hello';
54
+ themes?: boolean;
53
55
  } | {
54
56
  type: 'ready';
55
57
  } | {
@@ -11,12 +11,20 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
11
11
  readonly settings: Readonly<Record<string, unknown>>;
12
12
  readonly locale: string;
13
13
  readonly readonly: boolean;
14
+ /**
15
+ * The host's color theme. The frame also sets it as `data-theme` and `color-scheme` on its root element, so CSS
16
+ * can follow it with `:root[data-theme="dark"]`. `'light'` when the host passes none.
17
+ */
18
+ readonly theme: ComponentTheme;
14
19
  setValidity(error: string | null): void;
15
20
  /** fetch that adds the component token to requests to the frame's own origin. */
16
21
  readonly fetch: typeof fetch;
17
22
  /**
18
- * Handles a host event. Only the first handler registered for an event runs, and its result
19
- * (or thrown error) answers the host's `emit`; later handlers for the same event are not called.
23
+ * Handles a host event. Every handler registered for the event runs, in the order registered, each after the
24
+ * previous one settles. The first error thrown answers the host's `emit` and the later handlers do not run;
25
+ * otherwise `emit` resolves with the last result other than `undefined`. A handler registered again, as an effect
26
+ * does on a re-render, moves to the end, so keep steps that depend on each other in one handler. One removed while
27
+ * the event runs is skipped, and one registered meanwhile runs from the next event.
20
28
  */
21
29
  on(event: string, handler: (data: unknown) => unknown): () => void;
22
30
  /**
@@ -25,6 +33,7 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
25
33
  */
26
34
  call<T = unknown>(name: string, data?: unknown): Promise<T>;
27
35
  }
36
+ export type ComponentTheme = 'light' | 'dark';
28
37
  /** Optional static metadata a component file exports as `config`. */
29
38
  export interface ComponentConfig {
30
39
  readonly description?: string;
@@ -51,6 +60,8 @@ export interface ComponentInput<TValue = unknown, TContext = Record<string, unkn
51
60
  params?: Record<string, unknown>;
52
61
  readonly?: boolean;
53
62
  locale?: string;
63
+ /** The host's color theme, light by default. Update it when the host switches. */
64
+ theme?: ComponentTheme;
54
65
  }
55
66
  /** Short-lived platform token. `expires` is in epoch seconds. */
56
67
  export interface ComponentToken {
@@ -11,12 +11,20 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
11
11
  readonly settings: Readonly<Record<string, unknown>>;
12
12
  readonly locale: string;
13
13
  readonly readonly: boolean;
14
+ /**
15
+ * The host's color theme. The frame also sets it as `data-theme` and `color-scheme` on its root element, so CSS
16
+ * can follow it with `:root[data-theme="dark"]`. `'light'` when the host passes none.
17
+ */
18
+ readonly theme: ComponentTheme;
14
19
  setValidity(error: string | null): void;
15
20
  /** fetch that adds the component token to requests to the frame's own origin. */
16
21
  readonly fetch: typeof fetch;
17
22
  /**
18
- * Handles a host event. Only the first handler registered for an event runs, and its result
19
- * (or thrown error) answers the host's `emit`; later handlers for the same event are not called.
23
+ * Handles a host event. Every handler registered for the event runs, in the order registered, each after the
24
+ * previous one settles. The first error thrown answers the host's `emit` and the later handlers do not run;
25
+ * otherwise `emit` resolves with the last result other than `undefined`. A handler registered again, as an effect
26
+ * does on a re-render, moves to the end, so keep steps that depend on each other in one handler. One removed while
27
+ * the event runs is skipped, and one registered meanwhile runs from the next event.
20
28
  */
21
29
  on(event: string, handler: (data: unknown) => unknown): () => void;
22
30
  /**
@@ -25,6 +33,7 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
25
33
  */
26
34
  call<T = unknown>(name: string, data?: unknown): Promise<T>;
27
35
  }
36
+ export type ComponentTheme = 'light' | 'dark';
28
37
  /** Optional static metadata a component file exports as `config`. */
29
38
  export interface ComponentConfig {
30
39
  readonly description?: string;
@@ -51,6 +60,8 @@ export interface ComponentInput<TValue = unknown, TContext = Record<string, unkn
51
60
  params?: Record<string, unknown>;
52
61
  readonly?: boolean;
53
62
  locale?: string;
63
+ /** The host's color theme, light by default. Update it when the host switches. */
64
+ theme?: ComponentTheme;
54
65
  }
55
66
  /** Short-lived platform token. `expires` is in epoch seconds. */
56
67
  export interface ComponentToken {
@@ -1,4 +1,4 @@
1
- export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentToken, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.cjs';
1
+ export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentTheme, ComponentToken, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.cjs';
2
2
  export { createComponents } from './components-client.cjs';
3
3
  export type { Components, ComponentsOptions, MountOptions, NamedMountOptions, PlaceComponent, TargetMountOptions, TargetHandle } from './components-client.cjs';
4
4
  export type { ComponentHandle } from './components-host.cjs';
@@ -1,4 +1,4 @@
1
- export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentToken, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.js';
1
+ export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentTheme, ComponentToken, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.js';
2
2
  export { createComponents } from './components-client.js';
3
3
  export type { Components, ComponentsOptions, MountOptions, NamedMountOptions, PlaceComponent, TargetMountOptions, TargetHandle } from './components-client.js';
4
4
  export type { ComponentHandle } from './components-host.js';
@@ -1 +1 @@
1
- export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.8";
1
+ export declare const USER_AGENT = "swell-apps-sdk/2.0.0";
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.8";
1
+ export declare const USER_AGENT = "swell-apps-sdk/2.0.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // Replaced with the package version by the build.
2
- export const USER_AGENT = 'swell-apps-sdk/2.0.0-alpha.8';
2
+ export const USER_AGENT = 'swell-apps-sdk/2.0.0';
@@ -7,6 +7,15 @@ export interface VerifySwellWebhookOptions {
7
7
  storeId?: string;
8
8
  /** The id in swell.json of the app the webhook must belong to. Pass this or `storeId`. */
9
9
  appId?: string;
10
+ /**
11
+ * The address the webhook is set to in Swell, from your configuration. Refuses a request Swell signed for another
12
+ * endpoint. The request URL serves only where the platform routes requests to your endpoint strictly by its host;
13
+ * never build it from the Host or X-Forwarded-* headers, which the sender sets. A string, a URL, or an object with
14
+ * the URL's href, such as Next's request.nextUrl.
15
+ */
16
+ url: string | {
17
+ readonly href: string;
18
+ };
10
19
  }
11
20
  /** A webhook request Swell sent, with its event. */
12
21
  export interface SwellWebhook {
@@ -26,4 +35,4 @@ export interface SwellWebhook {
26
35
  * body must be the bytes the request carried, before any parsing. Uses ES256
27
36
  * and the same pinned JWKS endpoint as verifySwellContext.
28
37
  */
29
- export declare function verifySwellWebhook(headers: HeaderReader, body: string | ArrayBuffer | ArrayBufferView, options?: VerifySwellWebhookOptions): Promise<SwellWebhook>;
38
+ export declare function verifySwellWebhook(headers: HeaderReader, body: string | ArrayBuffer | ArrayBufferView, options: VerifySwellWebhookOptions): Promise<SwellWebhook>;
package/dist/webhook.d.ts CHANGED
@@ -7,6 +7,15 @@ export interface VerifySwellWebhookOptions {
7
7
  storeId?: string;
8
8
  /** The id in swell.json of the app the webhook must belong to. Pass this or `storeId`. */
9
9
  appId?: string;
10
+ /**
11
+ * The address the webhook is set to in Swell, from your configuration. Refuses a request Swell signed for another
12
+ * endpoint. The request URL serves only where the platform routes requests to your endpoint strictly by its host;
13
+ * never build it from the Host or X-Forwarded-* headers, which the sender sets. A string, a URL, or an object with
14
+ * the URL's href, such as Next's request.nextUrl.
15
+ */
16
+ url: string | {
17
+ readonly href: string;
18
+ };
10
19
  }
11
20
  /** A webhook request Swell sent, with its event. */
12
21
  export interface SwellWebhook {
@@ -26,4 +35,4 @@ export interface SwellWebhook {
26
35
  * body must be the bytes the request carried, before any parsing. Uses ES256
27
36
  * and the same pinned JWKS endpoint as verifySwellContext.
28
37
  */
29
- export declare function verifySwellWebhook(headers: HeaderReader, body: string | ArrayBuffer | ArrayBufferView, options?: VerifySwellWebhookOptions): Promise<SwellWebhook>;
38
+ export declare function verifySwellWebhook(headers: HeaderReader, body: string | ArrayBuffer | ArrayBufferView, options: VerifySwellWebhookOptions): Promise<SwellWebhook>;
package/dist/webhook.js CHANGED
@@ -20,6 +20,20 @@ function optionalString(value, field) {
20
20
  requireString(value, field);
21
21
  return value;
22
22
  }
23
+ // The same address written either way, such as with an upper-case host, a default port or a fragment, is one endpoint.
24
+ // An object is read by its href: a URL of another realm, or one like Next's request.nextUrl, is not a URL instance
25
+ function endpointOf(value) {
26
+ const href = typeof value === 'string' ? value : value?.href;
27
+ if (typeof href !== 'string')
28
+ return undefined;
29
+ try {
30
+ const { origin, pathname, search } = new URL(href);
31
+ return `${origin}${pathname}${search}`;
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ }
23
37
  async function sha256(body) {
24
38
  const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', body));
25
39
  return btoa(String.fromCharCode(...hash)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
@@ -29,7 +43,9 @@ async function sha256(body) {
29
43
  * body must be the bytes the request carried, before any parsing. Uses ES256
30
44
  * and the same pinned JWKS endpoint as verifySwellContext.
31
45
  */
32
- export async function verifySwellWebhook(headers, body, options = {}) {
46
+ export async function verifySwellWebhook(headers, body, options) {
47
+ // A JavaScript caller can leave out the options, and gets told what they need
48
+ options = options ?? {};
33
49
  const runtime = globalThis;
34
50
  const env = options.env ?? runtime.process?.env ?? {};
35
51
  const verify = env.SWELL_VERIFY_HEADERS !== 'false';
@@ -43,6 +59,12 @@ export async function verifySwellWebhook(headers, body, options = {}) {
43
59
  if (options.appId === undefined && options.storeId === undefined) {
44
60
  throw new Error('verifySwellWebhook needs options.appId or options.storeId');
45
61
  }
62
+ // Any endpoint a store's webhooks go to receives signed requests, and could pass one on to another
63
+ if (options.url === undefined)
64
+ throw new Error('verifySwellWebhook needs options.url, the address the webhook is set to');
65
+ const url = endpointOf(options.url);
66
+ if (url === undefined)
67
+ throw new Error('Invalid url: expected an absolute URL');
46
68
  // A parsed body no longer has the bytes the signature covers
47
69
  if (typeof body !== 'string' && !(body instanceof ArrayBuffer) && !ArrayBuffer.isView(body)) {
48
70
  throw new TypeError('verifySwellWebhook needs the body as the request carried it, a string or bytes');
@@ -90,6 +112,9 @@ export async function verifySwellWebhook(headers, body, options = {}) {
90
112
  if ((options.storeId !== undefined && payload.store_id !== options.storeId) ||
91
113
  (options.appId !== undefined && appId !== options.appId))
92
114
  throw invalidWebhook();
115
+ // Signatures Swell made before it named the endpoint have no aud
116
+ if (payload.aud !== undefined && endpointOf(payload.aud) !== url)
117
+ throw invalidWebhook();
93
118
  if (payload.body_sha256 !== await sha256(bytes))
94
119
  throw invalidWebhook();
95
120
  const event = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swell/apps-sdk",
3
- "version": "2.0.0-alpha.8",
3
+ "version": "2.0.0",
4
4
  "description": "Server SDK for Swell apps.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -22,14 +22,14 @@
22
22
  "verify": "npm test && npm run typecheck && npm run test:package && npm run test:boundaries && npm run test:worker"
23
23
  },
24
24
  "peerDependencies": {
25
- "swell-js": ">=5.9.2"
25
+ "swell-js": ">=5.9.4"
26
26
  },
27
27
  "devDependencies": {
28
28
  "esbuild": "0.24.2",
29
29
  "happy-dom": "20.14.5",
30
30
  "miniflare": "5.20260911.1-alpha",
31
31
  "playwright": "1.63.0",
32
- "swell-js": "5.9.2",
32
+ "swell-js": "5.9.4",
33
33
  "typescript": "5.7.3"
34
34
  },
35
35
  "main": "./dist/index.js",