@ebitex/content-sdk 1.1.282 → 1.1.326

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 +52 -0
  36. package/dist/react/routeData.d.ts.map +1 -0
  37. package/dist/react/routeData.js +219 -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 +112 -0
  44. package/dist/routeData.d.ts.map +1 -0
  45. package/dist/routeData.js +107 -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,219 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';
3
+ import { isAbortError } from '../errors.js';
4
+ import { appliesToRoute, assertDistinctContexts, isNotFound, paramsKey, } from '../routeData.js';
5
+ import { useContentContext } from './ContentProvider.js';
6
+ import { useRoute } from './routeContext.js';
7
+ const LOADING = Object.freeze({ status: 'loading' });
8
+ const NOT_FOUND_STATE = Object.freeze({ status: 'notFound' });
9
+ /**
10
+ * One load per definition and parameter set, shared by every section that reads it. The cache is
11
+ * keyed by the definition's identity and the serialized parameters (and locale), held for the
12
+ * life of the boundary: never by an effect over an array or function the parent rebuilds on each
13
+ * render.
14
+ */
15
+ class RouteDataStore {
16
+ entries = new Map();
17
+ listeners = new Set();
18
+ /** True while the boundary is mounted (and not between a strict-mode unmount and its immediate remount). */
19
+ active = false;
20
+ subscribe = (listener) => {
21
+ this.listeners.add(listener);
22
+ return () => this.listeners.delete(listener);
23
+ };
24
+ notify() {
25
+ for (const listener of this.listeners)
26
+ listener();
27
+ }
28
+ slot(definition) {
29
+ let slot = this.entries.get(definition);
30
+ if (slot === undefined) {
31
+ slot = new Map();
32
+ this.entries.set(definition, slot);
33
+ }
34
+ return slot;
35
+ }
36
+ /** Puts a server's already-loaded values in place, so the first render has them and nothing loads. */
37
+ seed(definitions, entryKey, snapshot) {
38
+ for (const definition of definitions) {
39
+ if (snapshot.missing?.includes(definition.context)) {
40
+ this.slot(definition).set(entryKey, { state: NOT_FOUND_STATE, controller: undefined });
41
+ }
42
+ else if (Object.hasOwn(snapshot.values, definition.context)) {
43
+ this.slot(definition).set(entryKey, { state: { status: 'ready', value: snapshot.values[definition.context] }, controller: undefined });
44
+ }
45
+ }
46
+ }
47
+ read(definition, entryKey) {
48
+ return this.entries.get(definition)?.get(entryKey)?.state ?? LOADING;
49
+ }
50
+ /** The first failed load for this key, if any. Stable until the failure changes. */
51
+ failure(entryKey) {
52
+ for (const slot of this.entries.values()) {
53
+ const state = slot.get(entryKey)?.state;
54
+ if (state?.status === 'error')
55
+ return this.failureOf(state);
56
+ }
57
+ return undefined;
58
+ }
59
+ failures = new WeakMap();
60
+ failureOf(state) {
61
+ let failure = this.failures.get(state);
62
+ if (failure === undefined) {
63
+ failure = { error: state.error };
64
+ this.failures.set(state, failure);
65
+ }
66
+ return failure;
67
+ }
68
+ hasNotFound(entryKey) {
69
+ for (const slot of this.entries.values()) {
70
+ if (slot.get(entryKey)?.state.status === 'notFound')
71
+ return true;
72
+ }
73
+ return false;
74
+ }
75
+ /**
76
+ * Makes `entryKey` the current parameter set: aborts and forgets everything loaded or loading for
77
+ * another, then starts a load for each applicable definition that has none yet.
78
+ */
79
+ start(definitions, params, entryKey, locale) {
80
+ let changed = false;
81
+ for (const slot of this.entries.values()) {
82
+ for (const [key, entry] of slot) {
83
+ if (key === entryKey)
84
+ continue;
85
+ entry.controller?.abort();
86
+ slot.delete(key);
87
+ changed = true;
88
+ }
89
+ }
90
+ for (const definition of definitions) {
91
+ const slot = this.slot(definition);
92
+ if (slot.has(entryKey))
93
+ continue;
94
+ const controller = new AbortController();
95
+ const entry = { state: LOADING, controller };
96
+ slot.set(entryKey, entry);
97
+ changed = true;
98
+ const settle = (state) => {
99
+ if (controller.signal.aborted)
100
+ return;
101
+ entry.state = state;
102
+ entry.controller = undefined;
103
+ this.notify();
104
+ };
105
+ const options = { locale, signal: controller.signal };
106
+ let pending;
107
+ try {
108
+ pending = definition.load(params, options);
109
+ }
110
+ catch (error) {
111
+ pending = Promise.reject(error);
112
+ }
113
+ pending.then((result) => settle(isNotFound(result) ? NOT_FOUND_STATE : { status: 'ready', value: result }), (error) => {
114
+ if (!isAbortError(error))
115
+ settle({ status: 'error', error });
116
+ });
117
+ }
118
+ if (changed)
119
+ this.notify();
120
+ }
121
+ abortAll() {
122
+ for (const slot of this.entries.values()) {
123
+ for (const entry of slot.values())
124
+ entry.controller?.abort();
125
+ }
126
+ }
127
+ }
128
+ const RouteDataContext = createContext(null);
129
+ const definitionIds = new WeakMap();
130
+ let nextDefinitionId = 1;
131
+ function idOf(definition) {
132
+ let id = definitionIds.get(definition);
133
+ if (id === undefined) {
134
+ id = nextDefinitionId++;
135
+ definitionIds.set(definition, id);
136
+ }
137
+ return id;
138
+ }
139
+ /**
140
+ * Mounted by `<Experience routeData>` inside the route context. Loads each definition whose tag
141
+ * matches the delivered route, once per parameter set; asks the route to render the host's
142
+ * not-found when a loader answers `NotFound`; replaces the page with the provider's error panel
143
+ * when a loader throws. With no route on the result (an ordinary page, an older server) no loader
144
+ * runs, and the page renders as it would without the boundary.
145
+ */
146
+ export function RouteDataBoundary({ definitions, initial, route, locale, path, errorComponent, children }) {
147
+ assertDistinctContexts(definitions);
148
+ // Throws in development when a tag differs from the delivered one, before anything mounts.
149
+ const applicableList = definitions.filter((definition) => appliesToRoute(definition, route));
150
+ const params = route?.params;
151
+ const entryKey = `${params === undefined ? '' : paramsKey(params)}|${locale ?? ''}`;
152
+ const definitionsKey = applicableList.map(idOf).join(',');
153
+ const listedKey = definitions.map(idOf).join(',');
154
+ const storeRef = useRef(null);
155
+ if (storeRef.current === null) {
156
+ storeRef.current = new RouteDataStore();
157
+ if (initial !== undefined)
158
+ storeRef.current.seed(applicableList, entryKey, initial);
159
+ }
160
+ const store = storeRef.current;
161
+ // 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.
162
+ const latest = useRef({ applicableList, params });
163
+ latest.current = { applicableList, params };
164
+ useEffect(() => {
165
+ store.active = true;
166
+ store.start(latest.current.applicableList, latest.current.params ?? {}, entryKey, locale);
167
+ return () => {
168
+ store.active = false;
169
+ // A strict-mode remount re-activates the store at once; only a real unmount lets this abort.
170
+ setTimeout(() => {
171
+ if (!store.active)
172
+ store.abortAll();
173
+ }, 0);
174
+ };
175
+ }, [store, entryKey, definitionsKey, locale]);
176
+ const value = useMemo(() => ({ store, entryKey, listed: new Set(definitions), applicable: new Set(applicableList) }),
177
+ // The sets are rebuilt only when the definitions (by identity) or the key change, not on each parent render.
178
+ // eslint-disable-next-line react-hooks/exhaustive-deps
179
+ [store, entryKey, listedKey, definitionsKey]);
180
+ const failure = useSyncExternalStore(store.subscribe, () => store.failure(entryKey), () => store.failure(entryKey));
181
+ const anyNotFound = useSyncExternalStore(store.subscribe, () => store.hasNotFound(entryKey), () => store.hasNotFound(entryKey));
182
+ const { notFound } = useRoute();
183
+ useEffect(() => {
184
+ if (anyNotFound)
185
+ notFound();
186
+ }, [anyNotFound, notFound]);
187
+ const { ErrorFallback } = useContentContext();
188
+ if (failure !== undefined) {
189
+ const Panel = errorComponent ?? ErrorFallback;
190
+ return _jsx(Panel, { error: failure.error, path: path });
191
+ }
192
+ return _jsx(RouteDataContext.Provider, { value: value, children: children });
193
+ }
194
+ /**
195
+ * The data a route-bound loader fetched for this page. Every section that calls it with the same
196
+ * definition shares one load, however many there are.
197
+ *
198
+ * ```tsx
199
+ * const person = useRouteData(personData)
200
+ * if (person.status === 'loading') return <Skeleton />
201
+ * if (person.status === 'ready') return <h1>{person.value.name}</h1>
202
+ * return null // 'notFound': the page is already drawing the site's not-found
203
+ * ```
204
+ *
205
+ * `definition` must be one of the list given to `<Experience routeData>`; anything else throws.
206
+ */
207
+ export function useRouteData(definition) {
208
+ const context = useContext(RouteDataContext);
209
+ if (context === null) {
210
+ throw new Error('@ebitex/content-sdk/react: useRouteData needs a page rendered by <Experience routeData={[…]}>, and none encloses this component.');
211
+ }
212
+ if (!context.listed.has(definition)) {
213
+ 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.`);
214
+ }
215
+ const applies = context.applicable.has(definition);
216
+ 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));
217
+ return state;
218
+ }
219
+ //# 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,YAAY,EAAE,MAAM,cAAc,CAAA;AAC3C,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,UAAU,EACV,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/E;;;;;GAKG;AACH,MAAM,cAAc;IACD,OAAO,GAAG,IAAI,GAAG,EAA8C,CAAA;IAC/D,SAAS,GAAG,IAAI,GAAG,EAAc,CAAA;IAClD,4GAA4G;IAC5G,MAAM,GAAG,KAAK,CAAA;IAEd,SAAS,GAAG,CAAC,QAAoB,EAAgB,EAAE;QACjD,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;QAC5B,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,MA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I,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,GAAG,CAAC,EAAE,CAAC;QACtC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YAC/C,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAA;YAC/C,SAAQ;QACV,CAAC;QAED,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;QAC1G,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,QAAQ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AAE,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,112 @@
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 a loader whose tag differs from the delivered one is refused in development.
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
+ * Decides whether a definition applies to the delivered route: `true` to load, `false` when there
68
+ * is no route at all (an ordinary page, or a server that predates parameterised addresses). A route
69
+ * whose tag differs from the definition's (or that has none) throws in development, naming both
70
+ * tags, and is skipped in production.
71
+ */
72
+ export declare function appliesToRoute(definition: AnyRouteDataDefinition, route: RouteResult | undefined): boolean;
73
+ /** Throws when two definitions share a tag, since the values are keyed by it. */
74
+ export declare function assertDistinctContexts(definitions: readonly AnyRouteDataDefinition[]): void;
75
+ /**
76
+ * The loaded data, keyed by route context tag, in a form that survives `JSON.stringify` so a
77
+ * server can hand it to the browser as the page's initial state (`<Experience initialRouteData>`).
78
+ */
79
+ export interface RouteDataSnapshot {
80
+ /** The data of every definition that loaded, by tag. */
81
+ values: Record<string, unknown>;
82
+ /** The tags whose loader answered {@link NotFound}. */
83
+ missing?: string[];
84
+ }
85
+ /** What {@link loadRouteData} returns. */
86
+ export interface LoadedRouteData extends RouteDataSnapshot {
87
+ /** True when any loader answered {@link NotFound}: the host should answer a real `404`. */
88
+ notFound: boolean;
89
+ missing: string[];
90
+ }
91
+ /** The same key for the same parameters, whatever order they were built in. */
92
+ export declare function paramsKey(params: Record<string, string>): string;
93
+ /**
94
+ * Loads the data a route needs, without React: for a server that resolved the page, to answer a
95
+ * real `404` before rendering and to hand the values to `<Experience initialRouteData>` so the
96
+ * browser does not load them again.
97
+ *
98
+ * ```ts
99
+ * const result = await client.resolveLocation(url)
100
+ * const data = result.kind === 'presentation' ? await loadRouteData([personData], result.route, { locale: result.locale }) : undefined
101
+ * if (data?.notFound) return new Response('Not found', { status: 404 })
102
+ * ```
103
+ *
104
+ * Only definitions whose tag matches the route's run; with no route (an ordinary page) nothing
105
+ * runs. A loader's own errors reject this promise.
106
+ */
107
+ export declare function loadRouteData(definitions: readonly AnyRouteDataDefinition[], route: RouteResult | undefined, options?: {
108
+ locale?: string;
109
+ signal?: AbortSignal;
110
+ }): Promise<LoadedRouteData>;
111
+ export {};
112
+ //# sourceMappingURL=routeData.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routeData.d.ts","sourceRoot":"","sources":["../src/routeData.ts"],"names":[],"mappings":"AACA,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,MA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AgB,sBAAsB,CAAC,WAAW,EAAE,SAAS,sBAAsB,EAAE,GAAG,IAAI,CAQ3F;AAED;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,wDAAwD;IACxD,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,uDAAuD;IACvD,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;CACnB;AAED,0CAA0C;AAC1C,MAAM,WAAW,eAAgB,SAAQ,iBAAiB;IACxD,2FAA2F;IAC3F,QAAQ,EAAE,OAAO,CAAA;IACjB,OAAO,EAAE,MAAM,EAAE,CAAA;CAClB;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,107 @@
1
+ import { isDevelopment } from './environment.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
+ const NOT_FOUND = Symbol.for('ebitex.content.routeData.notFound');
12
+ /**
13
+ * The marker a loader returns (or resolves to) when the value in the address names nothing:
14
+ * `return NotFound`. The page then draws the host's not-found, and a server answers a real `404`.
15
+ * Content never decides this, because Content never interprets the value.
16
+ */
17
+ export const NotFound = Object.freeze({ [NOT_FOUND]: true });
18
+ /** True for the {@link NotFound} marker, including one made by another copy of this package. */
19
+ export function isNotFound(value) {
20
+ return typeof value === 'object' && value !== null && value[NOT_FOUND] === true;
21
+ }
22
+ /**
23
+ * Binds a route context tag to a loader.
24
+ *
25
+ * ```ts
26
+ * const personData = defineRouteData({
27
+ * context: 'people.person',
28
+ * load: async ({ slug }, { signal }) => {
29
+ * const response = await fetch(`/api/people/${encodeURIComponent(slug)}`, { signal })
30
+ * return response.ok ? ((await response.json()) as Person) : NotFound
31
+ * },
32
+ * })
33
+ * ```
34
+ *
35
+ * `load` receives the route's parameters (annotate them to type them: `({ slug }: { slug: string })`)
36
+ * and returns the data, or {@link NotFound}. It runs once per parameter set however many sections read it.
37
+ * The tag is the contract between this loader and the page: the page's parameter node must carry
38
+ * the same one, and a loader whose tag differs from the delivered one is refused in development.
39
+ */
40
+ export function defineRouteData(definition) {
41
+ return Object.freeze({ context: definition.context, load: definition.load });
42
+ }
43
+ /**
44
+ * Decides whether a definition applies to the delivered route: `true` to load, `false` when there
45
+ * is no route at all (an ordinary page, or a server that predates parameterised addresses). A route
46
+ * whose tag differs from the definition's (or that has none) throws in development, naming both
47
+ * tags, and is skipped in production.
48
+ */
49
+ export function appliesToRoute(definition, route) {
50
+ if (route === undefined)
51
+ return false;
52
+ if (route.context === definition.context)
53
+ return true;
54
+ if (isDevelopment()) {
55
+ const delivered = route.context === undefined ? 'no route context tag' : `the route context tag "${route.context}"`;
56
+ throw new Error(`@ebitex/content-sdk: the route data definition for "${definition.context}" does not match this page: its address "${route.pattern}" carries ${delivered}. ` +
57
+ 'Give the parameter node the tag the loader names, or pass this loader only on the pages it belongs to.');
58
+ }
59
+ return false;
60
+ }
61
+ /** Throws when two definitions share a tag, since the values are keyed by it. */
62
+ export function assertDistinctContexts(definitions) {
63
+ const seen = new Set();
64
+ for (const definition of definitions) {
65
+ if (seen.has(definition.context)) {
66
+ 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.`);
67
+ }
68
+ seen.add(definition.context);
69
+ }
70
+ }
71
+ /** The same key for the same parameters, whatever order they were built in. */
72
+ export function paramsKey(params) {
73
+ return JSON.stringify(Object.entries(params).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
74
+ }
75
+ /**
76
+ * Loads the data a route needs, without React: for a server that resolved the page, to answer a
77
+ * real `404` before rendering and to hand the values to `<Experience initialRouteData>` so the
78
+ * browser does not load them again.
79
+ *
80
+ * ```ts
81
+ * const result = await client.resolveLocation(url)
82
+ * const data = result.kind === 'presentation' ? await loadRouteData([personData], result.route, { locale: result.locale }) : undefined
83
+ * if (data?.notFound) return new Response('Not found', { status: 404 })
84
+ * ```
85
+ *
86
+ * Only definitions whose tag matches the route's run; with no route (an ordinary page) nothing
87
+ * runs. A loader's own errors reject this promise.
88
+ */
89
+ export async function loadRouteData(definitions, route, options = {}) {
90
+ assertDistinctContexts(definitions);
91
+ const signal = options.signal ?? new AbortController().signal;
92
+ const loaded = { notFound: false, values: {}, missing: [] };
93
+ const applicable = definitions.filter((definition) => appliesToRoute(definition, route));
94
+ await Promise.all(applicable.map(async (definition) => {
95
+ const result = await definition.load(route?.params ?? {}, { locale: options.locale, signal });
96
+ if (isNotFound(result)) {
97
+ loaded.missing.push(definition.context);
98
+ loaded.notFound = true;
99
+ }
100
+ else {
101
+ loaded.values[definition.context] = result;
102
+ }
103
+ }));
104
+ loaded.missing.sort();
105
+ return loaded;
106
+ }
107
+ //# sourceMappingURL=routeData.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routeData.js","sourceRoot":"","sources":["../src/routeData.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAA;AAGhD;;;;;;;;GAQG;AAEH,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAA;AAOjE;;;;GAIG;AACH,MAAM,CAAC,MAAM,QAAQ,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,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAA;QACtL,IAAI,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;YACvB,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAA;YACvC,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAA;QACxB,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,MAAM,CAAA;QAC5C,CAAC;IACH,CAAC,CAAC,CACH,CAAA;IAED,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,CAAA;IACrB,OAAO,MAAM,CAAA;AACf,CAAC"}
@@ -0,0 +1,58 @@
1
+ import { type RouteParams } from './route.js';
2
+ /**
3
+ * The typed form of a route. Declare the pattern once, where the compiler can read it, and every
4
+ * use of it is checked: `fill()` takes exactly the parameters the pattern names, and `useRoute()`
5
+ * hands a renderer those parameters as `string`s.
6
+ *
7
+ * ```ts
8
+ * const personRoute = defineRoute('/people/{slug}')
9
+ *
10
+ * personRoute.fill({ slug: 'ada' }) // '/people/ada'
11
+ * personRoute.fill({ id: 'ada' }) // compile error: 'id' is not a parameter of this route
12
+ * personRoute.useRoute().params.slug // string
13
+ * ```
14
+ *
15
+ * The pattern string is written by hand and must match the one the site's address uses. In
16
+ * development, `useRoute()` warns once when the page delivered under it names different parameters.
17
+ */
18
+ export interface RouteDefinition<TPattern extends string> {
19
+ /** The pattern this definition was made from. */
20
+ readonly pattern: TPattern;
21
+ /** Fills the pattern with values (percent-encoded). Throws on a missing or empty value; the compiler already refuses a missing or unknown name. */
22
+ fill(params: RouteParams<TPattern>): string;
23
+ /**
24
+ * The current route, with `params` typed from the pattern. A React hook: call it in a renderer
25
+ * rendered by `<Experience>`. On a page that is not this route (or outside `<Experience>`) the
26
+ * values are absent at run time, so use it only in renderers that belong to the route.
27
+ */
28
+ useRoute(): TypedRoute<TPattern>;
29
+ }
30
+ /** What {@link RouteDefinition.useRoute} returns. */
31
+ export interface TypedRoute<TPattern extends string> {
32
+ /** The delivered pattern (in the site's own URL space, so it may be localized), or `null` where no route was delivered. */
33
+ pattern: string | null;
34
+ params: RouteParams<TPattern>;
35
+ /** The route context tag the page's parameter carries, when it has one. */
36
+ context: string | undefined;
37
+ /** Asks the enclosing `<Experience>` to render its `notFound` content for this address. */
38
+ notFound(): void;
39
+ }
40
+ /** The shape every route hook returns. The React entry registers the real hook; see {@link registerRouteHook}. */
41
+ export interface RouteHookResult {
42
+ pattern: string | null;
43
+ params: Record<string, string>;
44
+ context: string | undefined;
45
+ notFound(): void;
46
+ }
47
+ /**
48
+ * Wires `defineRoute(...).useRoute()` to the React hook. Called once by `@ebitex/content-sdk/react`
49
+ * when it loads; the root entry never imports React, so a server or a script can use `defineRoute`
50
+ * for `fill()` alone. Not for application code.
51
+ */
52
+ export declare function registerRouteHook(hook: () => RouteHookResult): void;
53
+ /**
54
+ * Declares a route by its pattern. See {@link RouteDefinition}. The pattern must be a string
55
+ * literal for its parameters to be typed.
56
+ */
57
+ export declare function defineRoute<const TPattern extends string>(pattern: TPattern): RouteDefinition<TPattern>;
58
+ //# sourceMappingURL=routeTypes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routeTypes.d.ts","sourceRoot":"","sources":["../src/routeTypes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyB,KAAK,WAAW,EAAE,MAAM,YAAY,CAAA;AAGpE;;;;;;;;;;;;;;;GAeG;AACH,MAAM,WAAW,eAAe,CAAC,QAAQ,SAAS,MAAM;IACtD,iDAAiD;IACjD,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAA;IAC1B,mJAAmJ;IACnJ,IAAI,CAAC,MAAM,EAAE,WAAW,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAA;IAC3C;;;;OAIG;IACH,QAAQ,IAAI,UAAU,CAAC,QAAQ,CAAC,CAAA;CACjC;AAED,qDAAqD;AACrD,MAAM,WAAW,UAAU,C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