@vectoriox/iox-ui 5.42.0 → 5.44.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/data-core/index.d.ts +360 -0
- package/data-core/package.json +3 -0
- package/design-core/index.d.ts +215 -3
- package/fesm2022/vectoriox-iox-ui-data-core.mjs +491 -0
- package/fesm2022/vectoriox-iox-ui-data-core.mjs.map +1 -0
- package/fesm2022/vectoriox-iox-ui-design-core.mjs +276 -3
- package/fesm2022/vectoriox-iox-ui-design-core.mjs.map +1 -1
- package/fesm2022/vectoriox-iox-ui-generation-core.mjs +7 -1
- package/fesm2022/vectoriox-iox-ui-generation-core.mjs.map +1 -1
- package/fesm2022/vectoriox-iox-ui.mjs +179 -526
- package/fesm2022/vectoriox-iox-ui.mjs.map +1 -1
- package/generation-core/index.d.ts +3 -0
- package/index.d.ts +112 -381
- package/package.json +5 -1
- package/src/data-core/data-source-resolver.ts +378 -0
- package/src/data-core/public-api.ts +12 -0
- package/src/data-core/relative-sources.ts +282 -0
- package/src/design-core/design-apply.ts +56 -3
- package/src/design-core/design-settings.ts +32 -3
- package/src/design-core/design-token.model.ts +23 -0
- package/src/design-core/flavor-spec.generated.ts +202 -0
- package/src/design-core/flavor-tokens.ts +2 -1
- package/src/generation-core/site-spec.generated.ts +4 -1
- package/src/generation-core/validate-site-plan.ts +3 -0
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared data-source resolving pattern — the SINGLE source of truth for how an IoxDataSource
|
|
3
|
+
* becomes a backend fetch, consumed by BOTH the page builder (iox-cms-client bindings panel) and
|
|
4
|
+
* the SSR client engine (iox-client-engine DataSourceResolverService). There must be no second
|
|
5
|
+
* copy of this decision logic; only the transport differs between the two:
|
|
6
|
+
*
|
|
7
|
+
* builder → authenticated org-scoped controllers (admin session):
|
|
8
|
+
* single by id → GET admin.../resources/:type/:id (ContentService.getContentById)
|
|
9
|
+
* collection → GET admin.../resources/:type (ContentService.getContent)
|
|
10
|
+
* engine → @Public() controllers (no auth, isPublished filter applied server-side):
|
|
11
|
+
* single by id → GET api/:type/:id (UserResourcesController)
|
|
12
|
+
* collection → GET api/:type?filters (UserResourcesController)
|
|
13
|
+
*
|
|
14
|
+
* The DECISION (by-id vs collection, which id, which filters, how to pick the single result) is
|
|
15
|
+
* identical for both — that's what this module owns. Each app maps the returned {@link DataSourcePlan}
|
|
16
|
+
* onto its own transport. A single item is ALWAYS fetched by its id as a path segment — never a
|
|
17
|
+
* `?_id=` query — to match the builder's getContentById.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export type DataSourceMode = 'single' | 'list';
|
|
21
|
+
export type DataSourceDomain = 'cms' | 'shop';
|
|
22
|
+
|
|
23
|
+
export interface DataSourceRouteFilter {
|
|
24
|
+
field?: string;
|
|
25
|
+
routeParam?: string;
|
|
26
|
+
defaultId?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface DataSourceQueryFilter {
|
|
30
|
+
field?: string;
|
|
31
|
+
/** URL query param the value is read from. OMIT for a CONSTANT filter — then `defaultValue`
|
|
32
|
+
* alone is the value, so `isReviewShow=true` filters identically in preview and on the site. */
|
|
33
|
+
queryParam?: string;
|
|
34
|
+
/** Value used when the query param is absent — i.e. always, for a constant filter, and in the
|
|
35
|
+
* builder preview, where there are no live query params. NOT preview-only: it is the runtime
|
|
36
|
+
* fallback too. An empty default with no query-param value means the filter is DROPPED. */
|
|
37
|
+
defaultValue?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The order a query source returns its rows in (CC2, board 4 "Sort" — the data source popover). */
|
|
41
|
+
export enum DataSourceSortDir {
|
|
42
|
+
Asc = 'asc',
|
|
43
|
+
Desc = 'desc',
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface DataSourceSort {
|
|
47
|
+
/** A field of the content type (a dot path into a nested object is allowed). */
|
|
48
|
+
field?: string;
|
|
49
|
+
dir?: DataSourceSortDir | `${DataSourceSortDir}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The query parameter carrying the order: `sort=order` ascending, `sort=-order` descending. A CONTROL like
|
|
53
|
+
* `limit`, not a field filter — the public controllers split it out (iox-cms `query-controls.ts`). */
|
|
54
|
+
export const SORT_PARAM = 'sort';
|
|
55
|
+
const SORT_FIELD = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/;
|
|
56
|
+
|
|
57
|
+
/** `sort`'s wire value, or null when the source sets no (valid) order. */
|
|
58
|
+
export function sortParamValue(sort: DataSourceSort | null | undefined): string | null {
|
|
59
|
+
const field = sort?.field?.trim();
|
|
60
|
+
if (!field || !SORT_FIELD.test(field)) return null;
|
|
61
|
+
return sort?.dir === DataSourceSortDir.Desc ? `-${field}` : field;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface DataSourceRequestSpec {
|
|
65
|
+
contentType?: string;
|
|
66
|
+
limit?: number;
|
|
67
|
+
/** A query source's order (CC2). Absent = the backend's natural order, as before. */
|
|
68
|
+
sort?: DataSourceSort;
|
|
69
|
+
filterByRouteParam?: DataSourceRouteFilter;
|
|
70
|
+
filterByQueryParams?: DataSourceQueryFilter[];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Structural (duck-typed) view of an IoxDataSource — kept free of the editor model so both libs
|
|
74
|
+
* can depend on it without pulling in iox-builder. */
|
|
75
|
+
export interface DataSourceSpec {
|
|
76
|
+
alias?: string;
|
|
77
|
+
type?: string; // 'cms' | 'shop' | 'external-api' | 'static'
|
|
78
|
+
mode?: DataSourceMode;
|
|
79
|
+
request?: {
|
|
80
|
+
cms?: DataSourceRequestSpec;
|
|
81
|
+
shop?: DataSourceRequestSpec;
|
|
82
|
+
endpoint?: string;
|
|
83
|
+
data?: any;
|
|
84
|
+
/** `derived` alias: a VIEW into another variable — resolve `from` then getByPath(value, path)
|
|
85
|
+
* (e.g. galleryImages = product.gallery). See repeater-binding-ux-plan.md. */
|
|
86
|
+
derived?: { from: string; path: string };
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export type DataSourcePlan =
|
|
91
|
+
| { kind: 'by-id'; domain: DataSourceDomain; resource: string; id: string; mode: DataSourceMode }
|
|
92
|
+
| { kind: 'collection'; domain: DataSourceDomain; resource: string; filter: Record<string, any>; limit?: number; sort?: string; mode: DataSourceMode }
|
|
93
|
+
| { kind: 'external'; endpoint: string; mode: DataSourceMode }
|
|
94
|
+
| { kind: 'static'; data: any; mode: DataSourceMode }
|
|
95
|
+
| { kind: 'derived'; from: string; path: string; mode: DataSourceMode }
|
|
96
|
+
| { kind: 'none' };
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Match a page route template against an actual path and extract named params.
|
|
100
|
+
* matchRouteParams('/project/:projectId', 'project/68abc') → { projectId: '68abc' }
|
|
101
|
+
* Both sides are normalised (leading slash stripped) and split on '/'; values are URL-decoded.
|
|
102
|
+
*/
|
|
103
|
+
export function matchRouteParams(template: string | undefined, actual: string | undefined): Record<string, string> {
|
|
104
|
+
const t = (template ?? '').replace(/^\/+/, '').split('/');
|
|
105
|
+
const a = (actual ?? '').replace(/^\/+/, '').split('/');
|
|
106
|
+
const params: Record<string, string> = {};
|
|
107
|
+
for (let i = 0; i < t.length; i++) {
|
|
108
|
+
const seg = t[i];
|
|
109
|
+
if (seg && seg.startsWith(':')) params[seg.slice(1)] = decodeURIComponent(a[i] ?? '');
|
|
110
|
+
}
|
|
111
|
+
return params;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Build the query filter for a data-source request from its filterByRouteParam / filterByQueryParams
|
|
116
|
+
* config. `field` is filtered by the route-param value (falling back to `defaultId`); query filters
|
|
117
|
+
* map each `field` to a query-param value (falling back to `defaultValue`), and a filter with NO
|
|
118
|
+
* `queryParam` is a constant on `defaultValue`. Empty values are omitted so the source isn't
|
|
119
|
+
* accidentally filtered to nothing.
|
|
120
|
+
*/
|
|
121
|
+
export function buildDataSourceFilter(
|
|
122
|
+
req: DataSourceRequestSpec | undefined,
|
|
123
|
+
routeParams: Record<string, any> = {},
|
|
124
|
+
queryParams: Record<string, any> = {},
|
|
125
|
+
): Record<string, any> {
|
|
126
|
+
const params: Record<string, any> = {};
|
|
127
|
+
const byRoute = req?.filterByRouteParam;
|
|
128
|
+
if (byRoute?.field && byRoute?.routeParam) {
|
|
129
|
+
const value = routeParams[byRoute.routeParam] ?? byRoute.defaultId;
|
|
130
|
+
if (value !== undefined && value !== null && value !== '') params[byRoute.field] = value;
|
|
131
|
+
}
|
|
132
|
+
for (const q of req?.filterByQueryParams ?? []) {
|
|
133
|
+
if (!q?.field) continue;
|
|
134
|
+
// No queryParam → a CONSTANT filter: defaultValue is the value, in the builder preview and
|
|
135
|
+
// on the live site alike. With a queryParam the URL wins and defaultValue is the fallback.
|
|
136
|
+
const value = q.queryParam ? (queryParams[q.queryParam] ?? q.defaultValue) : q.defaultValue;
|
|
137
|
+
if (value !== undefined && value !== null && value !== '') params[q.field] = value;
|
|
138
|
+
}
|
|
139
|
+
return params;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Mirrors the builder's getContentById decision. When a SINGLE source is filtered by the item id
|
|
144
|
+
* (`_id`) via a route param, the item is fetched by PATH (`.../:type/:id`), not a `?_id=` query.
|
|
145
|
+
* Returns that id (route-param value, else `defaultId`), or `null` when the source isn't a
|
|
146
|
+
* single-by-id fetch — in which case the caller uses the collection endpoint + filters. The
|
|
147
|
+
* path-based form only applies to the id field; a single source filtered by any other field still
|
|
148
|
+
* goes through the collection endpoint.
|
|
149
|
+
*/
|
|
150
|
+
export function resolveSingleItemId(req: DataSourceRequestSpec | undefined, routeParams: Record<string, any> = {}): string | null {
|
|
151
|
+
const byRoute = req?.filterByRouteParam;
|
|
152
|
+
if (!byRoute?.routeParam) return null;
|
|
153
|
+
if (byRoute.field && byRoute.field !== '_id') return null;
|
|
154
|
+
const value = routeParams[byRoute.routeParam] ?? byRoute.defaultId;
|
|
155
|
+
return value !== undefined && value !== null && value !== '' ? String(value) : null;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Resolve an IoxDataSource into a transport-agnostic {@link DataSourcePlan}. This is the shared
|
|
160
|
+
* decision both the builder and the SSR engine run; each then executes the plan with its own
|
|
161
|
+
* HTTP layer. Single sources with a route-param id resolve to a `by-id` (path) fetch — exactly like
|
|
162
|
+
* the builder's getContentById.
|
|
163
|
+
*/
|
|
164
|
+
export function planDataSource(
|
|
165
|
+
ds: DataSourceSpec | undefined,
|
|
166
|
+
routeParams: Record<string, any> = {},
|
|
167
|
+
queryParams: Record<string, any> = {},
|
|
168
|
+
): DataSourcePlan {
|
|
169
|
+
const mode: DataSourceMode = ds?.mode === 'single' ? 'single' : 'list';
|
|
170
|
+
switch (ds?.type) {
|
|
171
|
+
case 'cms':
|
|
172
|
+
case 'shop': {
|
|
173
|
+
const domain = ds.type as DataSourceDomain;
|
|
174
|
+
const req = domain === 'cms' ? ds.request?.cms : ds.request?.shop;
|
|
175
|
+
const resource = req?.contentType;
|
|
176
|
+
if (!resource) return { kind: 'none' };
|
|
177
|
+
const id = mode === 'single' ? resolveSingleItemId(req, routeParams) : null;
|
|
178
|
+
if (id) return { kind: 'by-id', domain, resource, id, mode };
|
|
179
|
+
const filter = buildDataSourceFilter(req, routeParams, queryParams);
|
|
180
|
+
const plan: DataSourcePlan = { kind: 'collection', domain, resource, filter, mode };
|
|
181
|
+
if (req?.limit) (plan as any).limit = req.limit;
|
|
182
|
+
const sort = sortParamValue(req?.sort);
|
|
183
|
+
if (sort) (plan as any).sort = sort;
|
|
184
|
+
return plan;
|
|
185
|
+
}
|
|
186
|
+
case 'external-api': {
|
|
187
|
+
const endpoint = ds.request?.endpoint;
|
|
188
|
+
return endpoint ? { kind: 'external', endpoint, mode } : { kind: 'none' };
|
|
189
|
+
}
|
|
190
|
+
case 'static':
|
|
191
|
+
return { kind: 'static', data: ds.request?.data ?? null, mode };
|
|
192
|
+
case 'derived': {
|
|
193
|
+
const d = ds.request?.derived;
|
|
194
|
+
return d?.from ? { kind: 'derived', from: d.from, path: d.path ?? '', mode } : { kind: 'none' };
|
|
195
|
+
}
|
|
196
|
+
case 'variable':
|
|
197
|
+
// A VARIABLE is a page-local resource whose value is WRITTEN at runtime by an interaction
|
|
198
|
+
// (setContext), never fetched. It resolves to nothing here on purpose: the page renders
|
|
199
|
+
// its empty state until something writes it. `request.variable.itemsFrom` only names the
|
|
200
|
+
// source whose items it holds, so the bind picker can suggest fields.
|
|
201
|
+
return { kind: 'none' };
|
|
202
|
+
default:
|
|
203
|
+
return { kind: 'none' };
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* The aliases on a page that are VARIABLES — runtime-written resources, not fetched data.
|
|
209
|
+
*
|
|
210
|
+
* Shared so the builder and the SSR engine agree on which aliases start empty and are filled by
|
|
211
|
+
* interactions. See element-context-state-plan.md.
|
|
212
|
+
*/
|
|
213
|
+
export function variableAliases(dataSources: readonly { alias?: string; type?: string }[] | undefined): Set<string> {
|
|
214
|
+
const out = new Set<string>();
|
|
215
|
+
for (const ds of dataSources ?? []) {
|
|
216
|
+
if (ds?.type === 'variable' && ds.alias) out.add(ds.alias);
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** The source alias whose items a variable holds, if it declares one (for field suggestions). */
|
|
222
|
+
export function variableItemsFrom(
|
|
223
|
+
dataSources: readonly { alias?: string; type?: string; request?: any }[] | undefined,
|
|
224
|
+
alias: string,
|
|
225
|
+
): string | undefined {
|
|
226
|
+
for (const ds of dataSources ?? []) {
|
|
227
|
+
if (ds?.type === 'variable' && ds.alias === alias) return ds.request?.variable?.itemsFrom || undefined;
|
|
228
|
+
}
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Normalise a collection response into the shape a source expects: unwraps `{items}`/`{data}`
|
|
234
|
+
* envelopes, then returns the first item for a `single` source or the whole array for a `list`.
|
|
235
|
+
* A `by-id` response is already the item, so callers pass it through unchanged.
|
|
236
|
+
*/
|
|
237
|
+
export function normalizeCollectionResult(mode: DataSourceMode, data: any): any {
|
|
238
|
+
const items = Array.isArray(data) ? data : (data?.items ?? data?.data ?? []);
|
|
239
|
+
return mode === 'single' ? (items[0] ?? null) : items;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Navigate a dot/bracket path into an object, e.g. `gallery`, `details.images`, `variants[0].skus`.
|
|
243
|
+
* Returns undefined if any segment is missing. Kept minimal + self-contained so it is shareable by
|
|
244
|
+
* both the builder and the SSR engine (the two have divergent local `resolvePath` copies). */
|
|
245
|
+
export function getByPath(obj: any, path: string): any {
|
|
246
|
+
if (obj == null || !path) return obj;
|
|
247
|
+
// Turn `a[0].b` into ['a','0','b'].
|
|
248
|
+
const segments = path.replace(/\[(\w+)\]/g, '.$1').split('.').filter(Boolean);
|
|
249
|
+
let cur = obj;
|
|
250
|
+
for (const seg of segments) {
|
|
251
|
+
if (cur == null) return undefined;
|
|
252
|
+
cur = cur[seg];
|
|
253
|
+
}
|
|
254
|
+
return cur;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* The array a Repeater (or a repeating Slider) iterates over — the SHARED decision so the builder
|
|
259
|
+
* canvas and the SSR engine agree (see data-source-resolving.md).
|
|
260
|
+
* - No `sourcePath`: the resolved source IS the list. An array passes through; a lone object degrades
|
|
261
|
+
* to a single-row list (back-compat with the old `fetchItems`); null/undefined → `[]`.
|
|
262
|
+
* - With `sourcePath`: the source resolved to a SINGLE resource (e.g. a product); dive into the
|
|
263
|
+
* nested array property (e.g. `gallery`). Non-array / missing → `[]`.
|
|
264
|
+
*/
|
|
265
|
+
/**
|
|
266
|
+
* Fill in `derived` aliases in an already-resolved map. Given the data sources and a map of resolved
|
|
267
|
+
* NON-derived values (by alias), compute each `type:'derived'` alias as `getByPath(parent, path)` in
|
|
268
|
+
* dependency order (chains resolved by iterating until stable). Mutates + returns the map. Used by the
|
|
269
|
+
* SSR engine after it resolves the root sources; the builder resolves derived lazily per alias.
|
|
270
|
+
*/
|
|
271
|
+
export function resolveDerivedInto(dataSources: DataSourceSpec[], resolved: Record<string, any>): Record<string, any> {
|
|
272
|
+
const derived = (dataSources ?? []).filter(d => d?.type === 'derived' && !!d.alias);
|
|
273
|
+
let changed = true, guard = 0;
|
|
274
|
+
while (changed && guard++ < 25) {
|
|
275
|
+
changed = false;
|
|
276
|
+
for (const d of derived) {
|
|
277
|
+
if (d.alias! in resolved) continue;
|
|
278
|
+
const from = d.request?.derived?.from;
|
|
279
|
+
if (from && from in resolved) {
|
|
280
|
+
resolved[d.alias!] = getByPath(resolved[from], d.request!.derived!.path ?? '');
|
|
281
|
+
changed = true;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return resolved;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export function resolveRepeaterItems(resolved: any, sourcePath?: string | null): any[] {
|
|
289
|
+
if (sourcePath) {
|
|
290
|
+
const nested = getByPath(resolved, sourcePath);
|
|
291
|
+
return Array.isArray(nested) ? nested : [];
|
|
292
|
+
}
|
|
293
|
+
if (Array.isArray(resolved)) return resolved;
|
|
294
|
+
return resolved == null ? [] : [resolved];
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// ── Referenced data sources (shared: builder-save + SSR resolve) ─────────────────────────────────
|
|
298
|
+
// Which data-source aliases a node tree uses, so a consumer resolves ONLY what a page/global needs
|
|
299
|
+
// (not the whole org library). Used by cms-client (persist globals' sources) and the SSR engine
|
|
300
|
+
// (resolve the referenced subset per page). See org-data-sources-plan.md.
|
|
301
|
+
|
|
302
|
+
/** Aliases referenced anywhere in a node tree: a repeater/slider `source` (a `bindings` entry with
|
|
303
|
+
* `prop === 'source'`, or `props.source` for the slider) plus every binding's `source`. */
|
|
304
|
+
export function collectReferencedAliases(nodes: any[], acc: Set<string> = new Set<string>()): Set<string> {
|
|
305
|
+
for (const n of nodes ?? []) {
|
|
306
|
+
for (const b of n?.bindings ?? []) { if (b?.source) acc.add(b.source); }
|
|
307
|
+
if (n?.props?.source) acc.add(n.props.source);
|
|
308
|
+
if (n?.children?.length) collectReferencedAliases(n.children, acc);
|
|
309
|
+
}
|
|
310
|
+
return acc;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** The subset of `all` whose `alias` is referenced by `nodes` (shallow — direct references only). */
|
|
314
|
+
export function referencedDataSources(nodes: any[], all: any[]): any[] {
|
|
315
|
+
const aliases = collectReferencedAliases(nodes);
|
|
316
|
+
return (all ?? []).filter(ds => aliases.has(ds?.alias));
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Like `referencedDataSources`, but also pulls in a referenced source's DEPENDENCIES (transitively),
|
|
320
|
+
* none of which the layout names directly:
|
|
321
|
+
* - a `derived` alias needs its `request.derived.from` parent;
|
|
322
|
+
* - a `relative` (route-context) alias needs its `request.relative.subjectFrom` (the current item)
|
|
323
|
+
* and `request.relative.from` (the collection it navigates).
|
|
324
|
+
* Use this when RESOLVING (the engine) so derived views and siblings/related don't resolve to nothing. */
|
|
325
|
+
export function referencedDataSourcesDeep(nodes: any[], all: any[]): any[] {
|
|
326
|
+
const byAlias = new Map((all ?? []).map(d => [d?.alias, d]));
|
|
327
|
+
const wanted = collectReferencedAliases(nodes);
|
|
328
|
+
const queue = [...wanted];
|
|
329
|
+
const enqueue = (alias?: string) => {
|
|
330
|
+
if (alias && !wanted.has(alias)) { wanted.add(alias); queue.push(alias); }
|
|
331
|
+
};
|
|
332
|
+
while (queue.length) {
|
|
333
|
+
const ds: any = byAlias.get(queue.pop() as string);
|
|
334
|
+
enqueue(ds?.request?.derived?.from);
|
|
335
|
+
enqueue(ds?.request?.relative?.subjectFrom);
|
|
336
|
+
enqueue(ds?.request?.relative?.from);
|
|
337
|
+
}
|
|
338
|
+
return (all ?? []).filter(d => wanted.has(d?.alias));
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Base URLs for the PUBLIC content controllers. Both must end with `/`. The builder and the SSR
|
|
342
|
+
* engine pass their own host (they proxy `/api` differently) but MUST target the public
|
|
343
|
+
* (`@Public()`) controllers, never the authed admin ones — data resolving is storefront data. */
|
|
344
|
+
export interface DataSourceEndpoints {
|
|
345
|
+
/** cms resources, e.g. `${HOST}` (engine, HOST ends `/api/`) or `${HOST}api/` (builder). */
|
|
346
|
+
cmsBase: string;
|
|
347
|
+
/** shop resources, e.g. `${HOST}shop/` (engine) or `${HOST}api/shop/` (builder). */
|
|
348
|
+
shopBase: string;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
export interface DataSourceRequest {
|
|
352
|
+
url: string;
|
|
353
|
+
params: Record<string, any>;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Turn a resolved {@link DataSourcePlan} into the concrete public HTTP request (url + params) — the
|
|
358
|
+
* SINGLE place that decides the URL shape, shared by the builder binding preview and the SSR engine
|
|
359
|
+
* so both hit the SAME public endpoints (no admin, no duplication). Returns `null` for `static` /
|
|
360
|
+
* `none` plans (no HTTP call). A single item is a PATH segment (`/:resource/:id`), never `?_id=`.
|
|
361
|
+
*/
|
|
362
|
+
export function dataSourcePlanToRequest(plan: DataSourcePlan, endpoints: DataSourceEndpoints): DataSourceRequest | null {
|
|
363
|
+
const baseFor = (domain: DataSourceDomain) => (domain === 'shop' ? endpoints.shopBase : endpoints.cmsBase);
|
|
364
|
+
switch (plan.kind) {
|
|
365
|
+
case 'by-id':
|
|
366
|
+
return { url: `${baseFor(plan.domain)}${plan.resource}/${encodeURIComponent(plan.id)}`, params: {} };
|
|
367
|
+
case 'collection': {
|
|
368
|
+
const params: Record<string, any> = { ...plan.filter };
|
|
369
|
+
if (plan.limit) params['limit'] = plan.limit;
|
|
370
|
+
if (plan.sort) params[SORT_PARAM] = plan.sort;
|
|
371
|
+
return { url: `${baseFor(plan.domain)}${plan.resource}`, params };
|
|
372
|
+
}
|
|
373
|
+
case 'external':
|
|
374
|
+
return { url: plan.endpoint, params: {} };
|
|
375
|
+
default:
|
|
376
|
+
return null;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @vectoriox/iox-ui/data-core — the shared, FRAMEWORK-FREE data-source core (data-source-resolving.md): the ONE
|
|
3
|
+
* decision of how a data source becomes a fetch (`planDataSource`), the route-param matcher, the derived /
|
|
4
|
+
* relative (`$siblings`, `$related`) resolvers, the repeater item reader, and which sources a node tree
|
|
5
|
+
* references (`referencedDataSourcesDeep`). The builder and the SSR engine resolve with it; iox-cms reads it
|
|
6
|
+
* under plain Node (W2's Undo: is a data source still in use). Pure: no transport, no Angular. The main
|
|
7
|
+
* entry re-exports it by package path, so `@vectoriox/iox-ui` keeps working.
|
|
8
|
+
* ⚠️ Consumers wire the usual trio — ng-package raw-ts assets, jest moduleNameMapper, tsconfig paths —
|
|
9
|
+
* or `nest start` dies with ERR_REQUIRE_ESM while jest and build both pass.
|
|
10
|
+
*/
|
|
11
|
+
export * from './data-source-resolver';
|
|
12
|
+
export * from './relative-sources';
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared RELATIVE (route-context) data resolving — the SINGLE source of truth for how a detail page
|
|
3
|
+
* derives values FROM its current route item, consumed by BOTH the page builder (iox-cms-client) and
|
|
4
|
+
* the SSR client engine (iox-client-engine). Companion to `data-source-resolver.ts`.
|
|
5
|
+
*
|
|
6
|
+
* These are the pure, transport-agnostic pieces behind the Route binding scope
|
|
7
|
+
* (`$route` / `$current` / `$siblings` / `$related`). Resolution is a DEPENDENT SECOND PASS: the
|
|
8
|
+
* consumer resolves `$current` first (the existing single by-id fetch via `planDataSource`), then
|
|
9
|
+
* calls these to derive the relative values — there is NO new `DataSourcePlan` kind (`$related` still
|
|
10
|
+
* feeds a normal `collection` plan built from {@link buildRelatedFilter}). See
|
|
11
|
+
* `architecture/builder/relative-data-sources-plan.md`.
|
|
12
|
+
*
|
|
13
|
+
* There must be no second copy of this decision logic; only the transport (which HTTP layer fetches
|
|
14
|
+
* the ordered collection / related list) differs between the two consumers.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { getByPath } from './data-source-resolver';
|
|
18
|
+
|
|
19
|
+
/** Aliases in the Route scope are platform-owned and start with this prefix; a USER alias may never
|
|
20
|
+
* start with it, which keeps the Route scope structurally collision-proof with Local/Global. Used to
|
|
21
|
+
* validate new/renamed aliases and to render the reserved (read-only) item state in the bind picker. */
|
|
22
|
+
export const RESERVED_ALIAS_PREFIX = '$';
|
|
23
|
+
|
|
24
|
+
/** True for a platform-owned Route-scope alias (`$route`, `$current`, `$siblings`, `$related`, …). */
|
|
25
|
+
export function isReservedAlias(alias: string | null | undefined): boolean {
|
|
26
|
+
return typeof alias === 'string' && alias.startsWith(RESERVED_ALIAS_PREFIX);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The `$siblings` value: the current item's neighbours within an ordered set. */
|
|
30
|
+
export interface SiblingsResult<T = any> {
|
|
31
|
+
/** The item before the current one (`null` at the start, unless `wrap`). */
|
|
32
|
+
prev: T | null;
|
|
33
|
+
/** The item after the current one (`null` at the end, unless `wrap`). */
|
|
34
|
+
next: T | null;
|
|
35
|
+
/** Zero-based position of the current item in the ordered set; `-1` when not found. */
|
|
36
|
+
index: number;
|
|
37
|
+
/** Total items in the set. */
|
|
38
|
+
count: number;
|
|
39
|
+
/** `true` when the current item is the first in the set. */
|
|
40
|
+
isFirst: boolean;
|
|
41
|
+
/** `true` when the current item is the last in the set. */
|
|
42
|
+
isLast: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface ResolveSiblingsOptions {
|
|
46
|
+
/** Field identifying the current item within the list. Default `_id`. */
|
|
47
|
+
idField?: string;
|
|
48
|
+
/** Dot/bracket path to sort by BEFORE locating neighbours (e.g. `order`, `date`). Omit to use the
|
|
49
|
+
* list's existing order. The same item neighbours differently per ordering, so this is the one
|
|
50
|
+
* choice `$siblings` requires. */
|
|
51
|
+
sortBy?: string;
|
|
52
|
+
/** Sort direction when `sortBy` is set. Default `asc`. */
|
|
53
|
+
sortDir?: 'asc' | 'desc';
|
|
54
|
+
/** Wrap around the ends (`last.next` → first, `first.prev` → last). Only applies when `count > 1`.
|
|
55
|
+
* Default `false`. */
|
|
56
|
+
wrap?: boolean;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const EMPTY_SIBLINGS: SiblingsResult = { prev: null, next: null, index: -1, count: 0, isFirst: false, isLast: false };
|
|
60
|
+
|
|
61
|
+
/** Generic, deterministic comparator: numbers numerically, Dates by time, everything else by
|
|
62
|
+
* locale-aware string compare (ISO date strings sort correctly this way). Nullish sorts first. */
|
|
63
|
+
function compareValues(a: any, b: any): number {
|
|
64
|
+
if (a == null && b == null) return 0;
|
|
65
|
+
if (a == null) return -1;
|
|
66
|
+
if (b == null) return 1;
|
|
67
|
+
if (typeof a === 'number' && typeof b === 'number') return a - b;
|
|
68
|
+
const da = a instanceof Date ? a.getTime() : NaN;
|
|
69
|
+
const db = b instanceof Date ? b.getTime() : NaN;
|
|
70
|
+
if (!isNaN(da) && !isNaN(db)) return da - db;
|
|
71
|
+
return String(a).localeCompare(String(b));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Locate the current item within an ordered set and return its neighbours + position. Pure: the input
|
|
76
|
+
* list is never mutated (sorting works on a shallow copy). `currentId` is compared to each item's
|
|
77
|
+
* `idField` via string equality (route-param values are strings). When the current id isn't found,
|
|
78
|
+
* `index` is `-1` and `prev`/`next` are `null` (but `count` still reflects the set size).
|
|
79
|
+
*/
|
|
80
|
+
export function resolveSiblings<T = any>(
|
|
81
|
+
items: T[] | null | undefined,
|
|
82
|
+
currentId: string | number | null | undefined,
|
|
83
|
+
options: ResolveSiblingsOptions = {},
|
|
84
|
+
): SiblingsResult<T> {
|
|
85
|
+
const list = Array.isArray(items) ? items.slice() : [];
|
|
86
|
+
const count = list.length;
|
|
87
|
+
if (count === 0) return { ...EMPTY_SIBLINGS };
|
|
88
|
+
|
|
89
|
+
const idField = options.idField ?? '_id';
|
|
90
|
+
if (options.sortBy) {
|
|
91
|
+
const dir = options.sortDir === 'desc' ? -1 : 1;
|
|
92
|
+
list.sort((a, b) => dir * compareValues(getByPath(a, options.sortBy!), getByPath(b, options.sortBy!)));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const cid = currentId == null ? null : String(currentId);
|
|
96
|
+
const index = cid == null ? -1 : list.findIndex(it => String(getByPath(it, idField)) === cid);
|
|
97
|
+
if (index === -1) return { prev: null, next: null, index: -1, count, isFirst: false, isLast: false };
|
|
98
|
+
|
|
99
|
+
const canWrap = !!options.wrap && count > 1;
|
|
100
|
+
const prev = index > 0 ? list[index - 1] : (canWrap ? list[count - 1] : null);
|
|
101
|
+
const next = index < count - 1 ? list[index + 1] : (canWrap ? list[0] : null);
|
|
102
|
+
return { prev, next, index, count, isFirst: index === 0, isLast: index === count - 1 };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface BuildRelatedFilterOptions {
|
|
106
|
+
/** Field(s) on the current item whose value(s) the related items must match (e.g. `category`,
|
|
107
|
+
* or `['category', 'brand']`). Each contributes an equality filter on that field. */
|
|
108
|
+
matchFields: string | string[];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** A value usable as an equality filter param: a non-empty scalar. Objects/arrays/nullish are skipped
|
|
112
|
+
* so a related query isn't built from an unresolved rel object (surfaced as a config issue in the UI
|
|
113
|
+
* rather than silently matching everything). Multi-value match is a v2 concern. */
|
|
114
|
+
function isScalarFilterValue(v: any): boolean {
|
|
115
|
+
if (v == null) return false;
|
|
116
|
+
if (typeof v === 'string') return v !== '';
|
|
117
|
+
if (typeof v === 'number') return Number.isFinite(v);
|
|
118
|
+
return typeof v === 'boolean';
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Build the collection filter for `$related` from the resolved current item: an equality match on
|
|
123
|
+
* each `matchField`'s value (e.g. same `category`). Feeds a normal `collection` plan — no new plan
|
|
124
|
+
* kind. Fields whose value is not a scalar (or is empty) are omitted, matching
|
|
125
|
+
* `buildDataSourceFilter`'s "don't over-filter" rule. Exclude-self is applied to the RESULT via
|
|
126
|
+
* {@link excludeSelf} (the public query controllers are equality-only, so it can't be a `$ne` param).
|
|
127
|
+
*/
|
|
128
|
+
export function buildRelatedFilter(current: any, options: BuildRelatedFilterOptions): Record<string, any> {
|
|
129
|
+
const fields = Array.isArray(options.matchFields) ? options.matchFields : [options.matchFields];
|
|
130
|
+
const filter: Record<string, any> = {};
|
|
131
|
+
for (const field of fields) {
|
|
132
|
+
if (!field) continue;
|
|
133
|
+
const value = getByPath(current, field);
|
|
134
|
+
if (isScalarFilterValue(value)) filter[field] = value;
|
|
135
|
+
}
|
|
136
|
+
return filter;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Drop the current item from a list by `idField` (default `_id`). Used to exclude self from a
|
|
141
|
+
* `$related` result after fetch. A nullish/empty `currentId` leaves the list unchanged.
|
|
142
|
+
*/
|
|
143
|
+
export function excludeSelf<T = any>(items: T[] | null | undefined, currentId: string | number | null | undefined, idField = '_id'): T[] {
|
|
144
|
+
if (!Array.isArray(items)) return [];
|
|
145
|
+
if (currentId == null || currentId === '') return items;
|
|
146
|
+
const cid = String(currentId);
|
|
147
|
+
return items.filter(it => String(getByPath(it, idField)) !== cid);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The resolved Route-scope context bound values read from (`$route.projectId`, `$current.title`,
|
|
151
|
+
* `$siblings.next`, `$related`). Assembled by each consumer during its dependent second pass. */
|
|
152
|
+
export interface RouteContext {
|
|
153
|
+
/** Route path params for the current URL (from `matchRouteParams`). */
|
|
154
|
+
$route: Record<string, string>;
|
|
155
|
+
/** The resolved current item (the page's single by-id source). */
|
|
156
|
+
$current: any;
|
|
157
|
+
/** Neighbours of the current item within a chosen ordered set. */
|
|
158
|
+
$siblings?: SiblingsResult;
|
|
159
|
+
/** Items related to the current one (same-attribute), excluding self. */
|
|
160
|
+
$related?: any[];
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ── Relative source declaration + the shared second-pass resolver ────────────────────────────────
|
|
164
|
+
// A relative source is declared like a `derived` one (`type:'relative'`), and resolved AFTER the
|
|
165
|
+
// root/derived sources by a PURE pass over the resolved map — mirroring `resolveDerivedInto`, so the
|
|
166
|
+
// SSR engine and the builder canvas agree with no forked logic. `planDataSource` returns `none` for
|
|
167
|
+
// it (not fetched); each consumer excludes `relative` from its fetched roots and runs this pass.
|
|
168
|
+
|
|
169
|
+
export type RelativeSourceKind = 'route' | 'current' | 'siblings' | 'related';
|
|
170
|
+
|
|
171
|
+
export interface RelativeSourceSpec {
|
|
172
|
+
kind: RelativeSourceKind;
|
|
173
|
+
/** The source alias this derives from: for `current` the subject single-source; for
|
|
174
|
+
* `siblings`/`related` the COLLECTION alias to locate within / search. Unused for `route`. */
|
|
175
|
+
from?: string;
|
|
176
|
+
/** `siblings`/`related`: the SUBJECT source alias (the current item) whose id / field values drive
|
|
177
|
+
* the computation. Defaults to `from` when omitted. May reference `$current`. */
|
|
178
|
+
subjectFrom?: string;
|
|
179
|
+
/** Field identifying an item. Default `_id`. */
|
|
180
|
+
idField?: string;
|
|
181
|
+
/** `siblings`: sort the set before locating neighbours. */
|
|
182
|
+
sortBy?: string;
|
|
183
|
+
sortDir?: 'asc' | 'desc';
|
|
184
|
+
wrap?: boolean;
|
|
185
|
+
/** `siblings`: resolve to a SINGLE neighbour ITEM (`next`/`prev`) instead of the whole
|
|
186
|
+
* `{prev,next,index,count,…}` object — so a source can be named e.g. `nextProject` and bound
|
|
187
|
+
* directly (`nextProject.route`). Omit for the whole-object shape. */
|
|
188
|
+
pick?: 'next' | 'prev';
|
|
189
|
+
/** `related`: field(s) on the subject the results must match. */
|
|
190
|
+
matchFields?: string | string[];
|
|
191
|
+
/** `related`: drop the subject from its own results. Default `true`. */
|
|
192
|
+
excludeSelf?: boolean;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Duck-typed view of a data source carrying an optional relative descriptor (avoids a hard dep on
|
|
196
|
+
* the full editor model / a circular type import). */
|
|
197
|
+
interface RelativeCapableSource {
|
|
198
|
+
alias?: string;
|
|
199
|
+
type?: string;
|
|
200
|
+
request?: { relative?: RelativeSourceSpec };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** The already-resolved inputs a single relative source computes from. Assembled by each consumer:
|
|
204
|
+
* the batch pass reads them from the resolved map; the builder resolves them async per alias. */
|
|
205
|
+
export interface RelativeInputs {
|
|
206
|
+
/** The subject item (the current resource) — for `current`/`siblings`/`related`. */
|
|
207
|
+
subject?: any;
|
|
208
|
+
/** The collection to locate within / search — for `siblings`/`related`. */
|
|
209
|
+
collection?: any;
|
|
210
|
+
/** Route path params — for `route`. */
|
|
211
|
+
routeParams?: Record<string, any>;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Resolve kinds in a fixed order so a `siblings`/`related` source may reference `$current` (or any
|
|
215
|
+
* earlier relative alias) via `subjectFrom` and still see it resolved. */
|
|
216
|
+
const KIND_ORDER: Record<RelativeSourceKind, number> = { route: 0, current: 1, siblings: 2, related: 3 };
|
|
217
|
+
|
|
218
|
+
/** Does an item satisfy every field in an equality predicate map (string-compared)? */
|
|
219
|
+
function matchesFilter(item: any, filter: Record<string, any>): boolean {
|
|
220
|
+
return Object.keys(filter).every(k => String(getByPath(item, k)) === String(filter[k]));
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Compute ONE relative source's value from its already-resolved {@link RelativeInputs} — the SHARED
|
|
225
|
+
* kind→computation decision, so the batch pass ({@link resolveRelativeInto}) and the builder's async
|
|
226
|
+
* per-alias resolver produce identical results with no forked switch. `route` → the route params;
|
|
227
|
+
* `current` → the subject; `siblings` → {@link resolveSiblings} over the collection; `related` → the
|
|
228
|
+
* collection filtered by {@link buildRelatedFilter}'s predicate (+ {@link excludeSelf}).
|
|
229
|
+
*/
|
|
230
|
+
export function computeRelative(spec: RelativeSourceSpec, inputs: RelativeInputs): any {
|
|
231
|
+
const idField = spec.idField ?? '_id';
|
|
232
|
+
switch (spec.kind) {
|
|
233
|
+
case 'route':
|
|
234
|
+
return inputs.routeParams ?? {};
|
|
235
|
+
case 'current':
|
|
236
|
+
return inputs.subject ?? null;
|
|
237
|
+
case 'siblings': {
|
|
238
|
+
const siblings = resolveSiblings(inputs.collection, getByPath(inputs.subject, idField), {
|
|
239
|
+
idField, sortBy: spec.sortBy, sortDir: spec.sortDir, wrap: spec.wrap,
|
|
240
|
+
});
|
|
241
|
+
// `pick` resolves the source directly to that neighbour item (named-source shape,
|
|
242
|
+
// e.g. `nextProject`); without it the caller binds a sub-path of the whole object.
|
|
243
|
+
return spec.pick ? siblings[spec.pick] : siblings;
|
|
244
|
+
}
|
|
245
|
+
case 'related': {
|
|
246
|
+
const filter = buildRelatedFilter(inputs.subject, { matchFields: spec.matchFields ?? [] });
|
|
247
|
+
const pool = Array.isArray(inputs.collection) ? inputs.collection : [];
|
|
248
|
+
const items = pool.filter(it => matchesFilter(it, filter));
|
|
249
|
+
return spec.excludeSelf !== false ? excludeSelf(items, getByPath(inputs.subject, idField), idField) : items;
|
|
250
|
+
}
|
|
251
|
+
default:
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Compute every `type:'relative'` source into `resolved` (keyed by alias), IN PLACE. Pure w.r.t. HTTP
|
|
258
|
+
* — it only reads already-resolved roots + the route params, so both consumers run it identically as
|
|
259
|
+
* a second pass. Delegates each source to {@link computeRelative}. `current`'s subject is `from`;
|
|
260
|
+
* `siblings`/`related` take `collection` = `from` and `subject` = `subjectFrom ?? from`. Mutates and
|
|
261
|
+
* returns `resolved`.
|
|
262
|
+
*/
|
|
263
|
+
export function resolveRelativeInto(
|
|
264
|
+
dataSources: RelativeCapableSource[],
|
|
265
|
+
resolved: Record<string, any>,
|
|
266
|
+
routeParams: Record<string, any> = {},
|
|
267
|
+
): Record<string, any> {
|
|
268
|
+
const relatives = (dataSources ?? [])
|
|
269
|
+
.filter(d => d?.type === 'relative' && !!d.alias && !!d.request?.relative)
|
|
270
|
+
.sort((a, b) => KIND_ORDER[a.request!.relative!.kind] - KIND_ORDER[b.request!.relative!.kind]);
|
|
271
|
+
|
|
272
|
+
for (const d of relatives) {
|
|
273
|
+
const spec = d.request!.relative!;
|
|
274
|
+
const subjectAlias = spec.kind === 'current' ? spec.from : (spec.subjectFrom ?? spec.from);
|
|
275
|
+
resolved[d.alias!] = computeRelative(spec, {
|
|
276
|
+
subject: subjectAlias ? resolved[subjectAlias] : undefined,
|
|
277
|
+
collection: spec.from ? resolved[spec.from] : undefined,
|
|
278
|
+
routeParams,
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
return resolved;
|
|
282
|
+
}
|