@veroxm/react-sdk 1.3.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +99 -5
  3. package/dist/auth.js +1 -0
  4. package/dist/client.d.ts +27 -9
  5. package/dist/client.js +62 -14
  6. package/dist/component-boundary.d.ts +25 -0
  7. package/dist/component-boundary.js +21 -0
  8. package/dist/components.d.ts +52 -0
  9. package/dist/components.js +73 -0
  10. package/dist/editor/handler.d.ts +4 -0
  11. package/dist/editor/handler.js +52 -1
  12. package/dist/editor/overlay.d.ts +5 -0
  13. package/dist/editor/overlay.js +59 -0
  14. package/dist/errors.d.ts +14 -15
  15. package/dist/errors.js +27 -17
  16. package/dist/hooks/use-cached-query.js +1 -0
  17. package/dist/hooks/use-collection.js +1 -0
  18. package/dist/hooks/use-entries.js +1 -0
  19. package/dist/hooks/use-entry.js +1 -0
  20. package/dist/hooks/use-media.js +1 -0
  21. package/dist/hydration-boundary.js +1 -0
  22. package/dist/index.d.ts +5 -0
  23. package/dist/index.js +4 -0
  24. package/dist/next/cache-components.d.ts +12 -1
  25. package/dist/next/cache-components.js +11 -0
  26. package/dist/next/content-cached.d.ts +12 -0
  27. package/dist/next/content-cached.js +61 -0
  28. package/dist/next/content-core.d.ts +27 -0
  29. package/dist/next/content-core.js +39 -0
  30. package/dist/next/content.d.ts +19 -0
  31. package/dist/next/content.js +57 -0
  32. package/dist/next/index.d.ts +9 -0
  33. package/dist/next/index.js +8 -0
  34. package/dist/next/region.d.ts +8 -0
  35. package/dist/next/region.js +9 -0
  36. package/dist/next/route.js +3 -0
  37. package/dist/preview.js +1 -0
  38. package/dist/provider.d.ts +5 -1
  39. package/dist/provider.js +9 -4
  40. package/dist/slots-core.d.ts +75 -1
  41. package/dist/slots-core.js +59 -1
  42. package/dist/slots.d.ts +2 -12
  43. package/dist/slots.js +4 -28
  44. package/dist/tracking.js +1 -0
  45. package/dist/use-slot.d.ts +12 -0
  46. package/dist/use-slot.js +28 -0
  47. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
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
+
27
+ ## 1.4.0
28
+
29
+ - The providers and hooks are `'use client'` modules: `VeroxmProvider`, `VeroxmPreviewProvider`, `VeroxmAuthProvider`,
30
+ `VeroxmTrackerProvider`, `VeroxmHydrationBoundary`, `useSlot` and the content hooks. A Server Component can import the
31
+ package root and render the providers directly with plain props; before, it had to wrap them in its own client
32
+ component. `useSlot` moved to its own module; it's still exported from the same places.
33
+ - A `VeroxmClient` created in a browser with an API key logs a warning once, outside production builds: the key is in
34
+ the page, and a key that reads content can read drafts too. See "Keys in the browser" in the README.
35
+
3
36
  ## 1.3.0
4
37
 
5
38
  - `<VeroxmForm lang="fr" />`: show the form in one of its languages (otherwise the visitor's browser language decides).
package/README.md CHANGED
@@ -62,6 +62,32 @@ the dashboard) -- it's the request's only source of project identity, so
62
62
  unlike the REST v2 API there's no separate project uuid to pass on every
63
63
  call.
64
64
 
