@cms0/cms0 0.2.20 → 0.2.22

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 (33) hide show
  1. package/README.md +11 -0
  2. package/dist/cjs/custom-types/registry.cjs +6 -0
  3. package/dist/cjs/index.cjs +400 -65
  4. package/dist/cjs/libs/cli/config-loader.cjs +45 -4
  5. package/dist/cjs/libs/cli/publisher.cjs +24 -11
  6. package/dist/esm/custom-types/registry.js +6 -0
  7. package/dist/esm/index.js +401 -66
  8. package/dist/esm/libs/cli/config-loader.js +45 -4
  9. package/dist/esm/libs/cli/publisher.js +24 -11
  10. package/dist/types/custom-types/index.d.ts +2 -1
  11. package/dist/types/custom-types/index.d.ts.map +1 -1
  12. package/dist/types/custom-types/registry.d.ts.map +1 -1
  13. package/dist/types/index.d.ts +131 -7
  14. package/dist/types/index.d.ts.map +1 -1
  15. package/dist/types/libs/cli/config-loader.d.ts.map +1 -1
  16. package/dist/types/libs/cli/publisher.d.ts.map +1 -1
  17. package/package.json +13 -9
  18. package/dist/cjs/index-old-1.cjs +0 -866
  19. package/dist/cjs/index-old.cjs +0 -1016
  20. package/dist/cjs/libs/cli/descriptor-builder.cjs +0 -273
  21. package/dist/cjs/utils/index.cjs +0 -2
  22. package/dist/esm/index-old-1.js +0 -862
  23. package/dist/esm/index-old.js +0 -1012
  24. package/dist/esm/libs/cli/descriptor-builder.js +0 -268
  25. package/dist/esm/utils/index.js +0 -1
  26. package/dist/types/index-old-1.d.ts +0 -175
  27. package/dist/types/index-old-1.d.ts.map +0 -1
  28. package/dist/types/index-old.d.ts +0 -151
  29. package/dist/types/index-old.d.ts.map +0 -1
  30. package/dist/types/libs/cli/descriptor-builder.d.ts +0 -5
  31. package/dist/types/libs/cli/descriptor-builder.d.ts.map +0 -1
  32. package/dist/types/utils/index.d.ts +0 -2
  33. package/dist/types/utils/index.d.ts.map +0 -1
