@swell/apps-sdk 2.1.1 → 2.1.2

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
@@ -46,10 +46,10 @@ import { isStorefrontRequest, verifySwellContext } from '@swell/apps-sdk';
46
46
 
47
47
  const context = await verifySwellContext(request.headers, { appId: 'my_app' });
48
48
  if (!isStorefrontRequest(context)) return new Response(null, { status: 403 });
49
- // context.storeId, context.storefrontId, context.storefrontHost, context.accountId, context.mode
49
+ // context.storeId, context.storefrontId, context.storefrontHost, context.accountId, context.mode, context.clientIp
50
50
  ```
51
51
 
52
- `isStorefrontRequest` is true when `surface` is `'storefront'` and the context names a storefront. It proves the request came through one of the store's storefronts, not who sent it: storefront pages are public, so rate-limit these routes, and check that `accountId` (the logged-in customer, `undefined` for a visitor) owns any private data you return. `storefrontHost` is the address the shopper used, custom domains included; `mode` is `'live'`, `'preview'` or `'editor'`.
52
+ `isStorefrontRequest` is true when `surface` is `'storefront'` and the context names a storefront. It proves the request came through one of the store's storefronts, not who sent it: storefront pages are public, so rate-limit these routes, and check that `accountId` (the logged-in customer, `undefined` for a visitor) owns any private data you return. `storefrontHost` is the address the shopper used, custom domains included; `mode` is `'live'`, `'preview'` or `'editor'`. When `context.hostApp` is set, another installed app (a storefront host such as Wave) made the call on a shopper's behalf, server to server: `storeId` and `installationId` are Swell's, but `storefrontId`, `storefrontHost`, `accountId` and `mode` are that host's assertion, checked by Swell only for consistency (the storefront is the host's, the account exists). Trust `accountId` as far as you trust the host; `clientIp` is unset. `clientIp` is the shopper's IP address as Swell's own rate limits take it: through the app proxy your server only sees Swell's, so key per-shopper rate limits on it. The proxy forwards one credential of your own, `X-App-Authorization` (a signed-in customer's token, say); `Authorization` is Swell's.
53
53
 
54
54
  In a server component, pass `await headers()`. Keep the context and clients on the
55
55
  server, scoped to the incoming request.
@@ -294,6 +294,47 @@ The platform returns every component of the store's active installed apps that d
294
294
 
295
295
  Hosts cannot override the built-in payment actions: `createIntent` and `getIntent` win over `actions` of the same names.
296
296
 
297
+ ### Hosting storefront app blocks
298
+
299
+ A storefront app that lets merchants place installed apps' blocks (widgets an app declares in its `swell.json` `storefront.embeds`) reads the declarations on its server, and starts the block runtimes in the page. `@swell/apps-sdk/blocks` reads the declarations as strictly as the app block standard asks: a declaration that breaks one rule is left out whole, so the page never shows part of an app.
300
+
301
+ ```ts
302
+ import { appFrontendOrigin, blockAllowedOn, blockCspSources, readInstalledBlocks } from '@swell/apps-sdk/blocks';
303
+
304
+ // GET /:clients/:self/apps?expand=app with your installation's key, on your server
305
+ const apps = readInstalledBlocks(installations, {
306
+ origin: (installationId) => appFrontendOrigin(context.adminUrl, context.storeId, installationId),
307
+ onProblem: (message) => console.warn(message), // log each once
308
+ });
309
+
310
+ blockAllowedOn(block, 'product'); // where a merchant may place a block, and where it renders
311
+ const csp = blockCspSources(scriptApps, componentApps); // { scriptSrc, connectSrc, imgSrc, frameSrc }
312
+ ```
313
+
314
+ Each app has its blocks, its script (an https URL on its installation's frontend) with its `integrity`, the third-party `connect` and `img` origins its script uses, and for `component` blocks the `frame` origin they load from. `readAppBlocks` reads one entry whose `script` is already an https URL.
315
+
316
+ Render each placed block as `<div class="swell-app-block" data-app-block="<app>/<block>" data-app-props="<json>">…fallback…</div>`, load each app's script once on pages that hold its `script` blocks, and start the runtimes:
317
+
318
+ ```ts
319
+ import { startBlockRegistry } from '@swell/apps-sdk/blocks';
320
+ import { startComponentBlocks } from '@swell/apps-sdk/components';
321
+
322
+ startBlockRegistry({ apps: ['my_app'], storefront: { storeId, storefrontId, mode: 'live' } });
323
+
324
+ startComponentBlocks({
325
+ storeId,
326
+ publicKey: 'host', // a placeholder: `url` reads the list on your server with your key
327
+ url: `${location.origin}/your-components`,
328
+ getToken: (app) => fetch(`/.swell/component-token?app=${app}`).then((r) => r.json()),
329
+ blocks: { 'my_app/gift_card': { component: 'GiftCardForm', title: 'Gift card' } },
330
+ storefront: { storeId, storefrontId, mode: 'live' },
331
+ });
332
+ ```
333
+
334
+ `startBlockRegistry` makes `window.SwellAppBlocks` an object whose `push` registers an app's blocks (registrations pushed before it starts count too). It mounts each block on every matching element, now and when one is added later (a cart drawer), once per element; it cleans up when the element leaves the page, and cleans up and mounts again when its props change. It ignores apps the page didn't load and a second registration of an app. Each mount gets `{ props, app, block, storefront, proxy }`, `proxy` being the app proxy's path on the page's origin.
335
+
336
+ `startComponentBlocks` mounts each `component` block's App Component in a frame on its app's origin, with the block's props as `params` and `{ storefront, tokens }` as `context` (`tokens`: the element's `--swell-*` theme properties, listed in `BLOCK_TOKENS`). It sets `data-app-frame-ready` on the element once the frame is ready, so your CSS can hide the fallback, and unmounts the frame when the element leaves. Both return a function that stops them, and take `attribute` for a host whose elements name their block in another attribute.
337
+
297
338
  ## API reference
298
339
 
299
340
  ### Backend client
@@ -0,0 +1,181 @@
1
+ export type BlockPage = 'home' | 'product' | 'category' | 'category_list' | 'search' | 'cart' | 'content' | 'blog' | 'blog_post' | 'account' | 'not_found';
2
+ /** The page types a block's `pages` may list. */
3
+ export declare const BLOCK_PAGES: readonly BlockPage[];
4
+ export type BlockPropType = 'text' | 'textarea' | 'url' | 'number' | 'boolean' | 'select';
5
+ /** A prop of a block: a field the host's editor renders, whose value reaches the block. */
6
+ export interface BlockProp {
7
+ id: string;
8
+ type: BlockPropType;
9
+ label: string;
10
+ description?: string;
11
+ default?: string | number | boolean;
12
+ options?: {
13
+ value: string;
14
+ label: string;
15
+ }[];
16
+ min?: number;
17
+ max?: number;
18
+ }
19
+ /** A block an app declares. `component` is set for a block whose render is "component". */
20
+ export interface Block {
21
+ id: string;
22
+ label: string;
23
+ description?: string;
24
+ icon?: string;
25
+ pages?: BlockPage[];
26
+ props?: BlockProp[];
27
+ component?: string;
28
+ }
29
+ /** One app's blocks, as a host uses them. */
30
+ export interface AppBlocks {
31
+ /** The installation's app slug. */
32
+ app: string;
33
+ name: string;
34
+ /** The exact https URL of the app's script; absent for an app of `component` blocks only. */
35
+ script?: string;
36
+ integrity?: string;
37
+ /** Third-party https origins its script calls (connect-src). */
38
+ connect: string[];
39
+ /** Third-party https origins, or "data:", its script loads images from (img-src). */
40
+ img: string[];
41
+ blocks: Block[];
42
+ /** An app with `component` blocks: its installation's frontend origin, where their frames load (frame-src). */
43
+ frame?: string;
44
+ /** ...and its app record id. */
45
+ appId?: string;
46
+ /** Its app record's icon, on Swell's CDN. */
47
+ icon?: string;
48
+ }
49
+ export type ReadResult = {
50
+ ok: true;
51
+ app: AppBlocks;
52
+ } | {
53
+ ok: false;
54
+ problem: string;
55
+ };
56
+ export declare const BLOCK_LIMITS: Readonly<{
57
+ /** Apps a host reads from one store. */
58
+ apps: 10;
59
+ /** Blocks per app (more are left out). */
60
+ blocks: 20;
61
+ /** Props per block. */
62
+ props: 20;
63
+ /** Options per select prop. */
64
+ options: 50;
65
+ /** connect and img origins, each. */
66
+ sources: 10;
67
+ /** Characters of a label or a name. */
68
+ label: 80;
69
+ /** Characters of a description. */
70
+ description: 300;
71
+ /** Characters of a text prop's default. */
72
+ textDefault: 500;
73
+ /** Characters of the script URL. */
74
+ url: 500;
75
+ }>;
76
+ export interface ReadOptions {
77
+ /**
78
+ * The installation origin and app record id of an installed app: its `component` blocks need them (their frames load
79
+ * there). Without them, `component` blocks are left out (onProblem says so) and only `script` blocks stay.
80
+ */
81
+ frame?: {
82
+ origin: string;
83
+ appId: string;
84
+ };
85
+ /** Where the problem is, for messages (default: the app's id). */
86
+ at?: string;
87
+ /** Problems that leave part of the declaration out but keep the rest. */
88
+ onProblem?: (message: string) => void;
89
+ /** Apps already read for this page or store: a second declaration of the same app is refused. */
90
+ seen?: ReadonlySet<string>;
91
+ }
92
+ /**
93
+ * One app's blocks from an entry of the form `{version?, app, name, script?, integrity?, connect?, img?, blocks}`,
94
+ * `script` being the exact https URL to load. A broken rule refuses the whole entry, naming it.
95
+ */
96
+ export declare function readAppBlocks(v: unknown, options?: ReadOptions): ReadResult;
97
+ /**
98
+ * The origin of an installation's frontend, where its block script and component frames load: Swell serves it at
99
+ * `<store>--<installation>--app` on the store's own domain, the host of `adminUrl` (a storefront request's verified
100
+ * context) less its first label. A loopback `adminUrl` (local mocks) gives `swell.test`. null: any other host, or ids
101
+ * of another form.
102
+ */
103
+ export declare function appFrontendOrigin(adminUrl: string, storeId: string, installationId: string): string | null;
104
+ export interface InstalledOptions {
105
+ /** An installation's frontend origin (appFrontendOrigin), or null to leave its app out. */
106
+ origin: (installationId: string) => string | null;
107
+ /** Each problem, as one line (a host logs it once). */
108
+ onProblem?: (message: string) => void;
109
+ }
110
+ /**
111
+ * The blocks of the store's installed apps, from `GET /:clients/:self/apps` with `app` expanded: one entry per
112
+ * installation that is neither uninstalled nor inactive and whose app declares blocks, named by the app's slug (its
113
+ * private id without the leading underscore), its `frontend://` script on that installation's frontend. At most
114
+ * BLOCK_LIMITS.apps; an app whose declaration breaks a rule is left out (onProblem).
115
+ */
116
+ export declare function readInstalledBlocks(raw: unknown, options: InstalledOptions): AppBlocks[];
117
+ /** Whether a block may be placed on (and rendered on) a page of that type: its `pages`, else every type but account. */
118
+ export declare const blockAllowedOn: (block: Pick<Block, "pages">, page: BlockPage) => boolean;
119
+ /** Whether a block renders as a component in a frame (render "component"). */
120
+ export declare const isComponentBlock: (block: Pick<Block, "component">) => boolean;
121
+ /** Whether an app has `script` blocks (its script loads on a page that holds one). */
122
+ export declare const hasScriptBlocks: (app: Pick<AppBlocks, "blocks">) => boolean;
123
+ /**
124
+ * The CSP sources a page adds for its blocks. scripts: the apps whose `script` blocks it holds (or may show, in a cart
125
+ * drawer); frames: those whose `component` blocks it holds. A script URL is a source without its query (CSP sources
126
+ * have none).
127
+ */
128
+ export declare function blockCspSources(scripts: readonly AppBlocks[], frames?: readonly AppBlocks[]): {
129
+ scriptSrc: string[];
130
+ connectSrc: string[];
131
+ imgSrc: string[];
132
+ frameSrc: string[];
133
+ };
134
+ /** What every `script` block's mount gets about the page. */
135
+ export interface BlockStorefront {
136
+ storeId: string;
137
+ storefrontId: string;
138
+ locale?: string;
139
+ currency?: string;
140
+ mode: 'live' | 'preview';
141
+ }
142
+ export interface BlockMountContext {
143
+ props: Record<string, unknown>;
144
+ app: string;
145
+ block: string;
146
+ storefront: BlockStorefront;
147
+ /** The app proxy's base path on this page's origin. */
148
+ proxy: string;
149
+ /** The storefront's own public key, once the platform issues one. Never a key of the host's own installation. */
150
+ publicKey?: string;
151
+ }
152
+ export interface BlockRegistration {
153
+ app: string;
154
+ blocks: Record<string, {
155
+ mount(element: HTMLElement, context: BlockMountContext): void | (() => void);
156
+ }>;
157
+ }
158
+ export interface BlockRegistryOptions {
159
+ /** The apps whose scripts this page loads: a registration of any other app is ignored. */
160
+ apps: readonly string[];
161
+ storefront: BlockStorefront;
162
+ publicKey?: string;
163
+ /** The mount element's id attribute (default `data-app-block`; the props are always in `data-app-props`). */
164
+ attribute?: string;
165
+ /** The document (default: the global one). */
166
+ document?: Document;
167
+ }
168
+ declare global {
169
+ interface Window {
170
+ SwellAppBlocks?: BlockRegistration[] | {
171
+ push(...registrations: BlockRegistration[]): void;
172
+ };
173
+ }
174
+ }
175
+ /**
176
+ * Starts the page's block registry: `window.SwellAppBlocks` becomes an object whose `push` registers an app's blocks
177
+ * (an array an app script pushed to before is registered too). Each registered block mounts on every matching element
178
+ * now and added later, once per element; its cleanup runs when the element leaves the page, and when its props change
179
+ * (the block then mounts again). Returns a function that stops the registry and cleans up every block.
180
+ */
181
+ export declare function startBlockRegistry(options: BlockRegistryOptions): () => void;
@@ -0,0 +1,181 @@
1
+ export type BlockPage = 'home' | 'product' | 'category' | 'category_list' | 'search' | 'cart' | 'content' | 'blog' | 'blog_post' | 'account' | 'not_found';
2
+ /** The page types a block's `pages` may list. */
3
+ export declare const BLOCK_PAGES: readonly BlockPage[];
4
+ export type BlockPropType = 'text' | 'textarea' | 'url' | 'number' | 'boolean' | 'select';
5
+ /** A prop of a block: a field the host's editor renders, whose value reaches the block. */
6
+ export interface BlockProp {
7
+ id: string;
8
+ type: BlockPropType;
9
+ label: string;
10
+ description?: string;
11
+ default?: string | number | boolean;
12
+ options?: {
13
+ value: string;
14
+ label: string;
15
+ }[];
16
+ min?: number;
17
+ max?: number;
18
+ }
19
+ /** A block an app declares. `component` is set for a block whose render is "component". */
20
+ export interface Block {
21
+ id: string;
22
+ label: string;
23
+ description?: string;
24
+ icon?: string;
25
+ pages?: BlockPage[];
26
+ props?: BlockProp[];
27
+ component?: string;
28
+ }
29
+ /** One app's blocks, as a host uses them. */
30
+ export interface AppBlocks {
31
+ /** The installation's app slug. */
32
+ app: string;
33
+ name: string;
34
+ /** The exact https URL of the app's script; absent for an app of `component` blocks only. */
35
+ script?: string;
36
+ integrity?: string;
37
+ /** Third-party https origins its script calls (connect-src). */
38
+ connect: string[];
39
+ /** Third-party https origins, or "data:", its script loads images from (img-src). */
40
+ img: string[];
41
+ blocks: Block[];
42
+ /** An app with `component` blocks: its installation's frontend origin, where their frames load (frame-src). */
43
+ frame?: string;
44
+ /** ...and its app record id. */
45
+ appId?: string;
46
+ /** Its app record's icon, on Swell's CDN. */
47
+ icon?: string;
48
+ }
49
+ export type ReadResult = {
50
+ ok: true;
51
+ app: AppBlocks;
52
+ } | {
53
+ ok: false;
54
+ problem: string;
55
+ };
56
+ export declare const BLOCK_LIMITS: Readonly<{
57
+ /** Apps a host reads from one store. */
58
+ apps: 10;
59
+ /** Blocks per app (more are left out). */
60
+ blocks: 20;
61
+ /** Props per block. */
62
+ props: 20;
63
+ /** Options per select prop. */
64
+ options: 50;
65
+ /** connect and img origins, each. */
66
+ sources: 10;
67
+ /** Characters of a label or a name. */
68
+ label: 80;
69
+ /** Characters of a description. */
70
+ description: 300;
71
+ /** Characters of a text prop's default. */
72
+ textDefault: 500;
73
+ /** Characters of the script URL. */
74
+ url: 500;
75
+ }>;
76
+ export interface ReadOptions {
77
+ /**
78
+ * The installation origin and app record id of an installed app: its `component` blocks need them (their frames load
79
+ * there). Without them, `component` blocks are left out (onProblem says so) and only `script` blocks stay.
80
+ */
81
+ frame?: {
82
+ origin: string;
83
+ appId: string;
84
+ };
85
+ /** Where the problem is, for messages (default: the app's id). */
86
+ at?: string;
87
+ /** Problems that leave part of the declaration out but keep the rest. */
88
+ onProblem?: (message: string) => void;
89
+ /** Apps already read for this page or store: a second declaration of the same app is refused. */
90
+ seen?: ReadonlySet<string>;
91
+ }
92
+ /**
93
+ * One app's blocks from an entry of the form `{version?, app, name, script?, integrity?, connect?, img?, blocks}`,
94
+ * `script` being the exact https URL to load. A broken rule refuses the whole entry, naming it.
95
+ */
96
+ export declare function readAppBlocks(v: unknown, options?: ReadOptions): ReadResult;
97
+ /**
98
+ * The origin of an installation's frontend, where its block script and component frames load: Swell serves it at
99
+ * `<store>--<installation>--app` on the store's own domain, the host of `adminUrl` (a storefront request's verified
100
+ * context) less its first label. A loopback `adminUrl` (local mocks) gives `swell.test`. null: any other host, or ids
101
+ * of another form.
102
+ */
103
+ export declare function appFrontendOrigin(adminUrl: string, storeId: string, installationId: string): string | null;
104
+ export interface InstalledOptions {
105
+ /** An installation's frontend origin (appFrontendOrigin), or null to leave its app out. */
106
+ origin: (installationId: string) => string | null;
107
+ /** Each problem, as one line (a host logs it once). */
108
+ onProblem?: (message: string) => void;
109
+ }
110
+ /**
111
+ * The blocks of the store's installed apps, from `GET /:clients/:self/apps` with `app` expanded: one entry per
112
+ * installation that is neither uninstalled nor inactive and whose app declares blocks, named by the app's slug (its
113
+ * private id without the leading underscore), its `frontend://` script on that installation's frontend. At most
114
+ * BLOCK_LIMITS.apps; an app whose declaration breaks a rule is left out (onProblem).
115
+ */
116
+ export declare function readInstalledBlocks(raw: unknown, options: InstalledOptions): AppBlocks[];
117
+ /** Whether a block may be placed on (and rendered on) a page of that type: its `pages`, else every type but account. */
118
+ export declare const blockAllowedOn: (block: Pick<Block, "pages">, page: BlockPage) => boolean;
119
+ /** Whether a block renders as a component in a frame (render "component"). */
120
+ export declare const isComponentBlock: (block: Pick<Block, "component">) => boolean;
121
+ /** Whether an app has `script` blocks (its script loads on a page that holds one). */
122
+ export declare const hasScriptBlocks: (app: Pick<AppBlocks, "blocks">) => boolean;
123
+ /**
124
+ * The CSP sources a page adds for its blocks. scripts: the apps whose `script` blocks it holds (or may show, in a cart
125
+ * drawer); frames: those whose `component` blocks it holds. A script URL is a source without its query (CSP sources
126
+ * have none).
127
+ */
128
+ export declare function blockCspSources(scripts: readonly AppBlocks[], frames?: readonly AppBlocks[]): {
129
+ scriptSrc: string[];
130
+ connectSrc: string[];
131
+ imgSrc: string[];
132
+ frameSrc: string[];
133
+ };
134
+ /** What every `script` block's mount gets about the page. */
135
+ export interface BlockStorefront {
136
+ storeId: string;
137
+ storefrontId: string;
138
+ locale?: string;
139
+ currency?: string;
140
+ mode: 'live' | 'preview';
141
+ }
142
+ export interface BlockMountContext {
143
+ props: Record<string, unknown>;
144
+ app: string;
145
+ block: string;
146
+ storefront: BlockStorefront;
147
+ /** The app proxy's base path on this page's origin. */
148
+ proxy: string;
149
+ /** The storefront's own public key, once the platform issues one. Never a key of the host's own installation. */
150
+ publicKey?: string;
151
+ }
152
+ export interface BlockRegistration {
153
+ app: string;
154
+ blocks: Record<string, {
155
+ mount(element: HTMLElement, context: BlockMountContext): void | (() => void);
156
+ }>;
157
+ }
158
+ export interface BlockRegistryOptions {
159
+ /** The apps whose scripts this page loads: a registration of any other app is ignored. */
160
+ apps: readonly string[];
161
+ storefront: BlockStorefront;
162
+ publicKey?: string;
163
+ /** The mount element's id attribute (default `data-app-block`; the props are always in `data-app-props`). */
164
+ attribute?: string;
165
+ /** The document (default: the global one). */
166
+ document?: Document;
167
+ }
168
+ declare global {
169
+ interface Window {
170
+ SwellAppBlocks?: BlockRegistration[] | {
171
+ push(...registrations: BlockRegistration[]): void;
172
+ };
173
+ }
174
+ }
175
+ /**
176
+ * Starts the page's block registry: `window.SwellAppBlocks` becomes an object whose `push` registers an app's blocks
177
+ * (an array an app script pushed to before is registered too). Each registered block mounts on every matching element
178
+ * now and added later, once per element; its cleanup runs when the element leaves the page, and when its props change
179
+ * (the block then mounts again). Returns a function that stops the registry and cleans up every block.
180
+ */
181
+ export declare function startBlockRegistry(options: BlockRegistryOptions): () => void;
package/dist/blocks.js ADDED
@@ -0,0 +1,392 @@
1
+ // Storefront app blocks, for hosts (the app block standard v1): reading the store's installed apps' declarations
2
+ // (swell.json storefront.embeds) as strictly as the standard asks, the rules a host applies when it places and renders
3
+ // a block, the page's CSP sources, and the block registry that mounts `script` blocks on a page.
4
+ //
5
+ // A declaration that breaks one rule is left out whole (every block of that app): a host shows no partial result. The
6
+ // reading has no DOM and runs on a server or in a Worker; startBlockRegistry runs in the page.
7
+ /** The page types a block's `pages` may list. */
8
+ export const BLOCK_PAGES = Object.freeze(['home', 'product', 'category', 'category_list', 'search', 'cart', 'content', 'blog', 'blog_post', 'account', 'not_found']);
9
+ export const BLOCK_LIMITS = Object.freeze({
10
+ /** Apps a host reads from one store. */
11
+ apps: 10,
12
+ /** Blocks per app (more are left out). */
13
+ blocks: 20,
14
+ /** Props per block. */
15
+ props: 20,
16
+ /** Options per select prop. */
17
+ options: 50,
18
+ /** connect and img origins, each. */
19
+ sources: 10,
20
+ /** Characters of a label or a name. */
21
+ label: 80,
22
+ /** Characters of a description. */
23
+ description: 300,
24
+ /** Characters of a text prop's default. */
25
+ textDefault: 500,
26
+ /** Characters of the script URL. */
27
+ url: 500,
28
+ });
29
+ const APP_ID_RE = /^[a-z0-9_-]{1,40}$/;
30
+ const BLOCK_ID_RE = /^[a-z0-9_]{1,40}$/;
31
+ // No characters a CSP source list or an HTML attribute would read otherwise (space, ';', ',', quotes).
32
+ const SCRIPT_RE = /^https:\/\/[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d{1,5})?\/[A-Za-z0-9._~/%-]*(?:\?[A-Za-z0-9._~=&%-]*)?$/;
33
+ const ORIGIN_RE = /^https:\/\/[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d{1,5})?$/;
34
+ const INTEGRITY_RE = /^(?:sha256-[A-Za-z0-9+/]{43}=|sha384-[A-Za-z0-9+/]{64}|sha512-[A-Za-z0-9+/]{86}==)$/;
35
+ const ENTRY_KEYS = new Set(['version', 'app', 'name', 'script', 'integrity', 'connect', 'img', 'blocks']);
36
+ const DECLARED_KEYS = new Set(['version', 'script', 'integrity', 'connect', 'img', 'blocks']);
37
+ const BLOCK_KEYS = new Set(['id', 'label', 'description', 'icon', 'render', 'component', 'pages', 'props']);
38
+ const COMPONENT_RE = /^[A-Za-z0-9_-]{1,64}$/;
39
+ const PROP_KEYS = new Set(['id', 'type', 'label', 'description', 'default', 'options', 'min', 'max']);
40
+ const PROP_TYPES = new Set(['text', 'textarea', 'url', 'number', 'boolean', 'select']);
41
+ const PROP_ID_RE = /^[A-Za-z][A-Za-z0-9_]{0,39}$/;
42
+ const ICON_RE = /^[a-z0-9-]{1,40}$/;
43
+ const FRONTEND_LINK = 'frontend://';
44
+ const RECORD_ID_RE = /^[a-f0-9]{24}$/;
45
+ const STORE_ID_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
46
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);
47
+ const ICON_URL_RE = /^https:\/\/cdn\.(?:swell\.store|schema\.io)\/[A-Za-z0-9._~/%-]{1,400}$/;
48
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
49
+ // Text a host shows as is: control characters dropped and spaces collapsed, 1 to max characters.
50
+ const text = (v, max = BLOCK_LIMITS.label) => {
51
+ if (typeof v !== 'string')
52
+ return null;
53
+ // whitespace (newlines, tabs) becomes one space; other control characters go
54
+ // eslint-disable-next-line no-control-regex
55
+ const s = v.replace(/\s+/g, ' ').replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim();
56
+ return s && s.length <= max ? s : null;
57
+ };
58
+ // The https URL as it would be loaded, when it is exactly its normalized form and safe in a CSP source list.
59
+ function scriptUrl(v) {
60
+ if (typeof v !== 'string' || v.length > BLOCK_LIMITS.url || !SCRIPT_RE.test(v))
61
+ return null;
62
+ try {
63
+ return new URL(v).href === v ? v : null;
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ function origins(v, data) {
70
+ if (v === undefined)
71
+ return [];
72
+ if (!Array.isArray(v) || v.length > BLOCK_LIMITS.sources)
73
+ return null;
74
+ return v.every((x) => typeof x === 'string' && (ORIGIN_RE.test(x) || (data && x === 'data:'))) ? [...new Set(v)] : null;
75
+ }
76
+ function propOf(v) {
77
+ if (!isObj(v) || Object.keys(v).some((k) => !PROP_KEYS.has(k)))
78
+ return 'must be {id, type, label, description?, default?, options?, min?, max?}';
79
+ const { id, type, min, max, default: d } = v;
80
+ if (typeof id !== 'string' || !PROP_ID_RE.test(id))
81
+ return 'id must match [A-Za-z][A-Za-z0-9_]{0,39}';
82
+ if (typeof type !== 'string' || !PROP_TYPES.has(type))
83
+ return `(${id}).type must be text, textarea, url, number, boolean or select`;
84
+ const label = text(v.label);
85
+ if (label === null)
86
+ return `(${id}).label must be text of 1 to ${BLOCK_LIMITS.label} characters`;
87
+ const description = v.description === undefined ? undefined : text(v.description, BLOCK_LIMITS.description);
88
+ if (description === null)
89
+ return `(${id}).description must be text of 1 to ${BLOCK_LIMITS.description} characters`;
90
+ const num = (x) => x === undefined || (typeof x === 'number' && Number.isFinite(x));
91
+ if ((min !== undefined || max !== undefined) && (type !== 'number' || !num(min) || !num(max) || min > max)) {
92
+ return `(${id}).min and max are numbers (min at most max) of a number prop`;
93
+ }
94
+ let options;
95
+ if (type === 'select') {
96
+ const list = Array.isArray(v.options) && v.options.length <= BLOCK_LIMITS.options ? v.options : [];
97
+ options = [];
98
+ for (const o of list) {
99
+ const optionLabel = isObj(o) ? text(o.label) : null;
100
+ if (!isObj(o) || typeof o.value !== 'string' || !o.value || o.value.length > BLOCK_LIMITS.label || optionLabel === null || Object.keys(o).some((k) => k !== 'value' && k !== 'label'))
101
+ break;
102
+ if (options.some((x) => x.value === o.value))
103
+ break;
104
+ options.push({ value: o.value, label: optionLabel });
105
+ }
106
+ if (!options.length || options.length !== list.length)
107
+ return `(${id}).options must be 1 to ${BLOCK_LIMITS.options} {value, label}, each value once`;
108
+ }
109
+ else if (v.options !== undefined)
110
+ return `(${id}).options are a select prop's`;
111
+ const ok = d === undefined || (type === 'boolean' ? typeof d === 'boolean'
112
+ : type === 'number' ? typeof d === 'number' && Number.isFinite(d) && !(typeof min === 'number' && d < min) && !(typeof max === 'number' && d > max)
113
+ : type === 'select' ? options.some((o) => o.value === d)
114
+ : typeof d === 'string' && d.length <= BLOCK_LIMITS.textDefault);
115
+ if (!ok)
116
+ return `(${id}).default must be a value of its type`;
117
+ return {
118
+ id, type: type, label, ...(description ? { description } : {}), ...(d !== undefined ? { default: d } : {}),
119
+ ...(options ? { options } : {}), ...(min !== undefined ? { min: min } : {}), ...(max !== undefined ? { max: max } : {}),
120
+ };
121
+ }
122
+ function blockOf(b) {
123
+ const label = isObj(b) ? text(b.label) : null;
124
+ if (!isObj(b) || typeof b.id !== 'string' || !BLOCK_ID_RE.test(b.id) || label === null || Object.keys(b).some((k) => !BLOCK_KEYS.has(k))) {
125
+ return 'must be {id: [a-z0-9_]{1,40}, label, description?, icon?, render?, component?, pages?, props?}';
126
+ }
127
+ const description = b.description === undefined ? undefined : text(b.description, BLOCK_LIMITS.description);
128
+ if (description === null)
129
+ return `(${b.id}).description must be text of 1 to ${BLOCK_LIMITS.description} characters`;
130
+ if (b.icon !== undefined && (typeof b.icon !== 'string' || !ICON_RE.test(b.icon)))
131
+ return `(${b.id}).icon must match [a-z0-9-]{1,40}`;
132
+ if (b.render !== undefined && b.render !== 'script' && b.render !== 'component')
133
+ return `(${b.id}).render must be "script" or "component"`;
134
+ const component = b.render === 'component';
135
+ if (component ? typeof b.component !== 'string' || !COMPONENT_RE.test(b.component) : b.component !== undefined) {
136
+ return `(${b.id}).component names a component (${COMPONENT_RE.source}) of a block whose render is "component", and only of one`;
137
+ }
138
+ const pages = b.pages;
139
+ if (pages !== undefined && (!Array.isArray(pages) || !pages.length || pages.some((x, i) => !BLOCK_PAGES.includes(x) || pages.indexOf(x) !== i))) {
140
+ return `(${b.id}).pages must be a non-empty list of ${BLOCK_PAGES.join(', ')}, each once`;
141
+ }
142
+ if (b.props !== undefined && (!Array.isArray(b.props) || b.props.length > BLOCK_LIMITS.props))
143
+ return `(${b.id}).props must be a list of at most ${BLOCK_LIMITS.props}`;
144
+ const props = [];
145
+ for (const [i, p] of (b.props ?? []).entries()) {
146
+ const prop = propOf(p);
147
+ if (typeof prop === 'string')
148
+ return `(${b.id}).props[${i}] ${prop}`;
149
+ if (props.some((x) => x.id === prop.id))
150
+ return `(${b.id}).props[${i}].id ${prop.id} is listed twice`;
151
+ props.push(prop);
152
+ }
153
+ return {
154
+ id: b.id, label, ...(description ? { description } : {}), ...(b.icon ? { icon: b.icon } : {}),
155
+ ...(pages !== undefined ? { pages: pages } : {}), ...(b.props !== undefined ? { props } : {}), ...(component ? { component: b.component } : {}),
156
+ };
157
+ }
158
+ /**
159
+ * One app's blocks from an entry of the form `{version?, app, name, script?, integrity?, connect?, img?, blocks}`,
160
+ * `script` being the exact https URL to load. A broken rule refuses the whole entry, naming it.
161
+ */
162
+ export function readAppBlocks(v, options = {}) {
163
+ const at = options.at ?? 'the app\'s storefront.embeds';
164
+ const fail = (problem) => ({ ok: false, problem });
165
+ if (!isObj(v))
166
+ return fail(`${at} is not an object`);
167
+ const extra = Object.keys(v).find((k) => !ENTRY_KEYS.has(k));
168
+ if (extra !== undefined)
169
+ return fail(`${at} has an unknown key ${JSON.stringify(extra.slice(0, 40))}`);
170
+ const { app, integrity } = v;
171
+ if (v.version !== undefined && v.version !== 1)
172
+ return fail(`${at}.version ${JSON.stringify(v.version).slice(0, 20)} is not one this storefront reads (1)`);
173
+ if (typeof app !== 'string' || !APP_ID_RE.test(app))
174
+ return fail(`${at}.app must match [a-z0-9_-]{1,40}`);
175
+ if (options.seen?.has(app))
176
+ return fail(`${at}.app ${app} is listed twice`);
177
+ const name = text(v.name);
178
+ if (name === null)
179
+ return fail(`${at} (${app}).name must be text of 1 to ${BLOCK_LIMITS.label} characters`);
180
+ const script = v.script === undefined ? undefined : scriptUrl(v.script);
181
+ if (script === null)
182
+ return fail(`${at} (${app}).script must be an https URL in normal form`);
183
+ if (integrity !== undefined && (typeof integrity !== 'string' || !INTEGRITY_RE.test(integrity)))
184
+ return fail(`${at} (${app}).integrity must be sha256-, sha384- or sha512-<base64>`);
185
+ const connect = origins(v.connect, false);
186
+ if (connect === null)
187
+ return fail(`${at} (${app}).connect must be a list of at most ${BLOCK_LIMITS.sources} https origins`);
188
+ const img = origins(v.img, true);
189
+ if (img === null)
190
+ return fail(`${at} (${app}).img must be a list of at most ${BLOCK_LIMITS.sources} https origins or "data:"`);
191
+ if (!Array.isArray(v.blocks) || !v.blocks.length)
192
+ return fail(`${at} (${app}).blocks must be a non-empty list`);
193
+ if (v.blocks.length > BLOCK_LIMITS.blocks)
194
+ options.onProblem?.(`${at} (${app}) has ${v.blocks.length} blocks; only the first ${BLOCK_LIMITS.blocks} are used`);
195
+ const blocks = [];
196
+ const dropped = [];
197
+ for (const [i, b] of v.blocks.slice(0, BLOCK_LIMITS.blocks).entries()) {
198
+ const block = blockOf(b);
199
+ if (typeof block === 'string')
200
+ return fail(`${at} (${app}).blocks[${i}] ${block}`);
201
+ if (blocks.some((x) => x.id === block.id) || dropped.includes(block.id))
202
+ return fail(`${at} (${app}).blocks[${i}].id ${block.id} is listed twice`);
203
+ if (isComponentBlock(block) && !options.frame)
204
+ dropped.push(block.id);
205
+ else
206
+ blocks.push(block);
207
+ }
208
+ if (dropped.length)
209
+ options.onProblem?.(`${at} (${app}) blocks ${dropped.join(', ')} render as components, which only an installed app's declaration can offer; left out`);
210
+ if (!blocks.length)
211
+ return fail(`${at} (${app}) has no blocks this storefront shows`);
212
+ if (hasScriptBlocks({ blocks }) && script === undefined)
213
+ return fail(`${at} (${app}).script is required for its script blocks`);
214
+ const framed = options.frame && blocks.some(isComponentBlock) ? { frame: options.frame.origin, appId: options.frame.appId } : {};
215
+ return { ok: true, app: { app, name, ...(script !== undefined ? { script } : {}), ...(integrity ? { integrity: integrity } : {}), connect, img, blocks, ...framed } };
216
+ }
217
+ /**
218
+ * The origin of an installation's frontend, where its block script and component frames load: Swell serves it at
219
+ * `<store>--<installation>--app` on the store's own domain, the host of `adminUrl` (a storefront request's verified
220
+ * context) less its first label. A loopback `adminUrl` (local mocks) gives `swell.test`. null: any other host, or ids
221
+ * of another form.
222
+ */
223
+ export function appFrontendOrigin(adminUrl, storeId, installationId) {
224
+ if (!STORE_ID_RE.test(storeId) || !RECORD_ID_RE.test(installationId))
225
+ return null;
226
+ let u;
227
+ try {
228
+ u = new URL(adminUrl);
229
+ }
230
+ catch {
231
+ return null;
232
+ }
233
+ const host = LOOPBACK.has(u.hostname) ? `${storeId}.swell.test` : u.host.toLowerCase();
234
+ return host.startsWith(`${storeId}.`) ? `https://${storeId}--${installationId}--app${host.slice(storeId.length)}` : null;
235
+ }
236
+ /**
237
+ * The blocks of the store's installed apps, from `GET /:clients/:self/apps` with `app` expanded: one entry per
238
+ * installation that is neither uninstalled nor inactive and whose app declares blocks, named by the app's slug (its
239
+ * private id without the leading underscore), its `frontend://` script on that installation's frontend. At most
240
+ * BLOCK_LIMITS.apps; an app whose declaration breaks a rule is left out (onProblem).
241
+ */
242
+ export function readInstalledBlocks(raw, options) {
243
+ const out = [];
244
+ const seen = new Set();
245
+ for (const r of isObj(raw) && Array.isArray(raw.results) ? raw.results : []) {
246
+ if (!isObj(r) || r.uninstalled === true || r.active === false || !isObj(r.app))
247
+ continue;
248
+ const declared = isObj(r.app.storefront) ? r.app.storefront.embeds : undefined;
249
+ if (declared === undefined || declared === null)
250
+ continue;
251
+ const slug = typeof r.app_private_id === 'string' ? r.app_private_id.replace(/^_/, '') : '';
252
+ const at = `the installed app ${JSON.stringify(slug.slice(0, 40))}'s storefront.embeds`;
253
+ if (out.length === BLOCK_LIMITS.apps) {
254
+ options.onProblem?.(`more than ${BLOCK_LIMITS.apps} installed apps declare app embeds; only the first ${BLOCK_LIMITS.apps} are used`);
255
+ break;
256
+ }
257
+ if (!isObj(declared) || Object.keys(declared).some((k) => !DECLARED_KEYS.has(k))) {
258
+ options.onProblem?.(`${at} must be {version?, script?, integrity?, connect?, img?, blocks}; left out`);
259
+ continue;
260
+ }
261
+ const base = typeof r.id === 'string' ? options.origin(r.id) : null;
262
+ const path = typeof declared.script === 'string' && declared.script.startsWith(FRONTEND_LINK) ? declared.script.slice(FRONTEND_LINK.length).replace(/^\/+/, '') : null;
263
+ const appId = typeof r.app_id === 'string' && RECORD_ID_RE.test(r.app_id) ? r.app_id : null;
264
+ if (base === null || (declared.script !== undefined && path === null)) {
265
+ options.onProblem?.(`${at}.script must be a ${FRONTEND_LINK} link on the app's frontend; left out`);
266
+ continue;
267
+ }
268
+ const result = readAppBlocks({ ...declared, app: slug, name: r.app.name, ...(path !== null ? { script: `${base}/${path}` } : {}) }, { at, seen, onProblem: options.onProblem, ...(appId ? { frame: { origin: base, appId } } : {}) });
269
+ if (!result.ok) {
270
+ options.onProblem?.(`${result.problem}; left out`);
271
+ continue;
272
+ }
273
+ seen.add(result.app.app);
274
+ const iconUrl = isObj(r.app.logo_icon) && typeof r.app.logo_icon.url === 'string' && ICON_URL_RE.test(r.app.logo_icon.url) ? r.app.logo_icon.url : null;
275
+ out.push(iconUrl ? { ...result.app, icon: iconUrl } : result.app);
276
+ }
277
+ return out;
278
+ }
279
+ /** Whether a block may be placed on (and rendered on) a page of that type: its `pages`, else every type but account. */
280
+ export const blockAllowedOn = (block, page) => (block.pages ? block.pages.includes(page) : page !== 'account');
281
+ /** Whether a block renders as a component in a frame (render "component"). */
282
+ export const isComponentBlock = (block) => typeof block.component === 'string';
283
+ /** Whether an app has `script` blocks (its script loads on a page that holds one). */
284
+ export const hasScriptBlocks = (app) => app.blocks.some((b) => !isComponentBlock(b));
285
+ /**
286
+ * The CSP sources a page adds for its blocks. scripts: the apps whose `script` blocks it holds (or may show, in a cart
287
+ * drawer); frames: those whose `component` blocks it holds. A script URL is a source without its query (CSP sources
288
+ * have none).
289
+ */
290
+ export function blockCspSources(scripts, frames = []) {
291
+ const uniq = (xs) => [...new Set(xs)];
292
+ return {
293
+ scriptSrc: uniq(scripts.flatMap((e) => {
294
+ if (!e.script)
295
+ return [];
296
+ const u = new URL(e.script);
297
+ return [u.origin + u.pathname];
298
+ })),
299
+ connectSrc: uniq(scripts.flatMap((e) => e.connect)),
300
+ imgSrc: uniq(scripts.flatMap((e) => e.img)),
301
+ frameSrc: uniq(frames.flatMap((e) => (e.frame ? [e.frame] : []))),
302
+ };
303
+ }
304
+ /**
305
+ * Starts the page's block registry: `window.SwellAppBlocks` becomes an object whose `push` registers an app's blocks
306
+ * (an array an app script pushed to before is registered too). Each registered block mounts on every matching element
307
+ * now and added later, once per element; its cleanup runs when the element leaves the page, and when its props change
308
+ * (the block then mounts again). Returns a function that stops the registry and cleans up every block.
309
+ */
310
+ export function startBlockRegistry(options) {
311
+ const doc = options.document ?? document;
312
+ const win = doc.defaultView;
313
+ if (!win)
314
+ throw new Error('startBlockRegistry needs a document with a window');
315
+ const attribute = options.attribute ?? 'data-app-block';
316
+ const selector = `[${attribute}][data-app-props]`;
317
+ const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
318
+ const registered = Object.create(null);
319
+ // each mounted element: the props it mounted with and its cleanup
320
+ const mounted = new Map();
321
+ const cleanup = (el) => {
322
+ const m = mounted.get(el);
323
+ mounted.delete(el);
324
+ if (m?.cleanup) {
325
+ try {
326
+ m.cleanup();
327
+ }
328
+ catch (e) {
329
+ console.error(e);
330
+ }
331
+ }
332
+ };
333
+ const mount = (el) => {
334
+ const raw = el.getAttribute('data-app-props') ?? '';
335
+ const was = mounted.get(el);
336
+ if (was && was.props === raw)
337
+ return;
338
+ if (was)
339
+ cleanup(el);
340
+ const id = el.getAttribute(attribute) ?? '';
341
+ const slash = id.indexOf('/');
342
+ const app = id.slice(0, slash);
343
+ const block = id.slice(slash + 1);
344
+ if (slash < 1 || !has(registered, app) || !has(registered[app], block))
345
+ return;
346
+ const definition = registered[app][block];
347
+ if (!definition || typeof definition.mount !== 'function')
348
+ return;
349
+ let props;
350
+ try {
351
+ props = JSON.parse(raw);
352
+ }
353
+ catch {
354
+ return;
355
+ }
356
+ if (!isObj(props))
357
+ return;
358
+ const entry = { props: raw };
359
+ mounted.set(el, entry);
360
+ try {
361
+ const off = definition.mount(el, { props, app, block, storefront: options.storefront, proxy: `/.swell/apps/${app}`, ...(options.publicKey ? { publicKey: options.publicKey } : {}) });
362
+ if (typeof off === 'function')
363
+ entry.cleanup = off;
364
+ }
365
+ catch (e) {
366
+ console.error(e);
367
+ }
368
+ };
369
+ const scan = () => {
370
+ doc.querySelectorAll(selector).forEach(mount);
371
+ for (const el of [...mounted.keys()])
372
+ if (!el.isConnected || !el.matches(selector))
373
+ cleanup(el);
374
+ };
375
+ const add = (x) => {
376
+ if (!isObj(x) || typeof x.app !== 'string' || !options.apps.includes(x.app) || has(registered, x.app) || !isObj(x.blocks))
377
+ return;
378
+ registered[x.app] = x.blocks;
379
+ scan();
380
+ };
381
+ const queued = win.SwellAppBlocks;
382
+ win.SwellAppBlocks = { push: (...registrations) => registrations.forEach(add) };
383
+ if (Array.isArray(queued))
384
+ queued.forEach(add);
385
+ const observer = new win.MutationObserver(scan);
386
+ observer.observe(doc.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-app-props', attribute] });
387
+ return () => {
388
+ observer.disconnect();
389
+ for (const el of [...mounted.keys()])
390
+ cleanup(el);
391
+ };
392
+ }
@@ -0,0 +1,32 @@
1
+ import type { ComponentToken } from './components-types.cjs';
2
+ /** The theme tokens a host passes as `context.tokens` (the standard's --swell-* custom properties, without the prefix). */
3
+ export declare const BLOCK_TOKENS: readonly string[];
4
+ export interface ComponentBlocksOptions {
5
+ storeId: string;
6
+ /** For the SDK's component list. A placeholder when `url` names the host's own list route, which reads with its key. */
7
+ publicKey: string;
8
+ /** Base of the component list (`<url>/api/apps/<app>/components`). Defaults to the store's storefront API. */
9
+ url?: string;
10
+ /** The block's component token (a storefront host fetches `/.swell/component-token?app=<app>`). */
11
+ getToken: (app: string) => Promise<ComponentToken>;
12
+ /** The page's `component` blocks by `"<app>/<block>"`: the component and the frame's accessible title. */
13
+ blocks: Readonly<Record<string, {
14
+ component: string;
15
+ title: string;
16
+ }>>;
17
+ /** `context.storefront`, as `script` blocks get it. */
18
+ storefront: Readonly<Record<string, unknown>>;
19
+ /** The mount element's id attribute (default `data-app-block`). */
20
+ attribute?: string;
21
+ /** Set on a mount element once its frame is ready (default `data-app-frame-ready`): hide the fallback with it. */
22
+ readyAttribute?: string;
23
+ /** Class of the element the frame mounts in, appended to the mount element (default `swell-app-frame`). */
24
+ frameClass?: string;
25
+ /** The document (default: the global one). */
26
+ document?: Document;
27
+ }
28
+ /**
29
+ * Mounts the page's `component` blocks, and keeps them in step with the page. A `script` block (not in `blocks`) is
30
+ * left alone. Returns a function that stops and unmounts every block.
31
+ */
32
+ export declare function startComponentBlocks(options: ComponentBlocksOptions): () => void;
@@ -0,0 +1,32 @@
1
+ import type { ComponentToken } from './components-types.js';
2
+ /** The theme tokens a host passes as `context.tokens` (the standard's --swell-* custom properties, without the prefix). */
3
+ export declare const BLOCK_TOKENS: readonly string[];
4
+ export interface ComponentBlocksOptions {
5
+ storeId: string;
6
+ /** For the SDK's component list. A placeholder when `url` names the host's own list route, which reads with its key. */
7
+ publicKey: string;
8
+ /** Base of the component list (`<url>/api/apps/<app>/components`). Defaults to the store's storefront API. */
9
+ url?: string;
10
+ /** The block's component token (a storefront host fetches `/.swell/component-token?app=<app>`). */
11
+ getToken: (app: string) => Promise<ComponentToken>;
12
+ /** The page's `component` blocks by `"<app>/<block>"`: the component and the frame's accessible title. */
13
+ blocks: Readonly<Record<string, {
14
+ component: string;
15
+ title: string;
16
+ }>>;
17
+ /** `context.storefront`, as `script` blocks get it. */
18
+ storefront: Readonly<Record<string, unknown>>;
19
+ /** The mount element's id attribute (default `data-app-block`). */
20
+ attribute?: string;
21
+ /** Set on a mount element once its frame is ready (default `data-app-frame-ready`): hide the fallback with it. */
22
+ readyAttribute?: string;
23
+ /** Class of the element the frame mounts in, appended to the mount element (default `swell-app-frame`). */
24
+ frameClass?: string;
25
+ /** The document (default: the global one). */
26
+ document?: Document;
27
+ }
28
+ /**
29
+ * Mounts the page's `component` blocks, and keeps them in step with the page. A `script` block (not in `blocks`) is
30
+ * left alone. Returns a function that stops and unmounts every block.
31
+ */
32
+ export declare function startComponentBlocks(options: ComponentBlocksOptions): () => void;
@@ -0,0 +1,97 @@
1
+ // The host of `component` storefront app blocks (the app block standard v1, 4.5): each block's App Component mounts in
2
+ // a frame on its app's installation origin, now and whenever its element is added (a cart drawer), with the block's
3
+ // props as params and the storefront and theme tokens as context; it unmounts when the element leaves the page, and
4
+ // mounts again when its props change. The fallback stays until the frame is ready, then the host hides it.
5
+ import { createComponents } from './components-client.js';
6
+ /** The theme tokens a host passes as `context.tokens` (the standard's --swell-* custom properties, without the prefix). */
7
+ export const BLOCK_TOKENS = Object.freeze(['color-text', 'color-muted', 'color-background', 'color-surface', 'color-accent', 'color-on-accent', 'color-border', 'font-body', 'font-heading', 'radius', 'space']);
8
+ /**
9
+ * Mounts the page's `component` blocks, and keeps them in step with the page. A `script` block (not in `blocks`) is
10
+ * left alone. Returns a function that stops and unmounts every block.
11
+ */
12
+ export function startComponentBlocks(options) {
13
+ const doc = options.document ?? document;
14
+ const win = doc.defaultView;
15
+ if (!win)
16
+ throw new Error('startComponentBlocks needs a document with a window');
17
+ const attribute = options.attribute ?? 'data-app-block';
18
+ const ready = options.readyAttribute ?? 'data-app-frame-ready';
19
+ const frameClass = options.frameClass ?? 'swell-app-frame';
20
+ const selector = `[${attribute}][data-app-props]`;
21
+ const components = createComponents({ storeId: options.storeId, publicKey: options.publicKey, url: options.url, getToken: options.getToken });
22
+ const mounted = new Map();
23
+ const tokens = (el) => {
24
+ const style = win.getComputedStyle(el);
25
+ const out = {};
26
+ for (const t of BLOCK_TOKENS) {
27
+ const v = style.getPropertyValue(`--swell-${t}`).trim();
28
+ if (v)
29
+ out[t] = v;
30
+ }
31
+ return out;
32
+ };
33
+ const unmount = (el) => {
34
+ const m = mounted.get(el);
35
+ if (!m)
36
+ return;
37
+ mounted.delete(el);
38
+ el.removeAttribute(ready);
39
+ m.handle.unmount();
40
+ m.frame.remove();
41
+ };
42
+ const mount = (el) => {
43
+ const raw = el.getAttribute('data-app-props') ?? '';
44
+ const was = mounted.get(el);
45
+ if (was && was.props === raw)
46
+ return;
47
+ if (was)
48
+ unmount(el);
49
+ const id = el.getAttribute(attribute) ?? '';
50
+ const block = Object.prototype.hasOwnProperty.call(options.blocks, id) ? options.blocks[id] : undefined;
51
+ if (!block || id.indexOf('/') < 1)
52
+ return;
53
+ let params;
54
+ try {
55
+ params = JSON.parse(raw);
56
+ }
57
+ catch {
58
+ return;
59
+ }
60
+ if (!params || typeof params !== 'object' || Array.isArray(params))
61
+ return;
62
+ const frame = doc.createElement('div');
63
+ frame.className = frameClass;
64
+ el.append(frame);
65
+ const handle = components.mount(frame, {
66
+ app: id.slice(0, id.indexOf('/')),
67
+ component: block.component,
68
+ title: block.title,
69
+ params: params,
70
+ context: { storefront: options.storefront, tokens: tokens(el) },
71
+ });
72
+ const entry = { props: raw, handle, frame };
73
+ mounted.set(el, entry);
74
+ handle.ready.then(() => {
75
+ if (mounted.get(el) === entry)
76
+ el.setAttribute(ready, '');
77
+ }, () => {
78
+ // it couldn't load or start, or left the page: the fallback stays
79
+ if (mounted.get(el) === entry)
80
+ unmount(el);
81
+ });
82
+ };
83
+ const scan = () => {
84
+ doc.querySelectorAll(selector).forEach(mount);
85
+ for (const el of [...mounted.keys()])
86
+ if (!el.isConnected || !el.matches(selector))
87
+ unmount(el);
88
+ };
89
+ scan();
90
+ const observer = new win.MutationObserver(scan);
91
+ observer.observe(doc.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-app-props', attribute] });
92
+ return () => {
93
+ observer.disconnect();
94
+ for (const el of [...mounted.keys()])
95
+ unmount(el);
96
+ };
97
+ }
@@ -4,3 +4,5 @@ export type { Components, ComponentsOptions, MountOptions, NamedMountOptions, Pl
4
4
  export type { ComponentHandle } from './components-host.cjs';
5
5
  export { startComponentFrame } from './components-frame.cjs';
6
6
  export type { FrameOptions } from './components-frame.cjs';
7
+ export { BLOCK_TOKENS, startComponentBlocks } from './components-blocks.cjs';
8
+ export type { ComponentBlocksOptions } from './components-blocks.cjs';
@@ -4,3 +4,5 @@ export type { Components, ComponentsOptions, MountOptions, NamedMountOptions, Pl
4
4
  export type { ComponentHandle } from './components-host.js';
5
5
  export { startComponentFrame } from './components-frame.js';
6
6
  export type { FrameOptions } from './components-frame.js';
7
+ export { BLOCK_TOKENS, startComponentBlocks } from './components-blocks.js';
8
+ export type { ComponentBlocksOptions } from './components-blocks.js';
@@ -1,2 +1,3 @@
1
1
  export { createComponents } from './components-client.js';
2
2
  export { startComponentFrame } from './components-frame.js';
3
+ export { BLOCK_TOKENS, startComponentBlocks } from './components-blocks.js';
@@ -32,6 +32,17 @@ export interface SwellRequestContext {
32
32
  readonly accountId?: string;
33
33
  /** The storefront's deployment mode on a storefront request. */
34
34
  readonly mode?: SwellStorefrontMode;
35
+ /**
36
+ * The shopper's IP address on a storefront request, as Swell's own rate limits take it. Through the storefront app
37
+ * proxy the app's server only sees Swell's, so rate-limit storefront routes on this.
38
+ */
39
+ readonly clientIp?: string;
40
+ /**
41
+ * Set when another installed app, a storefront host such as Wave, made the call on a shopper's behalf (the app's own
42
+ * id). Then storeId and installationId are Swell's, but storefrontId, storefrontHost, accountId and mode are that
43
+ * host's assertion, checked only for consistency: trust accountId as far as you trust the host. clientIp is unset.
44
+ */
45
+ readonly hostApp?: string;
35
46
  readonly apiHost: string;
36
47
  readonly adminUrl: string;
37
48
  readonly accessToken?: string;
@@ -32,6 +32,17 @@ export interface SwellRequestContext {
32
32
  readonly accountId?: string;
33
33
  /** The storefront's deployment mode on a storefront request. */
34
34
  readonly mode?: SwellStorefrontMode;
35
+ /**
36
+ * The shopper's IP address on a storefront request, as Swell's own rate limits take it. Through the storefront app
37
+ * proxy the app's server only sees Swell's, so rate-limit storefront routes on this.
38
+ */
39
+ readonly clientIp?: string;
40
+ /**
41
+ * Set when another installed app, a storefront host such as Wave, made the call on a shopper's behalf (the app's own
42
+ * id). Then storeId and installationId are Swell's, but storefrontId, storefrontHost, accountId and mode are that
43
+ * host's assertion, checked only for consistency: trust accountId as far as you trust the host. clientIp is unset.
44
+ */
45
+ readonly hostApp?: string;
35
46
  readonly apiHost: string;
36
47
  readonly adminUrl: string;
37
48
  readonly accessToken?: string;
@@ -5,6 +5,10 @@ const SURFACES = ['admin', 'checkout', 'storefront'];
5
5
  const MODES = ['live', 'preview', 'editor'];
6
6
  // host[:port], lowercase: what Swell puts in storefront_host
7
7
  const HOST_RE = /^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::\d{1,5})?$/;
8
+ // An app's id as Swell writes host_app (an app slug)
9
+ const APP_SLUG_RE = /^[a-z0-9_-]{1,64}$/;
10
+ // An IPv4 or IPv6 address as Swell writes client_ip (shape only: the claim is signed)
11
+ const IP_RE = /^(?:\d{1,3}(?:\.\d{1,3}){3}|[0-9A-Fa-f:.]{2,45})$/;
8
12
  function invalidContext() {
9
13
  return new SwellError('Missing or invalid Swell context', { status: 401, code: 'invalid_swell_context' });
10
14
  }
@@ -83,6 +87,10 @@ export async function verifySwellContext(headers, options = {}) {
83
87
  requireString(payload.account_id, 'account_id');
84
88
  if (payload.mode != null && !MODES.includes(payload.mode))
85
89
  throw invalidContext();
90
+ if (payload.client_ip != null && (typeof payload.client_ip !== 'string' || !IP_RE.test(payload.client_ip)))
91
+ throw invalidContext();
92
+ if (payload.host_app != null && (typeof payload.host_app !== 'string' || !APP_SLUG_RE.test(payload.host_app)))
93
+ throw invalidContext();
86
94
  let storeUser = null;
87
95
  if (payload.admin !== null) {
88
96
  object(payload.admin);
@@ -98,6 +106,8 @@ export async function verifySwellContext(headers, options = {}) {
98
106
  storefrontHost: payload.storefront_host ?? undefined,
99
107
  accountId: payload.account_id ?? undefined,
100
108
  mode: payload.mode ?? undefined,
109
+ clientIp: payload.client_ip ?? undefined,
110
+ hostApp: payload.host_app ?? undefined,
101
111
  apiHost: validateUrl(payload.api_host, 'api_host'), adminUrl: validateUrl(payload.admin_url, 'admin_url'),
102
112
  accessToken: headers.get('Swell-Access-Token') ?? undefined,
103
113
  publicKey: headers.get('Swell-Public-Key') ?? undefined,
@@ -1 +1 @@
1
- export declare const USER_AGENT = "swell-apps-sdk/2.1.1";
1
+ export declare const USER_AGENT = "swell-apps-sdk/2.1.2";
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const USER_AGENT = "swell-apps-sdk/2.1.1";
1
+ export declare const USER_AGENT = "swell-apps-sdk/2.1.2";
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.1.1';
2
+ export const USER_AGENT = 'swell-apps-sdk/2.1.2';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swell/apps-sdk",
3
- "version": "2.1.1",
3
+ "version": "2.1.2",
4
4
  "description": "Server SDK for Swell apps.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -61,6 +61,13 @@
61
61
  "require": "./dist/components.d.cts"
62
62
  },
63
63
  "default": "./dist/components.js"
64
+ },
65
+ "./blocks": {
66
+ "types": {
67
+ "import": "./dist/blocks.d.ts",
68
+ "require": "./dist/blocks.d.cts"
69
+ },
70
+ "default": "./dist/blocks.js"
64
71
  }
65
72
  },
66
73
  "sideEffects": [