@tinacms/schema-tools 0.0.0-20220629020212

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/index.js ADDED
@@ -0,0 +1,718 @@
1
+ (function(global, factory) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("yup"), require("zod")) : typeof define === "function" && define.amd ? define(["exports", "yup", "zod"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["@tinacms/schema-tools"] = {}, global.NOOP, global.NOOP));
3
+ })(this, function(exports2, yup, z) {
4
+ "use strict";
5
+ function _interopDefaultLegacy(e) {
6
+ return e && typeof e === "object" && "default" in e ? e : { "default": e };
7
+ }
8
+ function _interopNamespace(e) {
9
+ if (e && e.__esModule)
10
+ return e;
11
+ var n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
12
+ if (e) {
13
+ Object.keys(e).forEach(function(k) {
14
+ if (k !== "default") {
15
+ var d = Object.getOwnPropertyDescriptor(e, k);
16
+ Object.defineProperty(n, k, d.get ? d : {
17
+ enumerable: true,
18
+ get: function() {
19
+ return e[k];
20
+ }
21
+ });
22
+ }
23
+ });
24
+ }
25
+ n["default"] = e;
26
+ return Object.freeze(n);
27
+ }
28
+ var yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
29
+ var z__default = /* @__PURE__ */ _interopDefaultLegacy(z);
30
+ function addNamespaceToSchema(maybeNode, namespace = []) {
31
+ if (typeof maybeNode === "string") {
32
+ return maybeNode;
33
+ }
34
+ if (typeof maybeNode === "boolean") {
35
+ return maybeNode;
36
+ }
37
+ const newNode = maybeNode;
38
+ const keys = Object.keys(maybeNode);
39
+ Object.values(maybeNode).map((m, index) => {
40
+ const key = keys[index];
41
+ if (Array.isArray(m)) {
42
+ newNode[key] = m.map((element) => {
43
+ if (!element) {
44
+ return;
45
+ }
46
+ if (!element.hasOwnProperty("name")) {
47
+ return element;
48
+ }
49
+ const value = element.name || element.value;
50
+ return addNamespaceToSchema(element, [...namespace, value]);
51
+ });
52
+ } else {
53
+ if (!m) {
54
+ return;
55
+ }
56
+ if (!m.hasOwnProperty("name")) {
57
+ newNode[key] = m;
58
+ } else {
59
+ newNode[key] = addNamespaceToSchema(m, [...namespace, m.name]);
60
+ }
61
+ }
62
+ });
63
+ return { ...newNode, namespace };
64
+ }
65
+ function assertShape(value, yupSchema, errorMessage) {
66
+ const shape = yupSchema(yup__namespace);
67
+ try {
68
+ shape.validateSync(value);
69
+ } catch (e) {
70
+ const message = errorMessage || `Failed to assertShape - ${e.message}`;
71
+ throw new Error(message);
72
+ }
73
+ }
74
+ const lastItem = (arr) => {
75
+ if (typeof arr === "undefined") {
76
+ throw new Error("Can not call lastItem when arr is undefined");
77
+ }
78
+ return arr[arr.length - 1];
79
+ };
80
+ const capitalize = (s) => {
81
+ if (typeof s !== "string")
82
+ return "";
83
+ return s.charAt(0).toUpperCase() + s.slice(1);
84
+ };
85
+ const generateNamespacedFieldName = (names, suffix = "") => {
86
+ return (suffix ? [...names, suffix] : names).map(capitalize).join("");
87
+ };
88
+ const NAMER = {
89
+ dataFilterTypeNameOn: (namespace) => {
90
+ return generateNamespacedFieldName(namespace, "_FilterOn");
91
+ },
92
+ dataFilterTypeName: (namespace) => {
93
+ return generateNamespacedFieldName(namespace, "Filter");
94
+ },
95
+ dataMutationTypeNameOn: (namespace) => {
96
+ return generateNamespacedFieldName(namespace, "_MutationOn");
97
+ },
98
+ dataMutationTypeName: (namespace) => {
99
+ return generateNamespacedFieldName(namespace, "Mutation");
100
+ },
101
+ updateName: (namespace) => {
102
+ return "update" + generateNamespacedFieldName(namespace, "Document");
103
+ },
104
+ createName: (namespace) => {
105
+ return "create" + generateNamespacedFieldName(namespace, "Document");
106
+ },
107
+ queryName: (namespace) => {
108
+ return "get" + generateNamespacedFieldName(namespace, "Document");
109
+ },
110
+ generateQueryListName: (namespace) => {
111
+ return "get" + generateNamespacedFieldName(namespace, "List");
112
+ },
113
+ fragmentName: (namespace) => {
114
+ return generateNamespacedFieldName(namespace, "") + "Parts";
115
+ },
116
+ collectionTypeName: (namespace) => {
117
+ return generateNamespacedFieldName(namespace, "Collection");
118
+ },
119
+ documentTypeName: (namespace) => {
120
+ return generateNamespacedFieldName(namespace, "Document");
121
+ },
122
+ dataTypeName: (namespace) => {
123
+ return generateNamespacedFieldName(namespace, "");
124
+ },
125
+ referenceConnectionType: (namespace) => {
126
+ return generateNamespacedFieldName(namespace, "Connection");
127
+ },
128
+ referenceConnectionEdgesTypeName: (namespace) => {
129
+ return generateNamespacedFieldName(namespace, "ConnectionEdges");
130
+ }
131
+ };
132
+ function hasDuplicates(array) {
133
+ if (!array) {
134
+ return false;
135
+ } else {
136
+ return new Set(array).size !== array.length;
137
+ }
138
+ }
139
+ class TinaSchema {
140
+ constructor(config) {
141
+ this.config = config;
142
+ this.getIsTitleFieldName = (collection) => {
143
+ const col = this.getCollection(collection);
144
+ const field = col == null ? void 0 : col.fields.find((x) => x.type === "string" && x.isTitle);
145
+ return field == null ? void 0 : field.name;
146
+ };
147
+ this.getCollectionsByName = (collectionNames) => {
148
+ return this.schema.collections.filter((collection) => collectionNames.includes(collection.name));
149
+ };
150
+ this.getAllCollectionPaths = () => {
151
+ const paths = this.getCollections().map((collection) => `${collection.path}${collection.match || ""}`);
152
+ return paths;
153
+ };
154
+ this.getCollection = (collectionName) => {
155
+ const collection = this.schema.collections.find((collection2) => collection2.name === collectionName);
156
+ if (!collection) {
157
+ throw new Error(`Expected to find collection named ${collectionName}`);
158
+ }
159
+ const extraFields = {};
160
+ const templateInfo = this.getTemplatesForCollectable(collection);
161
+ switch (templateInfo.type) {
162
+ case "object":
163
+ extraFields["fields"] = templateInfo.template.fields;
164
+ break;
165
+ case "union":
166
+ extraFields["templates"] = templateInfo.templates;
167
+ break;
168
+ }
169
+ return {
170
+ slug: collection.name,
171
+ ...extraFields,
172
+ ...collection,
173
+ format: collection.format || "md"
174
+ };
175
+ };
176
+ this.getCollections = () => {
177
+ return this.schema.collections.map((collection) => this.getCollection(collection.name)) || [];
178
+ };
179
+ this.getGlobalTemplate = (templateName) => {
180
+ var _a;
181
+ const globalTemplate = (_a = this.schema.templates) == null ? void 0 : _a.find((template) => template.name === templateName);
182
+ if (!globalTemplate) {
183
+ throw new Error(`Expected to find global template of name ${templateName}`);
184
+ }
185
+ return globalTemplate;
186
+ };
187
+ this.getCollectionByFullPath = (filepath) => {
188
+ const collection = this.getCollections().find((collection2) => {
189
+ return filepath.replace("\\", "/").startsWith(collection2.path);
190
+ });
191
+ if (!collection) {
192
+ throw new Error(`Unable to find collection for file at ${filepath}`);
193
+ }
194
+ return collection;
195
+ };
196
+ this.getCollectionAndTemplateByFullPath = (filepath, templateName) => {
197
+ let template;
198
+ const collection = this.getCollections().find((collection2) => {
199
+ return filepath.replace("\\", "/").startsWith(collection2.path);
200
+ });
201
+ if (!collection) {
202
+ throw new Error(`Unable to find collection for file at ${filepath}`);
203
+ }
204
+ const templates = this.getTemplatesForCollectable(collection);
205
+ if (templates.type === "union") {
206
+ if (templateName) {
207
+ template = templates.templates.find((template2) => lastItem(template2.namespace) === templateName);
208
+ if (!template) {
209
+ throw new Error(`Unable to determine template for item at ${filepath}`);
210
+ }
211
+ } else {
212
+ throw new Error(`Unable to determine template for item at ${filepath}, no template name provided for collection with multiple templates`);
213
+ }
214
+ }
215
+ if (templates.type === "object") {
216
+ template = templates.template;
217
+ }
218
+ if (!template) {
219
+ throw new Error(`Something went wrong while trying to determine template for ${filepath}`);
220
+ }
221
+ return { collection, template };
222
+ };
223
+ this.getTemplateForData = ({
224
+ data,
225
+ collection
226
+ }) => {
227
+ const templateInfo = this.getTemplatesForCollectable(collection);
228
+ switch (templateInfo.type) {
229
+ case "object":
230
+ return templateInfo.template;
231
+ case "union":
232
+ assertShape(data, (yup2) => yup2.object({ _template: yup2.string().required() }));
233
+ const template = templateInfo.templates.find((template2) => template2.namespace[template2.namespace.length - 1] === data._template);
234
+ if (!template) {
235
+ throw new Error(`Expected to find template named '${data._template}' for collection '${lastItem(collection.namespace)}'`);
236
+ }
237
+ return template;
238
+ }
239
+ };
240
+ this.isMarkdownCollection = (collectionName) => {
241
+ const collection = this.getCollection(collectionName);
242
+ const format = collection.format;
243
+ if (!format) {
244
+ return true;
245
+ }
246
+ if (["markdown", "md"].includes(format)) {
247
+ return true;
248
+ }
249
+ return false;
250
+ };
251
+ this.getTemplatesForCollectable = (collection) => {
252
+ let extraFields = [];
253
+ if (collection.references) {
254
+ extraFields = collection.references;
255
+ }
256
+ if (collection.fields) {
257
+ const template = typeof collection.fields === "string" ? this.getGlobalTemplate(collection.fields) : collection;
258
+ if (typeof template.fields === "string" || typeof template.fields === "undefined") {
259
+ throw new Error("Exptected template to have fields but none were found");
260
+ }
261
+ return {
262
+ namespace: collection.namespace,
263
+ type: "object",
264
+ template: {
265
+ ...template,
266
+ fields: [...template.fields, ...extraFields]
267
+ }
268
+ };
269
+ } else {
270
+ if (collection.templates) {
271
+ return {
272
+ namespace: collection.namespace,
273
+ type: "union",
274
+ templates: collection.templates.map((templateOrTemplateString) => {
275
+ const template = typeof templateOrTemplateString === "string" ? this.getGlobalTemplate(templateOrTemplateString) : templateOrTemplateString;
276
+ return {
277
+ ...template,
278
+ fields: [...template.fields, ...extraFields]
279
+ };
280
+ })
281
+ };
282
+ } else {
283
+ throw new Error(`Expected either fields or templates array to be defined on collection ${collection.namespace.join("_")}`);
284
+ }
285
+ }
286
+ };
287
+ this.schema = config;
288
+ }
289
+ }
290
+ const resolveField = ({ namespace, ...field }, schema) => {
291
+ var _a;
292
+ field.parentTypename = NAMER.dataTypeName(namespace.filter((_, i) => i < namespace.length - 1));
293
+ const extraFields = field.ui || {};
294
+ switch (field.type) {
295
+ case "number":
296
+ return {
297
+ component: "number",
298
+ ...field,
299
+ ...extraFields
300
+ };
301
+ case "datetime":
302
+ return {
303
+ component: "date",
304
+ ...field,
305
+ ...extraFields
306
+ };
307
+ case "boolean":
308
+ return {
309
+ component: "toggle",
310
+ ...field,
311
+ ...extraFields
312
+ };
313
+ case "image":
314
+ return {
315
+ component: "image",
316
+ clearable: true,
317
+ ...field,
318
+ ...extraFields
319
+ };
320
+ case "string":
321
+ if (field.options) {
322
+ if (field.list) {
323
+ return {
324
+ component: "checkbox-group",
325
+ ...field,
326
+ ...extraFields,
327
+ options: field.options
328
+ };
329
+ }
330
+ return {
331
+ component: "select",
332
+ ...field,
333
+ ...extraFields,
334
+ options: [{ label: `Choose an option`, value: "" }, ...field.options]
335
+ };
336
+ }
337
+ if (field.list) {
338
+ return {
339
+ component: "list",
340
+ field: {
341
+ component: "text"
342
+ },
343
+ ...field,
344
+ ...extraFields
345
+ };
346
+ }
347
+ return {
348
+ component: "text",
349
+ ...field,
350
+ ...extraFields
351
+ };
352
+ case "object":
353
+ const templateInfo = schema.getTemplatesForCollectable({
354
+ ...field,
355
+ namespace
356
+ });
357
+ if (templateInfo.type === "object") {
358
+ return {
359
+ ...field,
360
+ component: field.list ? "group-list" : "group",
361
+ fields: templateInfo.template.fields.map((field2) => resolveField(field2, schema)),
362
+ ...extraFields
363
+ };
364
+ } else if (templateInfo.type === "union") {
365
+ const templates2 = {};
366
+ const typeMap2 = {};
367
+ templateInfo.templates.forEach((template) => {
368
+ const extraFields2 = template.ui || {};
369
+ const templateName = lastItem(template.namespace);
370
+ typeMap2[templateName] = NAMER.dataTypeName(template.namespace);
371
+ templates2[lastItem(template.namespace)] = {
372
+ label: template.label || templateName,
373
+ key: templateName,
374
+ fields: template.fields.map((field2) => resolveField(field2, schema)),
375
+ ...extraFields2
376
+ };
377
+ return true;
378
+ });
379
+ return {
380
+ ...field,
381
+ typeMap: typeMap2,
382
+ component: field.list ? "blocks" : "not-implemented",
383
+ templates: templates2,
384
+ ...extraFields
385
+ };
386
+ } else {
387
+ throw new Error(`Unknown object for resolveField function`);
388
+ }
389
+ case "rich-text":
390
+ const templates = {};
391
+ (_a = field.templates) == null ? void 0 : _a.forEach((template) => {
392
+ if (typeof template === "string") {
393
+ throw new Error(`Global templates not yet supported for rich-text`);
394
+ } else {
395
+ const extraFields2 = template.ui || {};
396
+ const templateName = lastItem(template.namespace);
397
+ NAMER.dataTypeName(template.namespace);
398
+ templates[lastItem(template.namespace)] = {
399
+ label: template.label || templateName,
400
+ key: templateName,
401
+ inline: template.inline,
402
+ name: templateName,
403
+ fields: template.fields.map((field2) => resolveField(field2, schema)),
404
+ ...extraFields2
405
+ };
406
+ return true;
407
+ }
408
+ });
409
+ return {
410
+ ...field,
411
+ templates: Object.values(templates),
412
+ component: "rich-text",
413
+ ...extraFields
414
+ };
415
+ case "reference":
416
+ return {
417
+ ...field,
418
+ component: "reference",
419
+ ...extraFields
420
+ };
421
+ default:
422
+ throw new Error(`Unknown field type ${field.type}`);
423
+ }
424
+ };
425
+ const resolveForm = ({
426
+ collection,
427
+ basename,
428
+ template,
429
+ schema
430
+ }) => {
431
+ return {
432
+ id: basename,
433
+ label: collection.label,
434
+ name: basename,
435
+ fields: template.fields.map((field) => {
436
+ return resolveField(field, schema);
437
+ })
438
+ };
439
+ };
440
+ const parseZodError = ({ zodError }) => {
441
+ var _a, _b;
442
+ const errors = zodError.flatten((issue) => {
443
+ const moreInfo = [];
444
+ if (issue.code === "invalid_union") {
445
+ issue.unionErrors.map((unionError) => {
446
+ moreInfo.push(parseZodError({ zodError: unionError }));
447
+ });
448
+ }
449
+ const errorMessage = `Error ${issue == null ? void 0 : issue.message} at path ${issue.path.join(".")}`;
450
+ const errorMessages = [errorMessage, ...moreInfo];
451
+ return {
452
+ errors: errorMessages
453
+ };
454
+ });
455
+ const formErrors = errors.formErrors.flatMap((x) => x.errors);
456
+ const parsedErrors = [
457
+ ...((_b = (_a = errors.fieldErrors) == null ? void 0 : _a.collections) == null ? void 0 : _b.flatMap((x) => x.errors)) || [],
458
+ ...formErrors
459
+ ];
460
+ return parsedErrors;
461
+ };
462
+ const name = z.z.string({
463
+ required_error: "Name is required but not provided",
464
+ invalid_type_error: "Name must be a string"
465
+ });
466
+ const TypeName = [
467
+ "string",
468
+ "boolean",
469
+ "number",
470
+ "datetime",
471
+ "image",
472
+ "object",
473
+ "reference",
474
+ "rich-text"
475
+ ];
476
+ const typeTypeError = `type must be one of ${TypeName.join(", ")}`;
477
+ const typeRequiredError = `type is required and must be one of ${TypeName.join(", ")}`;
478
+ const nameProp = z.z.string({
479
+ required_error: "name must be provided",
480
+ invalid_type_error: "name must be a sting"
481
+ });
482
+ const Option = z.z.union([z.z.string(), z.z.object({ label: z.z.string(), value: z.z.string() })], {
483
+ errorMap: () => {
484
+ return {
485
+ message: "Invalid option array. Must be a string[] or {label: string, value: string}[]"
486
+ };
487
+ }
488
+ });
489
+ const TinaField = z.z.object({
490
+ name: nameProp,
491
+ label: z.z.string().optional(),
492
+ description: z.z.string().optional(),
493
+ required: z.z.boolean().optional()
494
+ });
495
+ const FieldWithList = TinaField.extend({ list: z.z.boolean().optional() });
496
+ const TinaScalerBase = FieldWithList.extend({
497
+ options: z.z.array(Option).optional()
498
+ });
499
+ const StringField = TinaScalerBase.extend({
500
+ type: z.z.literal("string", {
501
+ invalid_type_error: typeTypeError,
502
+ required_error: typeRequiredError
503
+ }),
504
+ isTitle: z.z.boolean().optional()
505
+ });
506
+ const BooleanField = TinaScalerBase.extend({
507
+ type: z.z.literal("boolean", {
508
+ invalid_type_error: typeTypeError,
509
+ required_error: typeRequiredError
510
+ })
511
+ });
512
+ const NumberField = TinaScalerBase.extend({
513
+ type: z.z.literal("number", {
514
+ invalid_type_error: typeTypeError,
515
+ required_error: typeRequiredError
516
+ })
517
+ });
518
+ const ImageField = TinaScalerBase.extend({
519
+ type: z.z.literal("image", {
520
+ invalid_type_error: typeTypeError,
521
+ required_error: typeRequiredError
522
+ })
523
+ });
524
+ const DateTimeField = TinaScalerBase.extend({
525
+ type: z.z.literal("datetime", {
526
+ invalid_type_error: typeTypeError,
527
+ required_error: typeRequiredError
528
+ }),
529
+ dateFormat: z.z.string().optional(),
530
+ timeFormat: z.z.string().optional()
531
+ });
532
+ const ReferenceField = FieldWithList.extend({
533
+ type: z.z.literal("reference", {
534
+ invalid_type_error: typeTypeError,
535
+ required_error: typeRequiredError
536
+ })
537
+ });
538
+ const TinaFieldZod = z.z.lazy(() => {
539
+ const TemplateTemp = z.z.object({
540
+ label: z.z.string(),
541
+ name: nameProp,
542
+ fields: z.z.array(TinaFieldZod)
543
+ }).refine((val) => {
544
+ var _a;
545
+ return !hasDuplicates((_a = val.fields) == null ? void 0 : _a.map((x) => x.name));
546
+ }, {
547
+ message: "Fields must have a unique name"
548
+ });
549
+ const ObjectField = FieldWithList.extend({
550
+ type: z.z.literal("object", {
551
+ invalid_type_error: typeTypeError,
552
+ required_error: typeRequiredError
553
+ }),
554
+ fields: z.z.array(TinaFieldZod).min(1).optional().refine((val) => !hasDuplicates(val == null ? void 0 : val.map((x) => x.name)), {
555
+ message: "Fields must have a unique name"
556
+ }),
557
+ templates: z.z.array(TemplateTemp).min(1).optional().refine((val) => !hasDuplicates(val == null ? void 0 : val.map((x) => x.name)), {
558
+ message: "Templates must have a unique name"
559
+ })
560
+ });
561
+ const RichTextField = FieldWithList.extend({
562
+ type: z.z.literal("rich-text", {
563
+ invalid_type_error: typeTypeError,
564
+ required_error: typeRequiredError
565
+ }),
566
+ templates: z.z.array(TemplateTemp).optional().refine((val) => !hasDuplicates(val == null ? void 0 : val.map((x) => x.name)), {
567
+ message: "Templates must have a unique name"
568
+ })
569
+ });
570
+ return z.z.discriminatedUnion("type", [
571
+ StringField,
572
+ BooleanField,
573
+ NumberField,
574
+ ImageField,
575
+ DateTimeField,
576
+ ReferenceField,
577
+ ObjectField,
578
+ RichTextField
579
+ ], {
580
+ errorMap: (issue, ctx) => {
581
+ var _a;
582
+ if (issue.code === "invalid_union_discriminator") {
583
+ return {
584
+ message: `Invalid \`type\` property. In the schema is 'type: ${(_a = ctx.data) == null ? void 0 : _a.type}' and expected one of ${TypeName.join(", ")}`
585
+ };
586
+ }
587
+ return {
588
+ message: issue.message
589
+ };
590
+ }
591
+ }).superRefine((val, ctx) => {
592
+ if (val.type === "string") {
593
+ if (val.isTitle) {
594
+ if (val.list) {
595
+ ctx.addIssue({
596
+ code: z.z.ZodIssueCode.custom,
597
+ message: "You can not have `list: true` when using `isTitle`"
598
+ });
599
+ }
600
+ if (!val.required) {
601
+ ctx.addIssue({
602
+ code: z.z.ZodIssueCode.custom,
603
+ message: "You must have { required: true } when using `isTitle`"
604
+ });
605
+ }
606
+ }
607
+ }
608
+ if (val.type === "object") {
609
+ const message = "Must provide one of templates or fields in your collection";
610
+ let isValid = Boolean(val == null ? void 0 : val.templates) || Boolean(val == null ? void 0 : val.fields);
611
+ if (!isValid) {
612
+ ctx.addIssue({
613
+ code: z.z.ZodIssueCode.custom,
614
+ message
615
+ });
616
+ return false;
617
+ } else {
618
+ isValid = !((val == null ? void 0 : val.templates) && (val == null ? void 0 : val.fields));
619
+ if (!isValid) {
620
+ ctx.addIssue({
621
+ code: z.z.ZodIssueCode.custom,
622
+ message
623
+ });
624
+ }
625
+ return isValid;
626
+ }
627
+ }
628
+ return true;
629
+ });
630
+ });
631
+ const tinaConfigKey = z__default["default"].object({
632
+ publicFolder: z__default["default"].string(),
633
+ mediaRoot: z__default["default"].string()
634
+ }).strict().optional();
635
+ const tinaConfigZod = z__default["default"].object({
636
+ media: z__default["default"].object({
637
+ tina: tinaConfigKey
638
+ }).optional()
639
+ });
640
+ const validateTinaCloudSchemaConfig = (config) => {
641
+ const newConfig = tinaConfigZod.parse(config);
642
+ return newConfig;
643
+ };
644
+ const FORMATS = ["json", "md", "markdown", "mdx"];
645
+ const Template = z.z.object({
646
+ label: z.z.string({
647
+ invalid_type_error: "label must be a string",
648
+ required_error: "label was not provided but is required"
649
+ }),
650
+ name,
651
+ fields: z.z.array(TinaFieldZod)
652
+ }).refine((val) => {
653
+ var _a;
654
+ return !hasDuplicates((_a = val.fields) == null ? void 0 : _a.map((x) => x.name));
655
+ }, {
656
+ message: "Fields must have a unique name"
657
+ });
658
+ const TinaCloudCollectionBase = z.z.object({
659
+ label: z.z.string().optional(),
660
+ name,
661
+ format: z.z.enum(FORMATS).optional()
662
+ });
663
+ const TinaCloudCollection = TinaCloudCollectionBase.extend({
664
+ fields: z.z.array(TinaFieldZod).min(1).optional().refine((val) => !hasDuplicates(val == null ? void 0 : val.map((x) => x.name)), {
665
+ message: "Fields must have a unique name"
666
+ }).refine((val) => {
667
+ const arr = (val == null ? void 0 : val.filter((x) => x.type === "string" && x.isTitle)) || [];
668
+ return arr.length < 2;
669
+ }, {
670
+ message: "Fields can only have one use of `isTitle`"
671
+ }),
672
+ templates: z.z.array(Template).min(1).optional().refine((val) => !hasDuplicates(val == null ? void 0 : val.map((x) => x.name)), {
673
+ message: "Templates must have a unique name"
674
+ })
675
+ }).refine((val) => {
676
+ let isValid = Boolean(val == null ? void 0 : val.templates) || Boolean(val == null ? void 0 : val.fields);
677
+ if (!isValid) {
678
+ return false;
679
+ } else {
680
+ isValid = !((val == null ? void 0 : val.templates) && (val == null ? void 0 : val.fields));
681
+ return isValid;
682
+ }
683
+ }, { message: "Must provide one of templates or fields in your collection" });
684
+ const TinaCloudSchemaZod = z.z.object({
685
+ collections: z.z.array(TinaCloudCollection),
686
+ config: tinaConfigZod.optional()
687
+ }).refine((val) => !hasDuplicates(val.collections.map((x) => x.name)), {
688
+ message: "can not have two collections with the same name"
689
+ });
690
+ class TinaSchemaValidationError extends Error {
691
+ constructor(message) {
692
+ super(message);
693
+ this.name = "TinaSchemaValidationError";
694
+ }
695
+ }
696
+ const validateSchema = ({
697
+ config
698
+ }) => {
699
+ try {
700
+ TinaCloudSchemaZod.parse(config);
701
+ } catch (e) {
702
+ if (e instanceof z.ZodError) {
703
+ const errors = parseZodError({ zodError: e });
704
+ throw new TinaSchemaValidationError(errors.join(", \n"));
705
+ } else {
706
+ throw new Error(e);
707
+ }
708
+ }
709
+ };
710
+ exports2.TinaSchema = TinaSchema;
711
+ exports2.TinaSchemaValidationError = TinaSchemaValidationError;
712
+ exports2.addNamespaceToSchema = addNamespaceToSchema;
713
+ exports2.resolveField = resolveField;
714
+ exports2.resolveForm = resolveForm;
715
+ exports2.validateSchema = validateSchema;
716
+ exports2.validateTinaCloudSchemaConfig = validateTinaCloudSchemaConfig;
717
+ Object.defineProperties(exports2, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
718
+ });