@@ -1,862 +0,0 @@
1
- import { schemaDescriptor } from "@cms0/cms0/schema-descriptors";
2
- import { buildZodSchemasFromDescriptor, } from "@cms0/shared";
3
- import { getCustomInlineTypeMetadata } from "./custom-types/registry.js";
4
- const DEFAULT_MODEL_NORMALIZATION_CONCURRENCY = 8;
5
- const COLLECTION_SHAPE_ERROR = "Invalid collection response. Expected array or { items, total }.";
6
- function normalizeUploadsPath(uploadsPath) {
7
- const raw = uploadsPath?.trim() || "/uploads";
8
- const withLeadingSlash = raw.startsWith("/") ? raw : `/${raw}`;
9
- const normalized = withLeadingSlash.replace(/\/+$/, "");
10
- return normalized || "/uploads";
11
- }
12
- function normalizeAssetBaseUrl(baseUrl) {
13
- const trimmed = baseUrl?.trim() ?? "";
14
- return trimmed.replace(/\/+$/, "");
15
- }
16
- function encodeFilenameForUrl(filename) {
17
- const normalized = filename.replace(/\\/g, "/").replace(/^\/+/, "").trim();
18
- if (!normalized)
19
- return "";
20
- return normalized
21
- .split("/")
22
- .filter(Boolean)
23
- .map((segment) => encodeURIComponent(segment))
24
- .join("/");
25
- }
26
- function buildAssetUrlBuilder(apiBaseUrl, assetOptions) {
27
- const uploadsPath = normalizeUploadsPath(assetOptions?.uploadsPath);
28
- const explicitBaseUrl = normalizeAssetBaseUrl(assetOptions?.baseUrl);
29
- if (explicitBaseUrl) {
30
- return (filename) => `${explicitBaseUrl}${uploadsPath}/${encodeFilenameForUrl(filename)}`;
31
- }
32
- let inferredBaseUrl = "";
33
- try {
34
- inferredBaseUrl = new URL(apiBaseUrl).origin;
35
- }
36
- catch {
37
- inferredBaseUrl = "";
38
- }
39
- return (filename) => `${inferredBaseUrl}${uploadsPath}/${encodeFilenameForUrl(filename)}`;
40
- }
41
- function maybeAttachAssetUrl(value, assetUrlBuilder) {
42
- if (!value || typeof value !== "object" || Array.isArray(value))
43
- return value;
44
- const source = value;
45
- const filename = typeof source.filename === "string" ? source.filename.trim() : "";
46
- if (!filename)
47
- return value;
48
- const isAssetShape = typeof source.mimeType === "string" ||
49
- typeof source.extension === "string" ||
50
- typeof source.size === "number" ||
51
- typeof source.width === "number" ||
52
- typeof source.height === "number" ||
53
- typeof source.length === "number";
54
- if (!isAssetShape)
55
- return value;
56
- const existingUrl = typeof source.url === "string" && source.url.trim().length > 0
57
- ? source.url
58
- : null;
59
- return {
60
- ...source,
61
- url: existingUrl ?? assetUrlBuilder(filename),
62
- };
63
- }
64
- async function mapWithConcurrency(items, concurrency, mapper) {
65
- if (items.length === 0)
66
- return [];
67
- const limit = Math.max(1, Math.floor(concurrency));
68
- if (limit >= items.length) {
69
- return Promise.all(items.map((item, index) => mapper(item, index)));
70
- }
71
- const results = new Array(items.length);
72
- let nextIndex = 0;
73
- const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
74
- while (true) {
75
- const current = nextIndex++;
76
- if (current >= items.length)
77
- break;
78
- results[current] = await mapper(items[current], current);
79
- }
80
- });
81
- await Promise.all(workers);
82
- return results;
83
- }
84
- function extractId(value) {
85
- if (typeof value === "string" && value.length > 0)
86
- return value;
87
- if (value && typeof value === "object" && typeof value.id === "string") {
88
- return value.id;
89
- }
90
- return null;
91
- }
92
- function capitalize(input) {
93
- return input ? input[0].toUpperCase() + input.slice(1) : input;
94
- }
95
- function lowerFirst(input) {
96
- return input ? input[0].toLowerCase() + input.slice(1) : input;
97
- }
98
- function camelCaseModelIdKey(modelName) {
99
- return `${lowerFirst(modelName)}Id`;
100
- }
101
- function snakeCaseModelIdKey(modelName) {
102
- const snake = modelName
103
- .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
104
- .replace(/\s+/g, "_")
105
- .toLowerCase();
106
- return `${snake}_id`;
107
- }
108
- function extractModelRefId(raw, modelName, options) {
109
- if (typeof raw === "string")
110
- return raw;
111
- if (!raw || typeof raw !== "object")
112
- return null;
113
- const object = raw;
114
- const prop = options?.propertyName ?? "";
115
- const propertyCandidates = [
116
- prop ? `${prop}Id` : "",
117
- prop
118
- ? `${prop.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase()}_id`
119
- : "",
120
- ].filter(Boolean);
121
- const modelCandidates = [
122
- camelCaseModelIdKey(modelName),
123
- snakeCaseModelIdKey(modelName),
124
- ];
125
- // Prefer property-specific FKs (e.g., logoId) over model-level defaults
126
- // (e.g., imageId) when multiple refs share the same model in one object row.
127
- const candidates = Array.from(new Set([...propertyCandidates, ...modelCandidates, "value"]));
128
- for (const key of candidates) {
129
- const found = extractId(object[key]);
130
- if (found)
131
- return found;
132
- }
133
- const allowObjectIdFallback = options?.allowObjectIdFallback ?? true;
134
- if (allowObjectIdFallback) {
135
- const keys = Object.keys(object);
136
- const hasOnlyId = keys.length === 1 && keys[0] === "id";
137
- if (hasOnlyId) {
138
- const byId = extractId(object);
139
- if (byId)
140
- return byId;
141
- }
142
- }
143
- return null;
144
- }
145
- function isPrimitiveDescriptor(desc) {
146
- return desc.kind === "primitive";
147
- }
148
- function isModelRefDescriptor(desc) {
149
- return desc.kind === "modelRef";
150
- }
151
- function isObjectDescriptor(desc) {
152
- return desc.type === "object" && !!desc.properties;
153
- }
154
- function isArrayDescriptor(desc) {
155
- return desc.type === "array" && !!desc.items;
156
- }
157
- function attachIdIfObject(value, id) {
158
- if (!id)
159
- return value;
160
- if (value && typeof value === "object" && !Array.isArray(value) && !value.id) {
161
- return { ...value, id };
162
- }
163
- return value;
164
- }
165
- function attachIdForPrimitiveDescriptor(descriptor, value, id) {
166
- const withId = attachIdIfObject(value, id);
167
- if (!withId || typeof withId !== "object" || Array.isArray(withId)) {
168
- return withId;
169
- }
170
- const customType = descriptor.customType;
171
- if (typeof customType !== "string") {
172
- return withId;
173
- }
174
- const metadata = getCustomInlineTypeMetadata(customType);
175
- if (!metadata?.includeId?.mapLikeFields?.length) {
176
- return withId;
177
- }
178
- // Map-like objects (e.g., locales) are data containers, not entity rows.
179
- // Keep them untouched by id propagation.
180
- return { ...withId };
181
- }
182
- function buildModelRefCacheKey(modelName, id, context, isCollectionItem) {
183
- const locale = context.options.locale ?? "";
184
- const defaultLocale = context.options.defaultLocale ?? "";
185
- const includeIdMode = context.options.includeIdMode;
186
- const refsMode = context.options.resolveModelRefs ? "resolve" : "ids";
187
- const collectionFlag = isCollectionItem ? "collection" : "single";
188
- return [
189
- modelName,
190
- id,
191
- locale,
192
- defaultLocale,
193
- includeIdMode,
194
- refsMode,
195
- collectionFlag,
196
- ].join("|");
197
- }
198
- function extractInlineModelObject(raw, modelDescriptor) {
199
- if (!raw || typeof raw !== "object" || Array.isArray(raw))
200
- return null;
201
- if (!isObjectDescriptor(modelDescriptor))
202
- return null;
203
- const source = raw;
204
- const propertyKeys = Object.keys(modelDescriptor.properties ?? {});
205
- const hasModelField = propertyKeys.some((key) => key in source);
206
- if (!hasModelField)
207
- return null;
208
- return source;
209
- }
210
- function asModelObjectDescriptor(modelName, descriptor) {
211
- const model = descriptor.models?.[modelName];
212
- if (!model) {
213
- throw new Error(`Unknown model '${modelName}' in schema descriptor.`);
214
- }
215
- return {
216
- type: "object",
217
- properties: model.properties,
218
- optional: false,
219
- nullable: false,
220
- };
221
- }
222
- function formatValidationError(name, error) {
223
- const payload = error && typeof error === "object" && "format" in error
224
- ? error.format()
225
- : error;
226
- return `Invalid data received for '${name}': ${JSON.stringify(payload)}`;
227
- }
228
- function levenshtein(a, b) {
229
- if (a === b)
230
- return 0;
231
- if (!a.length)
232
- return b.length;
233
- if (!b.length)
234
- return a.length;
235
- const rows = a.length + 1;
236
- const cols = b.length + 1;
237
- const matrix = Array.from({ length: rows }, () => new Array(cols).fill(0));
238
- for (let i = 0; i < rows; i++)
239
- matrix[i][0] = i;
240
- for (let j = 0; j < cols; j++)
241
- matrix[0][j] = j;
242
- for (let i = 1; i < rows; i++) {
243
- for (let j = 1; j < cols; j++) {
244
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
245
- matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost);
246
- }
247
- }
248
- return matrix[rows - 1][cols - 1];
249
- }
250
- function unknownKeyError(key, roots, models) {
251
- const candidates = [...roots, ...models];
252
- const normalized = key.toLowerCase();
253
- const suggestions = candidates
254
- .map((candidate) => ({
255
- candidate,
256
- distance: levenshtein(normalized, candidate.toLowerCase()),
257
- }))
258
- .sort((a, b) => a.distance - b.distance)
259
- .slice(0, 3)
260
- .map((entry) => entry.candidate);
261
- const suggestionText = suggestions.length
262
- ? ` Did you mean: ${suggestions.join(", ")}?`
263
- : "";
264
- const rootsText = `Available roots: [${roots.join(", ")}]`;
265
- const modelsText = models.length
266
- ? `, models (under data.models.*): [${models.join(", ")}]`
267
- : "";
268
- throw new Error(`Unknown schema key '${key}'. ${rootsText}${modelsText}.${suggestionText}`);
269
- }
270
- function toPlainText(value) {
271
- if (typeof value === "string")
272
- return value;
273
- if (typeof value === "number" || typeof value === "boolean")
274
- return String(value);
275
- if (!value || typeof value !== "object")
276
- return "";
277
- const node = value;
278
- if (typeof node.text === "string")
279
- return node.text;
280
- if ("value" in node)
281
- return toPlainText(node.value);
282
- if (Array.isArray(node.content)) {
283
- return node.content
284
- .map((child) => toPlainText(child))
285
- .filter(Boolean)
286
- .join(" ")
287
- .trim();
288
- }
289
- return "";
290
- }
291
- function coerceRichTextValue(value) {
292
- const source = value && typeof value === "object" ? value : {};
293
- const nested = source.value && typeof source.value === "object"
294
- ? source.value
295
- : null;
296
- const normalizedValue = source.value !== undefined ? source.value : value ?? {};
297
- const html = typeof source.html === "string"
298
- ? source.html
299
- : typeof nested?.html === "string"
300
- ? nested.html
301
- : "";
302
- return {
303
- value: normalizedValue ?? {},
304
- html,
305
- };
306
- }
307
- function normalizeLocaleTag(value) {
308
- return typeof value === "string" ? value.trim() : "";
309
- }
310
- function normalizeLocalizedMap(source, normalizeValue) {
311
- const record = source && typeof source === "object" ? source : {};
312
- const localesSource = record.locales && typeof record.locales === "object" && !Array.isArray(record.locales)
313
- ? record.locales
314
- : {};
315
- const locales = {};
316
- for (const [locale, raw] of Object.entries(localesSource)) {
317
- const localeKey = normalizeLocaleTag(locale);
318
- if (!localeKey)
319
- continue;
320
- locales[localeKey] = normalizeValue(raw);
321
- }
322
- const explicitDefault = normalizeLocaleTag(record.defaultLocale);
323
- const firstLocale = Object.keys(locales)[0] ?? "";
324
- const defaultLocale = explicitDefault || firstLocale;
325
- return { defaultLocale, locales };
326
- }
327
- function projectLocalizedByLocale(localized, locale) {
328
- if (!locale || locale === "all")
329
- return localized;
330
- const requested = normalizeLocaleTag(locale);
331
- if (!requested)
332
- return localized;
333
- const requestedValue = localized.locales[requested];
334
- if (requestedValue === undefined) {
335
- return {
336
- defaultLocale: requested,
337
- locales: {},
338
- };
339
- }
340
- return {
341
- defaultLocale: requested,
342
- locales: {
343
- [requested]: requestedValue,
344
- },
345
- };
346
- }
347
- function coerceLocalizedStringValue(value, locale, defaultLocale) {
348
- const normalized = normalizeLocalizedMap(value, (entry) => toPlainText(entry));
349
- if (!normalized.defaultLocale && defaultLocale) {
350
- normalized.defaultLocale = defaultLocale;
351
- }
352
- return projectLocalizedByLocale(normalized, locale);
353
- }
354
- function coerceLocalizedRichTextValue(value, locale, defaultLocale) {
355
- const normalized = normalizeLocalizedMap(value, (entry) => coerceRichTextValue(entry));
356
- if (!normalized.defaultLocale && defaultLocale) {
357
- normalized.defaultLocale = defaultLocale;
358
- }
359
- return projectLocalizedByLocale(normalized, locale);
360
- }
361
- function coerceCustomTypeValue(descriptor, value, options) {
362
- const customType = descriptor.customType;
363
- if (!customType)
364
- return value;
365
- if (customType === "RichText")
366
- return coerceRichTextValue(value);
367
- if (customType === "File" || customType === "Image" || customType === "Video") {
368
- return maybeAttachAssetUrl(value, options?.assetUrlBuilder ?? ((filename) => filename));
369
- }
370
- if (customType === "LocalizedString") {
371
- return coerceLocalizedStringValue(value, options?.locale, options?.defaultLocale);
372
- }
373
- if (customType === "LocalizedRichText") {
374
- return coerceLocalizedRichTextValue(value, options?.locale, options?.defaultLocale);
375
- }
376
- return value;
377
- }
378
- function ensureCollectionEnvelope(data, path) {
379
- if (Array.isArray(data)) {
380
- return { items: data, total: data.length };
381
- }
382
- if (data && typeof data === "object" && Array.isArray(data.items)) {
383
- return {
384
- items: data.items,
385
- total: Number(data.total ?? data.items.length ?? 0),
386
- };
387
- }
388
- throw new Error(`${COLLECTION_SHAPE_ERROR} Path: '${path}'.`);
389
- }
390
- async function normalizeModelRef(modelName, id, context, trail, isCollectionItem, inlineValue) {
391
- if (!id)
392
- return null;
393
- if (!context.options.resolveModelRefs)
394
- return id;
395
- const nodeKey = buildModelRefCacheKey(modelName, id, context, isCollectionItem);
396
- if (trail.has(nodeKey)) {
397
- return shouldIncludeObjectId(context.options.includeIdMode, isCollectionItem)
398
- ? { id }
399
- : id;
400
- }
401
- const modelDescriptor = context.modelDescriptors.get(modelName);
402
- if (!modelDescriptor) {
403
- return id;
404
- }
405
- const inlineModel = extractInlineModelObject(inlineValue, modelDescriptor);
406
- const cached = context.modelCache.get(nodeKey);
407
- if (cached) {
408
- return cached;
409
- }
410
- const sharedInflight = context.sharedModelInflightCache.get(nodeKey);
411
- if (sharedInflight) {
412
- context.modelCache.set(nodeKey, sharedInflight);
413
- return sharedInflight;
414
- }
415
- const nextTrail = new Set(trail);
416
- nextTrail.add(nodeKey);
417
- const promise = (async () => {
418
- const rawModel = inlineModel ??
419
- (await context.requestJson(`models/${modelName}/${id}`, {
420
- query: {
421
- raw: 1,
422
- ...(context.options.locale ? { locale: context.options.locale } : {}),
423
- },
424
- }));
425
- return normalizeField(modelDescriptor, `models/${modelName}/${encodeURIComponent(id)}`, rawModel, context, nextTrail, isCollectionItem);
426
- })();
427
- context.modelCache.set(nodeKey, promise);
428
- context.sharedModelInflightCache.set(nodeKey, promise);
429
- promise
430
- .then(() => undefined, () => {
431
- context.modelCache.delete(nodeKey);
432
- })
433
- .finally(() => {
434
- context.sharedModelInflightCache.delete(nodeKey);
435
- });
436
- return promise;
437
- }
438
- function missingModelRefValue(descriptor) {
439
- if (descriptor.nullable)
440
- return null;
441
- if (descriptor.optional)
442
- return undefined;
443
- return null;
444
- }
445
- async function normalizeObjectField(descriptor, path, raw, context, trail, isCollectionItem) {
446
- const source = raw && typeof raw === "object" ? raw : {};
447
- const output = {};
448
- for (const [propertyName, propertyDescriptor] of Object.entries(descriptor.properties)) {
449
- if (isPrimitiveDescriptor(propertyDescriptor)) {
450
- output[propertyName] = coerceCustomTypeValue(propertyDescriptor, source[propertyName], {
451
- locale: context.options.locale,
452
- defaultLocale: context.options.defaultLocale,
453
- assetUrlBuilder: context.options.assetUrlBuilder,
454
- });
455
- continue;
456
- }
457
- if (isModelRefDescriptor(propertyDescriptor)) {
458
- const inlineValue = source[propertyName];
459
- const inlineModelDescriptor = context.modelDescriptors.get(propertyDescriptor.model);
460
- const inlineModel = inlineModelDescriptor
461
- ? extractInlineModelObject(inlineValue, inlineModelDescriptor)
462
- : null;
463
- const refId = extractModelRefId(inlineValue, propertyDescriptor.model, {
464
- allowObjectIdFallback: true,
465
- }) ??
466
- (inlineModel ? extractId(inlineModel) : null) ??
467
- extractModelRefId(source, propertyDescriptor.model, {
468
- propertyName,
469
- allowObjectIdFallback: false,
470
- });
471
- if (!refId) {
472
- const missing = missingModelRefValue(propertyDescriptor);
473
- if (missing !== undefined) {
474
- output[propertyName] = missing;
475
- }
476
- continue;
477
- }
478
- output[propertyName] = await normalizeModelRef(propertyDescriptor.model, refId, context, trail, false, inlineValue);
479
- continue;
480
- }
481
- if (isArrayDescriptor(propertyDescriptor)) {
482
- const childPath = `${path}/${propertyName}`;
483
- const childRaw = await context.requestJson(childPath, {
484
- query: {
485
- raw: 1,
486
- ...(context.options.locale ? { locale: context.options.locale } : {}),
487
- },
488
- });
489
- const normalizedChild = await normalizeArrayField(propertyDescriptor, childPath, childRaw, context, trail);
490
- output[propertyName] = coerceCustomTypeValue(propertyDescriptor, normalizedChild, {
491
- locale: context.options.locale,
492
- defaultLocale: context.options.defaultLocale,
493
- assetUrlBuilder: context.options.assetUrlBuilder,
494
- });
495
- continue;
496
- }
497
- if (isObjectDescriptor(propertyDescriptor)) {
498
- const childPath = `${path}/${propertyName}`;
499
- const childRaw = await context.requestJson(childPath, {
500
- query: {
501
- raw: 1,
502
- ...(context.options.locale ? { locale: context.options.locale } : {}),
503
- },
504
- });
505
- const normalizedChild = await normalizeObjectField(propertyDescriptor, childPath, childRaw, context, trail, false);
506
- output[propertyName] = coerceCustomTypeValue(propertyDescriptor, normalizedChild, {
507
- locale: context.options.locale,
508
- defaultLocale: context.options.defaultLocale,
509
- assetUrlBuilder: context.options.assetUrlBuilder,
510
- });
511
- }
512
- }
513
- if (shouldIncludeObjectId(context.options.includeIdMode, isCollectionItem)) {
514
- const rowId = extractId(source);
515
- if (rowId)
516
- output.id = rowId;
517
- }
518
- if (typeof source.url === "string" &&
519
- source.url.trim().length > 0 &&
520
- typeof output.filename === "string") {
521
- output.url = source.url;
522
- }
523
- return maybeAttachAssetUrl(output, context.options.assetUrlBuilder);
524
- }
525
- async function normalizeArrayField(descriptor, path, raw, context, trail) {
526
- const envelope = ensureCollectionEnvelope(raw, path);
527
- const itemDescriptor = descriptor.items;
528
- if (isPrimitiveDescriptor(itemDescriptor)) {
529
- return envelope.items.map((row) => {
530
- const value = row && typeof row === "object" && "value" in row
531
- ? row.value
532
- : row;
533
- if (context.options.includeIdMode !== "all") {
534
- return value;
535
- }
536
- const id = extractId(row);
537
- const valueWithId = attachIdForPrimitiveDescriptor(itemDescriptor, value, id);
538
- const isObjectValue = valueWithId && typeof valueWithId === "object" && !Array.isArray(valueWithId);
539
- if (!id) {
540
- return valueWithId;
541
- }
542
- return isObjectValue ? { id, ...valueWithId } : { id, value: valueWithId };
543
- });
544
- }
545
- if (isModelRefDescriptor(itemDescriptor)) {
546
- const inlineModelDescriptor = context.modelDescriptors.get(itemDescriptor.model);
547
- return mapWithConcurrency(envelope.items, context.options.modelNormalizationConcurrency, async (row) => {
548
- const inlineModel = inlineModelDescriptor
549
- ? extractInlineModelObject(row, inlineModelDescriptor)
550
- : null;
551
- const refId = extractModelRefId(row, itemDescriptor.model, {
552
- allowObjectIdFallback: false,
553
- }) ?? (inlineModel ? extractId(inlineModel) : null);
554
- return normalizeModelRef(itemDescriptor.model, refId, context, trail, true, row);
555
- });
556
- }
557
- if (isObjectDescriptor(itemDescriptor)) {
558
- return mapWithConcurrency(envelope.items, context.options.modelNormalizationConcurrency, async (row) => {
559
- const rowId = extractId(row);
560
- const rowPath = rowId
561
- ? `${path}/${encodeURIComponent(rowId)}`
562
- : path;
563
- return normalizeObjectField(itemDescriptor, rowPath, row, context, trail, true);
564
- });
565
- }
566
- return envelope.items;
567
- }
568
- async function normalizeField(descriptor, path, raw, context, trail, isCollectionItem) {
569
- if (isPrimitiveDescriptor(descriptor)) {
570
- const value = raw && typeof raw === "object" && "value" in raw
571
- ? raw.value
572
- : raw;
573
- let coerced = coerceCustomTypeValue(descriptor, value, {
574
- locale: context.options.locale,
575
- defaultLocale: context.options.defaultLocale,
576
- assetUrlBuilder: context.options.assetUrlBuilder,
577
- });
578
- if (shouldIncludeObjectId(context.options.includeIdMode, isCollectionItem)) {
579
- const id = extractId(raw);
580
- coerced = attachIdForPrimitiveDescriptor(descriptor, coerced, id);
581
- }
582
- return coerced;
583
- }
584
- if (isModelRefDescriptor(descriptor)) {
585
- const inlineModelDescriptor = context.modelDescriptors.get(descriptor.model);
586
- const inlineModel = inlineModelDescriptor
587
- ? extractInlineModelObject(raw, inlineModelDescriptor)
588
- : null;
589
- const refId = extractModelRefId(raw, descriptor.model, {
590
- allowObjectIdFallback: true,
591
- }) ?? (inlineModel ? extractId(inlineModel) : null);
592
- if (!refId) {
593
- return missingModelRefValue(descriptor);
594
- }
595
- return normalizeModelRef(descriptor.model, refId, context, trail, isCollectionItem, raw);
596
- }
597
- if (isArrayDescriptor(descriptor)) {
598
- const normalized = await normalizeArrayField(descriptor, path, raw, context, trail);
599
- return coerceCustomTypeValue(descriptor, normalized, {
600
- locale: context.options.locale,
601
- defaultLocale: context.options.defaultLocale,
602
- assetUrlBuilder: context.options.assetUrlBuilder,
603
- });
604
- }
605
- if (isObjectDescriptor(descriptor)) {
606
- const normalized = await normalizeObjectField(descriptor, path, raw, context, trail, isCollectionItem);
607
- return coerceCustomTypeValue(descriptor, normalized, {
608
- locale: context.options.locale,
609
- defaultLocale: context.options.defaultLocale,
610
- assetUrlBuilder: context.options.assetUrlBuilder,
611
- });
612
- }
613
- return raw;
614
- }
615
- function createResourceRegistry(descriptor) {
616
- const roots = new Map();
617
- const rootsCaseInsensitive = new Map();
618
- for (const [key, rootDescriptor] of Object.entries(descriptor.roots ?? {})) {
619
- const entry = {
620
- kind: "root",
621
- key,
622
- path: key,
623
- descriptor: rootDescriptor,
624
- isCollection: isArrayDescriptor(rootDescriptor),
625
- };
626
- roots.set(key, entry);
627
- rootsCaseInsensitive.set(key.toLowerCase(), entry);
628
- }
629
- const models = new Map();
630
- const modelsCaseInsensitive = new Map();
631
- for (const modelName of Object.keys(descriptor.models ?? {})) {
632
- const entry = {
633
- kind: "model",
634
- key: modelName,
635
- path: `models/${modelName}`,
636
- descriptor: asModelObjectDescriptor(modelName, descriptor),
637
- isCollection: true,
638
- modelName,
639
- };
640
- models.set(modelName, entry);
641
- modelsCaseInsensitive.set(modelName.toLowerCase(), entry);
642
- }
643
- return {
644
- roots,
645
- rootsCaseInsensitive,
646
- models,
647
- modelsCaseInsensitive,
648
- };
649
- }
650
- function normalizeBaseUrl(baseUrl) {
651
- const cleaned = baseUrl?.trim().replace(/\/$/, "") ?? "";
652
- if (!cleaned) {
653
- throw new Error("cms0: apiConfig.baseUrl is required to consume API resources.");
654
- }
655
- return cleaned;
656
- }
657
- function resolveIncludeIdMode(includeId, globalIncludeId) {
658
- const enabled = includeId ?? globalIncludeId ?? false;
659
- return enabled ? "all" : "none";
660
- }
661
- function shouldIncludeObjectId(mode, _isCollectionItem) {
662
- return mode === "all";
663
- }
664
- function buildSearchParams(query) {
665
- const params = new URLSearchParams();
666
- if (!query)
667
- return params;
668
- for (const [key, rawValue] of Object.entries(query)) {
669
- if (rawValue === undefined || rawValue === null)
670
- continue;
671
- if (Array.isArray(rawValue)) {
672
- rawValue.forEach((value) => {
673
- if (value === undefined || value === null)
674
- return;
675
- params.append(key, String(value));
676
- });
677
- continue;
678
- }
679
- params.set(key, String(rawValue));
680
- }
681
- return params;
682
- }
683
- async function requestJson(baseUrl, apiKey, path, options) {
684
- const params = buildSearchParams(options?.query);
685
- const url = `${baseUrl}/${path}${params.toString() ? `?${params.toString()}` : ""}`;
686
- const response = await fetch(url, {
687
- method: "GET",
688
- signal: options?.signal,
689
- headers: {
690
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
691
- },
692
- });
693
- if (!response.ok) {
694
- throw new Error(`Request failed for '${path}' with status ${response.status}: ${response.statusText}`);
695
- }
696
- return response.json();
697
- }
698
- function validateResult(resource, result, descriptor, includeIdMode, zodSchemas, modelZodSchemas) {
699
- if (includeIdMode === "all")
700
- return;
701
- if (resource.kind === "root") {
702
- const schema = zodSchemas[resource.key];
703
- if (!schema)
704
- return;
705
- const parsed = schema.safeParse(result);
706
- if (!parsed.success) {
707
- throw new Error(formatValidationError(resource.key, parsed.error));
708
- }
709
- return;
710
- }
711
- const modelName = resource.modelName;
712
- if (!modelName)
713
- return;
714
- const modelSchema = modelZodSchemas[modelName];
715
- if (!modelSchema)
716
- return;
717
- if (Array.isArray(result)) {
718
- const parsed = modelSchema.array().safeParse(result);
719
- if (!parsed.success) {
720
- throw new Error(formatValidationError(modelName, parsed.error));
721
- }
722
- return;
723
- }
724
- if (result === null || result === undefined)
725
- return;
726
- const parsed = modelSchema.safeParse(result);
727
- if (!parsed.success) {
728
- throw new Error(formatValidationError(modelName, parsed.error));
729
- }
730
- }
731
- async function runResource(resource, descriptor, baseUrl, apiKey, defaultLocale, assetUrlBuilder, zodSchemas, modelZodSchemas, globalIncludeId, sharedModelInflightCache, options, byId) {
732
- const responseMode = options?.response ?? "normalized";
733
- const includeIdMode = resolveIncludeIdMode(options?.includeId, globalIncludeId);
734
- const resolveModelRefs = options?.resolveModelRefs !== false;
735
- const requestedLocale = options?.locale ??
736
- (typeof options?.query?.locale === "string"
737
- ? options.query.locale
738
- : undefined);
739
- const locale = requestedLocale ??
740
- (responseMode === "normalized" ? "all" : undefined);
741
- const query = {
742
- ...(options?.query ?? {}),
743
- };
744
- const shouldNormalize = responseMode !== "raw";
745
- if (shouldNormalize && query.raw === undefined) {
746
- query.raw = 1;
747
- }
748
- if (locale && query.locale === undefined) {
749
- query.locale = locale;
750
- }
751
- const resourcePath = byId
752
- ? `${resource.path}/${encodeURIComponent(byId)}`
753
- : resource.path;
754
- const rawData = await requestJson(baseUrl, apiKey, resourcePath, {
755
- query,
756
- signal: options?.signal,
757
- });
758
- if (!shouldNormalize) {
759
- return rawData;
760
- }
761
- const modelDescriptors = new Map();
762
- for (const modelName of Object.keys(descriptor.models ?? {})) {
763
- modelDescriptors.set(modelName, asModelObjectDescriptor(modelName, descriptor));
764
- }
765
- const context = {
766
- requestJson: (path, requestOptions) => requestJson(baseUrl, apiKey, path, {
767
- ...requestOptions,
768
- signal: options?.signal,
769
- }),
770
- modelDescriptors,
771
- modelCache: new Map(),
772
- sharedModelInflightCache,
773
- options: {
774
- includeIdMode,
775
- resolveModelRefs,
776
- locale,
777
- defaultLocale,
778
- assetUrlBuilder,
779
- modelNormalizationConcurrency: DEFAULT_MODEL_NORMALIZATION_CONCURRENCY,
780
- },
781
- };
782
- if (resource.isCollection && !byId) {
783
- const envelope = ensureCollectionEnvelope(rawData, resource.path);
784
- const descriptorForCollection = resource.kind === "root" && isArrayDescriptor(resource.descriptor)
785
- ? resource.descriptor
786
- : {
787
- type: "array",
788
- items: resource.descriptor,
789
- optional: false,
790
- nullable: false,
791
- };
792
- const normalizedItems = await normalizeArrayField(descriptorForCollection, resource.path, envelope, context, new Set());
793
- if (responseMode === "envelope") {
794
- validateResult(resource, normalizedItems, descriptor, includeIdMode, zodSchemas, modelZodSchemas);
795
- return {
796
- items: normalizedItems,
797
- total: envelope.total,
798
- };
799
- }
800
- validateResult(resource, normalizedItems, descriptor, includeIdMode, zodSchemas, modelZodSchemas);
801
- return normalizedItems;
802
- }
803
- const normalized = await normalizeField(resource.descriptor, resourcePath, rawData, context, new Set(), false);
804
- validateResult(resource, normalized, descriptor, includeIdMode, zodSchemas, modelZodSchemas);
805
- return normalized;
806
- }
807
- export function createCmsClient(descriptor, config) {
808
- const baseUrl = normalizeBaseUrl(config.apiConfig?.baseUrl);
809
- const apiKey = config.apiConfig?.key;
810
- const assetUrlBuilder = buildAssetUrlBuilder(baseUrl, config.assets);
811
- const registry = createResourceRegistry(descriptor);
812
- const rootKeys = Array.from(registry.roots.keys());
813
- const modelKeys = Array.from(registry.models.keys());
814
- const { zodSchemas, modelZodSchemas } = buildZodSchemasFromDescriptor(descriptor);
815
- const globalIncludeId = !!config.includeId;
816
- const sharedModelInflightCache = new Map();
817
- const buildModelAccessor = (entry) => {
818
- const accessor = (async (options) => runResource(entry, descriptor, baseUrl, apiKey, config.defaultLocale, assetUrlBuilder, zodSchemas, modelZodSchemas, globalIncludeId, sharedModelInflightCache, options));
819
- accessor.byId = async (id, options) => runResource(entry, descriptor, baseUrl, apiKey, config.defaultLocale, assetUrlBuilder, zodSchemas, modelZodSchemas, globalIncludeId, sharedModelInflightCache, options, id);
820
- return accessor;
821
- };
822
- const modelsProxy = new Proxy({}, {
823
- get(_target, property) {
824
- if (typeof property !== "string")
825
- return undefined;
826
- if (property === "then")
827
- return undefined;
828
- const modelEntry = registry.models.get(property) ??
829
- registry.modelsCaseInsensitive.get(property.toLowerCase());
830
- if (!modelEntry) {
831
- unknownKeyError(property, [], modelKeys);
832
- }
833
- return buildModelAccessor(modelEntry);
834
- },
835
- });
836
- const rootProxy = new Proxy({}, {
837
- get(_target, property) {
838
- if (typeof property !== "string")
839
- return undefined;
840
- if (property === "then")
841
- return undefined;
842
- if (property === "models")
843
- return modelsProxy;
844
- const entry = registry.roots.get(property) ??
845
- registry.rootsCaseInsensitive.get(property.toLowerCase());
846
- if (!entry) {
847
- unknownKeyError(property, rootKeys, []);
848
- }
849
- return async (options) => runResource(entry, descriptor, baseUrl, apiKey, config.defaultLocale, assetUrlBuilder, zodSchemas, modelZodSchemas, globalIncludeId, sharedModelInflightCache, options);
850
- },
851
- });
852
- const client = Object.assign(rootProxy, {
853
- models: modelsProxy,
854
- locales: config.locales ?? [],
855
- defaultLocale: config.defaultLocale,
856
- includeIdDefault: !!config.includeId,
857
- });
858
- return client;
859
- }
860
- export function cms0(config) {
861
- return createCmsClient(schemaDescriptor, config);
862
- }