@swell/apps-sdk 2.0.0-alpha.4 → 2.0.0-alpha.6
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 +77 -1
- package/dist/component-frame.html +13 -0
- package/dist/components-client.d.cts +31 -0
- package/dist/components-client.d.ts +31 -0
- package/dist/components-client.js +85 -0
- package/dist/components-focus.d.cts +2 -0
- package/dist/components-focus.d.ts +2 -0
- package/dist/components-focus.js +68 -0
- package/dist/components-frame.d.cts +18 -0
- package/dist/components-frame.d.ts +18 -0
- package/dist/components-frame.js +226 -0
- package/dist/components-host.d.cts +58 -0
- package/dist/components-host.d.ts +58 -0
- package/dist/components-host.js +294 -0
- package/dist/components-placement.d.cts +18 -0
- package/dist/components-placement.d.ts +18 -0
- package/dist/components-placement.js +131 -0
- package/dist/components-protocol.d.cts +78 -0
- package/dist/components-protocol.d.ts +78 -0
- package/dist/components-protocol.js +20 -0
- package/dist/components-types.d.cts +46 -0
- package/dist/components-types.d.ts +46 -0
- package/dist/components-types.js +1 -0
- package/dist/components.d.cts +6 -0
- package/dist/components.d.ts +6 -0
- package/dist/components.js +2 -0
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/request-context.d.cts +4 -0
- package/dist/request-context.d.ts +4 -0
- package/dist/request-context.js +4 -0
- package/dist/version.d.cts +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +13 -3
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.
|
|
13
|
+
npm install @swell/apps-sdk@next swell-js@^5.9.2
|
|
14
14
|
```
|
|
15
15
|
|
|
16
16
|
Supports Node.js 22.22.2+ and Cloudflare Workers, with no Node compatibility flags
|
|
@@ -35,6 +35,8 @@ const context = await verifySwellContext(request.headers, {
|
|
|
35
35
|
});
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
+
When an app component makes the request, `context.surface` says where it runs: `'admin'`, `'checkout'` or `'storefront'`. Treat `'storefront'` and `'checkout'` calls like public routes; check `context.surface === 'admin'` before doing anything that only a merchant may do.
|
|
39
|
+
|
|
38
40
|
In a server component, pass `await headers()`. Keep the context and clients on the
|
|
39
41
|
server, scoped to the incoming request.
|
|
40
42
|
|
|
@@ -109,6 +111,80 @@ const storeUser = requireStoreUser(context); // { userId, storeId }, or a 401 Sw
|
|
|
109
111
|
const optional = context.storeUser; // null for a visitor; no exception needed.
|
|
110
112
|
```
|
|
111
113
|
|
|
114
|
+
## Components
|
|
115
|
+
|
|
116
|
+
App components are small UI bundles from an app's `components/` folder. Swell renders each one in an isolated iframe on the app installation's origin, so app code never runs in the host page. `@swell/apps-sdk/components` is browser code and is only bundled when you import it.
|
|
117
|
+
|
|
118
|
+
### Writing a component
|
|
119
|
+
|
|
120
|
+
Components are Preact components. Import only the props type from the SDK:
|
|
121
|
+
|
|
122
|
+
```tsx
|
|
123
|
+
import type { ComponentProps } from '@swell/apps-sdk/components';
|
|
124
|
+
|
|
125
|
+
export const config = { description: 'Brand color picker' };
|
|
126
|
+
|
|
127
|
+
export default function ColorPicker({ value, setValue, readonly }: ComponentProps<string>) {
|
|
128
|
+
return <input type="color" value={value} disabled={readonly} onInput={(e) => setValue(e.currentTarget.value)} />;
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
| Prop | Description |
|
|
133
|
+
| --- | --- |
|
|
134
|
+
| `value`, `setValue(value)` | The bound value, when the place provides one (for example a content field). `setValue` re-renders the component with the new value (in a microtask, before the next event) and sends it to the host; the host sends a value back only when it changes elsewhere or when the host rejects the one you set |
|
|
135
|
+
| `context` | Data of the place: for a content field `{ record, field }` |
|
|
136
|
+
| `params` | Configuration from the place that uses the component |
|
|
137
|
+
| `settings` | The app's public settings |
|
|
138
|
+
| `locale`, `readonly` | Display locale and read-only state |
|
|
139
|
+
| `setValidity(error)` | Report a validation error, or `null` when valid |
|
|
140
|
+
| `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` |
|
|
141
|
+
| `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` |
|
|
142
|
+
|
|
143
|
+
### Rendering components
|
|
144
|
+
|
|
145
|
+
Hosts render installed apps' components with `createComponents`:
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
import { createComponents } from '@swell/apps-sdk/components';
|
|
149
|
+
|
|
150
|
+
const components = createComponents({ storeId: 'my-store', publicKey: 'pk_...' });
|
|
151
|
+
|
|
152
|
+
const badge = components.mount('#badge', {
|
|
153
|
+
app: 'my_app',
|
|
154
|
+
component: 'ProductBadge',
|
|
155
|
+
context: { product },
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
badge.on('change', (value) => { /* … */ });
|
|
159
|
+
badge.on('error', (error) => { /* show that the component is unavailable */ });
|
|
160
|
+
badge.update({ context: { product: nextProduct } });
|
|
161
|
+
|
|
162
|
+
await badge.ready;
|
|
163
|
+
const result = await badge.emit('submit', data);
|
|
164
|
+
badge.unmount();
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
`mount` returns the handle right away and loads the app's component list in the background. It throws only when the target element does not exist.
|
|
168
|
+
|
|
169
|
+
| Handle | Description |
|
|
170
|
+
| --- | --- |
|
|
171
|
+
| `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 |
|
|
172
|
+
| `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 |
|
|
173
|
+
| `update(input)` | Re-render with new `value`, `context`, `params`, `readonly` or `locale`. Updates made before the component list loads are kept |
|
|
174
|
+
| `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 |
|
|
175
|
+
| `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 |
|
|
176
|
+
| `unmount()` | Removes the frame. Before the component list loads, it cancels the mount; `ready` and pending `emit` calls reject |
|
|
177
|
+
|
|
178
|
+
Props and event data must be structured-cloneable. Props that cannot be cloned fire `error`, and at mount they also reject `ready`; event data that cannot be cloned rejects that `emit` call.
|
|
179
|
+
|
|
180
|
+
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.
|
|
181
|
+
|
|
182
|
+
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.
|
|
183
|
+
|
|
184
|
+
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.
|
|
185
|
+
|
|
186
|
+
Component frames load from the app installation's origin, a subdomain of `swell.store`. If the host page has a Content Security Policy, allow these origins in `frame-src`, for example `frame-src https://*.swell.store`.
|
|
187
|
+
|
|
112
188
|
## API reference
|
|
113
189
|
|
|
114
190
|
### Backend client
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html>
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
</head>
|
|
7
|
+
<body>
|
|
8
|
+
<script type="module">
|
|
9
|
+
import { startComponentFrame } from "/.swell/sdk/components.js";
|
|
10
|
+
startComponentFrame();
|
|
11
|
+
</script>
|
|
12
|
+
</body>
|
|
13
|
+
</html>
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ComponentInput, ComponentToken } from './components-types.cjs';
|
|
2
|
+
import type { ComponentHandle } from './components-host.cjs';
|
|
3
|
+
export interface ComponentsOptions {
|
|
4
|
+
storeId: string;
|
|
5
|
+
publicKey: string;
|
|
6
|
+
/** Storefront API origin. Defaults to https://<storeId>.swell.store */
|
|
7
|
+
url?: string;
|
|
8
|
+
/**
|
|
9
|
+
* Token source for an app's components. Hosts with their own session, like the Swell admin, pass it.
|
|
10
|
+
* Without it the frame gets no token, and `props.fetch` sends no token header.
|
|
11
|
+
*/
|
|
12
|
+
getToken?: (app: string) => Promise<ComponentToken>;
|
|
13
|
+
}
|
|
14
|
+
export interface MountOptions<TValue = unknown, TContext = Record<string, unknown>> extends ComponentInput<TValue, TContext> {
|
|
15
|
+
/** App id or slug. */
|
|
16
|
+
app: string;
|
|
17
|
+
/** Component name: the file name in the app's components/ folder. */
|
|
18
|
+
component: string;
|
|
19
|
+
/** Accessible title of the frame. Defaults to the component name. */
|
|
20
|
+
title?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface Components {
|
|
23
|
+
/**
|
|
24
|
+
* Renders a component in `target` and returns its handle right away. The app's component list
|
|
25
|
+
* loads in the background: `update` calls made meanwhile are kept, `unmount` cancels, and a failure
|
|
26
|
+
* fires `error` and rejects `handle.ready`. Throws when `target` does not exist.
|
|
27
|
+
*/
|
|
28
|
+
mount<TValue = unknown, TContext = Record<string, unknown>>(target: string | HTMLElement, options: MountOptions<TValue, TContext>): ComponentHandle<TValue>;
|
|
29
|
+
}
|
|
30
|
+
/** Renders installed apps' components. Create one instance per store. */
|
|
31
|
+
export declare function createComponents(options: ComponentsOptions): Components;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ComponentInput, ComponentToken } from './components-types.js';
|
|
2
|
+
import type { ComponentHandle } from './components-host.js';
|
|
3
|
+
export interface ComponentsOptions {
|
|
4
|
+
storeId: string;
|
|
5
|
+
publicKey: string;
|
|
6
|
+
/** Storefront API origin. Defaults to https://<storeId>.swell.store */
|
|
7
|
+
url?: string;
|
|
8
|
+
/**
|
|
9
|
+
* Token source for an app's components. Hosts with their own session, like the Swell admin, pass it.
|
|
10
|
+
* Without it the frame gets no token, and `props.fetch` sends no token header.
|
|
11
|
+
*/
|
|
12
|
+
getToken?: (app: string) => Promise<ComponentToken>;
|
|
13
|
+
}
|
|
14
|
+
export interface MountOptions<TValue = unknown, TContext = Record<string, unknown>> extends ComponentInput<TValue, TContext> {
|
|
15
|
+
/** App id or slug. */
|
|
16
|
+
app: string;
|
|
17
|
+
/** Component name: the file name in the app's components/ folder. */
|
|
18
|
+
component: string;
|
|
19
|
+
/** Accessible title of the frame. Defaults to the component name. */
|
|
20
|
+
title?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface Components {
|
|
23
|
+
/**
|
|
24
|
+
* Renders a component in `target` and returns its handle right away. The app's component list
|
|
25
|
+
* loads in the background: `update` calls made meanwhile are kept, `unmount` cancels, and a failure
|
|
26
|
+
* fires `error` and rejects `handle.ready`. Throws when `target` does not exist.
|
|
27
|
+
*/
|
|
28
|
+
mount<TValue = unknown, TContext = Record<string, unknown>>(target: string | HTMLElement, options: MountOptions<TValue, TContext>): ComponentHandle<TValue>;
|
|
29
|
+
}
|
|
30
|
+
/** Renders installed apps' components. Create one instance per store. */
|
|
31
|
+
export declare function createComponents(options: ComponentsOptions): Components;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { createListeners, deferred, embedComponent, pickInput, toError } from './components-host.js';
|
|
2
|
+
/** Renders installed apps' components. Create one instance per store. */
|
|
3
|
+
export function createComponents(options) {
|
|
4
|
+
if (!options?.storeId || !options.publicKey)
|
|
5
|
+
throw new Error('createComponents requires storeId and publicKey');
|
|
6
|
+
const base = (options.url ?? `https://${options.storeId}.swell.store`).replace(/\/+$/, '');
|
|
7
|
+
const apps = new Map();
|
|
8
|
+
const load = (app) => {
|
|
9
|
+
let request = apps.get(app);
|
|
10
|
+
if (!request) {
|
|
11
|
+
request = fetch(`${base}/api/apps/${encodeURIComponent(app)}/components`, {
|
|
12
|
+
headers: { Authorization: `Basic ${btoa(options.publicKey)}` },
|
|
13
|
+
}).then(response => {
|
|
14
|
+
if (!response.ok)
|
|
15
|
+
throw new Error(`Cannot load components of app "${app}" (${response.status})`);
|
|
16
|
+
return response.json();
|
|
17
|
+
});
|
|
18
|
+
apps.set(app, request);
|
|
19
|
+
request.catch(() => apps.delete(app));
|
|
20
|
+
}
|
|
21
|
+
return request;
|
|
22
|
+
};
|
|
23
|
+
return {
|
|
24
|
+
mount(target, mountOptions) {
|
|
25
|
+
const placeholder = typeof target === 'string' ? globalThis.document?.querySelector(target) : target;
|
|
26
|
+
if (!placeholder)
|
|
27
|
+
throw new Error(`Component container "${String(target)}" not found`);
|
|
28
|
+
const { app, component, title, ...input } = mountOptions;
|
|
29
|
+
const { getToken } = options;
|
|
30
|
+
const { on, notify } = createListeners();
|
|
31
|
+
const { promise: ready, resolve: markReady, reject: failReady } = deferred();
|
|
32
|
+
// Settles once the frame is embedded, so `emit` still works when the frame starts after `ready` failed
|
|
33
|
+
const { promise: embedded, resolve: markEmbedded, reject: failEmbedded } = deferred();
|
|
34
|
+
let inner = null;
|
|
35
|
+
let unmounted = false;
|
|
36
|
+
load(app).then(({ settings, components = [] }) => {
|
|
37
|
+
if (unmounted)
|
|
38
|
+
return;
|
|
39
|
+
const found = components.find(item => item.name === component);
|
|
40
|
+
if (!found)
|
|
41
|
+
throw new Error(`Component "${component}" not found in app "${app}"`);
|
|
42
|
+
// `input` carries the updates made while the metadata loaded
|
|
43
|
+
inner = embedComponent(placeholder, { ...input, src: found.src, settings, title: title ?? component, getToken: getToken && (() => getToken(app)) });
|
|
44
|
+
inner.on('change', value => notify('change', value));
|
|
45
|
+
inner.on('validity', error => notify('validity', error));
|
|
46
|
+
inner.on('error', error => notify('error', error));
|
|
47
|
+
markEmbedded();
|
|
48
|
+
inner.ready.then(markReady, failReady);
|
|
49
|
+
}).catch((error) => {
|
|
50
|
+
if (unmounted)
|
|
51
|
+
return;
|
|
52
|
+
const reported = toError(error);
|
|
53
|
+
failReady(reported);
|
|
54
|
+
failEmbedded(reported);
|
|
55
|
+
notify('error', reported);
|
|
56
|
+
});
|
|
57
|
+
return {
|
|
58
|
+
ready,
|
|
59
|
+
on,
|
|
60
|
+
update(next) {
|
|
61
|
+
if (inner)
|
|
62
|
+
inner.update(next);
|
|
63
|
+
else
|
|
64
|
+
Object.assign(input, pickInput(next));
|
|
65
|
+
},
|
|
66
|
+
async emit(name, data) {
|
|
67
|
+
await embedded;
|
|
68
|
+
return inner.emit(name, data);
|
|
69
|
+
},
|
|
70
|
+
// Before the component list loads there is no frame to focus yet
|
|
71
|
+
focus() {
|
|
72
|
+
inner?.focus();
|
|
73
|
+
},
|
|
74
|
+
unmount() {
|
|
75
|
+
if (unmounted)
|
|
76
|
+
return;
|
|
77
|
+
unmounted = true;
|
|
78
|
+
inner?.unmount();
|
|
79
|
+
failReady(new Error('Component unmounted'));
|
|
80
|
+
failEmbedded(new Error('Component unmounted'));
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
const TABBABLE = 'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), iframe, summary, audio[controls], video[controls], [contenteditable]:not([contenteditable="false"]), [tabindex]';
|
|
2
|
+
function isVisible(element) {
|
|
3
|
+
const view = element.ownerDocument.defaultView;
|
|
4
|
+
const style = view?.getComputedStyle(element);
|
|
5
|
+
return element.getClientRects().length > 0 && style?.visibility !== 'hidden' && style?.visibility !== 'collapse';
|
|
6
|
+
}
|
|
7
|
+
// inert applies through shadow boundaries
|
|
8
|
+
function isInert(element) {
|
|
9
|
+
for (let node = element; node; node = node.parentElement ?? node.getRootNode().host ?? null) {
|
|
10
|
+
if (node.hasAttribute('inert'))
|
|
11
|
+
return true;
|
|
12
|
+
}
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
function isTabbable(element) {
|
|
16
|
+
return element.matches(TABBABLE) && element.tabIndex >= 0 && !isInert(element) && isVisible(element);
|
|
17
|
+
}
|
|
18
|
+
// Tree order, descending into open shadow roots
|
|
19
|
+
function collect(parent, found) {
|
|
20
|
+
for (const child of Array.from(parent.children))
|
|
21
|
+
visit(child, found);
|
|
22
|
+
}
|
|
23
|
+
function visit(element, found) {
|
|
24
|
+
// A host that delegates focus is not a stop itself: Tab goes on to the controls in its shadow root
|
|
25
|
+
if (!element.shadowRoot?.delegatesFocus && isTabbable(element))
|
|
26
|
+
found.push(element);
|
|
27
|
+
if (element.shadowRoot)
|
|
28
|
+
collect(element.shadowRoot, found);
|
|
29
|
+
else if (element.localName === 'slot') {
|
|
30
|
+
// A slot shows its assigned elements, or its own fallback content when nothing is assigned
|
|
31
|
+
const assigned = element.assignedElements?.({ flatten: true }) ?? [];
|
|
32
|
+
if (assigned.length)
|
|
33
|
+
for (const item of assigned)
|
|
34
|
+
visit(item, found);
|
|
35
|
+
else
|
|
36
|
+
collect(element, found);
|
|
37
|
+
}
|
|
38
|
+
else
|
|
39
|
+
collect(element, found);
|
|
40
|
+
}
|
|
41
|
+
// One stop per radio group: the checked radio, else the first
|
|
42
|
+
function onePerRadioGroup(stops) {
|
|
43
|
+
const groups = new Map();
|
|
44
|
+
const members = (radio) => {
|
|
45
|
+
const scope = radio.form ?? radio.getRootNode();
|
|
46
|
+
const names = groups.get(scope) ?? new Map();
|
|
47
|
+
groups.set(scope, names);
|
|
48
|
+
const list = names.get(radio.name) ?? [];
|
|
49
|
+
names.set(radio.name, list);
|
|
50
|
+
return list;
|
|
51
|
+
};
|
|
52
|
+
const isRadio = (element) => element.localName === 'input' && element.type === 'radio' && !!element.name;
|
|
53
|
+
for (const stop of stops)
|
|
54
|
+
if (isRadio(stop))
|
|
55
|
+
members(stop).push(stop);
|
|
56
|
+
return stops.filter((stop) => {
|
|
57
|
+
if (!isRadio(stop))
|
|
58
|
+
return true;
|
|
59
|
+
const group = members(stop);
|
|
60
|
+
return stop === (group.find(radio => radio.checked) ?? group[0]);
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/** The element's first Tab stop: the element itself when it is one (a bare iframe), else its first control. */
|
|
64
|
+
export function firstTabbable(element) {
|
|
65
|
+
const found = [];
|
|
66
|
+
visit(element, found);
|
|
67
|
+
return onePerRadioGroup(found)[0];
|
|
68
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface FrameOptions {
|
|
2
|
+
/**
|
|
3
|
+
* URL of the component bundle: an ES module exporting mount, update and unmount. Relative URLs resolve against the
|
|
4
|
+
* frame page. Without it the frame asks the platform: `<page path>.json` answers `{ bundleUrl }` for the build the
|
|
5
|
+
* installation runs, as the platform's shell page (`component-frame.html`) expects.
|
|
6
|
+
*/
|
|
7
|
+
bundleUrl?: string;
|
|
8
|
+
/** Render target. Defaults to #root, created when missing. */
|
|
9
|
+
root?: HTMLElement;
|
|
10
|
+
/** @internal Test seam: the frame window. */
|
|
11
|
+
window?: Window & typeof globalThis;
|
|
12
|
+
/** @internal Test seam: the host window. Defaults to window.parent. */
|
|
13
|
+
parent?: Pick<Window, 'postMessage'>;
|
|
14
|
+
/** @internal Test seam: loads the bundle. */
|
|
15
|
+
importModule?: (url: string) => Promise<unknown>;
|
|
16
|
+
}
|
|
17
|
+
/** Runs inside the component frame: connects to the host page and renders the component bundle. */
|
|
18
|
+
export declare function startComponentFrame(options?: FrameOptions): void;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface FrameOptions {
|
|
2
|
+
/**
|
|
3
|
+
* URL of the component bundle: an ES module exporting mount, update and unmount. Relative URLs resolve against the
|
|
4
|
+
* frame page. Without it the frame asks the platform: `<page path>.json` answers `{ bundleUrl }` for the build the
|
|
5
|
+
* installation runs, as the platform's shell page (`component-frame.html`) expects.
|
|
6
|
+
*/
|
|
7
|
+
bundleUrl?: string;
|
|
8
|
+
/** Render target. Defaults to #root, created when missing. */
|
|
9
|
+
root?: HTMLElement;
|
|
10
|
+
/** @internal Test seam: the frame window. */
|
|
11
|
+
window?: Window & typeof globalThis;
|
|
12
|
+
/** @internal Test seam: the host window. Defaults to window.parent. */
|
|
13
|
+
parent?: Pick<Window, 'postMessage'>;
|
|
14
|
+
/** @internal Test seam: loads the bundle. */
|
|
15
|
+
importModule?: (url: string) => Promise<unknown>;
|
|
16
|
+
}
|
|
17
|
+
/** Runs inside the component frame: connects to the host page and renders the component bundle. */
|
|
18
|
+
export declare function startComponentFrame(options?: FrameOptions): void;
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { firstTabbable } from './components-focus.js';
|
|
2
|
+
import { TOKEN_HEADER, unwrap, wrap } from './components-protocol.js';
|
|
3
|
+
// #root is a flow root, so its children's margins count in the height reported to the host
|
|
4
|
+
const BASE_STYLE = 'html,body{margin:0;padding:0;background:transparent}#root{display:flow-root}';
|
|
5
|
+
function isModule(value) {
|
|
6
|
+
const module = value;
|
|
7
|
+
return !!module && typeof module.mount === 'function' && typeof module.update === 'function' && typeof module.unmount === 'function';
|
|
8
|
+
}
|
|
9
|
+
const errorMessage = (error) => (error instanceof Error ? error.message : String(error));
|
|
10
|
+
// Only the platform knows which build the installation runs, so it answers next to the shell page
|
|
11
|
+
async function fetchBundleUrl(win) {
|
|
12
|
+
const response = await win.fetch(new URL(`${win.location.pathname}.json`, win.location.href).href, { headers: { Accept: 'application/json' } });
|
|
13
|
+
if (response.status === 404)
|
|
14
|
+
throw new Error('Component not found');
|
|
15
|
+
if (!response.ok)
|
|
16
|
+
throw new Error(`Component metadata failed (${response.status})`);
|
|
17
|
+
const { bundleUrl } = (await response.json());
|
|
18
|
+
if (typeof bundleUrl !== 'string' || !bundleUrl)
|
|
19
|
+
throw new Error('Component metadata has no bundle URL');
|
|
20
|
+
return new URL(bundleUrl, win.location.href).href;
|
|
21
|
+
}
|
|
22
|
+
/** Runs inside the component frame: connects to the host page and renders the component bundle. */
|
|
23
|
+
export function startComponentFrame(options = {}) {
|
|
24
|
+
const win = options.window ?? window;
|
|
25
|
+
const parent = options.parent ?? win.parent;
|
|
26
|
+
const params = new URLSearchParams(win.location.search);
|
|
27
|
+
const parentOrigin = params.get('parent');
|
|
28
|
+
const channel = params.get('channel');
|
|
29
|
+
if (!parentOrigin || !channel || parent === win)
|
|
30
|
+
throw new Error('App component frames must be embedded by a Swell host');
|
|
31
|
+
// Asked right away, so the answer arrives while the host handshake runs; a failure is reported when the bundle loads
|
|
32
|
+
const bundleUrl = options.bundleUrl !== undefined
|
|
33
|
+
? Promise.resolve(new URL(options.bundleUrl, win.location.href).href)
|
|
34
|
+
: fetchBundleUrl(win);
|
|
35
|
+
bundleUrl.catch(() => { });
|
|
36
|
+
const document = win.document;
|
|
37
|
+
const style = document.createElement('style');
|
|
38
|
+
style.textContent = BASE_STYLE;
|
|
39
|
+
document.head.appendChild(style);
|
|
40
|
+
let root = options.root ?? document.getElementById('root');
|
|
41
|
+
if (!root) {
|
|
42
|
+
root = document.createElement('div');
|
|
43
|
+
root.id = 'root';
|
|
44
|
+
document.body.appendChild(root);
|
|
45
|
+
}
|
|
46
|
+
const target = root;
|
|
47
|
+
const importModule = options.importModule ?? ((url) => import(/* webpackIgnore: true */ /* @vite-ignore */ url));
|
|
48
|
+
let props = null;
|
|
49
|
+
let token = null;
|
|
50
|
+
let module = null;
|
|
51
|
+
let mounting = null;
|
|
52
|
+
let overlay = false;
|
|
53
|
+
let lastHeight = -1;
|
|
54
|
+
let scheduled = 0;
|
|
55
|
+
let mayTurnOn = false;
|
|
56
|
+
// The viewport-covering element while overlay is on
|
|
57
|
+
let blocker = null;
|
|
58
|
+
const handlers = new Map();
|
|
59
|
+
const post = (message) => parent.postMessage(wrap(channel, message), parentOrigin);
|
|
60
|
+
const fail = (error) => post({ type: 'error', message: errorMessage(error) });
|
|
61
|
+
// The token only goes to the app origin (functions, /app-api), never to third parties.
|
|
62
|
+
const fetchWithToken = (input, init) => {
|
|
63
|
+
const url = new URL(input instanceof Request ? input.url : String(input), win.location.href);
|
|
64
|
+
if (!token || url.origin !== win.location.origin)
|
|
65
|
+
return win.fetch(input, init);
|
|
66
|
+
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
|
|
67
|
+
headers.set(TOKEN_HEADER, token);
|
|
68
|
+
return win.fetch(input, { ...init, headers });
|
|
69
|
+
};
|
|
70
|
+
// Created once, so the component gets the same functions on every render
|
|
71
|
+
const callbacks = {
|
|
72
|
+
// The component sees its own value before the next event; hosts only send values that change
|
|
73
|
+
// elsewhere. The re-render runs in a microtask, so setValue during a render does not re-enter it
|
|
74
|
+
setValue: (value) => {
|
|
75
|
+
if (props) {
|
|
76
|
+
props = { ...props, value };
|
|
77
|
+
Promise.resolve().then(() => module?.update(target, componentProps())).catch(fail);
|
|
78
|
+
}
|
|
79
|
+
post({ type: 'change', value });
|
|
80
|
+
},
|
|
81
|
+
setValidity: (error) => post({ type: 'validity', error: typeof error === 'string' ? error : null }),
|
|
82
|
+
fetch: fetchWithToken,
|
|
83
|
+
on(event, handler) {
|
|
84
|
+
handlers.set(event, [...(handlers.get(event) ?? []), handler]);
|
|
85
|
+
return () => {
|
|
86
|
+
handlers.set(event, (handlers.get(event) ?? []).filter(item => item !== handler));
|
|
87
|
+
};
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
const componentProps = () => ({ ...props, ...callbacks });
|
|
91
|
+
const reportHeight = () => {
|
|
92
|
+
if (overlay)
|
|
93
|
+
return;
|
|
94
|
+
const height = Math.ceil(target.getBoundingClientRect().height);
|
|
95
|
+
if (height !== lastHeight) {
|
|
96
|
+
lastHeight = height;
|
|
97
|
+
post({ type: 'resize', height });
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
const placeRoot = (rect) => Object.assign(target.style, { position: 'absolute', top: `${rect.top}px`, left: `${rect.left}px`, width: `${rect.width}px` });
|
|
101
|
+
const focusModal = () => blocker && firstTabbable(blocker)?.focus();
|
|
102
|
+
const setOverlay = (on) => {
|
|
103
|
+
if (overlay === on)
|
|
104
|
+
return;
|
|
105
|
+
overlay = on;
|
|
106
|
+
// The component's own controls are under the modal's backdrop: out of the Tab order and the pointer's reach
|
|
107
|
+
if (on)
|
|
108
|
+
target.setAttribute('inert', '');
|
|
109
|
+
else
|
|
110
|
+
target.removeAttribute('inert');
|
|
111
|
+
// The modal takes focus from the component under it, or when nothing has focus, unless it took focus itself
|
|
112
|
+
const active = document.activeElement;
|
|
113
|
+
if (on && (!active || active === document.body || target.contains(active)))
|
|
114
|
+
focusModal();
|
|
115
|
+
document.documentElement.style.overflow = on ? 'hidden' : '';
|
|
116
|
+
post({ type: 'overlay', on });
|
|
117
|
+
if (!on) {
|
|
118
|
+
Object.assign(target.style, { position: '', top: '', left: '', width: '' });
|
|
119
|
+
lastHeight = -1;
|
|
120
|
+
reportHeight();
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
// An SDK opened a modal: a fixed element covering the frame viewport (Stripe 3DS, QR codes, vendor modals).
|
|
124
|
+
// An element without area covers nothing, even while the frame itself is zero high.
|
|
125
|
+
const isBlocking = (element) => {
|
|
126
|
+
if (element === target || element.tagName === 'SCRIPT' || element.tagName === 'STYLE')
|
|
127
|
+
return false;
|
|
128
|
+
const computed = win.getComputedStyle(element);
|
|
129
|
+
if (computed.position !== 'fixed' || computed.display === 'none' || computed.visibility === 'hidden' || computed.opacity === '0')
|
|
130
|
+
return false;
|
|
131
|
+
const box = element.getBoundingClientRect();
|
|
132
|
+
return box.width > 0 && box.height > 0 && box.width >= win.innerWidth * 0.9 && box.height >= win.innerHeight * 0.9;
|
|
133
|
+
};
|
|
134
|
+
// DOM changes can switch overlay on and off. A frame resize can only switch it off: overlay itself
|
|
135
|
+
// resizes the frame, and an element that covers only the small frame would otherwise flip it forever.
|
|
136
|
+
const detectOverlay = (turnOn) => {
|
|
137
|
+
mayTurnOn ||= turnOn;
|
|
138
|
+
win.cancelAnimationFrame(scheduled);
|
|
139
|
+
scheduled = win.requestAnimationFrame(() => {
|
|
140
|
+
blocker = Array.from(document.body.children).find(isBlocking) ?? null;
|
|
141
|
+
if (mayTurnOn || !blocker)
|
|
142
|
+
setOverlay(!!blocker);
|
|
143
|
+
mayTurnOn = false;
|
|
144
|
+
});
|
|
145
|
+
};
|
|
146
|
+
// The frame moves the root itself during overlay; that is no new modal
|
|
147
|
+
new win.MutationObserver((records) => {
|
|
148
|
+
if (records.some(record => record.target !== target || record.type !== 'attributes'))
|
|
149
|
+
detectOverlay(true);
|
|
150
|
+
}).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });
|
|
151
|
+
win.addEventListener('resize', () => detectOverlay(false));
|
|
152
|
+
new win.ResizeObserver(reportHeight).observe(target);
|
|
153
|
+
let loading = null;
|
|
154
|
+
// One import per frame: an init that arrives while the bundle loads waits for the same import
|
|
155
|
+
const loadModule = () => {
|
|
156
|
+
loading ??= bundleUrl.then(importModule).then((loaded) => {
|
|
157
|
+
if (!isModule(loaded))
|
|
158
|
+
throw new Error('Component bundle must export mount, update and unmount');
|
|
159
|
+
return loaded;
|
|
160
|
+
});
|
|
161
|
+
return loading;
|
|
162
|
+
};
|
|
163
|
+
// Mounts with the latest props (updates may arrive while the bundle loads) and reports ready once mount resolves
|
|
164
|
+
async function mount() {
|
|
165
|
+
const loaded = await loadModule();
|
|
166
|
+
const mountedProps = props;
|
|
167
|
+
await loaded.mount(target, componentProps());
|
|
168
|
+
module = loaded;
|
|
169
|
+
if (props !== mountedProps)
|
|
170
|
+
await loaded.update(target, componentProps());
|
|
171
|
+
post({ type: 'ready' });
|
|
172
|
+
reportHeight();
|
|
173
|
+
}
|
|
174
|
+
async function handle(message) {
|
|
175
|
+
switch (message.type) {
|
|
176
|
+
case 'init':
|
|
177
|
+
props = message.props;
|
|
178
|
+
token = message.token;
|
|
179
|
+
if (!mounting) {
|
|
180
|
+
mounting = mount();
|
|
181
|
+
return mounting;
|
|
182
|
+
}
|
|
183
|
+
await mounting;
|
|
184
|
+
await module?.update(target, componentProps());
|
|
185
|
+
return;
|
|
186
|
+
case 'update':
|
|
187
|
+
if (!props)
|
|
188
|
+
return;
|
|
189
|
+
props = { ...props, ...message.props };
|
|
190
|
+
await module?.update(target, componentProps());
|
|
191
|
+
return;
|
|
192
|
+
case 'token':
|
|
193
|
+
token = message.token;
|
|
194
|
+
return;
|
|
195
|
+
case 'event': {
|
|
196
|
+
const [handler] = handlers.get(message.name) ?? [];
|
|
197
|
+
try {
|
|
198
|
+
post({ type: 'result', call: message.call, result: handler ? await handler(message.data) : undefined });
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
post({ type: 'result', call: message.call, error: errorMessage(error) });
|
|
202
|
+
}
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
case 'rect':
|
|
206
|
+
if (overlay)
|
|
207
|
+
placeRoot(message.rect);
|
|
208
|
+
return;
|
|
209
|
+
case 'focus':
|
|
210
|
+
// During overlay the modal takes focus, never the component under its backdrop
|
|
211
|
+
if (overlay)
|
|
212
|
+
focusModal();
|
|
213
|
+
else
|
|
214
|
+
firstTabbable(target)?.focus();
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
win.addEventListener('message', (event) => {
|
|
219
|
+
if (event.source !== parent || event.origin !== parentOrigin)
|
|
220
|
+
return;
|
|
221
|
+
const message = unwrap(event.data, channel);
|
|
222
|
+
if (message)
|
|
223
|
+
handle(message).catch(fail);
|
|
224
|
+
});
|
|
225
|
+
post({ type: 'hello' });
|
|
226
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { ComponentInput, ComponentToken } from './components-types.cjs';
|
|
2
|
+
import type { WireProps } from './components-protocol.cjs';
|
|
3
|
+
/** Controls one mounted component. */
|
|
4
|
+
export interface ComponentHandle<TValue = unknown> {
|
|
5
|
+
/**
|
|
6
|
+
* Resolves when the component has mounted in its frame. Rejects when the component cannot be
|
|
7
|
+
* loaded or started; the `error` event fires as well. `unmount` also rejects it, without an
|
|
8
|
+
* `error` event. A frame `error` is final: a later `ready` from that frame does not revive the
|
|
9
|
+
* handle. A frame that only missed the 10 s start timeout can still start later and then serves `emit`.
|
|
10
|
+
*/
|
|
11
|
+
readonly ready: Promise<void>;
|
|
12
|
+
/**
|
|
13
|
+
* Listens to the component. Returns a function that removes the listener; unknown events are ignored.
|
|
14
|
+
* A listener that throws is caught and logged with `console.error`; the other listeners still run.
|
|
15
|
+
*/
|
|
16
|
+
on(event: 'change', handler: (value: TValue) => void): () => void;
|
|
17
|
+
on(event: 'validity', handler: (error: string | null) => void): () => void;
|
|
18
|
+
on(event: 'error', handler: (error: Error) => void): () => void;
|
|
19
|
+
/** Re-renders the component with new data. */
|
|
20
|
+
update(input: ComponentInput<TValue>): void;
|
|
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.
|
|
24
|
+
*/
|
|
25
|
+
emit<T = unknown>(event: string, data?: unknown): Promise<T>;
|
|
26
|
+
/**
|
|
27
|
+
* Moves keyboard focus to the component's first control, as a form does for its first invalid field.
|
|
28
|
+
* During overlay, to the component's modal. A component without controls keeps focus on its frame.
|
|
29
|
+
*/
|
|
30
|
+
focus(): void;
|
|
31
|
+
unmount(): void;
|
|
32
|
+
}
|
|
33
|
+
export interface EmbedOptions<TValue = unknown, TContext = Record<string, unknown>> extends ComponentInput<TValue, TContext> {
|
|
34
|
+
/** Frame URL from the component metadata. */
|
|
35
|
+
src: string;
|
|
36
|
+
settings?: Record<string, unknown>;
|
|
37
|
+
title?: string;
|
|
38
|
+
getToken?: () => Promise<ComponentToken>;
|
|
39
|
+
}
|
|
40
|
+
type Listener = (value: never) => void;
|
|
41
|
+
type HandleEvent = 'change' | 'validity' | 'error';
|
|
42
|
+
export declare const toError: (error: unknown) => Error;
|
|
43
|
+
/** The props a handle update changes: only the keys the host passed. */
|
|
44
|
+
export declare function pickInput(input: ComponentInput<unknown, unknown>): Partial<WireProps>;
|
|
45
|
+
/** Handle event listeners. Unknown event names subscribe to nothing. */
|
|
46
|
+
export declare function createListeners(): {
|
|
47
|
+
on(event: string, handler: Listener): () => void;
|
|
48
|
+
notify(event: HandleEvent, value: unknown): void;
|
|
49
|
+
};
|
|
50
|
+
/** A promise with its settle functions. Rejections are handled, so an unobserved one is not reported. */
|
|
51
|
+
export declare function deferred(): {
|
|
52
|
+
promise: Promise<void>;
|
|
53
|
+
resolve: () => void;
|
|
54
|
+
reject: (error: Error) => void;
|
|
55
|
+
};
|
|
56
|
+
/** Embeds a component frame in `placeholder`. Internal: hosts use createComponents().mount(). */
|
|
57
|
+
export declare function embedComponent<TValue = unknown, TContext = Record<string, unknown>>(placeholder: HTMLElement, options: EmbedOptions<TValue, TContext>): ComponentHandle<TValue>;
|
|
58
|
+
export {};
|