65
+ ### Keys in the browser
66
+
67
+ The hooks read in the browser, so the key you give `<VeroxmProvider>` is in
68
+ the page: anyone can copy it and use it from anywhere, including to read
69
+ unpublished drafts. Outside production builds, a `VeroxmClient` created in a
70
+ browser with a key logs a warning once (from 1.4).
71
+
72
+ - In the App Router, read on the server where you can: a Server Component
73
+ with its own `VeroxmClient`, or the SSR helpers with
74
+ `<VeroxmHydrationBoundary>` (below). Keep the key in a server-only
75
+ environment variable (not `NEXT_PUBLIC_`).
76
+ - If a page does need the hooks in the browser, give it a key with only the
77
+ `read` ability, never `*`, so a copied key can't create, change or
78
+ delete content.
79
+
80
+ ### Server and client components
81
+
82
+ From 1.4 the providers and hooks are `'use client'` modules, and the package
83
+ root can be imported from a Server Component. A Server Component can render
84
+ `<VeroxmProvider>`, `<VeroxmPreviewProvider>`, `<VeroxmAuthProvider>`,
85
+ `<VeroxmTrackerProvider>` and `<VeroxmHydrationBoundary>` directly when their
86
+ props are plain values (strings, booleans, data). Objects such as a
87
+ `VeroxmClient` or a tracker, and render props such as `<Experience>`'s
88
+ children, can't cross from server to client: create and use those inside a
89
+ client component.
90
+
65
91
  ## Core hooks
66
92
 
67
93
  - **`useCollection(slug)`** -- a collection's field list. Build dynamic
