@cms0/cms0 0.0.9 → 0.0.11

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/dist/esm/index.js CHANGED
@@ -1,44 +1,639 @@
1
1
  import { schemaDescriptor } from "@cms0/cms0/schema-descriptors";
2
- import * as Shared from "@cms0/shared";
3
- /**
4
- * Initializes the CMS SDK for a given schema.
5
- * @param config configuration including API base URL or database URL.
6
- * @returns an object with typed accessors matching the schema.
7
- */
8
- export function cms0(config) {
9
- const baseUrl = config.apiConfig?.baseUrl?.replace(/\/$/, "") ?? "";
10
- const apiKey = config.apiConfig?.key;
11
- return new Proxy({}, {
12
- get(target, prop) {
13
- if (!(prop in schemaDescriptor.roots)) {
14
- throw new Error(`Unknown schema key '${prop}'`);
2
+ import { buildZodSchemasFromDescriptor, } from "@cms0/shared";
3
+ const COLLECTION_SHAPE_ERROR = "Invalid collection response. Expected array or { items, total }.";
4
+ function toPlainText(value) {
5
+ if (typeof value === "string")
6
+ return value;
7
+ if (typeof value === "number" || typeof value === "boolean")
8
+ return String(value);
9
+ if (!value || typeof value !== "object")
10
+ return "";
11
+ const node = value;
12
+ if (typeof node.text === "string")
13
+ return node.text;
14
+ if ("value" in node)
15
+ return toPlainText(node.value);
16
+ if (Array.isArray(node.content)) {
17
+ return node.content
18
+ .map((child) => toPlainText(child))
19
+ .filter(Boolean)
20
+ .join(" ")
21
+ .trim();
22
+ }
23
+ return "";
24
+ }
25
+ function coerceRichTextValue(value) {
26
+ const source = value && typeof value === "object" ? value : {};
27
+ const nested = source.value && typeof source.value === "object"
28
+ ? source.value
29
+ : null;
30
+ const normalizedValue = source.value !== undefined ? source.value : value ?? {};
31
+ const html = typeof source.html === "string"
32
+ ? source.html
33
+ : typeof nested?.html === "string"
34
+ ? nested.html
35
+ : "";
36
+ return {
37
+ value: normalizedValue ?? {},
38
+ html,
39
+ };
40
+ }
41
+ function shouldKeepLocalizedEntry(source, locale, defaultLocale) {
42
+ if (locale === "all")
43
+ return true;
44
+ const rowLocale = typeof source.locale === "string" ? source.locale : "";
45
+ if (locale) {
46
+ return rowLocale === locale;
47
+ }
48
+ if (defaultLocale) {
49
+ return rowLocale === defaultLocale;
50
+ }
51
+ return true;
52
+ }
53
+ function coerceLocalizedStringValue(value, locale, defaultLocale) {
54
+ const rows = Array.isArray(value) ? value : [];
55
+ return rows
56
+ .map((row) => {
57
+ const source = row && typeof row === "object" ? row : {};
58
+ return {
59
+ ...source,
60
+ locale: typeof source.locale === "string" ? source.locale : "",
61
+ isDefault: source.isDefault === true,
62
+ value: toPlainText(source.value),
63
+ };
64
+ })
65
+ .filter((row) => shouldKeepLocalizedEntry(row, locale, defaultLocale));
66
+ }
67
+ function coerceLocalizedRichTextValue(value, locale, defaultLocale) {
68
+ const rows = Array.isArray(value) ? value : [];
69
+ return rows
70
+ .map((row) => {
71
+ const source = row && typeof row === "object" ? row : {};
72
+ const rawValue = source.value;
73
+ const nested = rawValue && typeof rawValue === "object" ? rawValue : null;
74
+ const normalizedValue = nested && "value" in nested && nested.value !== undefined
75
+ ? nested.value
76
+ : rawValue ?? {};
77
+ const html = typeof source.html === "string"
78
+ ? source.html
79
+ : typeof nested?.html === "string"
80
+ ? nested.html
81
+ : "";
82
+ return {
83
+ ...source,
84
+ locale: typeof source.locale === "string" ? source.locale : "",
85
+ isDefault: source.isDefault === true,
86
+ value: normalizedValue ?? {},
87
+ html,
88
+ };
89
+ })
90
+ .filter((row) => shouldKeepLocalizedEntry(row, locale, defaultLocale));
91
+ }
92
+ function coerceCustomTypeValue(descriptor, value, options) {
93
+ const customType = descriptor.customType;
94
+ if (!customType)
95
+ return value;
96
+ if (customType === "RichText")
97
+ return coerceRichTextValue(value);
98
+ if (customType === "LocalizedString") {
99
+ return coerceLocalizedStringValue(value, options?.locale, options?.defaultLocale);
100
+ }
101
+ if (customType === "LocalizedRichText") {
102
+ return coerceLocalizedRichTextValue(value, options?.locale, options?.defaultLocale);
103
+ }
104
+ return value;
105
+ }
106
+ function isPrimitiveDescriptor(desc) {
107
+ return desc.kind === "primitive";
108
+ }
109
+ function isModelRefDescriptor(desc) {
110
+ return desc.kind === "modelRef";
111
+ }
112
+ function isObjectDescriptor(desc) {
113
+ return desc.type === "object" && !!desc.properties;
114
+ }
115
+ function isArrayDescriptor(desc) {
116
+ return desc.type === "array" && !!desc.items;
117
+ }
118
+ function asModelObjectDescriptor(modelName, descriptor) {
119
+ const model = descriptor.models?.[modelName];
120
+ if (!model) {
121
+ throw new Error(`Unknown model '${modelName}' in schema descriptor.`);
122
+ }
123
+ return {
124
+ type: "object",
125
+ properties: model.properties,
126
+ optional: false,
127
+ nullable: false,
128
+ };
129
+ }
130
+ function normalizeBaseUrl(baseUrl) {
131
+ const cleaned = baseUrl?.trim().replace(/\/$/, "") ?? "";
132
+ if (!cleaned) {
133
+ throw new Error("cms0: apiConfig.baseUrl is required to consume API resources.");
134
+ }
135
+ return cleaned;
136
+ }
137
+ function resolveIncludeIdMode(includeId) {
138
+ if (includeId === true)
139
+ return "all";
140
+ if (includeId === false)
141
+ return "none";
142
+ return "collections";
143
+ }
144
+ function shouldIncludeObjectId(mode, isCollectionItem) {
145
+ if (mode === "all")
146
+ return true;
147
+ if (mode === "collections")
148
+ return isCollectionItem;
149
+ return false;
150
+ }
151
+ function buildSearchParams(query) {
152
+ const params = new URLSearchParams();
153
+ if (!query)
154
+ return params;
155
+ for (const [key, rawValue] of Object.entries(query)) {
156
+ if (rawValue === undefined || rawValue === null)
157
+ continue;
158
+ if (Array.isArray(rawValue)) {
159
+ rawValue.forEach((value) => {
160
+ if (value === undefined || value === null)
161
+ return;
162
+ params.append(key, String(value));
163
+ });
164
+ continue;
165
+ }
166
+ params.set(key, String(rawValue));
167
+ }
168
+ return params;
169
+ }
170
+ function ensureCollectionEnvelope(data, path) {
171
+ if (Array.isArray(data)) {
172
+ return { items: data, total: data.length };
173
+ }
174
+ if (data && typeof data === "object" && Array.isArray(data.items)) {
175
+ return {
176
+ items: data.items,
177
+ total: Number(data.total ?? data.items.length ?? 0),
178
+ };
179
+ }
180
+ throw new Error(`${COLLECTION_SHAPE_ERROR} Path: '${path}'.`);
181
+ }
182
+ function extractId(value) {
183
+ if (typeof value === "string" && value.length > 0)
184
+ return value;
185
+ if (value && typeof value === "object" && typeof value.id === "string") {
186
+ return value.id;
187
+ }
188
+ return null;
189
+ }
190
+ function capitalize(input) {
191
+ return input ? input[0].toUpperCase() + input.slice(1) : input;
192
+ }
193
+ function lowerFirst(input) {
194
+ return input ? input[0].toLowerCase() + input.slice(1) : input;
195
+ }
196
+ function camelCaseModelIdKey(modelName) {
197
+ return `${lowerFirst(modelName)}Id`;
198
+ }
199
+ function snakeCaseModelIdKey(modelName) {
200
+ const snake = modelName
201
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
202
+ .replace(/\s+/g, "_")
203
+ .toLowerCase();
204
+ return `${snake}_id`;
205
+ }
206
+ function extractModelRefId(raw, modelName, options) {
207
+ if (typeof raw === "string")
208
+ return raw;
209
+ if (!raw || typeof raw !== "object")
210
+ return null;
211
+ const object = raw;
212
+ const prop = options?.propertyName ?? "";
213
+ const candidates = [
214
+ camelCaseModelIdKey(modelName),
215
+ snakeCaseModelIdKey(modelName),
216
+ prop ? `${prop}Id` : "",
217
+ prop
218
+ ? `${prop.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase()}_id`
219
+ : "",
220
+ "value",
221
+ ].filter(Boolean);
222
+ for (const key of candidates) {
223
+ const found = extractId(object[key]);
224
+ if (found)
225
+ return found;
226
+ }
227
+ const byId = extractId(object);
228
+ if (byId)
229
+ return byId;
230
+ return null;
231
+ }
232
+ function formatValidationError(name, error) {
233
+ const payload = error && typeof error === "object" && "format" in error
234
+ ? error.format()
235
+ : error;
236
+ return `Invalid data received for '${name}': ${JSON.stringify(payload)}`;
237
+ }
238
+ function levenshtein(a, b) {
239
+ if (a === b)
240
+ return 0;
241
+ if (!a.length)
242
+ return b.length;
243
+ if (!b.length)
244
+ return a.length;
245
+ const rows = a.length + 1;
246
+ const cols = b.length + 1;
247
+ const matrix = Array.from({ length: rows }, () => new Array(cols).fill(0));
248
+ for (let i = 0; i < rows; i++)
249
+ matrix[i][0] = i;
250
+ for (let j = 0; j < cols; j++)
251
+ matrix[0][j] = j;
252
+ for (let i = 1; i < rows; i++) {
253
+ for (let j = 1; j < cols; j++) {
254
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
255
+ matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost);
256
+ }
257
+ }
258
+ return matrix[rows - 1][cols - 1];
259
+ }
260
+ function unknownKeyError(key, roots, models) {
261
+ const candidates = [...roots, ...models];
262
+ const normalized = key.toLowerCase();
263
+ const suggestions = candidates
264
+ .map((candidate) => ({
265
+ candidate,
266
+ distance: levenshtein(normalized, candidate.toLowerCase()),
267
+ }))
268
+ .sort((a, b) => a.distance - b.distance)
269
+ .slice(0, 3)
270
+ .map((entry) => entry.candidate);
271
+ const suggestionText = suggestions.length
272
+ ? ` Did you mean: ${suggestions.join(", ")}?`
273
+ : "";
274
+ const rootsText = `Available roots: [${roots.join(", ")}]`;
275
+ const modelsText = models.length
276
+ ? `, models (under data.models.*): [${models.join(", ")}]`
277
+ : "";
278
+ throw new Error(`Unknown schema key '${key}'. ${rootsText}${modelsText}.${suggestionText}`);
279
+ }
280
+ async function normalizeModelRef(modelName, id, context, trail, isCollectionItem) {
281
+ if (!id)
282
+ return null;
283
+ if (!context.options.resolveModelRefs)
284
+ return id;
285
+ const nodeKey = `${modelName}:${id}`;
286
+ if (trail.has(nodeKey)) {
287
+ return shouldIncludeObjectId(context.options.includeIdMode, isCollectionItem)
288
+ ? { id }
289
+ : id;
290
+ }
291
+ const modelDescriptor = context.modelDescriptors.get(modelName);
292
+ if (!modelDescriptor) {
293
+ return id;
294
+ }
295
+ const cached = context.modelCache.get(nodeKey);
296
+ if (cached) {
297
+ return cached;
298
+ }
299
+ const nextTrail = new Set(trail);
300
+ nextTrail.add(nodeKey);
301
+ const promise = (async () => {
302
+ const rawModel = await context.requestJson(`models/${modelName}/${id}`, {
303
+ query: {
304
+ raw: 1,
305
+ ...(context.options.locale ? { locale: context.options.locale } : {}),
306
+ },
307
+ });
308
+ return normalizeField(modelDescriptor, `models/${modelName}/${encodeURIComponent(id)}`, rawModel, context, nextTrail, isCollectionItem);
309
+ })().catch((error) => {
310
+ context.modelCache.delete(nodeKey);
311
+ throw error;
312
+ });
313
+ context.modelCache.set(nodeKey, promise);
314
+ return promise;
315
+ }
316
+ async function normalizeObjectField(descriptor, path, raw, context, trail, isCollectionItem) {
317
+ const source = raw && typeof raw === "object" ? raw : {};
318
+ const output = {};
319
+ for (const [propertyName, propertyDescriptor] of Object.entries(descriptor.properties)) {
320
+ if (isPrimitiveDescriptor(propertyDescriptor)) {
321
+ output[propertyName] = coerceCustomTypeValue(propertyDescriptor, source[propertyName], {
322
+ locale: context.options.locale,
323
+ defaultLocale: context.options.defaultLocale,
324
+ });
325
+ continue;
326
+ }
327
+ if (isModelRefDescriptor(propertyDescriptor)) {
328
+ const refId = extractModelRefId(source, propertyDescriptor.model, {
329
+ propertyName,
330
+ });
331
+ output[propertyName] = await normalizeModelRef(propertyDescriptor.model, refId, context, trail, false);
332
+ continue;
333
+ }
334
+ if (isArrayDescriptor(propertyDescriptor)) {
335
+ const childPath = `${path}/${propertyName}`;
336
+ const childRaw = await context.requestJson(childPath, {
337
+ query: {
338
+ raw: 1,
339
+ ...(context.options.locale ? { locale: context.options.locale } : {}),
340
+ },
341
+ });
342
+ const normalizedChild = await normalizeArrayField(propertyDescriptor, childPath, childRaw, context, trail);
343
+ output[propertyName] = coerceCustomTypeValue(propertyDescriptor, normalizedChild, {
344
+ locale: context.options.locale,
345
+ defaultLocale: context.options.defaultLocale,
346
+ });
347
+ continue;
348
+ }
349
+ if (isObjectDescriptor(propertyDescriptor)) {
350
+ const childPath = `${path}/${propertyName}`;
351
+ const childRaw = await context.requestJson(childPath, {
352
+ query: {
353
+ raw: 1,
354
+ ...(context.options.locale ? { locale: context.options.locale } : {}),
355
+ },
356
+ });
357
+ const normalizedChild = await normalizeObjectField(propertyDescriptor, childPath, childRaw, context, trail, false);
358
+ output[propertyName] = coerceCustomTypeValue(propertyDescriptor, normalizedChild, {
359
+ locale: context.options.locale,
360
+ defaultLocale: context.options.defaultLocale,
361
+ });
362
+ }
363
+ }
364
+ if (shouldIncludeObjectId(context.options.includeIdMode, isCollectionItem)) {
365
+ const rowId = extractId(source);
366
+ if (rowId)
367
+ output.id = rowId;
368
+ }
369
+ return output;
370
+ }
371
+ async function normalizeArrayField(descriptor, path, raw, context, trail) {
372
+ const envelope = ensureCollectionEnvelope(raw, path);
373
+ const itemDescriptor = descriptor.items;
374
+ if (isPrimitiveDescriptor(itemDescriptor)) {
375
+ return envelope.items.map((row) => {
376
+ const value = row && typeof row === "object" && "value" in row
377
+ ? row.value
378
+ : row;
379
+ if (context.options.includeIdMode !== "all") {
380
+ return value;
15
381
  }
16
- return async () => {
17
- const url = `${baseUrl}/${prop}`;
18
- const res = await fetch(url, {
19
- method: "GET",
20
- headers: {
21
- "Content-Type": "application/json",
22
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
23
- },
24
- });
25
- if (!res.ok) {
26
- throw new Error(`Request failed for '${prop}' with status ${res.status}: ${res.statusText}`);
27
- }
28
- const data = await res.json();
29
- // Validate via Zod
30
- const { zodSchemas } = Shared.buildZodSchemasFromDescriptor(schemaDescriptor);
31
- const schema = zodSchemas[prop];
32
- if (!schema) {
33
- // If no schema found, return the raw data
34
- return data;
35
- }
36
- const result = schema.safeParse(data);
37
- if (!result.success) {
38
- throw new Error(`Invalid data received for '${prop}': ${JSON.stringify(result.error.format())}`);
39
- }
40
- return result.data;
382
+ const id = extractId(row);
383
+ return id ? { id, value } : value;
384
+ });
385
+ }
386
+ if (isModelRefDescriptor(itemDescriptor)) {
387
+ const resolved = await Promise.all(envelope.items.map(async (row) => {
388
+ const refId = extractModelRefId(row, itemDescriptor.model);
389
+ return normalizeModelRef(itemDescriptor.model, refId, context, trail, true);
390
+ }));
391
+ return resolved;
392
+ }
393
+ if (isObjectDescriptor(itemDescriptor)) {
394
+ return Promise.all(envelope.items.map(async (row) => {
395
+ const rowId = extractId(row);
396
+ const rowPath = rowId
397
+ ? `${path}/${encodeURIComponent(rowId)}`
398
+ : path;
399
+ return normalizeObjectField(itemDescriptor, rowPath, row, context, trail, true);
400
+ }));
401
+ }
402
+ return envelope.items;
403
+ }
404
+ async function normalizeField(descriptor, path, raw, context, trail, isCollectionItem) {
405
+ if (isPrimitiveDescriptor(descriptor)) {
406
+ const value = raw && typeof raw === "object" && "value" in raw
407
+ ? raw.value
408
+ : raw;
409
+ return coerceCustomTypeValue(descriptor, value, {
410
+ locale: context.options.locale,
411
+ defaultLocale: context.options.defaultLocale,
412
+ });
413
+ }
414
+ if (isModelRefDescriptor(descriptor)) {
415
+ const refId = extractModelRefId(raw, descriptor.model);
416
+ return normalizeModelRef(descriptor.model, refId, context, trail, isCollectionItem);
417
+ }
418
+ if (isArrayDescriptor(descriptor)) {
419
+ const normalized = await normalizeArrayField(descriptor, path, raw, context, trail);
420
+ return coerceCustomTypeValue(descriptor, normalized, {
421
+ locale: context.options.locale,
422
+ defaultLocale: context.options.defaultLocale,
423
+ });
424
+ }
425
+ if (isObjectDescriptor(descriptor)) {
426
+ const normalized = await normalizeObjectField(descriptor, path, raw, context, trail, isCollectionItem);
427
+ return coerceCustomTypeValue(descriptor, normalized, {
428
+ locale: context.options.locale,
429
+ defaultLocale: context.options.defaultLocale,
430
+ });
431
+ }
432
+ return raw;
433
+ }
434
+ function createResourceRegistry(descriptor) {
435
+ const roots = new Map();
436
+ const rootsCaseInsensitive = new Map();
437
+ for (const [key, rootDescriptor] of Object.entries(descriptor.roots ?? {})) {
438
+ const entry = {
439
+ kind: "root",
440
+ key,
441
+ path: key,
442
+ descriptor: rootDescriptor,
443
+ isCollection: isArrayDescriptor(rootDescriptor),
444
+ };
445
+ roots.set(key, entry);
446
+ rootsCaseInsensitive.set(key.toLowerCase(), entry);
447
+ }
448
+ const models = new Map();
449
+ const modelsCaseInsensitive = new Map();
450
+ for (const modelName of Object.keys(descriptor.models ?? {})) {
451
+ const entry = {
452
+ kind: "model",
453
+ key: modelName,
454
+ path: `models/${modelName}`,
455
+ descriptor: asModelObjectDescriptor(modelName, descriptor),
456
+ isCollection: true,
457
+ modelName,
458
+ };
459
+ models.set(modelName, entry);
460
+ modelsCaseInsensitive.set(modelName.toLowerCase(), entry);
461
+ }
462
+ return {
463
+ roots,
464
+ rootsCaseInsensitive,
465
+ models,
466
+ modelsCaseInsensitive,
467
+ };
468
+ }
469
+ async function requestJson(baseUrl, apiKey, path, options) {
470
+ const params = buildSearchParams(options?.query);
471
+ const url = `${baseUrl}/${path}${params.toString() ? `?${params.toString()}` : ""}`;
472
+ const response = await fetch(url, {
473
+ method: "GET",
474
+ signal: options?.signal,
475
+ headers: {
476
+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
477
+ },
478
+ });
479
+ if (!response.ok) {
480
+ throw new Error(`Request failed for '${path}' with status ${response.status}: ${response.statusText}`);
481
+ }
482
+ return response.json();
483
+ }
484
+ function validateResult(resource, result, descriptor, includeIdMode, zodSchemas, modelZodSchemas) {
485
+ if (includeIdMode === "all")
486
+ return;
487
+ if (resource.kind === "root") {
488
+ const schema = zodSchemas[resource.key];
489
+ if (!schema)
490
+ return;
491
+ const parsed = schema.safeParse(result);
492
+ if (!parsed.success) {
493
+ throw new Error(formatValidationError(resource.key, parsed.error));
494
+ }
495
+ return;
496
+ }
497
+ const modelName = resource.modelName;
498
+ if (!modelName)
499
+ return;
500
+ const modelSchema = modelZodSchemas[modelName];
501
+ if (!modelSchema)
502
+ return;
503
+ if (Array.isArray(result)) {
504
+ const parsed = modelSchema.array().safeParse(result);
505
+ if (!parsed.success) {
506
+ throw new Error(formatValidationError(modelName, parsed.error));
507
+ }
508
+ return;
509
+ }
510
+ if (result === null || result === undefined)
511
+ return;
512
+ const parsed = modelSchema.safeParse(result);
513
+ if (!parsed.success) {
514
+ throw new Error(formatValidationError(modelName, parsed.error));
515
+ }
516
+ }
517
+ async function runResource(resource, descriptor, baseUrl, apiKey, defaultLocale, zodSchemas, modelZodSchemas, options, byId) {
518
+ const responseMode = options?.response ?? "normalized";
519
+ const includeIdMode = resolveIncludeIdMode(options?.includeId);
520
+ const resolveModelRefs = options?.resolveModelRefs !== false;
521
+ const locale = options?.locale ??
522
+ (typeof options?.query?.locale === "string"
523
+ ? options.query.locale
524
+ : defaultLocale);
525
+ const query = {
526
+ ...(options?.query ?? {}),
527
+ };
528
+ const shouldNormalize = responseMode !== "raw";
529
+ if (shouldNormalize && query.raw === undefined) {
530
+ query.raw = 1;
531
+ }
532
+ if (locale && query.locale === undefined) {
533
+ query.locale = locale;
534
+ }
535
+ const resourcePath = byId
536
+ ? `${resource.path}/${encodeURIComponent(byId)}`
537
+ : resource.path;
538
+ const rawData = await requestJson(baseUrl, apiKey, resourcePath, {
539
+ query,
540
+ signal: options?.signal,
541
+ });
542
+ if (!shouldNormalize) {
543
+ return rawData;
544
+ }
545
+ const modelDescriptors = new Map();
546
+ for (const modelName of Object.keys(descriptor.models ?? {})) {
547
+ modelDescriptors.set(modelName, asModelObjectDescriptor(modelName, descriptor));
548
+ }
549
+ const context = {
550
+ requestJson: (path, requestOptions) => requestJson(baseUrl, apiKey, path, {
551
+ ...requestOptions,
552
+ signal: options?.signal,
553
+ }),
554
+ modelDescriptors,
555
+ modelCache: new Map(),
556
+ options: {
557
+ includeIdMode,
558
+ resolveModelRefs,
559
+ locale,
560
+ defaultLocale,
561
+ },
562
+ };
563
+ if (resource.isCollection && !byId) {
564
+ const envelope = ensureCollectionEnvelope(rawData, resource.path);
565
+ const descriptorForCollection = resource.kind === "root" && isArrayDescriptor(resource.descriptor)
566
+ ? resource.descriptor
567
+ : {
568
+ type: "array",
569
+ items: resource.descriptor,
570
+ optional: false,
571
+ nullable: false,
572
+ };
573
+ const normalizedItems = await normalizeArrayField(descriptorForCollection, resource.path, envelope, context, new Set());
574
+ if (responseMode === "envelope") {
575
+ validateResult(resource, normalizedItems, descriptor, includeIdMode, zodSchemas, modelZodSchemas);
576
+ return {
577
+ items: normalizedItems,
578
+ total: envelope.total,
41
579
  };
580
+ }
581
+ validateResult(resource, normalizedItems, descriptor, includeIdMode, zodSchemas, modelZodSchemas);
582
+ return normalizedItems;
583
+ }
584
+ const normalized = await normalizeField(resource.descriptor, resourcePath, rawData, context, new Set(), false);
585
+ validateResult(resource, normalized, descriptor, includeIdMode, zodSchemas, modelZodSchemas);
586
+ return normalized;
587
+ }
588
+ export function createCmsClient(descriptor, config) {
589
+ const baseUrl = normalizeBaseUrl(config.apiConfig?.baseUrl);
590
+ const apiKey = config.apiConfig?.key;
591
+ const registry = createResourceRegistry(descriptor);
592
+ const rootKeys = Array.from(registry.roots.keys());
593
+ const modelKeys = Array.from(registry.models.keys());
594
+ const { zodSchemas, modelZodSchemas } = buildZodSchemasFromDescriptor(descriptor);
595
+ const buildModelAccessor = (entry) => {
596
+ const accessor = (async (options) => runResource(entry, descriptor, baseUrl, apiKey, config.defaultLocale, zodSchemas, modelZodSchemas, options));
597
+ accessor.byId = async (id, options) => runResource(entry, descriptor, baseUrl, apiKey, config.defaultLocale, zodSchemas, modelZodSchemas, options, id);
598
+ return accessor;
599
+ };
600
+ const modelsProxy = new Proxy({}, {
601
+ get(_target, property) {
602
+ if (typeof property !== "string")
603
+ return undefined;
604
+ if (property === "then")
605
+ return undefined;
606
+ const modelEntry = registry.models.get(property) ??
607
+ registry.modelsCaseInsensitive.get(property.toLowerCase());
608
+ if (!modelEntry) {
609
+ unknownKeyError(property, [], modelKeys);
610
+ }
611
+ return buildModelAccessor(modelEntry);
42
612
  },
43
613
  });
614
+ const rootProxy = new Proxy({}, {
615
+ get(_target, property) {
616
+ if (typeof property !== "string")
617
+ return undefined;
618
+ if (property === "then")
619
+ return undefined;
620
+ if (property === "models")
621
+ return modelsProxy;
622
+ const entry = registry.roots.get(property) ??
623
+ registry.rootsCaseInsensitive.get(property.toLowerCase());
624
+ if (!entry) {
625
+ unknownKeyError(property, rootKeys, []);
626
+ }
627
+ return async (options) => runResource(entry, descriptor, baseUrl, apiKey, config.defaultLocale, zodSchemas, modelZodSchemas, options);
628
+ },
629
+ });
630
+ return rootProxy;
631
+ }
632
+ /**
633
+ * Initializes the CMS SDK for a given schema.
634
+ * @param config configuration including API base URL and API key.
635
+ * @returns typed accessors for root resources and model resources.
636
+ */
637
+ export function cms0(config) {
638
+ return createCmsClient(schemaDescriptor, config);
44
639
  }