@veroxm/react-sdk 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.5.0
4
+
5
+ - Content in Server Components, from `@veroxm/react-sdk/next`: `getEntries`, `getEntry`, `getCollection`,
6
+ `getMedia` and `getServerClient()` read with `VEROXM_API_KEY` on the server, cached by Next.js (60 s by default,
7
+ `revalidate`, tags `veroxm-content` and `veroxm-content:<collection>`); the same from
8
+ `@veroxm/react-sdk/next/cache-components` with `'use cache'`. `CONTENT_TAG`, `contentTag()`, `mediaTag()`.
9
+ - The `/api/veroxm` route refreshes content reads on a project webhook signed with `VEROXM_WEBHOOK_SECRET`
10
+ (`webhookSecret` in `configureSlots`); unsigned or older-than-5-minutes deliveries are refused.
11
+ - `VeroxmClient` takes a `fetch` to send with.
12
+ - Components editors choose: `defineComponent(name, { label, version, fields, render })` registers a component and the
13
+ fields editors may set; `<VeroxmRegion name components fallback empty>` (from the package root, `/next` and
14
+ `/next/cache-components`) lets editors choose which one shows; `field.component([...])` and `renderComponent()` do the
15
+ same inside a slot with other fields. Unknown components show the fallback, and a component that throws is caught
16
+ by `VeroxmComponentBoundary` (inside Suspense, so server rendering survives it too). The on-page editor offers the
17
+ registered components and their fields. Needs the VeroXM API with component fields (2026-10-20).
18
+ - Requests go through `@veroxm/sdk` (1.10's `graphqlRequest`), which replaces the `graphql-request` dependency. A page
19
+ that only uses `VeroxmClient` bundles about 5 KB gzipped instead of about 17 KB.
20
+ - `VeroxmClient` and `<VeroxmProvider>` take `timeoutMs` and `retries` (both off unless set), and `client.request()`
21
+ takes a third argument, `{ signal, timeoutMs }`. A document with a mutation is never retried.
22
+ - `VeroxmGraphQLError` is now a subclass of `@veroxm/sdk`'s `VeroXMGraphQLError` and `VeroXMApiError`. It keeps
23
+ `errors`, `status` and its name, and gains `code` and `body`. A failed answer without a GraphQL errors array (a 401,
24
+ say) now has the API's own message instead of `graphql-request`'s. `VeroxmGraphQLError.from()` wraps
25
+ `@veroxm/sdk` errors; it no longer recognises `graphql-request`'s `ClientError`.
26
+
3
27
  ## 1.4.0
4
28
 
5
29
  - The providers and hooks are `'use client'` modules: `VeroxmProvider`, `VeroxmPreviewProvider`, `VeroxmAuthProvider`,
package/README.md CHANGED
@@ -183,6 +183,26 @@ preview one specific unpublished entry, use `useEntries()` with
183
183
  mounted (`isDraftMode: false`, so an app that never uses preview mode
184
184
  doesn't need to wrap anything).
185
185
 
186
+ ## Content in Server Components
187
+
188
+ From 1.5, `@veroxm/react-sdk/next` reads content on the server with `VEROXM_API_KEY` (and `VEROXM_API_BASE`), cached
189
+ by Next.js; the key never reaches the browser:
190
+
191
+ ```tsx
192
+ import { getEntries, getEntry } from '@veroxm/react-sdk/next';
193
+
194
+ const post = await getEntry<Post>('posts', 42); // null when there's no such published entry
195
+ const latest = await getEntries<Post>('posts', { limit: 3, sort: 'created_at:desc', revalidate: 300 });
196
+ ```
197
+
198
+ - `getEntries`, `getEntry`, `getCollection`, `getMedia`; errors are thrown (`VeroxmGraphQLError`, `VeroXMTimeoutError`).
199
+ - Cached with `force-cache`, fresh for 60 s by default (`revalidate`), tagged `veroxm-content` and
200
+ `veroxm-content:<collection>` (`contentTag('posts')`); extra `tags` too. Draft mode skips the cache.
201
+ - With `cacheComponents: true`, import them from `@veroxm/react-sdk/next/cache-components` (`'use cache'`, same tags).
202
+ - Refresh on publish: a project webhook for `content.*` events pointing at `/api/veroxm/revalidate`, with its secret
203
+ in `VEROXM_WEBHOOK_SECRET`; the route checks the signature and age, then revalidates `veroxm-content`.
204
+ - `getServerClient()` gives the same cached client for the SSR helpers below.
205
+
186
206
  ## SSR / Next.js helpers
187
207
 
188
208
  Framework-agnostic fetch functions -- no hooks, safe to call from a Server
@@ -325,22 +345,70 @@ function ArticlePage({ article }: { article: Article }) {
325
345
  }
326
346
  ```
327
347
 
348
+ ## Components editors choose
349
+
350
+ Register a component once, with the fields editors may set; editors then choose which registered component shows in
351
+ a place and fill in its fields (from 1.5). Only declared fields can be set: VeroXM stores their values, checked on the
352
+ server, and never code.
353
+
354
+ ```tsx
355
+ import { VeroxmRegion, defineComponent, field } from '@veroxm/react-sdk/next';
356
+
357
+ const Hero = defineComponent('hero', {
358
+ label: 'Hero',
359
+ version: 1,
360
+ fields: { title: field.text({ max: 80, required: true }), image: field.media() },
361
+ render: ({ values }) => <h1>{values.title}</h1>,
362
+ });
363
+ const Banner = defineComponent('banner', {
364
+ fields: { text: field.text(), tone: field.select(['info', 'warning']) },
365
+ render: ({ values }) => <p className={values.tone}>{values.text}</p>,
366
+ });
367
+
368
+ <VeroxmRegion name="home.top" components={[Hero, Banner]} fallback={{ component: 'hero', values: { title: 'Welcome' } }} />;
369
+ ```
370
+
371
+ - `<VeroxmRegion>` is a slot with one component field; import it from the same entry as your `<VeroxmSlot>`.
372
+ - Inside a slot with other fields: `field.component([Hero, Banner])`, rendered with `renderComponent(values.block, [Hero, Banner])`.
373
+ The value is typed as a union of the components.
374
+ - A value naming a component the code no longer registers shows the fallback; a component that throws shows `empty`
375
+ in its place (an error boundary, with a Suspense boundary so it also works during server rendering).
376
+ - Raise `version` when fields change in a way saved values don't fit; old values still render with the new fields.
377
+
328
378
  ## Errors
329
379
 
330
- Every failed request throws `VeroxmGraphQLError` (`.status`, `.errors` --
331
- the raw GraphQL errors array, useful for checking a specific
332
- `extensions.code` like `QUERY_TOO_COMPLEX` -- and a `.message` pulled from
333
- the first GraphQL error):
380
+ A request the API answers with an error throws `VeroxmGraphQLError`:
381
+ `.status`, `.errors` (the raw GraphQL errors array, useful for checking a
382
+ specific `extensions.code` like `QUERY_TOO_COMPLEX`), `.code` (the first
383
+ error's `extensions.code`, or the API's reason), `.body`, and a `.message`
384
+ pulled from the first GraphQL error or the API's own error text:
334
385
 
335
386
  ```ts
336
387
  import { VeroxmGraphQLError } from '@veroxm/react-sdk';
337
388
 
338
389
  const { error } = useEntries('posts');
339
- if (error instanceof VeroxmGraphQLError && error.errors[0]?.extensions?.code === 'QUERY_TOO_COMPLEX') {
390
+ if (error instanceof VeroxmGraphQLError && error.code === 'QUERY_TOO_COMPLEX') {
340
391
  // this query's filters/pagination need narrowing
341
392
  }
342
393
  ```
343
394
 
395
+ From 1.5, requests go through `@veroxm/sdk` (a dependency now, in place of
396
+ `graphql-request`), so `VeroxmGraphQLError` is also a `VeroXMApiError`: one
397
+ `instanceof VeroXMApiError` check covers both SDKs. Network errors, timeouts
398
+ (`VeroXMTimeoutError`) and cancels are thrown as they are.
399
+
400
+ ### Timeouts, retries and cancelling
401
+
402
+ ```tsx
403
+ <VeroxmProvider apiBase="https://your-veroxm-host" apiKey={apiKey} timeoutMs={8000} retries={2}>
404
+ ```
405
+
406
+ `timeoutMs` gives up on a request with `VeroXMTimeoutError`; `retries` (0 to
407
+ 5) repeats a query after a network error, a timeout, or 429, 502, 503 or
408
+ 504. A document with a mutation is never repeated. Both are off unless set,
409
+ and `new VeroxmClient({ ... })` takes them too. `client.request(document,
410
+ variables, { signal, timeoutMs })` cancels or limits a single call.
411
+
344
412
  ## Stability
345
413
 
346
414
  Follows semantic versioning. The site building blocks (charts, maps, sliders, video, menus, header and footer) are `@experimental` and can still change in a minor release. From 1.0, breaking changes come only in a major version, after at least one minor release with the
package/dist/client.d.ts CHANGED
@@ -1,6 +1,8 @@
1
- import { type Variables } from 'graphql-request';
1
+ import { type RequestControl } from '@veroxm/sdk';
2
2
  import { VeroxmCache, type CacheOptions } from './cache.js';
3
3
  import type { CollectionMeta, Entry, EntryConnection, EntriesQueryOptions, MediaView } from './types.js';
4
+ /** GraphQL variables: any object. */
5
+ type Variables = object;
4
6
  export interface VeroxmClientOptions {
5
7
  /** Your VeroXM deployment's origin, e.g. "https://cms.example.com" -- the client builds the full GraphQL endpoint (`/public/v2/graphql`) itself. */
6
8
  apiBase: string;
@@ -30,29 +32,42 @@ export interface VeroxmClientOptions {
30
32
  * person signs in or out.
31
33
  */
32
34
  getAccessToken?: () => Promise<string | null> | string | null;
35
+ /** Gives up on a request after this many milliseconds with @veroxm/sdk's `VeroXMTimeoutError`. Default: no limit. */
36
+ timeoutMs?: number;
37
+ /**
38
+ * Extra attempts (0 to 5) for a query after a network error, a timeout, or 429, 502, 503 or 504, waiting longer each
39
+ * time (or as long as the API's Retry-After asks, up to 10 s). A document with a mutation is never repeated. Default: 0.
40
+ */
41
+ retries?: number;
42
+ /** The fetch to send with (e.g. one adding Next.js cache options; '@veroxm/react-sdk/next' content helpers use this). Default: the global fetch. */
43
+ fetch?: typeof fetch;
33
44
  }
34
45
  /** @internal Lets tests see the warning again. */
35
46
  export declare function resetBrowserKeyWarning(): void;
36
47
  /**
37
- * Thin wrapper over graphql-request's GraphQLClient -- one method per
38
- * query this API exposes (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md
39
- * §5.1), plus request() as an escape hatch for a custom document. Every
40
- * hook in ./hooks reads one of these through useVeroxmClient() rather
41
- * than talking to GraphQLClient directly, so this class is the one place
48
+ * One method per GraphQL query this API exposes
49
+ * (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md §5.1), plus request() as
50
+ * an escape hatch for a custom document, all sent with @veroxm/sdk's
51
+ * graphqlRequest (from 1.5; before, graphql-request). Every hook in
52
+ * ./hooks reads one of these through useVeroxmClient(), so this class is the one place
42
53
  * request-shaping logic lives -- and it's usable on its own outside
43
54
  * React too (see §5.5's SSR helpers in a later phase, which will build
44
55
  * on this same class).
45
56
  */
46
57
  export declare class VeroxmClient {
47
- private readonly gql;
58
+ private readonly apiBase;
59
+ private readonly apiKey;
60
+ private readonly timeoutMs;
61
+ private readonly retries;
62
+ private readonly fetchImpl;
48
63
  /** Echoes VeroxmClientOptions.projectUuid, if one was given -- see that field's own comment. */
49
64
  readonly projectUuid: string | undefined;
50
65
  /** This client's request cache -- read directly by every hook in ./hooks (via useVeroxmClient()) and by the SSR helpers in ./ssr.ts, so a server fetch and a client-side hook agree on exactly one cache instance per VeroxmClient. Call cache.invalidateCollection()/invalidateMedia()/invalidateAll() yourself once you know content changed -- see VeroxmCache's own doc comment for why this API is queries-only and has no auto-invalidation. */
51
66
  readonly cache: VeroxmCache;
52
67
  private readonly getAccessToken?;
53
68
  constructor(options: VeroxmClientOptions);
54
- /** Escape hatch for a custom GraphQL document against this same authenticated endpoint -- e.g. a query that only needs a subset of an object's fields, or combines more than one of this class's own queries into a single round trip. Errors are normalized the same way as every typed method below (see VeroxmGraphQLError). */
55
- request<T = unknown>(document: string, variables?: Variables): Promise<T>;
69
+ /** Escape hatch for a custom GraphQL document against this same authenticated endpoint -- e.g. a query that only needs a subset of an object's fields, or combines more than one of this class's own queries into a single round trip. Errors are normalized the same way as every typed method below (see VeroxmGraphQLError). `control` takes a `signal` to cancel and its own `timeoutMs`. */
70
+ request<T = unknown>(document: string, variables?: Variables, control?: RequestControl): Promise<T>;
56
71
  /** A collection's field list. `null` means no collection with that slug exists on this project. */
57
72
  getCollection(slug: string): Promise<CollectionMeta | null>;
58
73
  /** Every collection defined on this project. */
@@ -73,3 +88,4 @@ export declare class VeroxmClient {
73
88
  /** A single media item by id. `null` means no media with that id exists on this project. */
74
89
  getMedia(id: number): Promise<MediaView | null>;
75
90
  }
91
+ export {};
package/dist/client.js CHANGED
@@ -1,4 +1,4 @@
1
- import { GraphQLClient } from 'graphql-request';
1
+ import { graphqlRequest } from '@veroxm/sdk';
2
2
  import { VeroxmCache } from './cache.js';
3
3
  import { VeroxmGraphQLError } from './errors.js';
4
4
  const COLLECTION_FIELDS = `slug name description fields { name label type }`;
@@ -40,11 +40,11 @@ export function resetBrowserKeyWarning() {
40
40
  warnedBrowserKey = false;
41
41
  }
42
42
  /**
43
- * Thin wrapper over graphql-request's GraphQLClient -- one method per
44
- * query this API exposes (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md
45
- * §5.1), plus request() as an escape hatch for a custom document. Every
46
- * hook in ./hooks reads one of these through useVeroxmClient() rather
47
- * than talking to GraphQLClient directly, so this class is the one place
43
+ * One method per GraphQL query this API exposes
44
+ * (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md §5.1), plus request() as
45
+ * an escape hatch for a custom document, all sent with @veroxm/sdk's
46
+ * graphqlRequest (from 1.5; before, graphql-request). Every hook in
47
+ * ./hooks reads one of these through useVeroxmClient(), so this class is the one place
48
48
  * request-shaping logic lives -- and it's usable on its own outside
49
49
  * React too (see §5.5's SSR helpers in a later phase, which will build
50
50
  * on this same class).
@@ -52,20 +52,31 @@ export function resetBrowserKeyWarning() {
52
52
  export class VeroxmClient {
53
53
  constructor(options) {
54
54
  this.getAccessToken = options.getAccessToken;
55
- const endpoint = `${options.apiBase.replace(/\/$/, '')}/public/v2/graphql`;
56
- this.gql = new GraphQLClient(endpoint, {
57
- headers: { Authorization: `Bearer ${options.apiKey}` },
58
- });
55
+ this.apiBase = options.apiBase;
56
+ this.apiKey = options.apiKey;
57
+ this.timeoutMs = options.timeoutMs;
58
+ this.retries = options.retries;
59
+ this.fetchImpl = options.fetch;
59
60
  this.projectUuid = options.projectUuid;
60
61
  this.cache = new VeroxmCache(options.cache);
61
62
  if (options.apiKey)
62
63
  warnIfBrowserKey();
63
64
  }
64
- /** Escape hatch for a custom GraphQL document against this same authenticated endpoint -- e.g. a query that only needs a subset of an object's fields, or combines more than one of this class's own queries into a single round trip. Errors are normalized the same way as every typed method below (see VeroxmGraphQLError). */
65
- async request(document, variables) {
65
+ /** Escape hatch for a custom GraphQL document against this same authenticated endpoint -- e.g. a query that only needs a subset of an object's fields, or combines more than one of this class's own queries into a single round trip. Errors are normalized the same way as every typed method below (see VeroxmGraphQLError). `control` takes a `signal` to cancel and its own `timeoutMs`. */
66
+ async request(document, variables, control = {}) {
66
67
  try {
67
- const token = this.getAccessToken ? await this.getAccessToken() : null;
68
- return token ? await this.gql.request(document, variables, { Authorization: `Bearer ${token}` }) : await this.gql.request(document, variables);
68
+ const token = (this.getAccessToken ? await this.getAccessToken() : null) || this.apiKey;
69
+ // Sent through @veroxm/sdk, so both SDKs share one transport: timeouts, retries, cancelling and error types.
70
+ return await graphqlRequest({
71
+ baseUrl: this.apiBase,
72
+ token,
73
+ query: document,
74
+ variables,
75
+ signal: control.signal,
76
+ timeoutMs: control.timeoutMs ?? this.timeoutMs,
77
+ retries: this.retries,
78
+ fetch: this.fetchImpl,
79
+ });
69
80
  }
70
81
  catch (cause) {
71
82
  throw VeroxmGraphQLError.from(cause);
@@ -0,0 +1,25 @@
1
+ import { Component, type ErrorInfo, type ReactNode } from 'react';
2
+ interface Props {
3
+ /** The registered component's name, for the diagnostic. */
4
+ component: string;
5
+ /** Shown instead when the component throws while rendering (default: nothing). */
6
+ fallback?: ReactNode;
7
+ children?: ReactNode;
8
+ }
9
+ /**
10
+ * Keeps a registered component that throws while rendering from taking the rest of the page down: it shows
11
+ * `fallback` (or nothing) in its place and logs which component failed. Used by renderComponent / <VeroxmRegion>.
12
+ */
13
+ export declare class VeroxmComponentBoundary extends Component<Props, {
14
+ failed: boolean;
15
+ }> {
16
+ state: {
17
+ failed: boolean;
18
+ };
19
+ static getDerivedStateFromError(): {
20
+ failed: boolean;
21
+ };
22
+ componentDidCatch(error: Error, info: ErrorInfo): void;
23
+ render(): ReactNode;
24
+ }
25
+ export {};
@@ -0,0 +1,21 @@
1
+ 'use client';
2
+ import { Component } from 'react';
3
+ /**
4
+ * Keeps a registered component that throws while rendering from taking the rest of the page down: it shows
5
+ * `fallback` (or nothing) in its place and logs which component failed. Used by renderComponent / <VeroxmRegion>.
6
+ */
7
+ export class VeroxmComponentBoundary extends Component {
8
+ constructor() {
9
+ super(...arguments);
10
+ this.state = { failed: false };
11
+ }
12
+ static getDerivedStateFromError() {
13
+ return { failed: true };
14
+ }
15
+ componentDidCatch(error, info) {
16
+ console.error(`[veroxm] component "${this.props.component}" failed to render; showing its fallback.`, error, info.componentStack ?? '');
17
+ }
18
+ render() {
19
+ return this.state.failed ? (this.props.fallback ?? null) : this.props.children;
20
+ }
21
+ }
@@ -0,0 +1,52 @@
1
+ import { type ReactNode } from 'react';
2
+ import { type LoadSlotOptions, type RegisteredComponent, type SlotFieldDefs, type SlotInfo, type SlotValues, type VeroxmSlotProps } from './slots-core.js';
3
+ export interface RenderComponentOptions {
4
+ /** Shown when there's no value, the value names a component the code doesn't register, or the component throws. */
5
+ fallback?: ReactNode;
6
+ }
7
+ /**
8
+ * Renders a component field's value with the registered component it names, inside an error boundary. A value for a
9
+ * component the code no longer registers renders `fallback` (and warns once in development); values saved for an
10
+ * older version of the component still render, with the fields the current version has (and a warning).
11
+ */
12
+ export declare function renderComponent(value: {
13
+ component: string;
14
+ version: number | null;
15
+ values: Record<string, unknown>;
16
+ } | null | undefined, components: readonly RegisteredComponent[], options?: RenderComponentOptions): ReactNode;
17
+ /** The one field a region's slot has. */
18
+ export declare const REGION_FIELD = "component";
19
+ /** One of the components with (some of) its values, e.g. `{ component: 'hero', values: { title: 'Welcome' } }`. */
20
+ export type RegionFallback<L extends readonly RegisteredComponent[]> = {
21
+ [C in L[number] as C['name']]: {
22
+ component: C['name'];
23
+ values: Partial<SlotValues<C['fields']>>;
24
+ };
25
+ }[L[number]['name']];
26
+ export interface VeroxmRegionProps<L extends readonly RegisteredComponent[]> extends Omit<LoadSlotOptions<SlotFieldDefs>, 'fields' | 'fallback'> {
27
+ /** The slot's name, as for <VeroxmSlot>. */
28
+ name: string;
29
+ /** The components a marketer may choose from here. */
30
+ components: L;
31
+ /** What shows before anything is published: one of `components` with its values. */
32
+ fallback?: RegionFallback<L>;
33
+ /** Shown when there is nothing to show, or the chosen component throws while rendering. */
34
+ empty?: ReactNode;
35
+ /** Wraps the rendered component, e.g. to mark the region for the on-page editor: `(node, slot) => <div {...slot.edit('component')}>{node}</div>`. */
36
+ wrap?: (node: ReactNode, slot: SlotInfo) => ReactNode;
37
+ }
38
+ /**
39
+ * The <VeroxmSlot> props for a region: a slot with one component field. Each entry point's <VeroxmRegion> passes them
40
+ * to its own <VeroxmSlot>, so a region gets that entry's caching, A/B tests, personalisation and on-page editing.
41
+ */
42
+ export declare function regionSlotProps<L extends readonly RegisteredComponent[]>(props: VeroxmRegionProps<L>): VeroxmSlotProps<SlotFieldDefs>;
43
+ /**
44
+ * A place on the page where a marketer chooses which of your registered components shows, and fills in its fields
45
+ * (a slot with one component field). Server Component; in Next.js import it from '@veroxm/react-sdk/next' (or
46
+ * '/next/cache-components') for on-page editing, tests and caching.
47
+ *
48
+ * ```tsx
49
+ * <VeroxmRegion name="home.top" components={[Hero, Banner]} fallback={{ component: 'hero', values: { title: 'Welcome' } }} />
50
+ * ```
51
+ */
52
+ export declare function VeroxmRegion<const L extends readonly RegisteredComponent[]>(props: VeroxmRegionProps<L>): Promise<ReactNode>;
@@ -0,0 +1,73 @@
1
+ import { Suspense, createElement } from 'react';
2
+ import { VeroxmComponentBoundary } from './component-boundary.js';
3
+ import { VeroxmSlot, field } from './slots-core.js';
4
+ // Registered components (Step 4 of the product roadmap): developers register components and the fields marketers may
5
+ // set; marketers choose one for a place on the page in VeroXM; the page renders it with the registered code. Server-
6
+ // safe: no hooks here (the error boundary is its own client module), so Server Components can use all of it.
7
+ const warned = new Set();
8
+ function development() {
9
+ try {
10
+ return process.env.NODE_ENV !== 'production';
11
+ }
12
+ catch {
13
+ return true;
14
+ }
15
+ }
16
+ function diagnose(key, message) {
17
+ if (!development() || warned.has(key))
18
+ return;
19
+ warned.add(key);
20
+ console.warn(`[veroxm] ${message}`);
21
+ }
22
+ /**
23
+ * Renders a component field's value with the registered component it names, inside an error boundary. A value for a
24
+ * component the code no longer registers renders `fallback` (and warns once in development); values saved for an
25
+ * older version of the component still render, with the fields the current version has (and a warning).
26
+ */
27
+ export function renderComponent(value, components, options = {}) {
28
+ if (!value)
29
+ return options.fallback ?? null;
30
+ const registered = components.find((c) => c.name === value.component);
31
+ if (!registered) {
32
+ diagnose(`missing:${value.component}`, `component "${value.component}" isn't registered here; showing the fallback. Register it with defineComponent and pass it in \`components\`.`);
33
+ return options.fallback ?? null;
34
+ }
35
+ if (value.version !== null && value.version !== registered.version) {
36
+ diagnose(`version:${value.component}:${value.version}`, `component "${value.component}" was saved for version ${value.version}; the code registers version ${registered.version}. Fields the new version doesn't have are left out; fields it adds show their empty value until they are filled in.`);
37
+ }
38
+ // The Suspense boundary matters for server rendering: an error thrown while a Server Component page is rendered to
39
+ // HTML isn't caught by an error boundary, but inside Suspense it moves that part to the browser, where
40
+ // VeroxmComponentBoundary catches it. It also lets an async (data-loading) component stream in.
41
+ return createElement(VeroxmComponentBoundary, { component: registered.name, fallback: options.fallback }, createElement(Suspense, { fallback: options.fallback ?? null }, createElement(registered.render, { values: value.values })));
42
+ }
43
+ /** The one field a region's slot has. */
44
+ export const REGION_FIELD = 'component';
45
+ /**
46
+ * The <VeroxmSlot> props for a region: a slot with one component field. Each entry point's <VeroxmRegion> passes them
47
+ * to its own <VeroxmSlot>, so a region gets that entry's caching, A/B tests, personalisation and on-page editing.
48
+ */
49
+ export function regionSlotProps(props) {
50
+ const { components, fallback, empty, wrap, ...slot } = props;
51
+ const fields = { [REGION_FIELD]: field.component(components, { label: slot.label }) };
52
+ return {
53
+ ...slot,
54
+ fields,
55
+ fallback: (fallback ? { [REGION_FIELD]: { version: null, ...fallback } } : undefined),
56
+ children: (values, info) => {
57
+ const node = renderComponent(values[REGION_FIELD], components, { fallback: empty });
58
+ return wrap ? wrap(node, info) : node;
59
+ },
60
+ };
61
+ }
62
+ /**
63
+ * A place on the page where a marketer chooses which of your registered components shows, and fills in its fields
64
+ * (a slot with one component field). Server Component; in Next.js import it from '@veroxm/react-sdk/next' (or
65
+ * '/next/cache-components') for on-page editing, tests and caching.
66
+ *
67
+ * ```tsx
68
+ * <VeroxmRegion name="home.top" components={[Hero, Banner]} fallback={{ component: 'hero', values: { title: 'Welcome' } }} />
69
+ * ```
70
+ */
71
+ export function VeroxmRegion(props) {
72
+ return VeroxmSlot(regionSlotProps(props));
73
+ }
@@ -6,6 +6,8 @@ export interface EditorHandlerHooks {
6
6
  exit?(): Promise<void> | void;
7
7
  /** After a publish succeeds (e.g. revalidate cached reads). */
8
8
  published?(): void;
9
+ /** After a signed content webhook (e.g. revalidate cached content reads). */
10
+ contentChanged?(event: string): void;
9
11
  /** Serve GET published?names= with the server key. Default false. */
10
12
  servePublished?: boolean;
11
13
  }
@@ -13,4 +15,6 @@ export type EditorHandler = (request: Request, segments?: string[]) => Promise<R
13
15
  export declare function json(body: unknown, status?: number, cache?: string): Response;
14
16
  /** The path segments after /api/veroxm/ in a request URL. */
15
17
  export declare function segmentsOf(request: Request): string[];
18
+ /** Whether `signature` (hex) is the HMAC-SHA256 of `body` with `secret`, compared in constant time. Web Crypto, so any runtime. */
19
+ export declare function validSignature(secret: string, body: string, signature: string): Promise<boolean>;
16
20
  export declare function createEditorHandler(hooks?: EditorHandlerHooks): EditorHandler;
@@ -29,12 +29,39 @@ export function segmentsOf(request) {
29
29
  const i = path.indexOf(`${ROUTE_BASE}/`);
30
30
  return i === -1 ? [] : path.slice(i + ROUTE_BASE.length + 1).split('/').filter(Boolean).map(decodeURIComponent);
31
31
  }
32
+ /** How old a signed webhook may be (VeroXM signs `sentAt` with the body). */
33
+ const WEBHOOK_MAX_AGE_MS = 5 * 60000;
34
+ /** Whether `signature` (hex) is the HMAC-SHA256 of `body` with `secret`, compared in constant time. Web Crypto, so any runtime. */
35
+ export async function validSignature(secret, body, signature) {
36
+ if (!/^[0-9a-f]{64}$/i.test(signature))
37
+ return false;
38
+ const enc = new TextEncoder();
39
+ const key = await crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
40
+ const mac = new Uint8Array(await crypto.subtle.sign('HMAC', key, enc.encode(body)));
41
+ const expected = Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');
42
+ let diff = 0;
43
+ const given = signature.toLowerCase();
44
+ for (let i = 0; i < expected.length; i++)
45
+ diff |= expected.charCodeAt(i) ^ given.charCodeAt(i);
46
+ return diff === 0;
47
+ }
32
48
  /** At most this many purge confirmations per minute (a flood of fake pings can't turn into a flood of API calls). */
33
49
  const MAX_PURGE_CHECKS_PER_MINUTE = 30;
34
50
  export function createEditorHandler(hooks = {}) {
35
51
  const purgeChecks = [];
36
52
  async function revalidate(request) {
37
- const body = (await request.json().catch(() => null));
53
+ const raw = await request.text().catch(() => '');
54
+ const signature = request.headers.get('x-veroxm-signature');
55
+ if (signature !== null)
56
+ return contentWebhook(raw, signature);
57
+ const body = (() => {
58
+ try {
59
+ return JSON.parse(raw);
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ })();
38
65
  const id = typeof body?.id === 'string' ? body.id : '';
39
66
  if (!/^[A-Za-z0-9_-]{24}$/.test(id))
40
67
  return json({ error: 'Bad request' }, 400);
@@ -62,6 +89,30 @@ export function createEditorHandler(hooks = {}) {
62
89
  hooks.published?.();
63
90
  return json({ revalidated: true, slots: Array.isArray(slots) ? slots : [] });
64
91
  }
92
+ /** A project webhook (Settings > Webhooks) pointed at /api/veroxm/revalidate: content changed, so refresh content reads. */
93
+ async function contentWebhook(raw, signature) {
94
+ const secret = resolveSlotsConfig().webhookSecret;
95
+ if (!secret || !hooks.contentChanged)
96
+ return json({ error: 'Not configured' }, 404);
97
+ if (!(await validSignature(secret, raw, signature)))
98
+ return json({ error: 'Bad signature' }, 401);
99
+ let body;
100
+ try {
101
+ body = JSON.parse(raw);
102
+ }
103
+ catch {
104
+ return json({ error: 'Bad request' }, 400);
105
+ }
106
+ const sentAt = typeof body?.sentAt === 'string' ? Date.parse(body.sentAt) : NaN;
107
+ // A signed body replayed later is refused: VeroXM signs the time it sent it.
108
+ if (!Number.isFinite(sentAt) || Math.abs(Date.now() - sentAt) > WEBHOOK_MAX_AGE_MS)
109
+ return json({ error: 'Too old' }, 401);
110
+ const event = typeof body?.event === 'string' ? body.event : '';
111
+ if (!event.startsWith('content.'))
112
+ return json({ revalidated: false, ignored: event });
113
+ hooks.contentChanged(event);
114
+ return json({ revalidated: true, event });
115
+ }
65
116
  const isEditing = async (request) => hooks.isEditing ? hooks.isEditing(request) : Boolean(readCookie(request.headers.get('cookie'), EDITOR_COOKIE));
66
117
  async function relay(request, path, method) {
67
118
  const url = new URL(request.url);
@@ -9,6 +9,9 @@ import { parseVideoUrl } from '../site/video.js';
9
9
  import { parseMapLink } from '../site/map-math.js';
10
10
  import { CHART_KINDS, chartTableText, parseChartTable } from '../site/chart.js';
11
11
  import { canEditInline, startInlineEdit } from './inline.js';
12
+ function asComponentValue(v) {
13
+ return v && typeof v === 'object' && !Array.isArray(v) && typeof v.component === 'string' ? v : null;
14
+ }
12
15
  const TEST_STATUS = {
13
16
  draft: 'Test draft',
14
17
  pending_approval: 'Test waiting for approval',
@@ -68,6 +71,12 @@ function toPayload(fields, values) {
68
71
  out[name] = v && typeof v === 'object' ? { id: v.id } : null;
69
72
  else if (def.type === 'slides' && Array.isArray(v))
70
73
  out[name] = v.map((sl) => ({ ...sl, image: sl.image ? { id: sl.image.id } : null }));
74
+ else if (def.type === 'component') {
75
+ // A component's own values are stored the same way (media as { id }).
76
+ const c = asComponentValue(v);
77
+ const schema = c ? def.components?.[c.component] : undefined;
78
+ out[name] = c && schema ? { component: c.component, version: schema.version, values: toPayload(schema.fields, c.values ?? {}) } : null;
79
+ }
71
80
  else
72
81
  out[name] = v;
73
82
  }
@@ -668,8 +677,37 @@ function FieldInput({ name, def, value, shown, onChange, onFocus, }) {
668
677
  return _jsx(SlidesInput, { name: name, def: def, value: value, onChange: onChange, onFocus: onFocus });
669
678
  case 'menu':
670
679
  return _jsx(MenuInput, { name: name, label: def.label ?? name, required: def.required, depth: def.depth ?? 2, value: value, onChange: onChange, onFocus: onFocus });
680
+ case 'component':
681
+ return _jsx(ComponentInput, { name: name, def: def, value: value, onChange: onChange, onFocus: onFocus });
671
682
  }
672
683
  }
684
+ /**
685
+ * A component field: choose one of the components the developer registered for this place, then fill in that
686
+ * component's own fields. Switching components keeps what was typed into fields both have (same name and type).
687
+ */
688
+ function ComponentInput({ name, def, value, onChange, onFocus }) {
689
+ const id = useId();
690
+ const components = def.components ?? {};
691
+ const current = asComponentValue(value);
692
+ const chosen = current && components[current.component] ? current : null;
693
+ const schema = chosen ? components[chosen.component] : null;
694
+ const pick = (next) => {
695
+ if (!next)
696
+ return onChange(null);
697
+ const target = components[next];
698
+ const carried = {};
699
+ if (chosen && schema) {
700
+ for (const [f, d] of Object.entries(target.fields)) {
701
+ if (schema.fields[f]?.type === d.type && chosen.values?.[f] !== undefined)
702
+ carried[f] = chosen.values[f];
703
+ }
704
+ }
705
+ onChange({ component: next, version: target.version, values: carried });
706
+ };
707
+ return (_jsxs("fieldset", { className: "vx-field vx-fieldset", children: [_jsxs("legend", { className: "vx-label", children: [def.label ?? name, def.required ? _jsx("span", { "aria-hidden": "true", children: " *" }) : null] }), _jsx("label", { htmlFor: id, className: "vx-sublabel", children: "Component" }), _jsxs("select", { id: id, "data-field": name, onFocus: onFocus, value: chosen?.component ?? '', onChange: (e) => pick(e.target.value), children: [_jsx("option", { value: "", children: def.required ? 'Choose a component' : 'None (the site’s default)' }), Object.entries(components).map(([n, c]) => (_jsx("option", { value: n, children: c.label ?? n }, n)))] }), chosen && schema
708
+ ? Object.entries(schema.fields).map(([f, d]) => (_jsx(FieldInput, { name: `${name}.${f}`, def: d, value: chosen.values?.[f], onChange: (v) => onChange({ ...chosen, version: schema.version, values: { ...(chosen.values ?? {}), [f]: v } }), onFocus: onFocus }, `${chosen.component}.${f}`)))
709
+ : null] }));
710
+ }
673
711
  function VideoInput({ name, def, value, onChange, onFocus }) {
674
712
  const id = useId();
675
713
  const video = (value && typeof value === 'object' ? value : { url: typeof value === 'string' ? value : '' });
package/dist/errors.d.ts CHANGED
@@ -1,20 +1,19 @@
1
+ import { VeroXMGraphQLError } from '@veroxm/sdk';
1
2
  /**
2
- * Thrown for any GraphQL error response (a non-2xx HTTP status, or a 2xx
3
- * response whose `errors` array is non-empty) -- wraps graphql-request's
4
- * own ClientError with a message pulled from the first GraphQL error, the
5
- * same "surface the server's own message, don't just say 'request
6
- * failed'" convention @veroxm/sdk's VeroXMApiError follows (see
7
- * packages/sdk-js/src/errors.ts).
3
+ * Thrown for any failed GraphQL response: a 2xx response whose `errors` array is non-empty, or a non-2xx status. The
4
+ * message is the first GraphQL error's (or the API's own error text), the same "surface the server's own message"
5
+ * convention as @veroxm/sdk.
6
+ *
7
+ * From 1.5 this is a subclass of @veroxm/sdk's `VeroXMGraphQLError` (and so of `VeroXMApiError`): it also has `body`
8
+ * and `code` (the first error's `extensions.code`, or the API's reason), and one `instanceof VeroXMApiError` check covers
9
+ * errors from both SDKs. Network errors, timeouts (`VeroXMTimeoutError`) and cancels are not wrapped.
8
10
  */
9
- export declare class VeroxmGraphQLError extends Error {
10
- /** The raw GraphQL errors array from the response, if any -- inspect this for a specific error's `extensions.code` (e.g. `QUERY_TOO_COMPLEX`, see apps/api/src/public-api/graphql/complexity.plugin.ts). */
11
- readonly errors: readonly {
12
- message: string;
13
- extensions?: Record<string, unknown>;
14
- }[];
15
- /** The HTTP status of the underlying response, when available. */
16
- readonly status: number | undefined;
11
+ export declare class VeroxmGraphQLError extends VeroXMGraphQLError {
17
12
  private constructor();
18
- /** Wraps whatever graphql-request's client.request() threw -- a ClientError for a GraphQL-level failure, or rethrows anything else (a network error, say) unchanged so it isn't misreported as a GraphQL error. */
13
+ /**
14
+ * Wraps what a GraphQL request rejected with: an API answer (`VeroXMApiError`, including `VeroXMGraphQLError`) becomes
15
+ * a VeroxmGraphQLError; anything else (a network error, a timeout, a cancel) is returned unchanged so it isn't
16
+ * misreported as a GraphQL error, and a thrown non-Error becomes a plain Error.
17
+ */
19
18
  static from(cause: unknown): Error;
20
19
  }