@@ -157,6 +183,26 @@ preview one specific unpublished entry, use `useEntries()` with
157
183
  mounted (`isDraftMode: false`, so an app that never uses preview mode
158
184
  doesn't need to wrap anything).
159
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
+
160
206
  ## SSR / Next.js helpers
161
207
 
162
208
  Framework-agnostic fetch functions -- no hooks, safe to call from a Server
@@ -299,22 +345,70 @@ function ArticlePage({ article }: { article: Article }) {
299
345
  }
300
346
  ```
301
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
+
302
378
  ## Errors
303
379
 
304
- Every failed request throws `VeroxmGraphQLError` (`.status`, `.errors` --
305
- the raw GraphQL errors array, useful for checking a specific
306
- `extensions.code` like `QUERY_TOO_COMPLEX` -- and a `.message` pulled from
307
- 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:
308
385
 
309
386
  ```ts
310
387
  import { VeroxmGraphQLError } from '@veroxm/react-sdk';
311
388
 
312
389
  const { error } = useEntries('posts');
313
- if (error instanceof VeroxmGraphQLError && error.errors[0]?.extensions?.code === 'QUERY_TOO_COMPLEX') {
390
+ if (error instanceof VeroxmGraphQLError && error.code === 'QUERY_TOO_COMPLEX') {
314
391
  // this query's filters/pagination need narrowing
315
392
  }
316
393
  ```
317
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
+
318
412
  ## Stability
319
413
 
320
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/auth.js CHANGED
@@ -1,3 +1,4 @@
1
+ 'use client';
1
2
  import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
3
  import { createContext, useContext, useEffect, useState } from 'react';
3
4
  const AuthContext = createContext(null);
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,27 +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
  }
45
+ /** @internal Lets tests see the warning again. */
46
+ export declare function resetBrowserKeyWarning(): void;
34
47
  /**
35
- * Thin wrapper over graphql-request's GraphQLClient -- one method per
36
- * query this API exposes (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md
37
- * §5.1), plus request() as an escape hatch for a custom document. Every
38
- * hook in ./hooks reads one of these through useVeroxmClient() rather
39
- * 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
40
53
  * request-shaping logic lives -- and it's usable on its own outside
41
54
  * React too (see §5.5's SSR helpers in a later phase, which will build
42
55
  * on this same class).
43
56
  */
44
57
  export declare class VeroxmClient {
45
- private readonly gql;
58
+ private readonly apiBase;
59
+ private readonly apiKey;
60
+ private readonly timeoutMs;
61
+ private readonly retries;
62
+ private readonly fetchImpl;
46
63
  /** Echoes VeroxmClientOptions.projectUuid, if one was given -- see that field's own comment. */
47
64
  readonly projectUuid: string | undefined;
48
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. */
49
66
  readonly cache: VeroxmCache;
50
67
  private readonly getAccessToken?;
51
68
  constructor(options: VeroxmClientOptions);
52
- /** 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). */
53
- 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>;
54
71
  /** A collection's field list. `null` means no collection with that slug exists on this project. */
55
72
  getCollection(slug: string): Promise<CollectionMeta | null>;
56
73
  /** Every collection defined on this project. */
@@ -71,3 +88,4 @@ export declare class VeroxmClient {
71
88
  /** A single media item by id. `null` means no media with that id exists on this project. */
72
89
  getMedia(id: number): Promise<MediaView | null>;
73
90
  }
91
+ export {};
package/dist/client.js CHANGED
@@ -1,15 +1,50 @@
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 }`;
5
5
  const ENTRY_FIELDS = `id locale createdAt updatedAt publishedAt data`;
6
6
  const MEDIA_FIELDS = `id fileName fullUrl thumbUrl thumbWebpUrl fullWebpUrl caption tags size width height focalPoint { x y } hotspots { id x y label url }`;
7
+ let warnedBrowserKey = false;
7
8
  /**
8
- * Thin wrapper over graphql-request's GraphQLClient -- one method per
9
- * query this API exposes (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md
10
- * §5.1), plus request() as an escape hatch for a custom document. Every
11
- * hook in ./hooks reads one of these through useVeroxmClient() rather
12
- * than talking to GraphQLClient directly, so this class is the one place
9
+ * Written as the exact `process.env.NODE_ENV` so bundlers (Next.js, Vite, webpack) replace it with a literal; a
10
+ * browser with no `process` at all lands in the catch.
11
+ */
12
+ function isProductionBuild() {
13
+ try {
14
+ return process.env.NODE_ENV === 'production';
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ }
20
+ /**
21
+ * Development-only: a VeroxmClient made in a browser carries its API key in the page. Reading content needs a key with
22
+ * `read`, which VeroXM treats as a server key (apps/api/src/public-api/key-kind.ts): anyone can copy it from the
23
+ * page, use it from anywhere, and read unpublished drafts with it. Silent in production builds and on servers; once
24
+ * per page load.
25
+ */
26
+ function warnIfBrowserKey() {
27
+ if (warnedBrowserKey || typeof window === 'undefined' || typeof document === 'undefined')
28
+ return;
29
+ if (isProductionBuild())
30
+ return;
31
+ warnedBrowserKey = true;
32
+ console.warn('[veroxm] A VeroxmClient was created in the browser with an API key (for example <VeroxmProvider apiKey=...>). ' +
33
+ 'Anyone who opens the page can copy that key and use it from anywhere, including to read unpublished drafts. ' +
34
+ 'Read content on the server instead (Server Components, or the fetch helpers with <VeroxmHydrationBoundary>), ' +
35
+ 'and keep the key in a server-only environment variable, not NEXT_PUBLIC_. This warning only appears outside ' +
36
+ 'production builds. https://docs.veroxm.com/platform-tools/react-sdk#keys');
37
+ }
38
+ /** @internal Lets tests see the warning again. */
39
+ export function resetBrowserKeyWarning() {
40
+ warnedBrowserKey = false;
41
+ }
42
+ /**
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
13
48
  * request-shaping logic lives -- and it's usable on its own outside
14
49
  * React too (see §5.5's SSR helpers in a later phase, which will build
15
50
  * on this same class).
@@ -17,18 +52,31 @@ const MEDIA_FIELDS = `id fileName fullUrl thumbUrl thumbWebpUrl fullWebpUrl capt
17
52
  export class VeroxmClient {
18
53
  constructor(options) {
19
54
  this.getAccessToken = options.getAccessToken;
20
- const endpoint = `${options.apiBase.replace(/\/$/, '')}/public/v2/graphql`;
21
- this.gql = new GraphQLClient(endpoint, {
22
- headers: { Authorization: `Bearer ${options.apiKey}` },
23
- });
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;
24
60
  this.projectUuid = options.projectUuid;
25
61
  this.cache = new VeroxmCache(options.cache);
62
+ if (options.apiKey)
63
+ warnIfBrowserKey();
26
64
  }
27
- /** 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). */
28
- 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 = {}) {
29
67
  try {
30
- const token = this.getAccessToken ? await this.getAccessToken() : null;
31
- 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
+ });
32
80
  }
33
81
  catch (cause) {
34
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);
@@ -29,3 +29,8 @@ export interface EditorOverlayProps {
29
29
  * first mounted actually draws, so a page gets exactly one.
30
30
  */
31
31
  export declare function VeroxmEditorOverlay({ onChange, tools }: EditorOverlayProps): ReactNode;
32
+ /**
33
+ * Opens a slot's editing panel, as clicking it would (the script tag's heatmap uses it for "Edit this slot").
34
+ * False when no editor overlay is on the page.
35
+ */
36
+ export declare function openEditorSlot(name: string, locale?: string): boolean;