@ebitex/content-sdk 1.1.292 → 1.1.327

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 (53) hide show
  1. package/dist/content/client.d.ts +7 -1
  2. package/dist/content/client.d.ts.map +1 -1
  3. package/dist/content/client.js +4 -2
  4. package/dist/content/client.js.map +1 -1
  5. package/dist/environment.d.ts +9 -0
  6. package/dist/environment.d.ts.map +1 -0
  7. package/dist/environment.js +16 -0
  8. package/dist/environment.js.map +1 -0
  9. package/dist/index.d.ts +4 -1
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +5 -0
  12. package/dist/index.js.map +1 -1
  13. package/dist/model/compile.d.ts +5 -2
  14. package/dist/model/compile.d.ts.map +1 -1
  15. package/dist/model/compile.js +36 -7
  16. package/dist/model/compile.js.map +1 -1
  17. package/dist/model/decompile.d.ts.map +1 -1
  18. package/dist/model/decompile.js +7 -1
  19. package/dist/model/decompile.js.map +1 -1
  20. package/dist/model/types.d.ts +12 -1
  21. package/dist/model/types.d.ts.map +1 -1
  22. package/dist/model/types.js.map +1 -1
  23. package/dist/react/Experience.d.ts +11 -0
  24. package/dist/react/Experience.d.ts.map +1 -1
  25. package/dist/react/Experience.js +30 -9
  26. package/dist/react/Experience.js.map +1 -1
  27. package/dist/react/index.d.ts +2 -0
  28. package/dist/react/index.d.ts.map +1 -1
  29. package/dist/react/index.js +3 -0
  30. package/dist/react/index.js.map +1 -1
  31. package/dist/react/routeContext.d.ts +37 -0
  32. package/dist/react/routeContext.d.ts.map +1 -0
  33. package/dist/react/routeContext.js +25 -0
  34. package/dist/react/routeContext.js.map +1 -0
  35. package/dist/react/routeData.d.ts +55 -0
  36. package/dist/react/routeData.d.ts.map +1 -0
  37. package/dist/react/routeData.js +225 -0
  38. package/dist/react/routeData.js.map +1 -0
  39. package/dist/route.d.ts +53 -0
  40. package/dist/route.d.ts.map +1 -0
  41. package/dist/route.js +55 -0
  42. package/dist/route.js.map +1 -0
  43. package/dist/routeData.d.ts +117 -0
  44. package/dist/routeData.d.ts.map +1 -0
  45. package/dist/routeData.js +106 -0
  46. package/dist/routeData.js.map +1 -0
  47. package/dist/routeTypes.d.ts +58 -0
  48. package/dist/routeTypes.d.ts.map +1 -0
  49. package/dist/routeTypes.js +46 -0
  50. package/dist/routeTypes.js.map +1 -0
  51. package/dist/types.d.ts +26 -0
  52. package/dist/types.d.ts.map +1 -1
  53. package/package.json +2 -2
