@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.
- package/CHANGELOG.md +33 -0
- package/README.md +99 -5
- package/dist/auth.js +1 -0
- package/dist/client.d.ts +27 -9
- package/dist/client.js +62 -14
- package/dist/component-boundary.d.ts +25 -0
- package/dist/component-boundary.js +21 -0
- package/dist/components.d.ts +52 -0
- package/dist/components.js +73 -0
- package/dist/editor/handler.d.ts +4 -0
- package/dist/editor/handler.js +52 -1
- package/dist/editor/overlay.d.ts +5 -0
- package/dist/editor/overlay.js +59 -0
- package/dist/errors.d.ts +14 -15
- package/dist/errors.js +27 -17
- package/dist/hooks/use-cached-query.js +1 -0
- package/dist/hooks/use-collection.js +1 -0
- package/dist/hooks/use-entries.js +1 -0
- package/dist/hooks/use-entry.js +1 -0
- package/dist/hooks/use-media.js +1 -0
- package/dist/hydration-boundary.js +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/next/cache-components.d.ts +12 -1
- package/dist/next/cache-components.js +11 -0
- package/dist/next/content-cached.d.ts +12 -0
- package/dist/next/content-cached.js +61 -0
- package/dist/next/content-core.d.ts +27 -0
- package/dist/next/content-core.js +39 -0
- package/dist/next/content.d.ts +19 -0
- package/dist/next/content.js +57 -0
- package/dist/next/index.d.ts +9 -0
- package/dist/next/index.js +8 -0
- package/dist/next/region.d.ts +8 -0
- package/dist/next/region.js +9 -0
- package/dist/next/route.js +3 -0
- package/dist/preview.js +1 -0
- package/dist/provider.d.ts +5 -1
- package/dist/provider.js +9 -4
- package/dist/slots-core.d.ts +75 -1
- package/dist/slots-core.js +59 -1
- package/dist/slots.d.ts +2 -12
- package/dist/slots.js +4 -28
- package/dist/tracking.js +1 -0
- package/dist/use-slot.d.ts +12 -0
- package/dist/use-slot.js +28 -0
- package/package.json +2 -2
package/dist/editor/overlay.js
CHANGED
|
@@ -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
|
}
|
|
@@ -208,6 +217,18 @@ export function VeroxmEditorOverlay({ onChange, tools }) {
|
|
|
208
217
|
return null;
|
|
209
218
|
return createPortal(_jsx(Overlay, { onChange: stableChange, tools: tools }), document.body);
|
|
210
219
|
}
|
|
220
|
+
/** Set while an overlay is mounted: opens a slot's panel from outside it. */
|
|
221
|
+
let openFromOutside = null;
|
|
222
|
+
/**
|
|
223
|
+
* Opens a slot's editing panel, as clicking it would (the script tag's heatmap uses it for "Edit this slot").
|
|
224
|
+
* False when no editor overlay is on the page.
|
|
225
|
+
*/
|
|
226
|
+
export function openEditorSlot(name, locale = '') {
|
|
227
|
+
if (!openFromOutside)
|
|
228
|
+
return false;
|
|
229
|
+
openFromOutside(name, locale);
|
|
230
|
+
return true;
|
|
231
|
+
}
|
|
211
232
|
function Overlay({ onChange, tools }) {
|
|
212
233
|
const rootRef = useRef(null);
|
|
213
234
|
const [session, setSession] = useState(null);
|
|
@@ -220,6 +241,15 @@ function Overlay({ onChange, tools }) {
|
|
|
220
241
|
const [highlightField, setHighlightField] = useState(null);
|
|
221
242
|
const [inlineHint, setInlineHint] = useState(null);
|
|
222
243
|
useLayoutTick(Boolean(hover || open || inlineHint), rootRef);
|
|
244
|
+
useEffect(() => {
|
|
245
|
+
openFromOutside = (name, locale) => {
|
|
246
|
+
setListOpen(false);
|
|
247
|
+
setOpen({ name, locale, nonce: Date.now() });
|
|
248
|
+
};
|
|
249
|
+
return () => {
|
|
250
|
+
openFromOutside = null;
|
|
251
|
+
};
|
|
252
|
+
}, []);
|
|
223
253
|
useEffect(() => {
|
|
224
254
|
call('session')
|
|
225
255
|
.then(setSession)
|
|
@@ -647,8 +677,37 @@ function FieldInput({ name, def, value, shown, onChange, onFocus, }) {
|
|
|
647
677
|
return _jsx(SlidesInput, { name: name, def: def, value: value, onChange: onChange, onFocus: onFocus });
|
|
648
678
|
case 'menu':
|
|
649
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 });
|
|
650
682
|
}
|
|
651
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
|
+
}
|
|
652
711
|
function VideoInput({ name, def, value, onChange, onFocus }) {
|
|
653
712
|
const id = useId();
|
|
654
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
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
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
|
|
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
|
-
/**
|
|
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
|
}
|
package/dist/errors.js
CHANGED
|
@@ -1,25 +1,35 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { VeroXMApiError, VeroXMGraphQLError } from '@veroxm/sdk';
|
|
2
2
|
/**
|
|
3
|
-
* Thrown for any GraphQL
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
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.
|
|
9
10
|
*/
|
|
10
|
-
export class VeroxmGraphQLError extends
|
|
11
|
-
constructor(
|
|
12
|
-
super(
|
|
11
|
+
export class VeroxmGraphQLError extends VeroXMGraphQLError {
|
|
12
|
+
constructor(status, errors) {
|
|
13
|
+
super(status, { errors });
|
|
13
14
|
this.name = 'VeroxmGraphQLError';
|
|
14
|
-
this.errors = errors;
|
|
15
|
-
this.status = status;
|
|
16
15
|
}
|
|
17
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* Wraps what a GraphQL request rejected with: an API answer (`VeroXMApiError`, including `VeroXMGraphQLError`) becomes
|
|
18
|
+
* a VeroxmGraphQLError; anything else (a network error, a timeout, a cancel) is returned unchanged so it isn't
|
|
19
|
+
* misreported as a GraphQL error, and a thrown non-Error becomes a plain Error.
|
|
20
|
+
*/
|
|
18
21
|
static from(cause) {
|
|
19
|
-
if (cause instanceof
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
22
|
+
if (cause instanceof VeroxmGraphQLError)
|
|
23
|
+
return cause;
|
|
24
|
+
if (cause instanceof VeroXMApiError) {
|
|
25
|
+
const errors = cause instanceof VeroXMGraphQLError ? cause.errors : [];
|
|
26
|
+
const wrapped = new VeroxmGraphQLError(cause.status, errors);
|
|
27
|
+
// Keep what the API said: its message, body and reason code.
|
|
28
|
+
const target = wrapped;
|
|
29
|
+
target.message = cause.message;
|
|
30
|
+
target.body = cause.body;
|
|
31
|
+
target.code = cause.code;
|
|
32
|
+
return wrapped;
|
|
23
33
|
}
|
|
24
34
|
return cause instanceof Error ? cause : new Error(String(cause));
|
|
25
35
|
}
|
package/dist/hooks/use-entry.js
CHANGED
package/dist/hooks/use-media.js
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -45,6 +45,11 @@ export type { VeroxmFormProps, VeroxmFormOptions, VeroxmFormMode, VeroxmFormHand
|
|
|
45
45
|
export { VeroxmTrackerProvider, useTracker, usePageViews, useExperience, Experience, useContentView, useRecommendations, } from './tracking.js';
|
|
46
46
|
export type { VeroxmTrackerProviderProps, VeroxmTrackerLike, ExperienceDecision, ExperienceState, ExperienceProps, RecommendationsState, } from './tracking.js';
|
|
47
47
|
export { VeroxmSlot, useSlot, field, configureSlots, loadSlot, mergeSlotValues } from './slots.js';
|
|
48
|
+
export { defineComponent } from './slots.js';
|
|
49
|
+
export { VeroxmRegion, renderComponent, regionSlotProps } from './components.js';
|
|
50
|
+
export { VeroxmComponentBoundary } from './component-boundary.js';
|
|
51
|
+
export type { RegisteredComponent, ComponentSchema, SlotComponentValue } from './slots.js';
|
|
52
|
+
export type { VeroxmRegionProps, RegionFallback, RenderComponentOptions } from './components.js';
|
|
48
53
|
export type { VeroxmSlotProps, SlotFieldDef, SlotFieldDefs, SlotValues, SlotInfo, SlotTest, SlotMedia, SlotLink, SlotMenuItem, SlotVideo, SlotSlide, SlotMap, SlotPlace, SlotChart, SlotState, SlotsConfig, LoadSlotOptions, SlotPerson, } from './slots.js';
|
|
49
54
|
export { loadStructuredData, jsonLdScript } from './structured-data.js';
|
|
50
55
|
export type { StructuredDataOptions } from './structured-data.js';
|
package/dist/index.js
CHANGED
|
@@ -32,5 +32,9 @@ export { VeroxmForm, useVeroxmForm } from './form.js';
|
|
|
32
32
|
export { VeroxmTrackerProvider, useTracker, usePageViews, useExperience, Experience, useContentView, useRecommendations, } from './tracking.js';
|
|
33
33
|
// Visual slots (Experience Layer): named regions marketers edit from VeroXM.
|
|
34
34
|
export { VeroxmSlot, useSlot, field, configureSlots, loadSlot, mergeSlotValues } from './slots.js';
|
|
35
|
+
// Registered components: marketers choose which one shows in a region, and fill in its fields.
|
|
36
|
+
export { defineComponent } from './slots.js';
|
|
37
|
+
export { VeroxmRegion, renderComponent, regionSlotProps } from './components.js';
|
|
38
|
+
export { VeroxmComponentBoundary } from './component-boundary.js';
|
|
35
39
|
// Structured data (schema.org JSON-LD) for a page: render jsonLdScript(data) in a <script type="application/ld+json">.
|
|
36
40
|
export { loadStructuredData, jsonLdScript } from './structured-data.js';
|
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import type { ReactNode } from 'react';
|
|
2
|
-
import type { SlotFieldDefs, VeroxmSlotProps } from '../slots-core.js';
|
|
2
|
+
import type { RegisteredComponent, SlotFieldDefs, VeroxmSlotProps } from '../slots-core.js';
|
|
3
|
+
import { type VeroxmRegionProps } from '../components.js';
|
|
3
4
|
export declare function VeroxmSlot<F extends SlotFieldDefs>(props: VeroxmSlotProps<F>): Promise<ReactNode>;
|
|
5
|
+
/** <VeroxmRegion> with this entry's cached <VeroxmSlot>: a slot with one component field (see '@veroxm/react-sdk/next'). */
|
|
6
|
+
export declare function VeroxmRegion<const L extends readonly RegisteredComponent[]>(props: VeroxmRegionProps<L>): Promise<ReactNode>;
|
|
7
|
+
export { defineComponent } from '../slots-core.js';
|
|
8
|
+
export { renderComponent, regionSlotProps } from '../components.js';
|
|
9
|
+
export { VeroxmComponentBoundary } from '../component-boundary.js';
|
|
10
|
+
export type { RegisteredComponent, ComponentSchema, SlotComponentValue } from '../slots-core.js';
|
|
11
|
+
export type { VeroxmRegionProps, RegionFallback, RenderComponentOptions } from '../components.js';
|
|
12
|
+
export { getEntries, getEntry, getCollection, getMedia } from './content-cached.js';
|
|
13
|
+
export { CONTENT_TAG, contentTag, mediaTag } from './content-core.js';
|
|
14
|
+
export type { ContentReadOptions } from './content-core.js';
|
|
4
15
|
export { VeroxmEditor } from './editor.js';
|
|
5
16
|
export { field, configureSlots, mergeSlotValues } from '../slots-core.js';
|
|
6
17
|
export type { VeroxmSlotProps, SlotFieldDef, SlotFieldDefs, SlotValues, SlotInfo, SlotTest, SlotMedia, SlotLink, SlotMenuItem, SlotVideo, SlotSlide, SlotMap, SlotPlace, SlotChart, SlotsConfig } from '../slots-core.js';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { regionSlotProps } from '../components.js';
|
|
1
2
|
import { slotWith } from './slot.js';
|
|
2
3
|
import { cachedPublishedSlot } from './cached.js';
|
|
3
4
|
// @veroxm/react-sdk/next/cache-components -- <VeroxmSlot> for Next.js apps
|
|
@@ -11,6 +12,16 @@ import { cachedPublishedSlot } from './cached.js';
|
|
|
11
12
|
export function VeroxmSlot(props) {
|
|
12
13
|
return slotWith(props, cachedPublishedSlot, true);
|
|
13
14
|
}
|
|
15
|
+
/** <VeroxmRegion> with this entry's cached <VeroxmSlot>: a slot with one component field (see '@veroxm/react-sdk/next'). */
|
|
16
|
+
export function VeroxmRegion(props) {
|
|
17
|
+
return VeroxmSlot(regionSlotProps(props));
|
|
18
|
+
}
|
|
19
|
+
export { defineComponent } from '../slots-core.js';
|
|
20
|
+
export { renderComponent, regionSlotProps } from '../components.js';
|
|
21
|
+
export { VeroxmComponentBoundary } from '../component-boundary.js';
|
|
22
|
+
// Content for Server Components, cached with 'use cache' (tags veroxm-content, veroxm-content:<collection>).
|
|
23
|
+
export { getEntries, getEntry, getCollection, getMedia } from './content-cached.js';
|
|
24
|
+
export { CONTENT_TAG, contentTag, mediaTag } from './content-core.js';
|
|
14
25
|
export { VeroxmEditor } from './editor.js';
|
|
15
26
|
export { field, configureSlots, mergeSlotValues } from '../slots-core.js';
|
|
16
27
|
// Site parts: header, footer and menus from slot fields.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { CollectionMeta, Entry, EntriesQueryOptions, EntryConnection, MediaView } from '../types.js';
|
|
2
|
+
import { type ContentReadOptions } from './content-core.js';
|
|
3
|
+
/** A page of published entries (the same options as useEntries), cached with 'use cache'. */
|
|
4
|
+
export declare function getEntries<T = Record<string, unknown>>(collection: string, options?: EntriesQueryOptions & ContentReadOptions): Promise<EntryConnection<T>>;
|
|
5
|
+
/** One published entry, or null when there's none with that id. */
|
|
6
|
+
export declare function getEntry<T = Record<string, unknown>>(collection: string, id: number, options?: {
|
|
7
|
+
timestamps?: boolean;
|
|
8
|
+
} & ContentReadOptions): Promise<Entry<T> | null>;
|
|
9
|
+
/** A collection's field list, or null. */
|
|
10
|
+
export declare function getCollection(slug: string, options?: ContentReadOptions): Promise<CollectionMeta | null>;
|
|
11
|
+
/** One media item, or null. */
|
|
12
|
+
export declare function getMedia(id: number, options?: ContentReadOptions): Promise<MediaView | null>;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { cacheLife, cacheTag } from 'next/cache';
|
|
2
|
+
import { DEFAULT_REVALIDATE, assertServer, serverClientWith, tagsFor } from './content-core.js';
|
|
3
|
+
// The content helpers for apps with Next.js Cache Components (`cacheComponents: true`), from
|
|
4
|
+
// '@veroxm/react-sdk/next/cache-components'. Same names and results as the '@veroxm/react-sdk/next' ones; each read is
|
|
5
|
+
// a 'use cache' function, so it's part of the static shell, tagged `veroxm-content` and `veroxm-content:<collection>`
|
|
6
|
+
// (refreshed by revalidateTag or VeroXM's webhook through your /api/veroxm route). Kept apart because 'use cache' only
|
|
7
|
+
// compiles when Cache Components is on.
|
|
8
|
+
function life(read) {
|
|
9
|
+
const seconds = read.revalidate === false ? 60 * 60 * 24 * 365 : (read.revalidate ?? DEFAULT_REVALIDATE);
|
|
10
|
+
cacheLife({ stale: Math.min(seconds, 300), revalidate: seconds, expire: Math.max(seconds, 86400) });
|
|
11
|
+
}
|
|
12
|
+
async function entriesCached(collection, query, read) {
|
|
13
|
+
'use cache';
|
|
14
|
+
cacheTag(...tagsFor({ collection }, read.tags));
|
|
15
|
+
life(read);
|
|
16
|
+
return serverClientWith(undefined).listEntries(collection, query);
|
|
17
|
+
}
|
|
18
|
+
async function entryCached(collection, id, timestamps, read) {
|
|
19
|
+
'use cache';
|
|
20
|
+
cacheTag(...tagsFor({ collection }, read.tags));
|
|
21
|
+
life(read);
|
|
22
|
+
return serverClientWith(undefined).getEntry(collection, id, { timestamps });
|
|
23
|
+
}
|
|
24
|
+
async function collectionCached(slug, read) {
|
|
25
|
+
'use cache';
|
|
26
|
+
cacheTag(...tagsFor({ collection: slug }, read.tags));
|
|
27
|
+
life(read);
|
|
28
|
+
return serverClientWith(undefined).getCollection(slug);
|
|
29
|
+
}
|
|
30
|
+
async function mediaCached(id, read) {
|
|
31
|
+
'use cache';
|
|
32
|
+
cacheTag(...tagsFor({ media: id }, read.tags));
|
|
33
|
+
life(read);
|
|
34
|
+
return serverClientWith(undefined).getMedia(id);
|
|
35
|
+
}
|
|
36
|
+
function split(options) {
|
|
37
|
+
const { revalidate, tags, ...rest } = options;
|
|
38
|
+
return { read: { ...(revalidate !== undefined ? { revalidate } : {}), ...(tags ? { tags } : {}) }, rest };
|
|
39
|
+
}
|
|
40
|
+
/** A page of published entries (the same options as useEntries), cached with 'use cache'. */
|
|
41
|
+
export async function getEntries(collection, options = {}) {
|
|
42
|
+
assertServer('getEntries');
|
|
43
|
+
const { read, rest } = split(options);
|
|
44
|
+
return (await entriesCached(collection, rest, read));
|
|
45
|
+
}
|
|
46
|
+
/** One published entry, or null when there's none with that id. */
|
|
47
|
+
export async function getEntry(collection, id, options = {}) {
|
|
48
|
+
assertServer('getEntry');
|
|
49
|
+
const { read, rest } = split(options);
|
|
50
|
+
return (await entryCached(collection, id, rest.timestamps ?? false, read));
|
|
51
|
+
}
|
|
52
|
+
/** A collection's field list, or null. */
|
|
53
|
+
export async function getCollection(slug, options = {}) {
|
|
54
|
+
assertServer('getCollection');
|
|
55
|
+
return (await collectionCached(slug, split(options).read));
|
|
56
|
+
}
|
|
57
|
+
/** One media item, or null. */
|
|
58
|
+
export async function getMedia(id, options = {}) {
|
|
59
|
+
assertServer('getMedia');
|
|
60
|
+
return (await mediaCached(id, split(options).read));
|
|
61
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { VeroxmClient } from '../client.js';
|
|
2
|
+
/** Every content read is tagged with this: `revalidateTag('veroxm-content')` refreshes them all. */
|
|
3
|
+
export declare const CONTENT_TAG = "veroxm-content";
|
|
4
|
+
/** The tag of one collection's reads (entries, single entries, its field list): `revalidateTag(contentTag('posts'))`. */
|
|
5
|
+
export declare function contentTag(collection: string): string;
|
|
6
|
+
/** The tag of one media item's read. */
|
|
7
|
+
export declare function mediaTag(id: number): string;
|
|
8
|
+
/** Seconds a content read stays fresh in Next.js's cache unless a tag is revalidated first. */
|
|
9
|
+
export declare const DEFAULT_REVALIDATE = 60;
|
|
10
|
+
export interface ContentReadOptions {
|
|
11
|
+
/** Seconds Next.js may serve this read from its cache (default 60), or false to keep it until a tag is revalidated. */
|
|
12
|
+
revalidate?: number | false;
|
|
13
|
+
/** Extra cache tags for this read, besides `veroxm-content` and the collection's. */
|
|
14
|
+
tags?: string[];
|
|
15
|
+
}
|
|
16
|
+
/** Throws in a browser: these helpers read with the server's key. */
|
|
17
|
+
export declare function assertServer(name: string): void;
|
|
18
|
+
/**
|
|
19
|
+
* A VeroxmClient for the server, from VEROXM_API_BASE and VEROXM_API_KEY (or configureSlots), sending with `fetchImpl`.
|
|
20
|
+
* Throws an error that says which setting is missing, rather than reading anonymously.
|
|
21
|
+
*/
|
|
22
|
+
export declare function serverClientWith(fetchImpl: typeof fetch | undefined): VeroxmClient;
|
|
23
|
+
/** The tags of a read: everything, then the collection's (or the media item's), then the caller's own. */
|
|
24
|
+
export declare function tagsFor(scope: {
|
|
25
|
+
collection?: string;
|
|
26
|
+
media?: number;
|
|
27
|
+
}, extra?: readonly string[]): string[];
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { VeroxmClient } from '../client.js';
|
|
2
|
+
import { resolveSlotsConfig } from '../slots-core.js';
|
|
3
|
+
// Server-side content reads for Server Components (increment 5 of the product roadmap): what both Next.js entries
|
|
4
|
+
// share. The key comes from the server's environment (VEROXM_API_BASE, VEROXM_API_KEY, as slots use) and never
|
|
5
|
+
// reaches the browser; reads go through VeroxmClient, so they get @veroxm/sdk's errors, timeouts and retries.
|
|
6
|
+
/** Every content read is tagged with this: `revalidateTag('veroxm-content')` refreshes them all. */
|
|
7
|
+
export const CONTENT_TAG = 'veroxm-content';
|
|
8
|
+
/** The tag of one collection's reads (entries, single entries, its field list): `revalidateTag(contentTag('posts'))`. */
|
|
9
|
+
export function contentTag(collection) {
|
|
10
|
+
return `veroxm-content:${collection}`;
|
|
11
|
+
}
|
|
12
|
+
/** The tag of one media item's read. */
|
|
13
|
+
export function mediaTag(id) {
|
|
14
|
+
return `veroxm-media:${id}`;
|
|
15
|
+
}
|
|
16
|
+
/** Seconds a content read stays fresh in Next.js's cache unless a tag is revalidated first. */
|
|
17
|
+
export const DEFAULT_REVALIDATE = 60;
|
|
18
|
+
/** Throws in a browser: these helpers read with the server's key. */
|
|
19
|
+
export function assertServer(name) {
|
|
20
|
+
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
|
|
21
|
+
throw new Error(`[veroxm] ${name}() reads with your server key and only runs on the server (a Server Component, route handler or server action).`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* A VeroxmClient for the server, from VEROXM_API_BASE and VEROXM_API_KEY (or configureSlots), sending with `fetchImpl`.
|
|
26
|
+
* Throws an error that says which setting is missing, rather than reading anonymously.
|
|
27
|
+
*/
|
|
28
|
+
export function serverClientWith(fetchImpl) {
|
|
29
|
+
const cfg = resolveSlotsConfig();
|
|
30
|
+
const missing = [!cfg.baseUrl && 'VEROXM_API_BASE', !cfg.apiKey && 'VEROXM_API_KEY'].filter(Boolean);
|
|
31
|
+
if (missing.length) {
|
|
32
|
+
throw new Error(`[veroxm] set ${missing.join(' and ')} on the server (or call configureSlots) to read content.`);
|
|
33
|
+
}
|
|
34
|
+
return new VeroxmClient({ apiBase: cfg.baseUrl, apiKey: cfg.apiKey, projectUuid: cfg.projectId || undefined, fetch: fetchImpl });
|
|
35
|
+
}
|
|
36
|
+
/** The tags of a read: everything, then the collection's (or the media item's), then the caller's own. */
|
|
37
|
+
export function tagsFor(scope, extra = []) {
|
|
38
|
+
return [CONTENT_TAG, ...(scope.collection ? [contentTag(scope.collection)] : []), ...(scope.media !== undefined ? [mediaTag(scope.media)] : []), ...extra].slice(0, 64);
|
|
39
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { VeroxmClient } from '../client.js';
|
|
2
|
+
import type { CollectionMeta, Entry, EntriesQueryOptions, EntryConnection, MediaView } from '../types.js';
|
|
3
|
+
import { type ContentReadOptions } from './content-core.js';
|
|
4
|
+
/** A page of published entries (the same options as useEntries). */
|
|
5
|
+
export declare function getEntries<T = Record<string, unknown>>(collection: string, options?: EntriesQueryOptions & ContentReadOptions): Promise<EntryConnection<T>>;
|
|
6
|
+
/** One published entry, or null when there's none with that id (call notFound() yourself). */
|
|
7
|
+
export declare function getEntry<T = Record<string, unknown>>(collection: string, id: number, options?: {
|
|
8
|
+
timestamps?: boolean;
|
|
9
|
+
} & ContentReadOptions): Promise<Entry<T> | null>;
|
|
10
|
+
/** A collection's field list, or null when the project has no such collection. */
|
|
11
|
+
export declare function getCollection(slug: string, options?: ContentReadOptions): Promise<CollectionMeta | null>;
|
|
12
|
+
/** One media item, or null. */
|
|
13
|
+
export declare function getMedia(id: number, options?: ContentReadOptions): Promise<MediaView | null>;
|
|
14
|
+
/**
|
|
15
|
+
* The server's VeroxmClient (reads cached like the helpers above, tagged `veroxm-content`), for the SSR helpers
|
|
16
|
+
* (fetchEntries and the rest) when client components also need the data: pass their `hydration` to
|
|
17
|
+
* <VeroxmHydrationBoundary>.
|
|
18
|
+
*/
|
|
19
|
+
export declare function getServerClient(options?: ContentReadOptions): VeroxmClient;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { cache } from 'react';
|
|
2
|
+
import { DEFAULT_REVALIDATE, assertServer, serverClientWith, tagsFor } from './content-core.js';
|
|
3
|
+
/** A fetch that adds Next.js's cache options to every request. */
|
|
4
|
+
function nextFetch(options, scope) {
|
|
5
|
+
const revalidate = options.revalidate ?? DEFAULT_REVALIDATE;
|
|
6
|
+
return (input, init) => fetch(input, { ...init, cache: 'force-cache', next: { revalidate, tags: tagsFor(scope, options.tags) } });
|
|
7
|
+
}
|
|
8
|
+
const client = (name, options, scope) => {
|
|
9
|
+
assertServer(name);
|
|
10
|
+
return serverClientWith(nextFetch(options, scope));
|
|
11
|
+
};
|
|
12
|
+
// One read per distinct call in a render (React's cache), keyed by its arguments as JSON.
|
|
13
|
+
const once = cache(async (kind, json) => {
|
|
14
|
+
const args = JSON.parse(json);
|
|
15
|
+
switch (kind) {
|
|
16
|
+
case 'entries':
|
|
17
|
+
return client('getEntries', args.read, { collection: args.collection }).listEntries(args.collection, args.query);
|
|
18
|
+
case 'entry':
|
|
19
|
+
return client('getEntry', args.read, { collection: args.collection }).getEntry(args.collection, args.id, { timestamps: args.timestamps });
|
|
20
|
+
case 'collection':
|
|
21
|
+
return client('getCollection', args.read, { collection: args.slug }).getCollection(args.slug);
|
|
22
|
+
case 'media':
|
|
23
|
+
return client('getMedia', args.read, { media: args.id }).getMedia(args.id);
|
|
24
|
+
default:
|
|
25
|
+
throw new Error(`[veroxm] unknown read ${kind}`);
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
function split(options) {
|
|
29
|
+
const { revalidate, tags, ...rest } = options;
|
|
30
|
+
return { read: { revalidate, tags }, rest };
|
|
31
|
+
}
|
|
32
|
+
/** A page of published entries (the same options as useEntries). */
|
|
33
|
+
export async function getEntries(collection, options = {}) {
|
|
34
|
+
const { read, rest } = split(options);
|
|
35
|
+
return (await once('entries', JSON.stringify({ collection, query: rest, read })));
|
|
36
|
+
}
|
|
37
|
+
/** One published entry, or null when there's none with that id (call notFound() yourself). */
|
|
38
|
+
export async function getEntry(collection, id, options = {}) {
|
|
39
|
+
const { read, rest } = split(options);
|
|
40
|
+
return (await once('entry', JSON.stringify({ collection, id, timestamps: rest.timestamps ?? false, read })));
|
|
41
|
+
}
|
|
42
|
+
/** A collection's field list, or null when the project has no such collection. */
|
|
43
|
+
export async function getCollection(slug, options = {}) {
|
|
44
|
+
return (await once('collection', JSON.stringify({ slug, read: split(options).read })));
|
|
45
|
+
}
|
|
46
|
+
/** One media item, or null. */
|
|
47
|
+
export async function getMedia(id, options = {}) {
|
|
48
|
+
return (await once('media', JSON.stringify({ id, read: split(options).read })));
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The server's VeroxmClient (reads cached like the helpers above, tagged `veroxm-content`), for the SSR helpers
|
|
52
|
+
* (fetchEntries and the rest) when client components also need the data: pass their `hydration` to
|
|
53
|
+
* <VeroxmHydrationBoundary>.
|
|
54
|
+
*/
|
|
55
|
+
export function getServerClient(options = {}) {
|
|
56
|
+
return client('getServerClient', options, {});
|
|
57
|
+
}
|
package/dist/next/index.d.ts
CHANGED
|
@@ -1,4 +1,13 @@
|
|
|
1
1
|
export { VeroxmSlot } from './slot.js';
|
|
2
|
+
export { getEntries, getEntry, getCollection, getMedia, getServerClient } from './content.js';
|
|
3
|
+
export { CONTENT_TAG, contentTag, mediaTag } from './content-core.js';
|
|
4
|
+
export type { ContentReadOptions } from './content-core.js';
|
|
5
|
+
export { VeroxmRegion } from './region.js';
|
|
6
|
+
export { defineComponent } from '../slots-core.js';
|
|
7
|
+
export { renderComponent, regionSlotProps } from '../components.js';
|
|
8
|
+
export { VeroxmComponentBoundary } from '../component-boundary.js';
|
|
9
|
+
export type { RegisteredComponent, ComponentSchema, SlotComponentValue } from '../slots-core.js';
|
|
10
|
+
export type { VeroxmRegionProps, RegionFallback, RenderComponentOptions } from '../components.js';
|
|
2
11
|
export { VeroxmEditor } from './editor.js';
|
|
3
12
|
export { field, configureSlots, loadSlot, mergeSlotValues } from '../slots-core.js';
|
|
4
13
|
export type { VeroxmSlotProps, SlotFieldDef, SlotFieldDefs, SlotValues, SlotInfo, SlotTest, SlotMedia, SlotLink, SlotMenuItem, SlotVideo, SlotSlide, SlotMap, SlotPlace, SlotChart, SlotsConfig, LoadSlotOptions, SlotPerson } from '../slots-core.js';
|
package/dist/next/index.js
CHANGED
|
@@ -5,6 +5,14 @@
|
|
|
5
5
|
// // app/api/veroxm/[...veroxm]/route.ts
|
|
6
6
|
// export { GET, PUT, POST } from '@veroxm/react-sdk/next/route';
|
|
7
7
|
export { VeroxmSlot } from './slot.js';
|
|
8
|
+
// Content for Server Components, read on the server with VEROXM_API_KEY and cached by Next.js.
|
|
9
|
+
export { getEntries, getEntry, getCollection, getMedia, getServerClient } from './content.js';
|
|
10
|
+
export { CONTENT_TAG, contentTag, mediaTag } from './content-core.js';
|
|
11
|
+
// Registered components: marketers choose which one shows in a region, and fill in its fields.
|
|
12
|
+
export { VeroxmRegion } from './region.js';
|
|
13
|
+
export { defineComponent } from '../slots-core.js';
|
|
14
|
+
export { renderComponent, regionSlotProps } from '../components.js';
|
|
15
|
+
export { VeroxmComponentBoundary } from '../component-boundary.js';
|
|
8
16
|
export { VeroxmEditor } from './editor.js';
|
|
9
17
|
export { field, configureSlots, loadSlot, mergeSlotValues } from '../slots-core.js';
|
|
10
18
|
// Site parts (also in '@veroxm/react-sdk'), here so a Next.js site imports from one place.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import { type VeroxmRegionProps } from '../components.js';
|
|
3
|
+
import type { RegisteredComponent } from '../slots-core.js';
|
|
4
|
+
/**
|
|
5
|
+
* <VeroxmRegion> for Next.js App Router: a slot with one component field, rendered by this entry's <VeroxmSlot>, so it
|
|
6
|
+
* gets draft-mode editing on the page, A/B tests, personalised versions and the same caching as any slot.
|
|
7
|
+
*/
|
|
8
|
+
export declare function VeroxmRegion<const L extends readonly RegisteredComponent[]>(props: VeroxmRegionProps<L>): Promise<ReactNode>;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { regionSlotProps } from '../components.js';
|
|
2
|
+
import { VeroxmSlot } from './slot.js';
|
|
3
|
+
/**
|
|
4
|
+
* <VeroxmRegion> for Next.js App Router: a slot with one component field, rendered by this entry's <VeroxmSlot>, so it
|
|
5
|
+
* gets draft-mode editing on the page, A/B tests, personalised versions and the same caching as any slot.
|
|
6
|
+
*/
|
|
7
|
+
export function VeroxmRegion(props) {
|
|
8
|
+
return VeroxmSlot(regionSlotProps(props));
|
|
9
|
+
}
|
package/dist/next/route.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { draftMode } from 'next/headers';
|
|
2
2
|
import { revalidateTag } from 'next/cache';
|
|
3
3
|
import { createEditorHandler } from '../editor/handler.js';
|
|
4
|
+
import { CONTENT_TAG } from './content-core.js';
|
|
4
5
|
const handle = createEditorHandler({
|
|
5
6
|
isEditing: async () => (await draftMode()).isEnabled,
|
|
6
7
|
enter: async () => (await draftMode()).enable(),
|
|
7
8
|
exit: async () => (await draftMode()).disable(),
|
|
8
9
|
published: () => revalidateTag('veroxm-slots', { expire: 0 }),
|
|
10
|
+
// A signed content webhook: every content read (getEntries, getEntry...) is tagged veroxm-content.
|
|
11
|
+
contentChanged: () => revalidateTag(CONTENT_TAG, { expire: 0 }),
|
|
9
12
|
});
|
|
10
13
|
async function route(request, ctx) {
|
|
11
14
|
const params = ctx?.params ? await ctx.params : undefined;
|
package/dist/preview.js
CHANGED
package/dist/provider.d.ts
CHANGED
|
@@ -19,10 +19,14 @@ export interface VeroxmProviderProps extends Partial<VeroxmClientOptions> {
|
|
|
19
19
|
* your app's root:
|
|
20
20
|
*
|
|
21
21
|
* ```tsx
|
|
22
|
-
* <VeroxmProvider apiBase="https://cms.example.com" apiKey={
|
|
22
|
+
* <VeroxmProvider apiBase="https://cms.example.com" apiKey={apiKey}>
|
|
23
23
|
* <App />
|
|
24
24
|
* </VeroxmProvider>
|
|
25
25
|
* ```
|
|
26
|
+
*
|
|
27
|
+
* The hooks read in the browser, so `apiKey` ends up in the page: anyone can copy it and read what it can read,
|
|
28
|
+
* drafts included. In the App Router, prefer reading on the server (Server Components, or ./ssr.ts with
|
|
29
|
+
* <VeroxmHydrationBoundary>). Outside production builds a browser client with a key logs a warning once.
|
|
26
30
|
*/
|
|
27
31
|
export declare function VeroxmProvider(props: VeroxmProviderProps): ReactElement;
|
|
28
32
|
/** Reads the VeroxmClient supplied by the nearest <VeroxmProvider> -- throws if none is mounted, same fail-loud philosophy as @veroxm/sdk's own methods (see packages/sdk-js/src/errors.ts's VeroXMNotAuthenticatedError). Every hook in ./hooks calls this rather than reading context directly. */
|