@@ -0,0 +1,225 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';
3
+ import { isDevelopment } from '../environment.js';
4
+ import { isAbortError } from '../errors.js';
5
+ import { assertDistinctContexts, describeMismatch, isNotFound, matchesRoute, paramsKey, } from '../routeData.js';
6
+ import { useContentContext } from './ContentProvider.js';
7
+ import { useRoute } from './routeContext.js';
8
+ const LOADING = Object.freeze({ status: 'loading' });
9
+ const NOT_FOUND_STATE = Object.freeze({ status: 'notFound' });
10
+ /**
11
+ * One load per definition and parameter set, shared by every section that reads it. The cache is
12
+ * keyed by the definition's identity and the serialized parameters (and locale), held for the
13
+ * life of the boundary: never by an effect over an array or function the parent rebuilds on each
14
+ * render.
15
+ */
16
+ class RouteDataStore {
17
+ entries = new Map();
18
+ listeners = new Set();
19
+ /** True while the boundary is mounted (and not between a strict-mode unmount and its immediate remount). */
20
+ active = false;
21
+ subscribe = (listener) => {
22
+ this.listeners.add(listener);
23
+ return () => this.listeners.delete(listener);
24
+ };
25
+ notify() {
26
+ for (const listener of this.listeners)
27
+ listener();
28
+ }
29
+ slot(definition) {
30
+ let slot = this.entries.get(definition);
31
+ if (slot === undefined) {
32
+ slot = new Map();
33
+ this.entries.set(definition, slot);
34
+ }
35
+ return slot;
36
+ }
37
+ /** Puts a server's already-loaded values in place, so the first render has them and nothing loads. */
38
+ seed(definitions, entryKey, snapshot) {
39
+ for (const definition of definitions) {
40
+ if (snapshot.missing?.includes(definition.context)) {
41
+ this.slot(definition).set(entryKey, { state: NOT_FOUND_STATE, controller: undefined });
42
+ }
43
+ else if (Object.hasOwn(snapshot.values, definition.context)) {
44
+ this.slot(definition).set(entryKey, { state: { status: 'ready', value: snapshot.values[definition.context] }, controller: undefined });
45
+ }
46
+ }
47
+ }
48
+ read(definition, entryKey) {
49
+ return this.entries.get(definition)?.get(entryKey)?.state ?? LOADING;
50
+ }
51
+ /** The first failed load for this key, if any. Stable until the failure changes. */
52
+ failure(entryKey) {
53
+ for (const slot of this.entries.values()) {
54
+ const state = slot.get(entryKey)?.state;
55
+ if (state?.status === 'error')
56
+ return this.failureOf(state);
57
+ }
58
+ return undefined;
59
+ }
60
+ failures = new WeakMap();
61
+ failureOf(state) {
62
+ let failure = this.failures.get(state);
63
+ if (failure === undefined) {
64
+ failure = { error: state.error };
65
+ this.failures.set(state, failure);
66
+ }
67
+ return failure;
68
+ }
69
+ hasNotFound(entryKey) {
70
+ for (const slot of this.entries.values()) {
71
+ if (slot.get(entryKey)?.state.status === 'notFound')
72
+ return true;
73
+ }
74
+ return false;
75
+ }
76
+ /**
77
+ * Makes `entryKey` the current parameter set: aborts and forgets everything loaded or loading for
78
+ * another, then starts a load for each applicable definition that has none yet.
79
+ */
80
+ start(definitions, params, entryKey, locale) {
81
+ let changed = false;
82
+ for (const slot of this.entries.values()) {
83
+ for (const [key, entry] of slot) {
84
+ if (key === entryKey)
85
+ continue;
86
+ entry.controller?.abort();
87
+ slot.delete(key);
88
+ changed = true;
89
+ }
90
+ }
91
+ for (const definition of definitions) {
92
+ const slot = this.slot(definition);
93
+ if (slot.has(entryKey))
94
+ continue;
95
+ const controller = new AbortController();
96
+ const entry = { state: LOADING, controller };
97
+ slot.set(entryKey, entry);
98
+ changed = true;
99
+ const settle = (state) => {
100
+ if (controller.signal.aborted)
101
+ return;
102
+ entry.state = state;
103
+ entry.controller = undefined;
104
+ this.notify();
105
+ };
106
+ const options = { locale, signal: controller.signal };
107
+ let pending;
108
+ try {
109
+ pending = definition.load(params, options);
110
+ }
111
+ catch (error) {
112
+ pending = Promise.reject(error);
113
+ }
114
+ pending.then((result) => settle(isNotFound(result) ? NOT_FOUND_STATE : { status: 'ready', value: result }), (error) => {
115
+ if (!isAbortError(error))
116
+ settle({ status: 'error', error });
117
+ });
118
+ }
119
+ if (changed)
120
+ this.notify();
121
+ }
122
+ abortAll() {
123
+ for (const slot of this.entries.values()) {
124
+ for (const entry of slot.values())
125
+ entry.controller?.abort();
126
+ }
127
+ }
128
+ }
129
+ const RouteDataContext = createContext(null);
130
+ const definitionIds = new WeakMap();
131
+ let nextDefinitionId = 1;
132
+ function idOf(definition) {
133
+ let id = definitionIds.get(definition);
134
+ if (id === undefined) {
135
+ id = nextDefinitionId++;
136
+ definitionIds.set(definition, id);
137
+ }
138
+ return id;
139
+ }
140
+ /**
141
+ * Mounted by `<Experience routeData>` inside the route context. Loads each definition whose tag
142
+ * matches the delivered route, once per parameter set; asks the route to render the host's
143
+ * not-found when a loader answers `NotFound`; replaces the page with the provider's error panel
144
+ * when a loader throws. A definition whose tag does not match is skipped without error. With no route on the result (an ordinary page, an older server) no loader
145
+ * runs, and the page renders as it would without the boundary.
146
+ */
147
+ export function RouteDataBoundary({ definitions, initial, route, locale, path, errorComponent, children }) {
148
+ assertDistinctContexts(definitions);
149
+ // A definition for another address is skipped, never an error: the development check is at the read (useRouteData).
150
+ const applicableList = definitions.filter((definition) => matchesRoute(definition, route));
151
+ const params = route?.params;
152
+ const entryKey = `${params === undefined ? '' : paramsKey(params)}|${locale ?? ''}`;
153
+ const definitionsKey = applicableList.map(idOf).join(',');
154
+ const listedKey = definitions.map(idOf).join(',');
155
+ const storeRef = useRef(null);
156
+ if (storeRef.current === null) {
157
+ storeRef.current = new RouteDataStore();
158
+ if (initial !== undefined)
159
+ storeRef.current.seed(applicableList, entryKey, initial);
160
+ }
161
+ const store = storeRef.current;
162
+ // Read in the effect through a ref: the array and the params object are the parent's, rebuilt each render, so they must never be dependencies.
163
+ const latest = useRef({ applicableList, params });
164
+ latest.current = { applicableList, params };
165
+ useEffect(() => {
166
+ store.active = true;
167
+ store.start(latest.current.applicableList, latest.current.params ?? {}, entryKey, locale);
168
+ return () => {
169
+ store.active = false;
170
+ // A strict-mode remount re-activates the store at once; only a real unmount lets this abort.
171
+ setTimeout(() => {
172
+ if (!store.active)
173
+ store.abortAll();
174
+ }, 0);
175
+ };
176
+ }, [store, entryKey, definitionsKey, locale]);
177
+ const value = useMemo(() => ({ store, entryKey, route, listed: new Set(definitions), applicable: new Set(applicableList) }),
178
+ // The sets are rebuilt only when the definitions (by identity) or the key change, not on each parent render.
179
+ // eslint-disable-next-line react-hooks/exhaustive-deps
180
+ [store, entryKey, route?.pattern, route?.context, listedKey, definitionsKey]);
181
+ const failure = useSyncExternalStore(store.subscribe, () => store.failure(entryKey), () => store.failure(entryKey));
182
+ const anyNotFound = useSyncExternalStore(store.subscribe, () => store.hasNotFound(entryKey), () => store.hasNotFound(entryKey));
183
+ const { notFound } = useRoute();
184
+ useEffect(() => {
185
+ if (anyNotFound)
186
+ notFound();
187
+ }, [anyNotFound, notFound]);
188
+ const { ErrorFallback } = useContentContext();
189
+ if (failure !== undefined) {
190
+ const Panel = errorComponent ?? ErrorFallback;
191
+ return _jsx(Panel, { error: failure.error, path: path });
192
+ }
193
+ return _jsx(RouteDataContext.Provider, { value: value, children: children });
194
+ }
195
+ /**
196
+ * The data a route-bound loader fetched for this page. Every section that calls it with the same
197
+ * definition shares one load, however many there are.
198
+ *
199
+ * ```tsx
200
+ * const person = useRouteData(personData)
201
+ * if (person.status === 'loading') return <Skeleton />
202
+ * if (person.status === 'ready') return <h1>{person.value.name}</h1>
203
+ * return null // 'notFound': the page is already drawing the site's not-found
204
+ * ```
205
+ *
206
+ * `definition` must be one of the list given to `<Experience routeData>`; anything else throws.
207
+ * When the page has a route whose tag is not the definition's (or has none), reading it throws in
208
+ * development, naming both tags; in production it reports `notFound`. On a page with no route it
209
+ * reports `notFound` in both modes. Listing a definition no section reads on such a page is fine.
210
+ */
211
+ export function useRouteData(definition) {
212
+ const context = useContext(RouteDataContext);
213
+ if (context === null) {
214
+ throw new Error('@ebitex/content-sdk/react: useRouteData needs a page rendered by <Experience routeData={[…]}>, and none encloses this component.');
215
+ }
216
+ if (!context.listed.has(definition)) {
217
+ throw new Error(`@ebitex/content-sdk/react: useRouteData was given a definition for "${definition.context}" that is not in this page's <Experience routeData>. Add it to the list.`);
218
+ }
219
+ const applies = context.applicable.has(definition);
220
+ if (!applies && context.route !== undefined && isDevelopment())
221
+ throw new Error(describeMismatch(definition, context.route));
222
+ const state = useSyncExternalStore(context.store.subscribe, () => (applies ? context.store.read(definition, context.entryKey) : NOT_FOUND_STATE), () => (applies ? context.store.read(definition, context.entryKey) : NOT_FOUND_STATE));
223
+ return state;
224
+ }
225
+ //# sourceMappingURL=routeData.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routeData.js","sourceRoot":"","sources":["../../src/react/routeData.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,oBAAoB,EAAsC,MAAM,OAAO,CAAA;AACvI,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAC3C,OAAO,EACL,sBAAsB,EACtB,gBAAgB,EAChB,UAAU,EACV,YAAY,EACZ,SAAS,GAKV,MAAM,iBAAiB,CAAA;AAExB,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAA;AAExD,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAe5C,MAAM,OAAO,GAAY,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,SAAkB,EAAE,CAAC,CAAA;AACtE,MAAM,eAAe,GAAY,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,UAAmB,EAAE,CAAC,CAAA;AAQ/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;IAED,MAAM,OAAO,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,UAAU,CAAC,CAAA;IAClD,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,KAAK,KAAK,SAAS,IAAI,aAAa,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,UAAU,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,CAAA;IAC5H,MAAM,KAAK,GAAG,oBAAoB,CAChC,OAAO,CAAC,KAAK,CAAC,SAAS,EACvB,GAAG,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,EACpF,GAAG,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CACrF,CAAA;IAED,OAAO,KAAiD,CAAA;AAC1D,CAAC"}
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Pure helpers for parameterised addresses (`/products/{key}`): no React, no network, no client.
3
+ * The pattern is the form the Delivery API reports in `route.pattern` and in a link's `route`: a
4
+ * path whose parameter segments are a name in braces. A parameter is a whole segment, never part of
5
+ * one, and a value never contains a `/`.
6
+ */
7
+ /** The parameter names in a pattern literal, as a union: `ParamNames<'/a/{x}/b/{y}'>` is `'x' | 'y'`. */
8
+ export type ParamNames<TPattern extends string> = TPattern extends `${string}{${infer Name}}${infer Rest}` ? Name | ParamNames<Rest> : never;
9
+ /**
10
+ * The values a pattern needs, keyed by parameter name: `RouteParams<'/products/{key}'>` is
11
+ * `{ key: string }`. A pattern the compiler cannot see (a `string`, not a literal) is
12
+ * `Record<string, string>`.
13
+ */
14
+ export type RouteParams<TPattern extends string> = string extends TPattern ? Record<string, string> : [ParamNames<TPattern>] extends [never] ? Record<string, never> : {
15
+ [Name in ParamNames<TPattern>]: string;
16
+ };
17
+ /** One segment of a parsed pattern: fixed text, or a parameter. */
18
+ export type RouteSegment = {
19
+ kind: 'literal';
20
+ value: string;
21
+ } | {
22
+ kind: 'parameter';
23
+ name: string;
24
+ };
25
+ export interface ParsedRoute {
26
+ pattern: string;
27
+ /** Every segment in order, including the empty one a trailing slash leaves. */
28
+ segments: RouteSegment[];
29
+ /** The parameter names in the order they appear. */
30
+ parameters: string[];
31
+ }
32
+ /**
33
+ * Splits a pattern into its segments. Throws when a segment mixes text and braces (`a{b}`), a
34
+ * brace is unbalanced, a parameter has no name, or a name appears twice.
35
+ *
36
+ * ```ts
37
+ * parseRoute('/products/{key}').parameters // ['key']
38
+ * ```
39
+ */
40
+ export declare function parseRoute(pattern: string): ParsedRoute;
41
+ /**
42
+ * Fills a pattern with a value for each parameter, percent-encoding every value, so the result is
43
+ * a path to link to or navigate to. Throws when a parameter has no value or an empty one: an
44
+ * address with a hole in it is never what a caller meant.
45
+ *
46
+ * ```ts
47
+ * fillRoute('/products/{key}', { key: 'trail runner' }) // '/products/trail%20runner'
48
+ * ```
49
+ *
50
+ * With a pattern the compiler can read (a string literal), the values are checked at compile time.
51
+ */
52
+ export declare function fillRoute<TPattern extends string>(pattern: TPattern, params: RouteParams<TPattern>): string;
53
+ //# sourceMappingURL=route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../src/route.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AAEH,yGAAyG;AACzG,MAAM,MAAM,UAAU,CAAC,QAAQ,SAAS,MAAM,IAAI,QAAQ,SAAS,GAAG,MAAM,IAAI,MAAM,IAAI,IAAI,MAAM,IAAI,EAAE,GAAG,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC,GAAG,KAAK,CAAA;AAE5I;;;;GAIG;AACH,MAAM,MAAM,WAAW,CAAC,QAAQ,SAAS,MAAM,IAAI,MAAM,SAAS,QAAQ,GACtE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACtB,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,GACpC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,GACrB;KAAG,IAAI,IAAI,UAAU,CAAC,QAAQ,CAAC,GAAG,MAAM;CAAE,CAAA;AAEhD,mEAAmE;AACnE,MAAM,MAAM,YAAY,GAAG;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAA;AAEnG,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAA;IACf,+EAA+E;IAC/E,QAAQ,EAAE,YAAY,EAAE,CAAA;IACxB,oDAAoD;IACpD,UAAU,EAAE,MAAM,EAAE,CAAA;CACrB;AAED;;;;;;;GAOG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW,CAwBvD;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,QAAQ,SAAS,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,CAAC,QAAQ,CAAC,GAAG,MAAM,CAc3G"}
package/dist/route.js ADDED
@@ -0,0 +1,55 @@
1
+ import { ContentSdkError } from './errors.js';
2
+ /**
3
+ * Splits a pattern into its segments. Throws when a segment mixes text and braces (`a{b}`), a
4
+ * brace is unbalanced, a parameter has no name, or a name appears twice.
5
+ *
6
+ * ```ts
7
+ * parseRoute('/products/{key}').parameters // ['key']
8
+ * ```
9
+ */
10
+ export function parseRoute(pattern) {
11
+ const segments = [];
12
+ const parameters = [];
13
+ for (const part of pattern.split('/')) {
14
+ if (!part.includes('{') && !part.includes('}')) {
15
+ segments.push({ kind: 'literal', value: part });
16
+ continue;
17
+ }
18
+ const name = part.length > 2 && part.startsWith('{') && part.endsWith('}') ? part.slice(1, -1) : undefined;
19
+ if (name === undefined || name.includes('{') || name.includes('}')) {
20
+ throw new ContentSdkError('invalid_options', `"${pattern}" is not a route pattern: the segment "${part}" must be a parameter name alone in braces, such as {key}.`, { pattern, segment: part });
21
+ }
22
+ if (parameters.includes(name)) {
23
+ throw new ContentSdkError('invalid_options', `"${pattern}" is not a route pattern: the parameter {${name}} appears twice.`, { pattern, parameter: name });
24
+ }
25
+ parameters.push(name);
26
+ segments.push({ kind: 'parameter', name });
27
+ }
28
+ return { pattern, segments, parameters };
29
+ }
30
+ /**
31
+ * Fills a pattern with a value for each parameter, percent-encoding every value, so the result is
32
+ * a path to link to or navigate to. Throws when a parameter has no value or an empty one: an
33
+ * address with a hole in it is never what a caller meant.
34
+ *
35
+ * ```ts
36
+ * fillRoute('/products/{key}', { key: 'trail runner' }) // '/products/trail%20runner'
37
+ * ```
38
+ *
39
+ * With a pattern the compiler can read (a string literal), the values are checked at compile time.
40
+ */
41
+ export function fillRoute(pattern, params) {
42
+ const values = params;
43
+ return parseRoute(pattern)
44
+ .segments.map((segment) => {
45
+ if (segment.kind === 'literal')
46
+ return segment.value;
47
+ const value = values[segment.name];
48
+ if (typeof value !== 'string' || value === '') {
49
+ throw new ContentSdkError('invalid_options', `Cannot fill "${pattern}": the parameter {${segment.name}} has no value.`, { pattern, parameter: segment.name });
50
+ }
51
+ return encodeURIComponent(value);
52
+ })
53
+ .join('/');
54
+ }
55
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route.js","sourceRoot":"","sources":["../src/route.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAkC7C;;;;;;;GAOG;AACH,MAAM,UAAU,UAAU,CAAC,OAAe;IACxC,MAAM,QAAQ,GAAmB,EAAE,CAAA;IACnC,MAAM,UAAU,GAAa,EAAE,CAAA;IAE/B,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,KAAK,CAAC,G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;;GAUG;AACH,MAAM,UAAU,SAAS,CAA0B,OAAiB,EAAE,MAA6B;IACjG,MAAM,MAAM,GAAG,MAA4C,CAAA;IAC3D,OAAO,UAAU,CAAC,OAAO,CAAC;SACvB,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE;QACxB,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS;YAAE,OAAO,OAAO,CAAC,KAAK,CAAA;QAEpD,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;QAClC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,EAAE,EAAE,CAAC;YAC9C,MAAM,IAAI,eAAe,CAAC,iBAAiB,EAAE,gBAAgB,OAAO,qBAAqB,OAAO,CAAC,IAAI,iBAAiB,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAA;QAC/J,CAAC;QAED,OAAO,kBAAkB,CAAC,KAAK,CAAC,CAAA;IAClC,CAAC,CAAC;SACD,IAAI,CAAC,GAAG,CAAC,CAAA;AACd,CAAC"}
@@ -0,0 +1,117 @@
1
+ import type { RouteResult } from './types.js';
2
+ /**
3
+ * Data that belongs to a parameterised page rather than to any one section on it. A route's
4
+ * parameter (`/products/{key}`) names something the Content tree does not hold, so the host says
5
+ * how to fetch it once, here, and every section on the page reads the same result.
6
+ *
7
+ * This file has no React in it: it is what a server uses to load the data and answer a real `404`
8
+ * before rendering. The React side is `<Experience routeData>` and `useRouteData`, in
9
+ * `@ebitex/content-sdk/react`.
10
+ */
11
+ declare const NOT_FOUND: unique symbol;
12
+ /** What a loader returns when the value in the address names nothing. See {@link NotFound}. */
13
+ export interface NotFound {
14
+ readonly [NOT_FOUND]: true;
15
+ }
16
+ /**
17
+ * The marker a loader returns (or resolves to) when the value in the address names nothing:
18
+ * `return NotFound`. The page then draws the host's not-found, and a server answers a real `404`.
19
+ * Content never decides this, because Content never interprets the value.
20
+ */
21
+ export declare const NotFound: NotFound;
22
+ /** True for the {@link NotFound} marker, including one made by another copy of this package. */
23
+ export declare function isNotFound(value: unknown): value is NotFound;
24
+ /** What a loader is given besides the parameters. */
25
+ export interface RouteDataLoadOptions {
26
+ /** The locale the page resolved in, when there is one. */
27
+ locale: string | undefined;
28
+ /** Aborted when the page moves to other parameters or unmounts. Pass it to `fetch`. */
29
+ signal: AbortSignal;
30
+ }
31
+ /**
32
+ * A loader bound to a route context tag. Made by {@link defineRouteData}; pass it in the list given
33
+ * to `<Experience routeData>` and read it with `useRouteData`.
34
+ */
35
+ export interface RouteDataDefinition<TContext extends string = string, TData = unknown, TParams = never> {
36
+ /** The tag the page's route must carry for this loader to run. */
37
+ readonly context: TContext;
38
+ readonly load: (params: TParams, options: RouteDataLoadOptions) => Promise<TData | NotFound>;
39
+ }
40
+ /** Any definition, whatever its parameters: what a list of them is typed as. */
41
+ export type AnyRouteDataDefinition = RouteDataDefinition<string, unknown, never>;
42
+ /** The data a definition loads. */
43
+ export type RouteDataOf<TDefinition> = TDefinition extends RouteDataDefinition<string, infer TData, never> ? TData : never;
44
+ /**
45
+ * Binds a route context tag to a loader.
46
+ *
47
+ * ```ts
48
+ * const personData = defineRouteData({
49
+ * context: 'people.person',
50
+ * load: async ({ slug }, { signal }) => {
51
+ * const response = await fetch(`/api/people/${encodeURIComponent(slug)}`, { signal })
52
+ * return response.ok ? ((await response.json()) as Person) : NotFound
53
+ * },
54
+ * })
55
+ * ```
56
+ *
57
+ * `load` receives the route's parameters (annotate them to type them: `({ slug }: { slug: string })`)
58
+ * and returns the data, or {@link NotFound}. It runs once per parameter set however many sections read it.
59
+ * The tag is the contract between this loader and the page: the page's parameter node must carry
60
+ * the same one, and in development a section that reads a loader whose tag differs from the delivered one throws.
61
+ */
62
+ export declare function defineRouteData<TContext extends string, TData, TParams extends Record<string, string> = Record<string, string>>(definition: {
63
+ context: TContext;
64
+ load: (params: TParams, options: RouteDataLoadOptions) => Promise<TData | NotFound>;
65
+ }): RouteDataDefinition<TContext, TData, TParams>;
66
+ /**
67
+ * True when the definition applies to the delivered route: the page has a route and its tag is the
68
+ * definition's. Pure: never throws, in either mode, so a list of definitions can be filtered with
69
+ * it on any page (a loader listed for one address is simply skipped on another).
70
+ */
71
+ export declare function matchesRoute(definition: AnyRouteDataDefinition, route: RouteResult | undefined): boolean;
72
+ /**
73
+ * The development message for a definition that does not match a route that exists, naming both
74
+ * tags. Thrown by `useRouteData` when a section reads a definition its page does not carry the tag
75
+ * for: the mistake is in the section that reads it, not in listing the definition.
76
+ */
77
+ export declare function describeMismatch(definition: AnyRouteDataDefinition, route: RouteResult): string;
78
+ /** Throws when two definitions share a tag, since the values are keyed by it. */
79
+ export declare function assertDistinctContexts(definitions: readonly AnyRouteDataDefinition[]): void;
80
+ /**
81
+ * The loaded data, keyed by route context tag, in a form that survives `JSON.stringify` so a
82
+ * server can hand it to the browser as the page's initial state (`<Experience initialRouteData>`).
83
+ */
84
+ export interface RouteDataSnapshot {
85
+ /** The data of every definition that loaded, by tag. */
86
+ values: Record<string, unknown>;
87
+ /** The tags whose loader answered {@link NotFound}. */
88
+ missing?: string[];
89
+ }
90
+ /** What {@link loadRouteData} returns. */
91
+ export interface LoadedRouteData extends RouteDataSnapshot {
92
+ /** True when any loader answered {@link NotFound}: the host should answer a real `404`. */
93
+ notFound: boolean;
94
+ missing: string[];
95
+ }
96
+ /** The same key for the same parameters, whatever order they were built in. */
97
+ export declare function paramsKey(params: Record<string, string>): string;
98
+ /**
99
+ * Loads the data a route needs, without React: for a server that resolved the page, to answer a
100
+ * real `404` before rendering and to hand the values to `<Experience initialRouteData>` so the
101
+ * browser does not load them again.
102
+ *
103
+ * ```ts
104
+ * const result = await client.resolveLocation(url)
105
+ * const data = result.kind === 'presentation' ? await loadRouteData([personData], result.route, { locale: result.locale }) : undefined
106
+ * if (data?.notFound) return new Response('Not found', { status: 404 })
107
+ * ```
108
+ *
109
+ * Only definitions whose tag matches the route's run; with no route (an ordinary page) nothing
110
+ * runs. A definition for another address is skipped, never an error, in either mode. A loader's own errors reject this promise.
111
+ */
112
+ export declare function loadRouteData(definitions: readonly AnyRouteDataDefinition[], route: RouteResult | undefined, options?: {
113
+ locale?: string;
114
+ signal?: AbortSignal;
115
+ }): Promise<LoadedRouteData>;
116
+ export {};
117
+ //# sourceMappingURL=routeData.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routeData.d.ts","sourceRoot":"","sources":["../src/routeData.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAE7C;;;;;;;;GAQG;AAEH,QAAA,MAAM,SAAS,eAAkD,CAAA;AAEjE,+FAA+F;AAC/F,MAAM,WAAW,QAAQ;IACvB,QAAQ,CAAC,CAAC,SAAS,CAAC,EAAE,IAAI,CAAA;CAC3B;AAED;;;;GAIG;AACH,eAAO,MAAM,QAAQ,EAAE,QAAwD,CAAA;AAE/E,gGAAgG;AAChG,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAE5D;AAED,qDAAqD;AACrD,MAAM,WAAW,oBAAoB;IACnC,0DAA0D;IAC1D,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B,uFAAuF;IACvF,MAAM,EAAE,WAAW,CAAA;CACpB;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAmB,CAAC,QAAQ,SAAS,MAAM,GAAG,MAAM,EAAE,KAAK,GAAG,OAAO,EAAE,OAAO,GAAG,KAAK;IACrG,kEAAkE;IAClE,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAA;IAC1B,QAAQ,CAAC,IAAI,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,oBAAoB,KAAK,OAAO,CAAC,KAAK,GAAG,QAAQ,CAAC,CAAA;CAC7F;AAED,gFAAgF;AAChF,MAAM,MAAM,sBAAsB,GAAG,mBAAmB,CAAC,MAAM,EAAE,OAAO,EAAE,K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ClB;AAED,+EAA+E;AAC/E,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAEhE;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,aAAa,CACjC,WAAW,EAAE,SAAS,sBAAsB,EAAE,EAC9C,KAAK,EAAE,WAAW,GAAG,SAAS,EAC9B,OAAO,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,WAAW,CAAA;CAAO,GACtD,OAAO,CAAC,eAAe,CAAC,CAoB1B"}
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Data that belongs to a parameterised page rather than to any one section on it. A route's
3
+ * parameter (`/products/{key}`) names something the Content tree does not hold, so the host says
4
+ * how to fetch it once, here, and every section on the page reads the same result.
5
+ *
6
+ * This file has no React in it: it is what a server uses to load the data and answer a real `404`
7
+ * before rendering. The React side is `<Experience routeData>` and `useRouteData`, in
8
+ * `@ebitex/content-sdk/react`.
9
+ */
10
+ const NOT_FOUND = Symbol.for('ebitex.content.routeData.notFound');
11
+ /**
12
+ * The marker a loader returns (or resolves to) when the value in the address names nothing:
13
+ * `return NotFound`. The page then draws the host's not-found, and a server answers a real `404`.
14
+ * Content never decides this, because Content never interprets the value.
15
+ */
16
+ export const NotFound = Object.freeze({ [NOT_FOUND]: true });
17
+ /** True for the {@link NotFound} marker, including one made by another copy of this package. */
18
+ export function isNotFound(value) {
19
+ return typeof value === 'object' && value !== null && value[NOT_FOUND] === true;
20
+ }
21
+ /**
22
+ * Binds a route context tag to a loader.
23
+ *
24
+ * ```ts
25
+ * const personData = defineRouteData({
26
+ * context: 'people.person',
27
+ * load: async ({ slug }, { signal }) => {
28
+ * const response = await fetch(`/api/people/${encodeURIComponent(slug)}`, { signal })
29
+ * return response.ok ? ((await response.json()) as Person) : NotFound
30
+ * },
31
+ * })
32
+ * ```
33
+ *
34
+ * `load` receives the route's parameters (annotate them to type them: `({ slug }: { slug: string })`)
35
+ * and returns the data, or {@link NotFound}. It runs once per parameter set however many sections read it.
36
+ * The tag is the contract between this loader and the page: the page's parameter node must carry
37
+ * the same one, and in development a section that reads a loader whose tag differs from the delivered one throws.
38
+ */
39
+ export function defineRouteData(definition) {
40
+ return Object.freeze({ context: definition.context, load: definition.load });
41
+ }
42
+ /**
43
+ * True when the definition applies to the delivered route: the page has a route and its tag is the
44
+ * definition's. Pure: never throws, in either mode, so a list of definitions can be filtered with
45
+ * it on any page (a loader listed for one address is simply skipped on another).
46
+ */
47
+ export function matchesRoute(definition, route) {
48
+ return route !== undefined && route.context === definition.context;
49
+ }
50
+ /**
51
+ * The development message for a definition that does not match a route that exists, naming both
52
+ * tags. Thrown by `useRouteData` when a section reads a definition its page does not carry the tag
53
+ * for: the mistake is in the section that reads it, not in listing the definition.
54
+ */
55
+ export function describeMismatch(definition, route) {
56
+ const delivered = route.context === undefined ? 'no route context tag' : `the route context tag "${route.context}"`;
57
+ return (`@ebitex/content-sdk: the route data definition for "${definition.context}" does not match this page: its address "${route.pattern}" carries ${delivered}. ` +
58
+ 'Give the parameter node the tag the loader names, or read this loader only in sections placed on the pages it belongs to.');
59
+ }
60
+ /** Throws when two definitions share a tag, since the values are keyed by it. */
61
+ export function assertDistinctContexts(definitions) {
62
+ const seen = new Set();
63
+ for (const definition of definitions) {
64
+ if (seen.has(definition.context)) {
65
+ throw new Error(`@ebitex/content-sdk: two route data definitions name the context "${definition.context}". Each tag takes one loader; return both pieces of data from one.`);
66
+ }
67
+ seen.add(definition.context);
68
+ }
69
+ }
70
+ /** The same key for the same parameters, whatever order they were built in. */
71
+ export function paramsKey(params) {
72
+ return JSON.stringify(Object.entries(params).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
73
+ }
74
+ /**
75
+ * Loads the data a route needs, without React: for a server that resolved the page, to answer a
76
+ * real `404` before rendering and to hand the values to `<Experience initialRouteData>` so the
77
+ * browser does not load them again.
78
+ *
79
+ * ```ts
80
+ * const result = await client.resolveLocation(url)
81
+ * const data = result.kind === 'presentation' ? await loadRouteData([personData], result.route, { locale: result.locale }) : undefined
82
+ * if (data?.notFound) return new Response('Not found', { status: 404 })
83
+ * ```
84
+ *
85
+ * Only definitions whose tag matches the route's run; with no route (an ordinary page) nothing
86
+ * runs. A definition for another address is skipped, never an error, in either mode. A loader's own errors reject this promise.
87
+ */
88
+ export async function loadRouteData(definitions, route, options = {}) {
89
+ assertDistinctContexts(definitions);
90
+ const signal = options.signal ?? new AbortController().signal;
91
+ const loaded = { notFound: false, values: {}, missing: [] };
92
+ const applicable = definitions.filter((definition) => matchesRoute(definition, route));
93
+ await Promise.all(applicable.map(async (definition) => {
94
+ const result = await definition.load(route?.params ?? {}, { locale: options.locale, signal });
95
+ if (isNotFound(result)) {
96
+ loaded.missing.push(definition.context);
97
+ loaded.notFound = true;
98
+ }
99
+ else {
100
+ loaded.values[definition.context] = result;
101
+ }
102
+ }));
103
+ loaded.missing.sort();
104
+ return loaded;
105
+ }
106
+ //# sourceMappingURL=routeData.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routeData.js","sourceRoot":"","sources":["../src/routeData.ts"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AAEH,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAA;AAOjE;;;;GAIG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAa,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,SAAS,CAAC,EAAE,IAAa,EAAE,CAAC,CAAA;AAE/E,gGAAgG;AAChG,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,SAAS,CAAC,KAAK,IAAI,CAAA;AAC9G,CAAC;AA0BD;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,eAAe,CAAkG,UAGhI;IACC,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,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