@sanity/schema 4.19.1-next.1 → 4.19.1-next.10

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/lib/_internal.mjs DELETED
@@ -1,2723 +0,0 @@
1
- import { SetBuilder, processSetSynchronization } from "@sanity/descriptors";
2
- import isEqual from "lodash/isEqual.js";
3
- import isObject from "lodash/isObject.js";
4
- import { OWN_PROPS_NAME, Rule, Schema } from "./_chunks-es/Rule.mjs";
5
- import { ALL_FIELDS_GROUP_NAME, DEFAULT_MAX_FIELD_DEPTH, resolveSearchConfig, resolveSearchConfigForBaseFieldPaths } from "./_chunks-es/Rule.mjs";
6
- import difference from "lodash/difference.js";
7
- import cloneDeep from "lodash/cloneDeep.js";
8
- import flatten from "lodash/flatten.js";
9
- import get from "lodash/get.js";
10
- import uniq from "lodash/uniq.js";
11
- import humanizeList from "humanize-list";
12
- import partition from "lodash/partition.js";
13
- import isPlainObject from "lodash/isPlainObject.js";
14
- import omit from "lodash/omit.js";
15
- import leven from "leven";
16
- import inspect from "object-inspect";
17
- import { createReferenceTypeNode } from "groq-js";
18
- const MAX_DEPTH_UKNOWN = 5;
19
- class DescriptorConverter {
20
- opts;
21
- cache = /* @__PURE__ */ new WeakMap();
22
- constructor(opts) {
23
- this.opts = opts;
24
- }
25
- /**
26
- * Returns a synchronization object for a schema.
27
- *
28
- * This is automatically cached in a weak map.
29
- */
30
- get(schema) {
31
- let value = this.cache.get(schema);
32
- if (value) return value;
33
- const builder = new SetBuilder();
34
- for (const name of schema.getLocalTypeNames()) {
35
- const typeDef = convertTypeDef(schema.get(name));
36
- builder.addObject("sanity.schema.namedType", { name, typeDef });
37
- }
38
- return schema.parent && builder.addSet(this.get(schema.parent)), value = builder.build("sanity.schema.registry"), this.cache.set(schema, value), value;
39
- }
40
- }
41
- function convertCommonTypeDef(schemaType, opts) {
42
- const ownProps = OWN_PROPS_NAME in schemaType ? schemaType[OWN_PROPS_NAME] : schemaType;
43
- let fields;
44
- Array.isArray(ownProps.fields) && (fields = ownProps.fields.map(
45
- ({ name, group, fieldset, type }) => ({
46
- name,
47
- typeDef: convertTypeDef(type),
48
- groups: arrayifyString(group),
49
- fieldset
50
- })
51
- ));
52
- let fieldsets;
53
- Array.isArray(ownProps.fieldsets) && (fieldsets = filterStringKey(
54
- "name",
55
- ownProps.fieldsets.map(
56
- ({ name, title, description, group, hidden, readOnly, options }) => ({
57
- name,
58
- title: maybeString(title),
59
- description: maybeString(description),
60
- group: maybeString(group),
61
- hidden: conditionalTrue(hidden),
62
- readOnly: conditionalTrue(readOnly),
63
- options: convertUnknown(options)
64
- })
65
- )
66
- ));
67
- let groups;
68
- Array.isArray(ownProps.groups) && (groups = filterStringKey(
69
- "name",
70
- ownProps.groups.map(
71
- ({ name, title, hidden, default: def, i18n }) => ({
72
- name,
73
- title: maybeString(title),
74
- hidden: conditionalTrue(hidden),
75
- default: maybeTrue(def),
76
- i18n: maybeI18n(i18n)
77
- })
78
- )
79
- ));
80
- const reason = ownProps.deprecated?.reason;
81
- let orderings;
82
- return Array.isArray(ownProps.orderings) && (orderings = ownProps.orderings.map(maybeOrdering).filter((o) => o !== void 0)), {
83
- title: maybeString(ownProps.title),
84
- description: maybeStringOrJSX(ownProps.description),
85
- readOnly: conditionalTrue(ownProps.readOnly),
86
- hidden: conditionalTrue(ownProps.hidden),
87
- liveEdit: maybeTrue(ownProps.liveEdit),
88
- options: convertUnknown(ownProps.options),
89
- initialValue: convertUnknown(ownProps.initialValue),
90
- deprecated: typeof reason == "string" ? { reason } : void 0,
91
- placeholder: maybeString(ownProps.placeholder),
92
- rows: maybeNumberAsString(ownProps.rows),
93
- fields,
94
- fieldsets,
95
- groups,
96
- validation: maybeValidations(ownProps),
97
- orderings
98
- };
99
- }
100
- function convertTypeDef(schemaType, opts) {
101
- const common2 = convertCommonTypeDef(schemaType);
102
- if (!schemaType.type)
103
- return {
104
- extends: null,
105
- jsonType: schemaType.jsonType,
106
- ...common2
107
- };
108
- switch (schemaType.type.name) {
109
- case "array":
110
- return {
111
- extends: "array",
112
- of: schemaType.of.map((ofType) => ({
113
- name: ofType.name,
114
- typeDef: convertTypeDef(ofType)
115
- })),
116
- ...common2
117
- };
118
- case "reference":
119
- case "globalDocumentReference":
120
- case "crossDatasetReference":
121
- return {
122
- extends: schemaType.type.name,
123
- to: filterStringKey(
124
- "name",
125
- schemaType.to.map((toType) => ({ name: toType.name || toType.type?.name || toType.type }))
126
- ),
127
- ...common2
128
- };
129
- default:
130
- return { extends: schemaType.type.name, ...common2 };
131
- }
132
- }
133
- function maybeString(val) {
134
- return typeof val == "string" ? val : void 0;
135
- }
136
- function maybeNumberAsString(val) {
137
- return typeof val == "number" ? val.toString() : void 0;
138
- }
139
- function maybeTrue(val) {
140
- return val === !0 ? !0 : void 0;
141
- }
142
- function conditionalTrue(val) {
143
- return typeof val == "function" ? FUNCTION_MARKER : maybeTrue(val);
144
- }
145
- function filterStringKey(key, arr) {
146
- return arr.filter((obj) => typeof obj[key] == "string");
147
- }
148
- function arrayifyString(val) {
149
- if (typeof val == "string")
150
- return [val];
151
- if (Array.isArray(val))
152
- return val.filter((elem) => typeof elem == "string");
153
- }
154
- const FUNCTION_MARKER = { __type: "function" }, UNKNOWN_MARKER = { __type: "unknown" }, UNDEFINED_MARKER = { __type: "undefined" }, CYCLIC_MARKER = { __type: "cyclic" }, MAX_DEPTH_MARKER = { __type: "maxDepth" };
155
- function convertUnknown(val, seen = /* @__PURE__ */ new Set(), maxDepth = MAX_DEPTH_UKNOWN) {
156
- if (maxDepth === 0) return MAX_DEPTH_MARKER;
157
- if (typeof val == "string" || typeof val == "boolean" || val === null || val === void 0)
158
- return val;
159
- if (typeof val == "number")
160
- return { __type: "number", value: val.toString() };
161
- if (typeof val == "function") return FUNCTION_MARKER;
162
- if (seen.has(val))
163
- return CYCLIC_MARKER;
164
- if (seen.add(val), isObject(val)) {
165
- if (Array.isArray(val))
166
- return val.map((elem) => {
167
- const res = convertUnknown(elem, seen, maxDepth - 1);
168
- return res === void 0 ? UNDEFINED_MARKER : res;
169
- });
170
- if ("$$typeof" in val && "type" in val && "props" in val) {
171
- const { type, props } = val, strType = typeof type == "function" ? type.name : type;
172
- return typeof strType != "string" ? void 0 : {
173
- __type: "jsx",
174
- type: strType,
175
- props: convertUnknown(props, seen, maxDepth - 1)
176
- };
177
- }
178
- let hasType = !1;
179
- const result = {};
180
- for (const [key, field] of Object.entries(val))
181
- key === "__type" && (hasType = !0), result[key] = convertUnknown(field, seen, maxDepth - 1);
182
- return hasType ? { __type: "object", value: result } : result;
183
- }
184
- return UNKNOWN_MARKER;
185
- }
186
- function maybeStringOrJSX(val) {
187
- if (typeof val == "string") return val;
188
- if (isObject(val) && "$$typeof" in val && "type" in val && "props" in val) {
189
- const { type, props } = val, strType = typeof type == "function" ? type.name : type;
190
- return typeof strType != "string" ? void 0 : { __type: "jsx", type: strType, props: convertUnknown(props) };
191
- }
192
- }
193
- function maybeValidations(obj) {
194
- if (!isObject(obj) || !("type" in obj)) return;
195
- const impliedRules = [];
196
- switch ("options" in obj && isObject(obj.options) && "list" in obj.options && Array.isArray(obj.options.list) && impliedRules.push({
197
- type: "enum",
198
- values: obj.options.list.map((o) => convertUnknown(extractValueFromListOption(o, obj))).filter((v) => v !== void 0)
199
- }), obj.type) {
200
- case "url":
201
- impliedRules.push({
202
- type: "uri",
203
- allowRelative: !1
204
- });
205
- break;
206
- case "slug":
207
- impliedRules.push({
208
- type: "custom"
209
- });
210
- break;
211
- case "reference":
212
- impliedRules.push({
213
- type: "reference"
214
- });
215
- break;
216
- case "email":
217
- impliedRules.push({
218
- type: "email"
219
- });
220
- break;
221
- }
222
- if (!("validation" in obj) || !obj.validation)
223
- return impliedRules.length > 0 ? [
224
- {
225
- level: "error",
226
- rules: impliedRules
227
- }
228
- ] : void 0;
229
- const validations = [], rules = Array.isArray(obj.validation) ? obj.validation : [obj.validation];
230
- for (const rule of rules) {
231
- const validation = maybeValidation(rule);
232
- if (validation === void 0)
233
- continue;
234
- const rulesToAdd = impliedRules.filter((ir) => !validation.rules.some((r) => isEqual(r, ir)));
235
- rulesToAdd.length > 0 && validation.rules.unshift(...rulesToAdd), !validations.some((v) => isEqual(v, validation)) && validations.push(validation);
236
- }
237
- return validations.length > 0 ? validations : void 0;
238
- }
239
- function hasValueField(typeDef) {
240
- return !typeDef || typeof typeDef != "object" ? !1 : "fields" in typeDef ? Array.isArray(typeDef.fields) ? typeDef.fields.some((field) => field.name === "value") : !1 : "type" in typeDef && typeDef.type ? hasValueField(typeDef.type) : !1;
241
- }
242
- function extractValueFromListOption(option, typeDef) {
243
- return typeDef.jsonType === "object" && hasValueField(typeDef) ? option : isObject(option) && "value" in option && option.value ? option.value : option;
244
- }
245
- function maybeValidation(val) {
246
- if (val) {
247
- if (isIRuleFunction(val))
248
- try {
249
- const result = val(new Rule());
250
- if (isIRule(result))
251
- return maybeValidation(result);
252
- throw new Error("failed to convert to plain rule");
253
- } catch {
254
- return {
255
- level: "error",
256
- rules: [{ type: "custom", name: "function" }]
257
- };
258
- }
259
- if (isIRule(val)) {
260
- const level = val._level || "error", message = maybeValidationMessage(val._message), rules = [];
261
- for (const spec of val._rules || []) {
262
- const optional = val._required === "optional" || void 0, convertedRule = convertRuleSpec(spec, optional);
263
- convertedRule !== void 0 && (rules.some((r) => isEqual(r, convertedRule)) || rules.push(convertedRule));
264
- }
265
- return rules.length === 0 ? void 0 : {
266
- level,
267
- rules,
268
- ...message && { message }
269
- };
270
- }
271
- }
272
- }
273
- function isIRule(val) {
274
- return isObject(val) && "_rules" in val;
275
- }
276
- function maybeValidationMessage(val) {
277
- if (typeof val == "string") return val;
278
- if (!isObject(val) || Array.isArray(val)) return;
279
- const objectMessage = {};
280
- for (const [field, value] of Object.entries(val))
281
- typeof field != "string" || typeof value != "string" || (objectMessage[field] = value);
282
- return Object.keys(objectMessage).length > 0 ? objectMessage : void 0;
283
- }
284
- function isIRuleFunction(val) {
285
- return typeof val == "function";
286
- }
287
- function convertRuleSpec(spec, optional) {
288
- if (!isObject(spec) || !("flag" in spec))
289
- return;
290
- const constraint = "constraint" in spec ? spec.constraint : void 0;
291
- switch (spec.flag) {
292
- case "integer":
293
- return { type: "integer" };
294
- case "email":
295
- return { type: "email" };
296
- case "unique":
297
- return { type: "uniqueItems" };
298
- case "reference":
299
- return { type: "reference" };
300
- case "assetRequired":
301
- return { type: "assetRequired" };
302
- case "stringCasing":
303
- return constraint === "uppercase" ? { type: "uppercase" } : constraint === "lowercase" ? { type: "lowercase" } : void 0;
304
- case "all":
305
- if (Array.isArray(constraint)) {
306
- const children = constraint.map((childRule) => maybeValidation(childRule)).filter((c) => c !== void 0);
307
- if (children.length > 0)
308
- return { type: "allOf", children };
309
- }
310
- return;
311
- case "either":
312
- if (Array.isArray(constraint)) {
313
- const children = constraint.map((childRule) => maybeValidation(childRule)).filter((c) => c !== void 0);
314
- if (children.length > 0)
315
- return { type: "anyOf", children };
316
- }
317
- return;
318
- case "valid":
319
- return Array.isArray(constraint) ? {
320
- type: "enum",
321
- values: constraint.map((c) => convertUnknown(c)).filter((v) => v !== void 0)
322
- } : void 0;
323
- case "min":
324
- return { type: "minimum", value: convertConstraintValue(constraint) };
325
- case "max":
326
- return { type: "maximum", value: convertConstraintValue(constraint) };
327
- case "length":
328
- return { type: "length", value: convertConstraintValue(constraint) };
329
- case "precision":
330
- return { type: "precision", value: convertConstraintValue(constraint) };
331
- case "lessThan":
332
- return { type: "exclusiveMaximum", value: convertConstraintValue(constraint) };
333
- case "greaterThan":
334
- return { type: "exclusiveMinimum", value: convertConstraintValue(constraint) };
335
- case "regex":
336
- if (isObject(constraint) && "pattern" in constraint) {
337
- const { pattern } = constraint, invert = "invert" in constraint ? maybeBoolean(constraint.invert) : void 0;
338
- if (pattern instanceof RegExp)
339
- return {
340
- type: "regex",
341
- pattern: pattern.source,
342
- ...invert && { invert: !0 }
343
- };
344
- }
345
- return;
346
- case "uri": {
347
- const allowRelative = isObject(constraint) && "options" in constraint && isObject(constraint.options) && "allowRelative" in constraint.options ? maybeBoolean(constraint.options.allowRelative) : void 0;
348
- return {
349
- type: "uri",
350
- ...allowRelative !== void 0 && { allowRelative }
351
- };
352
- }
353
- case "custom":
354
- return { type: "custom", ...optional && { optional } };
355
- case "media":
356
- return { type: "custom", name: "media" };
357
- case "type":
358
- return;
359
- case "presence":
360
- return constraint === "required" ? { type: "required" } : void 0;
361
- default:
362
- return;
363
- }
364
- }
365
- function convertConstraintValue(constraint) {
366
- return isObject(constraint) && "type" in constraint && "path" in constraint && constraint.type && constraint.path ? {
367
- type: "fieldReference",
368
- path: Array.isArray(constraint.path) ? constraint.path : [constraint.path]
369
- } : String(constraint);
370
- }
371
- function maybeBoolean(val) {
372
- if (typeof val == "boolean")
373
- return val;
374
- }
375
- function maybeI18n(val) {
376
- if (!isObject(val) || Array.isArray(val)) return;
377
- const localizedMessage = {};
378
- for (const entry of Object.entries(val))
379
- if (isI18nEntry(entry)) {
380
- const [field, value] = entry;
381
- localizedMessage[field] = {
382
- ns: value.ns,
383
- key: value.key
384
- };
385
- }
386
- return Object.keys(localizedMessage).length > 0 ? localizedMessage : void 0;
387
- }
388
- function isI18nEntry(entry) {
389
- const [key, value] = entry;
390
- return typeof key == "string" && !!value && typeof value == "object" && "key" in value && "ns" in value && typeof value.key == "string" && typeof value.ns == "string";
391
- }
392
- function maybeOrdering(val) {
393
- if (!isObject(val) || Array.isArray(val)) return;
394
- const name = "name" in val && typeof val.name == "string" ? val.name : void 0;
395
- if (name === void 0) return;
396
- const title = "title" in val && typeof val.title == "string" ? val.title : name, by = "by" in val && Array.isArray(val.by) ? val.by : [], orderingBy = [];
397
- for (const item of by) {
398
- const orderingItem = maybeOrderingBy(item);
399
- orderingItem && orderingBy.push(orderingItem);
400
- }
401
- if (orderingBy.length === 0) return;
402
- const i18n = "i18n" in val ? maybeI18n(val.i18n) : void 0;
403
- return {
404
- name,
405
- title,
406
- by: orderingBy,
407
- ...i18n && { i18n }
408
- };
409
- }
410
- function maybeOrderingBy(val) {
411
- if (!isObject(val) || Array.isArray(val)) return;
412
- const field = "field" in val && typeof val.field == "string" ? val.field : void 0, direction = "direction" in val && (val.direction === "asc" || val.direction === "desc") ? val.direction : void 0;
413
- if (!(!field || !direction))
414
- return { field, direction };
415
- }
416
- function processSchemaSynchronization(sync, response) {
417
- return processSetSynchronization(sync, response);
418
- }
419
- const ACTIONS_FLAG = "__experimental_actions", DEFAULT_ACTIONS = ["create", "update", "delete", "publish"], VALID_ACTIONS = DEFAULT_ACTIONS, readActions = (schemaType) => ACTIONS_FLAG in schemaType ? schemaType[ACTIONS_FLAG] : DEFAULT_ACTIONS, validateActions = (typeName, actions) => {
420
- if (!Array.isArray(actions))
421
- throw new Error(
422
- `The value of <type>.${ACTIONS_FLAG} should be an array with any of the actions ${VALID_ACTIONS.join(
423
- ", "
424
- )}`
425
- );
426
- const invalid = difference(actions, VALID_ACTIONS);
427
- if (invalid.length > 0)
428
- throw new Error(
429
- `Invalid action${invalid.length > 1 ? "s" : ""} configured for schema type "${typeName}": ${invalid.join(
430
- ", "
431
- )}. Valid actions are: ${VALID_ACTIONS.join(", ")}`
432
- );
433
- return actions;
434
- }, resolveEnabledActions = (schemaType) => validateActions(schemaType.name, readActions(schemaType)), isActionEnabled = (schemaType, action) => resolveEnabledActions(schemaType).includes(action);
435
- var assetSourceData = {
436
- name: "sanity.assetSourceData",
437
- title: "Asset Source Data",
438
- type: "object",
439
- fields: [
440
- {
441
- name: "name",
442
- title: "Source name",
443
- description: "A canonical name for the source this asset is originating from",
444
- type: "string"
445
- },
446
- {
447
- name: "id",
448
- title: "Asset Source ID",
449
- description: "The unique ID for the asset within the originating source so you can programatically find back to it",
450
- type: "string"
451
- },
452
- {
453
- name: "url",
454
- title: "Asset information URL",
455
- description: "A URL to find more information about this asset in the originating source",
456
- type: "string"
457
- }
458
- ]
459
- }, fileAsset = {
460
- name: "sanity.fileAsset",
461
- title: "File",
462
- type: "document",
463
- fieldsets: [
464
- {
465
- name: "system",
466
- title: "System fields",
467
- description: "These fields are managed by the system and not editable"
468
- }
469
- ],
470
- fields: [
471
- {
472
- name: "originalFilename",
473
- type: "string",
474
- title: "Original file name",
475
- readOnly: !0
476
- },
477
- {
478
- name: "label",
479
- type: "string",
480
- title: "Label"
481
- },
482
- {
483
- name: "title",
484
- type: "string",
485
- title: "Title"
486
- },
487
- {
488
- name: "description",
489
- type: "string",
490
- title: "Description"
491
- },
492
- {
493
- name: "altText",
494
- type: "string",
495
- title: "Alternative text"
496
- },
497
- {
498
- name: "sha1hash",
499
- type: "string",
500
- title: "SHA1 hash",
501
- readOnly: !0,
502
- fieldset: "system"
503
- },
504
- {
505
- name: "extension",
506
- type: "string",
507
- title: "File extension",
508
- readOnly: !0,
509
- fieldset: "system"
510
- },
511
- {
512
- name: "mimeType",
513
- type: "string",
514
- title: "Mime type",
515
- readOnly: !0,
516
- fieldset: "system"
517
- },
518
- {
519
- name: "size",
520
- type: "number",
521
- title: "File size in bytes",
522
- readOnly: !0,
523
- fieldset: "system"
524
- },
525
- {
526
- name: "assetId",
527
- type: "string",
528
- title: "Asset ID",
529
- readOnly: !0,
530
- fieldset: "system"
531
- },
532
- {
533
- name: "uploadId",
534
- type: "string",
535
- readOnly: !0,
536
- hidden: !0,
537
- fieldset: "system"
538
- },
539
- {
540
- name: "path",
541
- type: "string",
542
- title: "Path",
543
- readOnly: !0,
544
- fieldset: "system"
545
- },
546
- {
547
- name: "url",
548
- type: "string",
549
- title: "Url",
550
- readOnly: !0,
551
- fieldset: "system"
552
- },
553
- {
554
- name: "source",
555
- type: "sanity.assetSourceData",
556
- title: "Source",
557
- readOnly: !0,
558
- fieldset: "system"
559
- }
560
- ],
561
- preview: {
562
- select: {
563
- title: "originalFilename",
564
- path: "path",
565
- mimeType: "mimeType",
566
- size: "size"
567
- },
568
- prepare(doc) {
569
- return {
570
- title: doc.title || doc.path.split("/").slice(-1)[0],
571
- subtitle: `${doc.mimeType} (${(doc.size / 1024 / 1024).toFixed(2)} MB)`
572
- };
573
- }
574
- },
575
- orderings: [
576
- {
577
- title: "File size",
578
- name: "fileSizeDesc",
579
- by: [{ field: "size", direction: "desc" }]
580
- }
581
- ]
582
- }, geopoint = {
583
- title: "Geographical Point",
584
- name: "geopoint",
585
- type: "object",
586
- fields: [
587
- {
588
- name: "lat",
589
- type: "number",
590
- title: "Latitude"
591
- },
592
- {
593
- name: "lng",
594
- type: "number",
595
- title: "Longitude"
596
- },
597
- {
598
- name: "alt",
599
- type: "number",
600
- title: "Altitude"
601
- }
602
- ]
603
- }, imageAsset = {
604
- name: "sanity.imageAsset",
605
- title: "Image",
606
- type: "document",
607
- fieldsets: [
608
- {
609
- name: "system",
610
- title: "System fields",
611
- description: "These fields are managed by the system and not editable"
612
- }
613
- ],
614
- fields: [
615
- {
616
- name: "originalFilename",
617
- type: "string",
618
- title: "Original file name",
619
- readOnly: !0
620
- },
621
- {
622
- name: "label",
623
- type: "string",
624
- title: "Label"
625
- },
626
- {
627
- name: "title",
628
- type: "string",
629
- title: "Title"
630
- },
631
- {
632
- name: "description",
633
- type: "string",
634
- title: "Description"
635
- },
636
- {
637
- name: "altText",
638
- type: "string",
639
- title: "Alternative text"
640
- },
641
- {
642
- name: "sha1hash",
643
- type: "string",
644
- title: "SHA1 hash",
645
- readOnly: !0,
646
- fieldset: "system"
647
- },
648
- {
649
- name: "extension",
650
- type: "string",
651
- readOnly: !0,
652
- title: "File extension",
653
- fieldset: "system"
654
- },
655
- {
656
- name: "mimeType",
657
- type: "string",
658
- readOnly: !0,
659
- title: "Mime type",
660
- fieldset: "system"
661
- },
662
- {
663
- name: "size",
664
- type: "number",
665
- title: "File size in bytes",
666
- readOnly: !0,
667
- fieldset: "system"
668
- },
669
- {
670
- name: "assetId",
671
- type: "string",
672
- title: "Asset ID",
673
- readOnly: !0,
674
- fieldset: "system"
675
- },
676
- {
677
- name: "uploadId",
678
- type: "string",
679
- readOnly: !0,
680
- hidden: !0,
681
- fieldset: "system"
682
- },
683
- {
684
- name: "path",
685
- type: "string",
686
- title: "Path",
687
- readOnly: !0,
688
- fieldset: "system"
689
- },
690
- {
691
- name: "url",
692
- type: "string",
693
- title: "Url",
694
- readOnly: !0,
695
- fieldset: "system"
696
- },
697
- {
698
- name: "metadata",
699
- type: "sanity.imageMetadata",
700
- title: "Metadata"
701
- },
702
- {
703
- name: "source",
704
- type: "sanity.assetSourceData",
705
- title: "Source",
706
- readOnly: !0,
707
- fieldset: "system"
708
- }
709
- ],
710
- preview: {
711
- select: {
712
- id: "_id",
713
- title: "originalFilename",
714
- mimeType: "mimeType",
715
- size: "size"
716
- },
717
- prepare(doc) {
718
- return {
719
- title: doc.title || typeof doc.path == "string" && doc.path.split("/").slice(-1)[0],
720
- media: { asset: { _ref: doc.id } },
721
- subtitle: `${doc.mimeType} (${(Number(doc.size) / 1024 / 1024).toFixed(2)} MB)`
722
- };
723
- }
724
- },
725
- orderings: [
726
- {
727
- title: "File size",
728
- name: "fileSizeDesc",
729
- by: [{ field: "size", direction: "desc" }]
730
- }
731
- ]
732
- }, imageCrop = {
733
- name: "sanity.imageCrop",
734
- title: "Image crop",
735
- type: "object",
736
- fields: [
737
- {
738
- name: "top",
739
- type: "number",
740
- validation: (Rule2) => Rule2.required()
741
- },
742
- {
743
- name: "bottom",
744
- type: "number",
745
- validation: (Rule2) => Rule2.required()
746
- },
747
- {
748
- name: "left",
749
- type: "number",
750
- validation: (Rule2) => Rule2.required()
751
- },
752
- {
753
- name: "right",
754
- type: "number",
755
- validation: (Rule2) => Rule2.required()
756
- }
757
- ]
758
- }, imageDimensions = {
759
- name: "sanity.imageDimensions",
760
- type: "object",
761
- title: "Image dimensions",
762
- fields: [
763
- {
764
- name: "height",
765
- type: "number",
766
- title: "Height",
767
- readOnly: !0,
768
- validation: (Rule2) => Rule2.required()
769
- },
770
- {
771
- name: "width",
772
- type: "number",
773
- title: "Width",
774
- readOnly: !0,
775
- validation: (Rule2) => Rule2.required()
776
- },
777
- {
778
- name: "aspectRatio",
779
- type: "number",
780
- title: "Aspect ratio",
781
- readOnly: !0,
782
- validation: (Rule2) => Rule2.required()
783
- }
784
- ]
785
- }, imageHotspot = {
786
- name: "sanity.imageHotspot",
787
- title: "Image hotspot",
788
- type: "object",
789
- fields: [
790
- {
791
- name: "x",
792
- type: "number",
793
- validation: (Rule2) => Rule2.required()
794
- },
795
- {
796
- name: "y",
797
- type: "number",
798
- validation: (Rule2) => Rule2.required()
799
- },
800
- {
801
- name: "height",
802
- type: "number",
803
- validation: (Rule2) => Rule2.required()
804
- },
805
- {
806
- name: "width",
807
- type: "number",
808
- validation: (Rule2) => Rule2.required()
809
- }
810
- ]
811
- }, imageMetadata = {
812
- name: "sanity.imageMetadata",
813
- title: "Image metadata",
814
- type: "object",
815
- fieldsets: [
816
- {
817
- name: "extra",
818
- title: "Extra metadata\u2026",
819
- options: {
820
- collapsable: !0
821
- }
822
- }
823
- ],
824
- fields: [
825
- {
826
- name: "location",
827
- type: "geopoint"
828
- },
829
- {
830
- name: "dimensions",
831
- title: "Dimensions",
832
- type: "sanity.imageDimensions",
833
- fieldset: "extra"
834
- },
835
- {
836
- name: "palette",
837
- type: "sanity.imagePalette",
838
- title: "Palette",
839
- fieldset: "extra"
840
- },
841
- {
842
- name: "lqip",
843
- title: "LQIP (Low-Quality Image Placeholder)",
844
- type: "string",
845
- readOnly: !0
846
- },
847
- {
848
- name: "blurHash",
849
- title: "BlurHash",
850
- type: "string",
851
- readOnly: !0
852
- },
853
- {
854
- name: "hasAlpha",
855
- title: "Has alpha channel",
856
- type: "boolean",
857
- readOnly: !0
858
- },
859
- {
860
- name: "isOpaque",
861
- title: "Is opaque",
862
- type: "boolean",
863
- readOnly: !0
864
- }
865
- ]
866
- }, imagePalette = {
867
- name: "sanity.imagePalette",
868
- title: "Image palette",
869
- type: "object",
870
- fields: [
871
- { name: "darkMuted", type: "sanity.imagePaletteSwatch", title: "Dark Muted" },
872
- { name: "lightVibrant", type: "sanity.imagePaletteSwatch", title: "Light Vibrant" },
873
- { name: "darkVibrant", type: "sanity.imagePaletteSwatch", title: "Dark Vibrant" },
874
- { name: "vibrant", type: "sanity.imagePaletteSwatch", title: "Vibrant" },
875
- { name: "dominant", type: "sanity.imagePaletteSwatch", title: "Dominant" },
876
- { name: "lightMuted", type: "sanity.imagePaletteSwatch", title: "Light Muted" },
877
- { name: "muted", type: "sanity.imagePaletteSwatch", title: "Muted" }
878
- ]
879
- }, imagePaletteSwatch = {
880
- name: "sanity.imagePaletteSwatch",
881
- title: "Image palette swatch",
882
- type: "object",
883
- fields: [
884
- { name: "background", type: "string", title: "Background", readOnly: !0 },
885
- { name: "foreground", type: "string", title: "Foreground", readOnly: !0 },
886
- { name: "population", type: "number", title: "Population", readOnly: !0 },
887
- { name: "title", type: "string", title: "String", readOnly: !0 }
888
- ]
889
- }, slug$1 = {
890
- title: "Slug",
891
- name: "slug",
892
- type: "object",
893
- fields: [
894
- {
895
- name: "current",
896
- title: "Current slug",
897
- type: "string",
898
- validation: (Rule2) => Rule2.required()
899
- },
900
- {
901
- // The source field is deprecated/unused, but leaving it included and hidden
902
- // to prevent rendering "Unknown field" warnings on legacy data
903
- name: "source",
904
- title: "Source field",
905
- type: "string",
906
- hidden: !0
907
- }
908
- ]
909
- };
910
- const builtinTypes = [
911
- assetSourceData,
912
- slug$1,
913
- geopoint,
914
- // legacyRichDate,
915
- imageAsset,
916
- fileAsset,
917
- imageCrop,
918
- imageHotspot,
919
- imageMetadata,
920
- imageDimensions,
921
- imagePalette,
922
- imagePaletteSwatch
923
- ], HELP_IDS = {
924
- TYPE_INVALID: "schema-type-invalid",
925
- TYPE_IS_ESM_MODULE: "schema-type-is-esm-module",
926
- TYPE_NAME_RESERVED: "schema-type-name-reserved",
927
- TYPE_MISSING_NAME: "schema-type-missing-name-or-type",
928
- TYPE_MISSING_TYPE: "schema-type-missing-name-or-type",
929
- TYPE_TITLE_RECOMMENDED: "schema-type-title-is-recommended",
930
- TYPE_TITLE_INVALID: "schema-type-title-is-recommended",
931
- OBJECT_FIELDS_INVALID: "schema-object-fields-invalid",
932
- OBJECT_FIELD_NOT_UNIQUE: "schema-object-fields-invalid",
933
- OBJECT_FIELD_NAME_INVALID: "schema-object-fields-invalid",
934
- OBJECT_FIELD_DEFINITION_INVALID_TYPE: "schema-object-fields-invalid",
935
- ARRAY_PREDEFINED_CHOICES_INVALID: "schema-predefined-choices-invalid",
936
- ARRAY_OF_ARRAY: "schema-array-of-array",
937
- ARRAY_OF_INVALID: "schema-array-of-invalid",
938
- ARRAY_OF_NOT_UNIQUE: "schema-array-of-invalid",
939
- ARRAY_OF_TYPE_GLOBAL_TYPE_CONFLICT: "schema-array-of-type-global-type-conflict",
940
- ARRAY_OF_TYPE_BUILTIN_TYPE_CONFLICT: "schema-array-of-type-builtin-type-conflict",
941
- REFERENCE_TO_INVALID: "schema-reference-to-invalid",
942
- REFERENCE_TO_NOT_UNIQUE: "schema-reference-to-invalid",
943
- REFERENCE_INVALID_OPTIONS: "schema-reference-invalid-options",
944
- REFERENCE_INVALID_OPTIONS_LOCATION: "schema-reference-options-nesting",
945
- REFERENCE_INVALID_FILTER_PARAMS_COMBINATION: "schema-reference-filter-params-combination",
946
- SLUG_SLUGIFY_FN_RENAMED: "slug-slugifyfn-renamed",
947
- ASSET_METADATA_FIELD_INVALID: "asset-metadata-field-invalid",
948
- CROSS_DATASET_REFERENCE_INVALID: "cross-dataset-reference-invalid",
949
- GLOBAL_DOCUMENT_REFERENCE_INVALID: "global-document-reference-invalid",
950
- DEPRECATED_BLOCKEDITOR_KEY: "schema-deprecated-blockeditor-key",
951
- STANDALONE_BLOCK_TYPE: "schema-standalone-block-type"
952
- };
953
- function createValidationResult(severity, message, helpId) {
954
- if (helpId && !Object.keys(HELP_IDS).some((id) => HELP_IDS[id] === helpId))
955
- throw new Error(
956
- `Used the unknown helpId "${helpId}", please add it to the array in createValidationResult.js`
957
- );
958
- return {
959
- severity,
960
- message,
961
- helpId
962
- };
963
- }
964
- const error = (message, helpId) => createValidationResult("error", message, helpId), warning = (message, helpId) => createValidationResult("warning", message, helpId);
965
- function groupProblems(types) {
966
- return flatten(types.map((type) => getTypeProblems(type))).filter(
967
- (type) => type.problems.length > 0
968
- );
969
- }
970
- function createTypeWithMembersProblemsAccessor(memberPropertyName, getMembers = (type) => get(type, memberPropertyName)) {
971
- return function(type, parentPath) {
972
- const currentPath = [
973
- ...parentPath,
974
- { kind: "type", type: type.type, name: type.name }
975
- ], members = getMembers(type) || [], memberProblems = Array.isArray(members) ? members.map((memberType) => {
976
- const propertySegment = {
977
- kind: "property",
978
- name: memberPropertyName
979
- }, memberPath = [...currentPath, propertySegment];
980
- return getTypeProblems(memberType, memberPath);
981
- }) : [
982
- [
983
- {
984
- path: currentPath,
985
- problems: [error(`Member declaration (${memberPropertyName}) is not an array`)]
986
- }
987
- ]
988
- ];
989
- return [
990
- {
991
- path: currentPath,
992
- problems: type._problems || []
993
- },
994
- ...flatten(memberProblems)
995
- ];
996
- };
997
- }
998
- const arrify = (val) => Array.isArray(val) ? val : typeof val > "u" && [] || [val], getObjectProblems = createTypeWithMembersProblemsAccessor("fields"), getImageProblems = createTypeWithMembersProblemsAccessor("fields"), getFileProblems = createTypeWithMembersProblemsAccessor("fields"), getArrayProblems = createTypeWithMembersProblemsAccessor("of"), getReferenceProblems = createTypeWithMembersProblemsAccessor(
999
- "to",
1000
- (type) => "to" in type ? arrify(type.to) : []
1001
- ), getBlockAnnotationProblems = createTypeWithMembersProblemsAccessor("marks.annotations"), getBlockMemberProblems = createTypeWithMembersProblemsAccessor("of"), getBlockProblems = (type, problems) => [
1002
- ...getBlockAnnotationProblems(type, problems),
1003
- ...getBlockMemberProblems(type, problems)
1004
- ];
1005
- function getDefaultProblems(type, path = []) {
1006
- return [
1007
- {
1008
- path: [...path, { kind: "type", type: type.type, name: type.name }],
1009
- problems: type._problems || []
1010
- }
1011
- ];
1012
- }
1013
- function getTypeProblems(type, path = []) {
1014
- switch (type.type) {
1015
- case "object":
1016
- return getObjectProblems(type, path);
1017
- case "document":
1018
- return getObjectProblems(type, path);
1019
- case "array":
1020
- return getArrayProblems(type, path);
1021
- case "reference":
1022
- return getReferenceProblems(type, path);
1023
- case "block":
1024
- return getBlockProblems(type, path);
1025
- case "image":
1026
- return getImageProblems(type, path);
1027
- case "file":
1028
- return getFileProblems(type, path);
1029
- default:
1030
- return getDefaultProblems(type, path);
1031
- }
1032
- }
1033
- function getDupes(array2, selector = (v) => v) {
1034
- const dupes = array2.reduce((acc, item) => {
1035
- const key = selector(item);
1036
- return acc[key] || (acc[key] = []), acc[key].push(item), acc;
1037
- }, {});
1038
- return Object.keys(dupes).map((key) => dupes[key].length > 1 ? dupes[key] : null).filter(Boolean);
1039
- }
1040
- const NOOP_VISITOR = (typeDef) => typeDef, TYPE_TYPE = { name: "type", type: null }, FUTURE_RESERVED = ["any", "time", "date"];
1041
- function traverseSchema(types = [], coreTypes2 = [], visitor = NOOP_VISITOR) {
1042
- const coreTypesRegistry = /* @__PURE__ */ Object.create(null), registry = /* @__PURE__ */ Object.create(null), coreTypeNames2 = coreTypes2.map((typeDef) => typeDef.name), reservedTypeNames = FUTURE_RESERVED.concat(coreTypeNames2), typeNames = types.map((typeDef) => typeDef && typeDef.name).filter(Boolean);
1043
- coreTypes2.forEach((coreType) => {
1044
- coreTypesRegistry[coreType.name] = coreType;
1045
- }), types.forEach((type, i) => {
1046
- registry[type && type.name || `__unnamed_${i}`] = {};
1047
- });
1048
- function getType(typeName) {
1049
- return typeName === "type" ? TYPE_TYPE : coreTypesRegistry[typeName] || registry[typeName] || null;
1050
- }
1051
- const duplicateNames = uniq(flatten(getDupes(typeNames)));
1052
- function isDuplicate(typeName) {
1053
- return duplicateNames.includes(typeName);
1054
- }
1055
- function getTypeNames() {
1056
- return typeNames.concat(coreTypeNames2);
1057
- }
1058
- function isReserved(typeName) {
1059
- return typeName === "type" || reservedTypeNames.includes(typeName);
1060
- }
1061
- const visitType = (isRoot) => (typeDef, index) => visitor(typeDef, {
1062
- visit: visitType(!1),
1063
- isRoot,
1064
- getType,
1065
- getTypeNames,
1066
- isReserved,
1067
- isDuplicate,
1068
- index
1069
- });
1070
- return coreTypes2.forEach((coreTypeDef) => {
1071
- Object.assign(coreTypesRegistry[coreTypeDef.name], visitType(coreTypeDef));
1072
- }), types.forEach((typeDef, i) => {
1073
- Object.assign(
1074
- registry[typeDef && typeDef.name || `__unnamed_${i}`],
1075
- visitType(!0)(typeDef, i)
1076
- );
1077
- }), {
1078
- get(typeName) {
1079
- const res = registry[typeName] || coreTypesRegistry[typeName];
1080
- if (res)
1081
- return res;
1082
- throw new Error(`No such type: ${typeName}`);
1083
- },
1084
- has(typeName) {
1085
- return typeName in registry || typeName in coreTypesRegistry;
1086
- },
1087
- getTypeNames() {
1088
- return Object.keys(registry);
1089
- },
1090
- getTypes() {
1091
- return this.getTypeNames().map(this.get);
1092
- },
1093
- toJSON() {
1094
- return this.getTypes();
1095
- }
1096
- };
1097
- }
1098
- const coreTypes = [
1099
- { name: "array", jsonType: "array", type: "type" },
1100
- { name: "block", jsonType: "object", type: "type" },
1101
- { name: "boolean", jsonType: "boolean", type: "type" },
1102
- { name: "datetime", jsonType: "string", type: "type" },
1103
- { name: "date", jsonType: "string", type: "type" },
1104
- { name: "document", jsonType: "object", type: "type" },
1105
- { name: "email", jsonType: "string", type: "type" },
1106
- { name: "file", jsonType: "object", type: "type" },
1107
- { name: "geopoint", jsonType: "object", type: "type" },
1108
- { name: "image", jsonType: "object", type: "type" },
1109
- { name: "number", jsonType: "number", type: "type" },
1110
- { name: "object", jsonType: "object", type: "type" },
1111
- { name: "reference", jsonType: "object", type: "type" },
1112
- { name: "crossDatasetReference", jsonType: "object", type: "type" },
1113
- { name: "globalDocumentReference", jsonType: "object", type: "type" },
1114
- { name: "slug", jsonType: "object", type: "type" },
1115
- { name: "span", jsonType: "object", type: "type" },
1116
- { name: "string", jsonType: "string", type: "type" },
1117
- { name: "telephone", jsonType: "string", type: "type" },
1118
- { name: "text", jsonType: "string", type: "type" },
1119
- { name: "url", jsonType: "string", type: "type" }
1120
- ], coreTypeNames = coreTypes.map((t) => t.name);
1121
- function traverseSanitySchema(schemaTypes, visitor) {
1122
- return traverseSchema(schemaTypes, coreTypes, visitor);
1123
- }
1124
- function isPrimitiveTypeName(typeName) {
1125
- return typeName === "string" || typeName === "number" || typeName === "boolean";
1126
- }
1127
- function isAssignable(typeName, type) {
1128
- return (typeof type.name == "string" ? type.name : type.type) === typeName;
1129
- }
1130
- function quote$2(n) {
1131
- return `"${n}"`;
1132
- }
1133
- function pluralize(arr, suf = "s") {
1134
- return arr.length === 1 ? "" : suf;
1135
- }
1136
- function format(value) {
1137
- return Array.isArray(value) ? `array with ${value.length} entries` : typeof value == "object" && value !== null ? `object with keys ${humanizeList(Object.keys(value).map(quote$2))}` : quote$2(value);
1138
- }
1139
- var array = (typeDef, visitorContext) => {
1140
- const ofIsArray = Array.isArray(typeDef.of);
1141
- if (ofIsArray) {
1142
- const invalid = typeDef.of.reduce((errs, def, idx) => {
1143
- if (typeof def.name == "string" && // specifying the same name as the type is redundant, but should not be a hard error at this point
1144
- // Consider showing a warning for this and deprecate this ability eventually
1145
- def.name !== def.type && coreTypeNames.includes(def.name))
1146
- return errs.concat(
1147
- error(
1148
- `Found array member declaration with the same type name as a built-in type ("${def.name}"). Array members can not be given the same name as a built-in type.`,
1149
- HELP_IDS.ARRAY_OF_TYPE_BUILTIN_TYPE_CONFLICT
1150
- )
1151
- );
1152
- if (def.type === "object" && def.name && visitorContext.getType(def.name))
1153
- return errs.concat(
1154
- warning(
1155
- `Found array member declaration with the same name as the global schema type "${def.name}". It's recommended to use a unique name to avoid possibly incompatible data types that shares the same name.`,
1156
- HELP_IDS.ARRAY_OF_TYPE_GLOBAL_TYPE_CONFLICT
1157
- )
1158
- );
1159
- if (def.type === "array")
1160
- return errs.concat(
1161
- error(
1162
- 'Found array member declaration of type "array" - multidimensional arrays are not currently supported by Sanity',
1163
- HELP_IDS.ARRAY_OF_ARRAY
1164
- )
1165
- );
1166
- if (def)
1167
- return errs;
1168
- const err = `Found ${def === null ? "null" : typeof def}, expected member declaration`;
1169
- return errs.concat(
1170
- error(
1171
- `Found invalid type member declaration in array at index ${idx}: ${err}`,
1172
- HELP_IDS.ARRAY_OF_INVALID
1173
- )
1174
- );
1175
- }, []);
1176
- if (invalid.length > 0)
1177
- return {
1178
- ...typeDef,
1179
- of: [],
1180
- _problems: invalid
1181
- };
1182
- }
1183
- const problems = flatten([
1184
- ofIsArray ? getDupes(typeDef.of, (t) => `${t.name};${t.type}`).map(
1185
- (dupes) => error(
1186
- `Found ${dupes.length} members with same type, but not unique names "${dupes[0].type}" in array. This makes it impossible to tell their values apart and you should consider naming them`,
1187
- HELP_IDS.ARRAY_OF_NOT_UNIQUE
1188
- )
1189
- ) : error(
1190
- 'The array type is missing or having an invalid value for the required "of" property',
1191
- HELP_IDS.ARRAY_OF_INVALID
1192
- )
1193
- ]), of = ofIsArray ? typeDef.of : [], hasObjectTypesWithoutName = of.some(
1194
- (type) => type.type === "object" && typeof type.name > "u"
1195
- );
1196
- of.some((ofType) => ofType.type === "block") && hasObjectTypesWithoutName && problems.push(
1197
- error(
1198
- "The array type's 'of' property can't have an object type without a 'name' property as member, when the 'block' type is also a member of that array.",
1199
- HELP_IDS.ARRAY_OF_INVALID
1200
- )
1201
- );
1202
- const [primitiveTypes, objectTypes] = partition(
1203
- of,
1204
- (ofType) => isPrimitiveTypeName(ofType.type) || isPrimitiveTypeName(visitorContext.getType(ofType.type)?.jsonType)
1205
- ), isMixedArray = primitiveTypes.length > 0 && objectTypes.length > 0;
1206
- if (isMixedArray) {
1207
- const primitiveTypeNames = primitiveTypes.map((t) => t.type), objectTypeNames = objectTypes.map((t) => t.type);
1208
- problems.push(
1209
- error(
1210
- `The array type's 'of' property can't have both object types and primitive types (found primitive type ${pluralize(
1211
- primitiveTypeNames
1212
- )} ${humanizeList(primitiveTypeNames.map(quote$2))} and object type${pluralize(
1213
- objectTypeNames
1214
- )} ${humanizeList(objectTypeNames.map(quote$2))})`,
1215
- HELP_IDS.ARRAY_OF_INVALID
1216
- )
1217
- );
1218
- }
1219
- const list = typeDef?.options?.list;
1220
- return !isMixedArray && Array.isArray(list) && (primitiveTypes.length > 0 ? list.forEach((option) => {
1221
- const value = option?.value ?? option;
1222
- if (!primitiveTypes.some((primitiveType) => typeof value === visitorContext.getType(primitiveType.type).jsonType)) {
1223
- const formattedTypeList = humanizeList(
1224
- primitiveTypes.map((t) => t.name || t.type),
1225
- { conjunction: "or" }
1226
- );
1227
- problems.push(
1228
- error(
1229
- `An invalid entry found in options.list: ${format(
1230
- value
1231
- )}. Must be either a value of type ${formattedTypeList}, or an object with {title: string, value: ${formattedTypeList}}`,
1232
- HELP_IDS.ARRAY_PREDEFINED_CHOICES_INVALID
1233
- )
1234
- );
1235
- }
1236
- }) : list.forEach((option) => {
1237
- const optionTypeName = option._type || "object";
1238
- objectTypes.some(
1239
- (validObjectType) => isAssignable(optionTypeName, validObjectType)
1240
- ) || problems.push(
1241
- error(
1242
- `An invalid entry found in options.list: ${format(
1243
- option
1244
- )}. Must be an object with "_type" set to ${humanizeList(
1245
- objectTypes.map((t) => t.name || t.type).map((t) => t === "object" ? "undefined" : quote$2(t)),
1246
- { conjunction: "or" }
1247
- )}`,
1248
- HELP_IDS.ARRAY_PREDEFINED_CHOICES_INVALID
1249
- )
1250
- );
1251
- })), typeDef?.options?.list && typeDef?.options?.layout === "tags" && problems.push(
1252
- warning(
1253
- "Found array member declaration with both tags layout and a list of predefined values. If you want to display a list of predefined values, remove the tags layout from `options`."
1254
- )
1255
- ), {
1256
- ...typeDef,
1257
- of: of.map(visitorContext.visit),
1258
- _problems: problems
1259
- };
1260
- };
1261
- function isJSONTypeOf(type, jsonType, visitorContext) {
1262
- if ("jsonType" in type)
1263
- return type.jsonType === jsonType;
1264
- const parentType = visitorContext.getType(type.type);
1265
- if (!parentType)
1266
- throw new Error(`Could not resolve jsonType of ${type.name}. No parent type found`);
1267
- return isJSONTypeOf(parentType, jsonType, visitorContext);
1268
- }
1269
- const getTypeOf = (thing) => Array.isArray(thing) ? "array" : typeof thing, quote$1 = (str) => `"${str}"`, allowedKeys = [
1270
- "components",
1271
- "lists",
1272
- "marks",
1273
- "name",
1274
- "of",
1275
- "options",
1276
- "styles",
1277
- "title",
1278
- "type",
1279
- "validation"
1280
- ], allowedMarkKeys = ["decorators", "annotations"], allowedStyleKeys = ["blockEditor", "title", "value", "icon", "component"], allowedDecoratorKeys = ["blockEditor", "title", "value", "icon", "component"], allowedListKeys = ["title", "value", "icon", "component"], supportedBuiltInObjectTypes = [
1281
- "file",
1282
- "image",
1283
- "object",
1284
- "reference",
1285
- "crossDatasetReference",
1286
- "globalDocumentReference"
1287
- ];
1288
- function validateBlockType(typeDef, visitorContext) {
1289
- const problems = [];
1290
- let styles = typeDef.styles, lists = typeDef.lists, marks = typeDef.marks, members = typeDef.of;
1291
- const disallowedKeys = Object.keys(typeDef).filter(
1292
- (key) => !allowedKeys.includes(key) && !key.startsWith("_")
1293
- );
1294
- return disallowedKeys.length > 0 && problems.push(
1295
- error(
1296
- `Found unknown properties for block declaration: ${humanizeList(
1297
- disallowedKeys.map(quote$1)
1298
- )}`
1299
- )
1300
- ), marks && (marks = validateMarks(typeDef.marks, visitorContext, problems)), styles && (styles = validateStyles(styles, visitorContext, problems)), lists && (lists = validateLists(lists, visitorContext, problems)), members && (members = validateMembers(members, visitorContext, problems)), {
1301
- ...omit(typeDef, disallowedKeys),
1302
- marks,
1303
- styles,
1304
- name: typeDef.name || typeDef.type,
1305
- of: members,
1306
- _problems: problems
1307
- };
1308
- }
1309
- function validateMarks(marks, visitorContext, problems) {
1310
- let decorators = marks.decorators, annotations = marks.annotations;
1311
- if (!isPlainObject(marks))
1312
- return problems.push(error(`"marks" declaration should be an object, got ${getTypeOf(marks)}`)), problems;
1313
- const disallowedMarkKeys = Object.keys(marks).filter(
1314
- (key) => !allowedMarkKeys.includes(key) && !key.startsWith("_")
1315
- );
1316
- return disallowedMarkKeys.length > 0 && problems.push(
1317
- error(
1318
- `Found unknown properties for block declaration: ${humanizeList(
1319
- disallowedMarkKeys.map(quote$1)
1320
- )}`
1321
- )
1322
- ), decorators && !Array.isArray(decorators) ? problems.push(
1323
- error(`"marks.decorators" declaration should be an array, got ${getTypeOf(decorators)}`)
1324
- ) : decorators && (decorators.filter((dec) => !!dec.blockEditor).forEach((dec) => {
1325
- dec.icon = dec.blockEditor.icon, dec.component = dec.blockEditor.render;
1326
- }), decorators = validateDecorators(decorators, visitorContext, problems)), annotations && !Array.isArray(annotations) ? problems.push(
1327
- error(`"marks.annotations" declaration should be an array, got ${getTypeOf(annotations)}`)
1328
- ) : annotations && (annotations = validateAnnotations(annotations, visitorContext, problems)), { ...marks, decorators, annotations };
1329
- }
1330
- function validateLists(lists, visitorContext, problems) {
1331
- return Array.isArray(lists) ? (lists.forEach((list, index) => {
1332
- if (!isPlainObject(list)) {
1333
- problems.push(error(`List must be an object, got ${getTypeOf(list)}`));
1334
- return;
1335
- }
1336
- const name = list.value || `#${index}`, disallowedKeys = Object.keys(list).filter(
1337
- (key) => !allowedListKeys.includes(key) && !key.startsWith("_")
1338
- );
1339
- disallowedKeys.length > 0 && problems.push(
1340
- error(
1341
- `Found unknown properties for list ${name}: ${humanizeList(disallowedKeys.map(quote$1))}`
1342
- )
1343
- ), list.value ? typeof list.value != "string" ? problems.push(
1344
- error(
1345
- `List type #${index} has an invalid "value" property, expected string, got ${getTypeOf(
1346
- list.value
1347
- )}`
1348
- )
1349
- ) : list.title || problems.push(warning(`List type ${name} is missing recommended "title" property`)) : problems.push(error(`List #${index} is missing required "value" property`));
1350
- }), lists) : (problems.push(error(`"lists" declaration should be an array, got ${getTypeOf(lists)}`)), problems);
1351
- }
1352
- function validateStyles(styles, visitorContext, problems) {
1353
- return Array.isArray(styles) ? (styles.forEach((style, index) => {
1354
- if (!isPlainObject(style)) {
1355
- problems.push(error(`Style must be an object, got ${getTypeOf(style)}`));
1356
- return;
1357
- }
1358
- const name = style.value || `#${index}`, disallowedKeys = Object.keys(style).filter(
1359
- (key) => !allowedStyleKeys.includes(key) && !key.startsWith("_")
1360
- );
1361
- disallowedKeys.length > 0 && problems.push(
1362
- error(
1363
- `Found unknown properties for style ${name}: ${humanizeList(disallowedKeys.map(quote$1))}`
1364
- )
1365
- ), style.value ? typeof style.value != "string" ? problems.push(
1366
- error(
1367
- `Style #${index} has an invalid "value" property, expected string, got ${getTypeOf(
1368
- style.value
1369
- )}`
1370
- )
1371
- ) : style.title || problems.push(warning(`Style ${name} is missing recommended "title" property`)) : problems.push(error(`Style #${index} is missing required "value" property`)), typeof style.blockEditor < "u" && (problems.push(
1372
- warning(
1373
- 'Style has deprecated key "blockEditor", please refer to the documentation on how to configure the block type for version 3.',
1374
- HELP_IDS.DEPRECATED_BLOCKEDITOR_KEY
1375
- )
1376
- ), style.component = style.component || style.blockEditor.render);
1377
- }), styles) : (problems.push(error(`"styles" declaration should be an array, got ${getTypeOf(styles)}`)), problems);
1378
- }
1379
- function validateDecorators(decorators, visitorContext, problems) {
1380
- return decorators.forEach((decorator, index) => {
1381
- if (!isPlainObject(decorator)) {
1382
- problems.push(error(`Annotation must be an object, got ${getTypeOf(decorator)}`));
1383
- return;
1384
- }
1385
- const name = decorator.value || `#${index}`, disallowedKeys = Object.keys(decorator).filter(
1386
- (key) => !allowedDecoratorKeys.includes(key) && !key.startsWith("_")
1387
- );
1388
- disallowedKeys.length > 0 && problems.push(
1389
- error(
1390
- `Found unknown properties for decorator ${name}: ${humanizeList(
1391
- disallowedKeys.map(quote$1)
1392
- )}`
1393
- )
1394
- ), decorator.value ? typeof decorator.value != "string" ? problems.push(
1395
- error(
1396
- `Decorator #${index} has an invalid "value" property, expected string, got ${getTypeOf(
1397
- decorator.value
1398
- )}`
1399
- )
1400
- ) : decorator.title || problems.push(warning(`Decorator ${name} is missing recommended "title" property`)) : problems.push(error(`Decorator #${index} is missing required "value" property`)), typeof decorator.blockEditor < "u" && (problems.push(
1401
- warning(
1402
- `Decorator "${name}" has deprecated key "blockEditor", please refer to the documentation on how to configure the block type for version 3.`,
1403
- HELP_IDS.DEPRECATED_BLOCKEDITOR_KEY
1404
- )
1405
- ), decorator.icon = decorator.icon || decorator.blockEditor.icon, decorator.component = decorator.component || decorator.blockEditor.render);
1406
- }), decorators;
1407
- }
1408
- function validateAnnotations(annotations, visitorContext, problems) {
1409
- return annotations.map((annotation) => {
1410
- if (!isPlainObject(annotation))
1411
- return {
1412
- ...annotation,
1413
- _problems: [error(`Annotation must be an object, got ${getTypeOf(annotation)}`)]
1414
- };
1415
- const { _problems } = visitorContext.visit(annotation, visitorContext), targetType = annotation.type && visitorContext.getType(annotation.type);
1416
- return targetType && !isJSONTypeOf(targetType, "object", visitorContext) && _problems.push(
1417
- error(
1418
- `Annotation cannot have type "${annotation.type}" - annotation types must inherit from object`
1419
- )
1420
- ), typeof annotation.blockEditor < "u" && (problems.push(
1421
- warning(
1422
- 'Annotation has deprecated key "blockEditor", please refer to the documentation on how to configure the block type for version 3.',
1423
- HELP_IDS.DEPRECATED_BLOCKEDITOR_KEY
1424
- )
1425
- ), annotation.icon = annotation.icon || annotation.blockEditor.icon, annotation.blockEditor?.render && !annotation.components?.annotation && (annotation.components = annotation.components || {}, annotation.components.annotation = annotation.components.annotation || annotation.blockEditor.render)), { ...annotation, _problems };
1426
- });
1427
- }
1428
- function validateMembers(members, visitorContext, problems) {
1429
- if (!Array.isArray(members)) {
1430
- problems.push(error(`"of" declaration should be an array, got ${getTypeOf(members)}`));
1431
- return;
1432
- }
1433
- return members.map((member) => {
1434
- const { _problems } = visitorContext.visit(member, visitorContext);
1435
- if (member.type === "object" && member.name && visitorContext.getType(member.name))
1436
- return {
1437
- ...member,
1438
- _problems: [
1439
- warning(
1440
- `Found array member declaration with the same name as the global schema type "${member.name}". It's recommended to use a unique name to avoid possibly incompatible data types that shares the same name.`,
1441
- HELP_IDS.ARRAY_OF_TYPE_GLOBAL_TYPE_CONFLICT
1442
- )
1443
- ]
1444
- };
1445
- let type = member;
1446
- for (; type && !type.jsonType; )
1447
- type = visitorContext.getType(type.type);
1448
- const nonObjectCoreTypes = coreTypeNames.filter((n) => !supportedBuiltInObjectTypes.includes(n));
1449
- return (
1450
- // Must be object-like type (to validate hoisted types)
1451
- type && type.jsonType !== "object" || // Can't be a core type, or core object type that isn't supported (like 'span')
1452
- nonObjectCoreTypes.some((coreName) => coreName === member.type) ? {
1453
- ...member,
1454
- _problems: [
1455
- error(
1456
- `Block member types must be a supported object-like type. The following built-in types are supported: '${supportedBuiltInObjectTypes.join(
1457
- "', '"
1458
- )}'. You can also use shorthands for previously defined object types like {type: 'myObjectType'}`,
1459
- HELP_IDS.ARRAY_OF_TYPE_BUILTIN_TYPE_CONFLICT
1460
- )
1461
- ]
1462
- } : { ...member, _problems }
1463
- );
1464
- });
1465
- }
1466
- function validateNonObjectFieldsProp(typeDef, visitorContext) {
1467
- if (!("fields" in typeDef))
1468
- return [];
1469
- let type = typeDef;
1470
- for (; type && !type.jsonType; )
1471
- type = visitorContext.getType(type.type);
1472
- return type && type.jsonType !== "object" ? [error('Type has propery "fields", but is not an object/document type.')] : [];
1473
- }
1474
- const quote = (str) => `"${str}"`;
1475
- function validateTypeName(typeName, visitorContext) {
1476
- const possibleTypeNames = visitorContext.getTypeNames();
1477
- if (!typeName)
1478
- return [error("Type is missing a type.", HELP_IDS.TYPE_MISSING_TYPE)];
1479
- if (typeof typeName != "string")
1480
- return [
1481
- error(
1482
- 'Type has an invalid "type"-property - should be a string.',
1483
- HELP_IDS.TYPE_MISSING_TYPE
1484
- )
1485
- ];
1486
- if (!possibleTypeNames.includes(typeName)) {
1487
- const suggestions = possibleTypeNames.map((possibleTypeName) => [leven(typeName, possibleTypeName), possibleTypeName]).filter(([distance]) => distance < 3).map(([_, name]) => name), suggestion = suggestions.length > 0 ? ` Did you mean ${humanizeList(suggestions.map(quote), { conjunction: "or" })}?` : "";
1488
- return [error(`Unknown type: ${typeName}.${suggestion}`)];
1489
- }
1490
- return [];
1491
- }
1492
- function validateDeprecatedProperties(type) {
1493
- const warnings = [];
1494
- return type?.inputComponent && warnings.push(
1495
- warning('The "inputComponent" property is deprecated. Use "components.input" instead.')
1496
- ), type?.preview?.component && warnings.push(
1497
- warning('The "preview.component" property is deprecated. Use "components.preview" instead.')
1498
- ), type?.diffComponent && warnings.push(
1499
- warning('The "diffComponent" property is deprecated. Use "components.diff" instead.')
1500
- ), type?.options?.editModal && warnings.push(
1501
- warning('The "options.editModal" property is deprecated. Use "options.modal" instead.')
1502
- ), type?.options?.isHighlighted && warnings.push(
1503
- warning(
1504
- 'The "options.isHighlighted" property is deprecated. You can put fields behind a collapsed fieldset if you want to hide them from plain sight.'
1505
- )
1506
- ), warnings;
1507
- }
1508
- var common = (typeDef, visitorContext) => ({
1509
- ...typeDef,
1510
- _problems: [
1511
- ...validateTypeName(typeDef.type, visitorContext),
1512
- ...validateNonObjectFieldsProp(typeDef, visitorContext),
1513
- ...validateDeprecatedProperties(typeDef)
1514
- ].filter(Boolean)
1515
- });
1516
- function normalizeToProp$2(typeDef) {
1517
- return Array.isArray(typeDef.to) ? typeDef.to : typeDef.to ? [typeDef.to] : typeDef.to;
1518
- }
1519
- const VALID_DATASET = /^[a-z0-9~][-_a-z0-9]+$/;
1520
- function isValidDatasetName(name) {
1521
- return name.length >= 2 && name.toLowerCase() === name && VALID_DATASET.test(name) || `The provided dataset "${name}" doesn't look like a valid dataset. Dataset names must be more than 2 characters, can only contain lowercase characters, numbers, underscores and dashes and can not start with a dash or an underscore`;
1522
- }
1523
- var crossDatasetReference = (typeDef, visitorContext) => {
1524
- const isValidTo = Array.isArray(typeDef.to) || isPlainObject(typeDef.to), normalizedTo = normalizeToProp$2(typeDef), problems = flatten([
1525
- isValidTo ? getDupes(normalizedTo, (t) => `${t.name};${t.type}`).map(
1526
- (dupes) => error(
1527
- `Found ${dupes.length} members with same type, but not unique names "${dupes[0].type}" in reference. This makes it impossible to tell their values apart and you should consider naming them`,
1528
- HELP_IDS.CROSS_DATASET_REFERENCE_INVALID
1529
- )
1530
- ) : error(
1531
- 'The cross dataset reference type is missing or having an invalid value for the required "to" property. It should be an array of accepted types.',
1532
- HELP_IDS.CROSS_DATASET_REFERENCE_INVALID
1533
- )
1534
- ]);
1535
- if (isValidTo && normalizedTo.length === 0 && problems.push(
1536
- error(
1537
- 'The cross dataset reference type should define at least one referenced type. Please check the "to" property.',
1538
- HELP_IDS.CROSS_DATASET_REFERENCE_INVALID
1539
- )
1540
- ), normalizedTo.forEach((crossDatasetTypeDef, index) => {
1541
- crossDatasetTypeDef.type || problems.push(
1542
- error(
1543
- `The referenced type at index ${index} must be named. Specify the name of the type you want to create references to.`,
1544
- HELP_IDS.CROSS_DATASET_REFERENCE_INVALID
1545
- )
1546
- ), isPlainObject(crossDatasetTypeDef.preview) || problems.push(
1547
- error(
1548
- `Missing required preview config for the referenced type "${crossDatasetTypeDef.type || "<unknown type>"}"`,
1549
- HELP_IDS.CROSS_DATASET_REFERENCE_INVALID
1550
- )
1551
- );
1552
- }), typeof typeDef.dataset == "string") {
1553
- const datasetValidation = isValidDatasetName(typeDef.dataset);
1554
- datasetValidation !== !0 && problems.push(error(datasetValidation, HELP_IDS.CROSS_DATASET_REFERENCE_INVALID));
1555
- } else
1556
- problems.push(
1557
- error(
1558
- "A cross dataset reference must specify a `dataset`",
1559
- HELP_IDS.CROSS_DATASET_REFERENCE_INVALID
1560
- )
1561
- );
1562
- return typeDef.studioUrl && typeof typeDef.studioUrl != "function" && problems.push(
1563
- error(
1564
- 'The "studioUrl" property on a cross dataset reference must be a function taking "{id, type}" as argument and returning a studio url.',
1565
- HELP_IDS.CROSS_DATASET_REFERENCE_INVALID
1566
- )
1567
- ), problems.push(...getOptionErrors$2(typeDef)), {
1568
- ...typeDef,
1569
- _problems: problems
1570
- };
1571
- };
1572
- function getOptionErrors$2(typeDef) {
1573
- const { options } = typeDef, problems = [];
1574
- return problems.push(
1575
- ...["filter", "filterParams"].filter((key) => key in typeDef).map(
1576
- (key) => error(
1577
- `\`${key}\` is not allowed on a reference type definition - did you mean \`options.${key}\`?`,
1578
- HELP_IDS.REFERENCE_INVALID_OPTIONS_LOCATION
1579
- )
1580
- )
1581
- ), options ? isPlainObject(options) ? typeof options.filter == "function" && typeof options.filterParams < "u" ? problems.concat(
1582
- error(
1583
- "`filterParams` cannot be used if `filter` is a function. Either statically define `filter` as a string, or return `params` from the `filter`-function.",
1584
- HELP_IDS.REFERENCE_INVALID_FILTER_PARAMS_COMBINATION
1585
- )
1586
- ) : typeof options.filter == "function" || !options.filter && !options.filterParams ? problems : typeof options.filter != "string" ? problems.concat(
1587
- error(`If set, \`filter\` must be a string. Got ${typeof options.filter}`)
1588
- ) : typeof options.filterParams < "u" && !isPlainObject(options.filterParams) ? problems.concat(error("If set, `filterParams` must be an object.")) : options.filterParams ? problems.concat(
1589
- Object.keys(options.filterParams).filter((key) => key.startsWith("__") || key.startsWith("$")).map((key) => error(`Filter parameter cannot be prefixed with "$" or "__". Got ${key}".`))
1590
- ) : problems : problems.concat(
1591
- error(
1592
- "The reference type expects `options` to be an object",
1593
- HELP_IDS.REFERENCE_INVALID_OPTIONS
1594
- )
1595
- ) : problems;
1596
- }
1597
- const REACT_SYM_RE = /^Symbol\(react\..+\)$/;
1598
- function isComponentLike(value) {
1599
- return typeof value == "function" || typeof value?.$$typeof == "symbol" && REACT_SYM_RE.test(String(value?.$$typeof));
1600
- }
1601
- function validateComponent(typeDef) {
1602
- const components = "components" in typeDef ? typeDef.components : !1;
1603
- if (!components)
1604
- return [];
1605
- const warnings = [];
1606
- return components.input && !isComponentLike(components.input) && warnings.push(
1607
- warning(
1608
- `The \`components.input\` property is set but does not appear to be a valid React component (expected a function, but saw ${inspect(
1609
- components.input
1610
- )}). If you have imported a custom input component, please verify that you have imported the correct named/default export.`
1611
- )
1612
- ), components.field && !isComponentLike(components.field) && warnings.push(
1613
- warning(
1614
- `The \`components.field\` property is set but does not appear to be a valid React component (expected a function, but saw ${inspect(
1615
- components.field
1616
- )}). If you have imported a custom field component, please verify that you have imported the correct named/default export.`
1617
- )
1618
- ), components.item && !isComponentLike(components.item) && warnings.push(
1619
- warning(
1620
- `The \`components.item\` property is set but does not appear to be a valid React component (expected a function, but saw ${inspect(
1621
- components.item
1622
- )}). If you have imported a custom item component, please verify that you have imported the correct named/default export.`
1623
- )
1624
- ), components.preview && !isComponentLike(components.preview) && warnings.push(
1625
- warning(
1626
- `The \`components.preview\` property is set but does not appear to be a valid React component (expected a function, but saw ${inspect(
1627
- components.preview
1628
- )}). If you have imported a custom preview component, please verify that you have imported the correct named/default export.`
1629
- )
1630
- ), warnings;
1631
- }
1632
- const VALID_FIELD_RE = /^[A-Za-z]+[0-9A-Za-z_]*$/, CONVENTIONAL_FIELD_RE = /^[A-Za-z_]+[0-9A-Za-z_]*$/;
1633
- function validateFieldName(name) {
1634
- return typeof name != "string" ? [
1635
- error(
1636
- `Field names must be strings. Saw "${inspect(name)}"`,
1637
- HELP_IDS.OBJECT_FIELD_NAME_INVALID
1638
- )
1639
- ] : name.startsWith("_") ? [
1640
- error(
1641
- `Invalid field name "${name}". Field names cannot start with underscores "_" as it's reserved for system fields.`,
1642
- HELP_IDS.OBJECT_FIELD_NAME_INVALID
1643
- )
1644
- ] : VALID_FIELD_RE.test(name) ? CONVENTIONAL_FIELD_RE.test(name) ? [] : [
1645
- warning(
1646
- "Thats an interesting field name for sure! But it is... how to put it... a bit... unconventional? It may be wise to keep special characters out of field names for easier access later on."
1647
- ),
1648
- HELP_IDS.OBJECT_FIELD_NAME_INVALID
1649
- ] : [
1650
- error(
1651
- `Invalid field name: "${name}". Fields can only contain characters from A-Z, numbers and underscores and should not start with a number (must pass the regular expression ${String(
1652
- VALID_FIELD_RE
1653
- )}).`,
1654
- HELP_IDS.OBJECT_FIELD_NAME_INVALID
1655
- )
1656
- ];
1657
- }
1658
- function validateField(field, _visitorContext) {
1659
- if (!isPlainObject(field))
1660
- return [
1661
- error(
1662
- `Incorrect type for field definition - should be an object, saw ${inspect(field)}`,
1663
- HELP_IDS.OBJECT_FIELD_DEFINITION_INVALID_TYPE
1664
- )
1665
- ];
1666
- const problems = [];
1667
- return problems.push(
1668
- ..."name" in field ? validateFieldName(field.name) : [error("Missing field name", HELP_IDS.OBJECT_FIELD_NAME_INVALID)]
1669
- ), problems.push(...validateComponent(field)), problems;
1670
- }
1671
- function getDuplicateFields(array2) {
1672
- const dupes = {};
1673
- return array2.forEach((field) => {
1674
- dupes[field.name] || (dupes[field.name] = []), dupes[field.name].push(field);
1675
- }), Object.keys(dupes).map((fieldName) => dupes[fieldName].length > 1 ? dupes[fieldName] : null).filter(Boolean);
1676
- }
1677
- function validateFields(fields, options = { allowEmpty: !1 }) {
1678
- const problems = [];
1679
- if (!Array.isArray(fields))
1680
- return [
1681
- error(
1682
- `The "fields" property must be an array of fields. Instead saw "${typeof fields}"`,
1683
- HELP_IDS.OBJECT_FIELDS_INVALID
1684
- )
1685
- ];
1686
- const fieldsWithNames = fields.filter((field) => typeof field.name == "string");
1687
- getDuplicateFields(fieldsWithNames).forEach((dupes) => {
1688
- problems.push(
1689
- error(
1690
- `Found ${dupes.length} fields with name "${dupes[0].name}" in object`,
1691
- HELP_IDS.OBJECT_FIELD_NOT_UNIQUE
1692
- )
1693
- );
1694
- }), fields.length === 0 && !options.allowEmpty && problems.push(error("Object should have at least one field", HELP_IDS.OBJECT_FIELDS_INVALID));
1695
- const standaloneBlockFields = fields.filter((field) => field.type === "block").map((field) => `"${field.name}"`);
1696
- if (standaloneBlockFields.length > 0) {
1697
- const fmtFields = standaloneBlockFields.join(", ");
1698
- problems.push(
1699
- error(
1700
- `Invalid standalone block field(s) ${fmtFields}. Block content must be defined as an array of blocks`,
1701
- HELP_IDS.STANDALONE_BLOCK_TYPE
1702
- )
1703
- );
1704
- }
1705
- return problems;
1706
- }
1707
- function validatePreview(preview) {
1708
- return isPlainObject(preview) ? typeof preview.prepare < "u" && typeof preview.prepare != "function" ? [
1709
- error(
1710
- `The "preview.prepare" property must be a function, instead saw "${typeof preview.prepare}"`
1711
- )
1712
- ] : preview.select ? isPlainObject(preview.select) ? Object.keys(preview.select).reduce((errs, key) => typeof preview.select[key] == "string" ? errs : errs.concat(
1713
- error(
1714
- `The key "${key}" of "preview.select" must be a string, instead saw "${typeof preview.select[key]}"`
1715
- )
1716
- ), []) : [
1717
- error(
1718
- `The "preview.select" property must be an object, instead saw "${typeof preview.prepare}"`
1719
- )
1720
- ] : [] : [error(`The "preview" property must be an object, instead saw "${typeof preview}"`)];
1721
- }
1722
- var object = (typeDef, visitorContext) => {
1723
- let problems = validateFields(typeDef.fields), preview = typeDef.preview;
1724
- if (preview) {
1725
- const previewErrors = validatePreview(typeDef.preview);
1726
- problems = problems.concat(previewErrors), preview = previewErrors.some((err) => err.severity === "error") ? {} : preview;
1727
- }
1728
- return typeDef.type !== "document" && typeDef.type !== "object" && typeof typeDef.initialValue < "u" && problems.push(
1729
- error('The "initialValue" property is currently only supported for document & object types.')
1730
- ), {
1731
- ...typeDef,
1732
- preview,
1733
- fields: (Array.isArray(typeDef.fields) ? typeDef.fields : []).map((field, index) => {
1734
- const { name, ...fieldTypeDef } = field, { _problems, ...fieldType } = visitorContext.visit(fieldTypeDef, index);
1735
- return {
1736
- name,
1737
- ...fieldType,
1738
- _problems: validateField(field).concat(_problems || [])
1739
- };
1740
- }),
1741
- _problems: problems
1742
- };
1743
- }, documentVisitor = (typeDefinition, visitorContext) => {
1744
- const typeDef = object(typeDefinition, visitorContext), { initialValue, initialValues } = typeDef;
1745
- return typeof initialValue < "u" && !isPlainObject(initialValue) && typeof initialValue != "function" && typeDef._problems.push(
1746
- error('The "initialValue" property must be either a plain object or a function')
1747
- ), typeof initialValues < "u" && typeDef._problems.push(error('Found property "initialValues" - did you mean "initialValue"?')), typeDef;
1748
- }, file = (typeDef, visitorContext) => {
1749
- const problems = [], fields = typeDef.fields;
1750
- fields && problems.push(...validateFields(fields, { allowEmpty: !0 }));
1751
- const invalidFieldNames = Array.isArray(fields) ? fields?.filter((field) => field.name === "asset") : [];
1752
- return typeDef.options && typeof typeDef.options.metadata < "u" && !Array.isArray(typeDef.options.metadata) ? problems.push(
1753
- error(
1754
- "Invalid type for file `metadata` field - must be an array of strings",
1755
- HELP_IDS.ASSET_METADATA_FIELD_INVALID
1756
- )
1757
- ) : invalidFieldNames.length > 0 && problems.push(error("The name `asset` is not a valid field name for type `file`.")), {
1758
- ...typeDef,
1759
- fields: (Array.isArray(fields) ? fields : []).map((field, index) => {
1760
- const { name, ...fieldTypeDef } = field, { _problems, ...fieldType } = visitorContext.visit(fieldTypeDef, index);
1761
- return {
1762
- name,
1763
- ...fieldType,
1764
- _problems: validateField(field).concat(_problems || [])
1765
- };
1766
- }),
1767
- _problems: problems
1768
- };
1769
- };
1770
- function normalizeToProp$1(typeDef) {
1771
- return Array.isArray(typeDef.to) ? typeDef.to : typeDef.to ? [typeDef.to] : [];
1772
- }
1773
- function isValidResourceType(resourceType) {
1774
- return resourceType ? resourceType != "media-library" && resourceType != "dataset" ? 'The resource type must be either "media-library" or "dataset"' : !0 : "The resource type must be a non-empty string";
1775
- }
1776
- function isValidResourceId(resourceType, resourceId) {
1777
- return resourceId ? resourceType === "dataset" ? resourceId.split(".").length !== 2 ? 'The resource ID for a dataset reference must be on the form "<projectId>.<datasetName>"' : !0 : resourceType === "media-library" ? !0 : `Cannot validate resource ID for resource type: ${resourceType}` : "The resource ID must be a non-empty string";
1778
- }
1779
- var globalDocumentReference = (typeDef, visitorContext) => {
1780
- const isValidTo = Array.isArray(typeDef.to) || isPlainObject(typeDef.to), normalizedTo = normalizeToProp$1(typeDef), problems = flatten([
1781
- isValidTo ? getDupes(normalizedTo, (t) => `${t.name};${t.type}`).map(
1782
- (dupes) => error(
1783
- `Found ${dupes.length} members with same type, but not unique names "${dupes[0].type}" in reference. This makes it impossible to tell their values apart and you should consider naming them`,
1784
- HELP_IDS.GLOBAL_DOCUMENT_REFERENCE_INVALID
1785
- )
1786
- ) : error(
1787
- 'The global document reference type is missing or having an invalid value for the required "to" property. It should be an array of accepted types.',
1788
- HELP_IDS.GLOBAL_DOCUMENT_REFERENCE_INVALID
1789
- )
1790
- ]);
1791
- if (isValidTo && normalizedTo.length === 0 && problems.push(
1792
- error(
1793
- 'The global document reference type should define at least one referenced type. Please check the "to" property.',
1794
- HELP_IDS.GLOBAL_DOCUMENT_REFERENCE_INVALID
1795
- )
1796
- ), normalizedTo.forEach((crossDatasetTypeDef, index) => {
1797
- crossDatasetTypeDef.type || problems.push(
1798
- error(
1799
- `The referenced type at index ${index} must be named. Specify the name of the type you want to create references to.`,
1800
- HELP_IDS.GLOBAL_DOCUMENT_REFERENCE_INVALID
1801
- )
1802
- ), isPlainObject(crossDatasetTypeDef.preview) || problems.push(
1803
- error(
1804
- `Missing required preview config for the referenced type "${crossDatasetTypeDef.type || "<unknown type>"}"`,
1805
- HELP_IDS.GLOBAL_DOCUMENT_REFERENCE_INVALID
1806
- )
1807
- );
1808
- }), typeof typeDef.resourceType == "string") {
1809
- const validation = isValidResourceType(typeDef.resourceType);
1810
- validation !== !0 && problems.push(error(validation, HELP_IDS.GLOBAL_DOCUMENT_REFERENCE_INVALID));
1811
- } else
1812
- problems.push(
1813
- error(
1814
- "A global document reference must specify a `resourceType`",
1815
- HELP_IDS.GLOBAL_DOCUMENT_REFERENCE_INVALID
1816
- )
1817
- );
1818
- if (typeof typeDef.resourceId == "string") {
1819
- const datasetValidation = isValidResourceId(typeDef.resourceType, typeDef.resourceId);
1820
- datasetValidation !== !0 && problems.push(error(datasetValidation, HELP_IDS.GLOBAL_DOCUMENT_REFERENCE_INVALID));
1821
- } else
1822
- problems.push(
1823
- error(
1824
- "A global document reference must specify a `resourceId`",
1825
- HELP_IDS.GLOBAL_DOCUMENT_REFERENCE_INVALID
1826
- )
1827
- );
1828
- return typeDef.studioUrl && typeof typeDef.studioUrl != "function" && typeof typeDef.studioUrl != "string" && problems.push(
1829
- error(
1830
- 'The "studioUrl" property on a global document reference must either be a function taking "{id, type}" as argument and returning a studio url, or a string being the base url pointing to a studio.',
1831
- HELP_IDS.GLOBAL_DOCUMENT_REFERENCE_INVALID
1832
- )
1833
- ), problems.push(...getOptionErrors$1(typeDef)), {
1834
- ...typeDef,
1835
- _problems: problems
1836
- };
1837
- };
1838
- function getOptionErrors$1(typeDef) {
1839
- const { options } = typeDef, problems = [];
1840
- return problems.push(
1841
- ...["filter", "filterParams"].filter((key) => key in typeDef).map(
1842
- (key) => error(
1843
- `\`${key}\` is not allowed on a reference type definition - did you mean \`options.${key}\`?`,
1844
- HELP_IDS.REFERENCE_INVALID_OPTIONS_LOCATION
1845
- )
1846
- )
1847
- ), options ? isPlainObject(options) ? typeof options.filter == "function" && typeof options.filterParams < "u" ? problems.concat(
1848
- error(
1849
- "`filterParams` cannot be used if `filter` is a function. Either statically define `filter` as a string, or return `params` from the `filter`-function.",
1850
- HELP_IDS.REFERENCE_INVALID_FILTER_PARAMS_COMBINATION
1851
- )
1852
- ) : typeof options.filter == "function" || !options.filter && !options.filterParams ? problems : typeof options.filter != "string" ? problems.concat(
1853
- error(`If set, \`filter\` must be a string. Got ${typeof options.filter}`)
1854
- ) : typeof options.filterParams < "u" && !isPlainObject(options.filterParams) ? problems.concat(error("If set, `filterParams` must be an object.")) : options.filterParams ? problems.concat(
1855
- Object.keys(options.filterParams).filter((key) => key.startsWith("__") || key.startsWith("$")).map((key) => error(`Filter parameter cannot be prefixed with "$" or "__". Got ${key}".`))
1856
- ) : problems : problems.concat(
1857
- error(
1858
- "The reference type expects `options` to be an object",
1859
- HELP_IDS.REFERENCE_INVALID_OPTIONS
1860
- )
1861
- ) : problems;
1862
- }
1863
- const autoMeta = ["dimensions", "hasAlpha", "isOpaque"];
1864
- var image = (typeDef, visitorContext) => {
1865
- const problems = [], fields = typeDef.fields;
1866
- fields && problems.push(...validateFields(fields, { allowEmpty: !0 }));
1867
- let options = typeDef.options;
1868
- const metadata = options?.metadata, superfluousMeta = Array.isArray(metadata) ? metadata.filter((meta) => autoMeta.includes(meta)) : [], invalidFieldNames = ["asset", "hotspot", "crop"], fieldsWithInvalidName = Array.isArray(fields) ? fields?.filter((field) => invalidFieldNames.includes(field.name)) : [];
1869
- return typeof metadata < "u" && !Array.isArray(metadata) ? problems.push(
1870
- error(
1871
- "Invalid type for image `metadata` field - must be an array of strings",
1872
- HELP_IDS.ASSET_METADATA_FIELD_INVALID
1873
- )
1874
- ) : superfluousMeta.length > 0 ? (problems.push(
1875
- warning(
1876
- `Image \`metadata\` field contains superfluous properties (they are always included): ${superfluousMeta.join(
1877
- ", "
1878
- )}`
1879
- )
1880
- ), options = { ...options, metadata: metadata.filter((meta) => !autoMeta.includes(meta)) }) : fieldsWithInvalidName.length > 0 && problems.push(
1881
- error(
1882
- `The names \`${invalidFieldNames.join(
1883
- "`, `"
1884
- )}\` are invalid field names for type \`image\`.`
1885
- )
1886
- ), {
1887
- ...typeDef,
1888
- options,
1889
- fields: (Array.isArray(fields) ? fields : []).map((field, index) => {
1890
- const { name, ...fieldTypeDef } = field, { _problems, ...fieldType } = visitorContext.visit(fieldTypeDef, index);
1891
- return {
1892
- name,
1893
- ...fieldType,
1894
- _problems: validateField(field).concat(_problems || [])
1895
- };
1896
- }),
1897
- _problems: problems
1898
- };
1899
- };
1900
- function normalizeToProp(typeDef) {
1901
- return Array.isArray(typeDef.to) ? typeDef.to : typeDef.to ? [typeDef.to] : typeDef.to;
1902
- }
1903
- var reference = (typeDef, visitorContext) => {
1904
- const isValidTo = Array.isArray(typeDef.to) || isPlainObject(typeDef.to), normalizedTo = normalizeToProp(typeDef), problems = flatten([
1905
- isValidTo ? getDupes(normalizedTo, (t) => `${t.name};${t.type}`).map(
1906
- (dupes) => error(
1907
- `Found ${dupes.length} members with same type, but not unique names "${dupes[0].type}" in reference. This makes it impossible to tell their values apart and you should consider naming them`,
1908
- HELP_IDS.REFERENCE_TO_INVALID
1909
- )
1910
- ) : error(
1911
- 'The reference type is missing or having an invalid value for the required "to" property. It should be an array of accepted types.',
1912
- HELP_IDS.REFERENCE_TO_INVALID
1913
- )
1914
- ]);
1915
- return isValidTo && normalizedTo.length === 0 && problems.push(
1916
- error(
1917
- 'The reference type should define at least one accepted type. Please check the "to" property.',
1918
- HELP_IDS.REFERENCE_TO_INVALID
1919
- )
1920
- ), problems.push(...getOptionErrors(typeDef)), {
1921
- ...typeDef,
1922
- to: (isValidTo ? normalizedTo : []).map(visitorContext.visit),
1923
- _problems: problems
1924
- };
1925
- };
1926
- function getOptionErrors(typeDef) {
1927
- const { options } = typeDef, problems = [];
1928
- return problems.push(
1929
- ...["filter", "filterParams"].filter((key) => key in typeDef).map(
1930
- (key) => error(
1931
- `\`${key}\` is not allowed on a reference type definition - did you mean \`options.${key}\`?`,
1932
- HELP_IDS.REFERENCE_INVALID_OPTIONS_LOCATION
1933
- )
1934
- )
1935
- ), options ? isPlainObject(options) ? typeof options.filter == "function" && typeof options.filterParams < "u" ? problems.concat(
1936
- error(
1937
- "`filterParams` cannot be used if `filter` is a function. Either statically define `filter` as a string, or return `params` from the `filter`-function.",
1938
- HELP_IDS.REFERENCE_INVALID_FILTER_PARAMS_COMBINATION
1939
- )
1940
- ) : typeof options.filter == "function" || !options.filter && !options.filterParams ? problems : typeof options.filter != "string" ? problems.concat(
1941
- error(`If set, \`filter\` must be a string. Got ${typeof options.filter}`)
1942
- ) : typeof options.filterParams < "u" && !isPlainObject(options.filterParams) ? problems.concat(error("If set, `filterParams` must be an object.")) : options.filterParams ? problems.concat(
1943
- Object.keys(options.filterParams).filter((key) => key.startsWith("__") || key.startsWith("$")).map((key) => error(`Filter parameter cannot be prefixed with "$" or "__". Got ${key}".`))
1944
- ) : problems : problems.concat(
1945
- error(
1946
- "The reference type expects `options` to be an object",
1947
- HELP_IDS.REFERENCE_INVALID_OPTIONS
1948
- )
1949
- ) : problems;
1950
- }
1951
- var rootType = (typeDef, visitorContext) => {
1952
- const hasName = !!typeDef.name;
1953
- if (!hasName && Object.keys(typeDef).length === 1)
1954
- return {
1955
- ...typeDef,
1956
- _problems: [
1957
- error(
1958
- "Invalid/undefined type declaration, check declaration or the import/export of the schema type.",
1959
- HELP_IDS.TYPE_INVALID
1960
- )
1961
- ]
1962
- };
1963
- const problems = [];
1964
- return looksLikeEsmModule(typeDef) ? problems.push(
1965
- error(
1966
- "Type appears to be an ES6 module imported through CommonJS require - use an import statement or access the `.default` property",
1967
- HELP_IDS.TYPE_IS_ESM_MODULE
1968
- )
1969
- ) : hasName ? visitorContext.isReserved(typeDef.name) && problems.push(
1970
- error(
1971
- `Invalid type name: "${typeDef.name}" is a reserved name.`,
1972
- HELP_IDS.TYPE_NAME_RESERVED
1973
- )
1974
- ) : problems.push(error("Missing type name", HELP_IDS.TYPE_MISSING_NAME)), visitorContext.isDuplicate(typeDef.name) && problems.push(
1975
- error(
1976
- `Invalid type name: A type with name "${typeDef.name}" is already defined in the schema.`
1977
- )
1978
- ), problems.push(...validateComponent(typeDef)), "title" in typeDef && typeof typeDef.title != "string" && problems.push(warning("Type title is not a string.", HELP_IDS.TYPE_TITLE_INVALID)), {
1979
- ...typeDef,
1980
- _problems: problems
1981
- };
1982
- };
1983
- function looksLikeEsmModule(typeDef) {
1984
- return !typeDef.name && typeDef.default && (typeDef.default.name || typeDef.default.title);
1985
- }
1986
- var slug = (typeDef, visitorContext) => {
1987
- const problems = [];
1988
- return typeDef.options && typeDef.options.slugifyFn && (problems.push(
1989
- warning(
1990
- 'Heads up! The "slugifyFn" option has been renamed to "slugify".',
1991
- HELP_IDS.SLUG_SLUGIFY_FN_RENAMED
1992
- )
1993
- ), typeDef.options.slugify = typeDef.options.slugifyFn), {
1994
- ...typeDef,
1995
- _problems: problems
1996
- };
1997
- };
1998
- const typeVisitors = {
1999
- array,
2000
- object,
2001
- slug,
2002
- file,
2003
- image,
2004
- block: validateBlockType,
2005
- document: documentVisitor,
2006
- reference,
2007
- crossDatasetReference,
2008
- globalDocumentReference
2009
- }, getNoopVisitor = (visitorContext) => (schemaDef) => ({
2010
- name: `<unnamed_type_@_index_${visitorContext.index}>`,
2011
- ...schemaDef,
2012
- _problems: []
2013
- });
2014
- function combine(...visitors) {
2015
- return (schemaType, visitorContext) => visitors.reduce(
2016
- (result, visitor) => {
2017
- const res = visitor(result, visitorContext);
2018
- return {
2019
- ...res,
2020
- _problems: result._problems.concat(res._problems)
2021
- };
2022
- },
2023
- { _problems: [], ...schemaType }
2024
- );
2025
- }
2026
- function validateSchema(schemaTypes, {
2027
- transformTypeVisitors = (visitors) => visitors,
2028
- transformCommonVisitors = (visitors) => visitors
2029
- } = {}) {
2030
- return traverseSanitySchema(schemaTypes, (schemaDef, visitorContext) => {
2031
- const typeVisitor = schemaDef && schemaDef.type && transformTypeVisitors(typeVisitors)[schemaDef.type] || getNoopVisitor(visitorContext), commonVisitors = transformCommonVisitors([common]);
2032
- return visitorContext.isRoot ? combine(rootType, ...commonVisitors, typeVisitor)(schemaDef, visitorContext) : combine(...commonVisitors, typeVisitor)(schemaDef, visitorContext);
2033
- });
2034
- }
2035
- class ValidationError extends Error {
2036
- problems;
2037
- constructor(problems) {
2038
- super("ValidationError"), this.problems = problems, this.name = "ValidationError";
2039
- }
2040
- }
2041
- const builtinSchema = Schema.compile({
2042
- name: "studio",
2043
- types: builtinTypes
2044
- });
2045
- function createSchemaFromManifestTypes(schemaDef) {
2046
- const validated = validateSchema(schemaDef.types).getTypes(), problems = groupProblems(validated).filter(
2047
- (group) => group.problems.some((problem) => problem.severity === "error")
2048
- );
2049
- if (problems.length > 0)
2050
- throw new ValidationError(problems);
2051
- return Schema.compile({
2052
- name: schemaDef.name,
2053
- types: schemaDef.types.map(coerceType).filter(Boolean),
2054
- parent: builtinSchema
2055
- });
2056
- }
2057
- function coerceType(obj) {
2058
- if (!isObject(obj)) return;
2059
- const typ = cloneDeep(obj);
2060
- return traverse(typ), typ;
2061
- }
2062
- function traverse(obj) {
2063
- if (isObject(obj)) {
2064
- if (Array.isArray(obj)) {
2065
- obj.forEach(traverse);
2066
- return;
2067
- }
2068
- for (const v of Object.values(obj))
2069
- traverse(v);
2070
- coerceValidation(obj);
2071
- }
2072
- }
2073
- function coerceValidation(val) {
2074
- if (!isObject(val) || !("validation" in val)) return;
2075
- const manifestValidation = Array.isArray(val.validation) ? val.validation : [val.validation];
2076
- val.validation = manifestValidation.map((group) => {
2077
- if (isObject(group))
2078
- return (baseRule) => {
2079
- let rule = baseRule;
2080
- const level = "level" in group ? group.level : void 0, rules = "rules" in group ? group.rules : void 0, message = "message" in group ? group.message : void 0;
2081
- if (!(!rules || !Array.isArray(rules))) {
2082
- isValidLevel(level) && (message === void 0 || typeof message == "string") && (rule = rule[level](message));
2083
- for (const ruleSpec of rules)
2084
- rule = applyRuleSpec(rule, ruleSpec);
2085
- return rule;
2086
- }
2087
- };
2088
- }).filter(Boolean);
2089
- }
2090
- function coerceConstraintRule(val) {
2091
- if (isObject(val))
2092
- return Array.isArray(val) ? val.map(coerceConstraintRule).filter(Boolean) : (baseRule) => {
2093
- let rule = baseRule;
2094
- const rules = "_rules" in val ? val._rules : void 0, level = "_level" in val ? val._level : void 0, message = "_message" in val ? val._message : void 0;
2095
- if (!(!rules || !Array.isArray(rules))) {
2096
- typeof level == "string" && (rule = rule[level](message));
2097
- for (const ruleSpec of rules)
2098
- rule = applyRuleSpec(rule, ruleSpec);
2099
- return rule;
2100
- }
2101
- };
2102
- }
2103
- function applyRuleSpec(rule, ruleSpec) {
2104
- if (!ruleSpec || typeof ruleSpec != "object")
2105
- return rule;
2106
- const flag = "flag" in ruleSpec ? ruleSpec.flag : void 0, constraint = "constraint" in ruleSpec ? ruleSpec.constraint : void 0;
2107
- switch (flag) {
2108
- case "presence":
2109
- if (constraint === "required")
2110
- return rule.required();
2111
- if (constraint === "optional")
2112
- return rule.optional();
2113
- break;
2114
- case "type":
2115
- if (typeof constraint == "string")
2116
- return rule.type(constraint);
2117
- break;
2118
- case "min":
2119
- if (typeof constraint == "number" || typeof constraint == "string")
2120
- return rule.min(constraint);
2121
- break;
2122
- case "max":
2123
- if (typeof constraint == "number" || typeof constraint == "string")
2124
- return rule.max(constraint);
2125
- break;
2126
- case "length":
2127
- if (typeof constraint == "number")
2128
- return rule.length(constraint);
2129
- break;
2130
- case "integer":
2131
- return rule.integer();
2132
- case "email":
2133
- return rule.email();
2134
- case "unique":
2135
- return rule.unique();
2136
- case "reference":
2137
- return rule.reference();
2138
- case "precision":
2139
- if (typeof constraint == "number")
2140
- return rule.precision(constraint);
2141
- break;
2142
- case "positive":
2143
- return rule.positive();
2144
- case "negative":
2145
- return rule.negative();
2146
- case "greaterThan":
2147
- if (typeof constraint == "number")
2148
- return rule.greaterThan(constraint);
2149
- break;
2150
- case "lessThan":
2151
- if (typeof constraint == "number")
2152
- return rule.lessThan(constraint);
2153
- break;
2154
- case "stringCasing":
2155
- if (constraint === "uppercase")
2156
- return rule.uppercase();
2157
- if (constraint === "lowercase")
2158
- return rule.lowercase();
2159
- break;
2160
- case "valid":
2161
- if (Array.isArray(constraint))
2162
- return rule.valid(constraint);
2163
- break;
2164
- case "regex":
2165
- if (isObject(constraint) && "pattern" in constraint && (typeof constraint.pattern == "string" || constraint.pattern instanceof RegExp)) {
2166
- const options = {};
2167
- "name" in constraint && typeof constraint.name == "string" && (options.name = constraint.name), "invert" in constraint && (options.invert = constraint.invert);
2168
- const pattern = typeof constraint.pattern == "string" ? stringToRegExp(constraint.pattern) : constraint.pattern;
2169
- return rule.regex(pattern, options);
2170
- }
2171
- break;
2172
- case "uri":
2173
- if (isObject(constraint) && "options" in constraint)
2174
- return rule.uri(constraint.options);
2175
- break;
2176
- case "assetRequired":
2177
- return rule.assetRequired();
2178
- case "all":
2179
- return rule.all(coerceConstraintRule(constraint));
2180
- case "either":
2181
- return rule.either(coerceConstraintRule(constraint));
2182
- case "custom":
2183
- if (constraint === void 0) return rule.custom(() => !0);
2184
- if (typeof constraint == "function") return rule.custom(constraint);
2185
- break;
2186
- case "media":
2187
- if (constraint === void 0) return rule.media(() => !0);
2188
- if (typeof constraint == "function") return rule.media(constraint);
2189
- break;
2190
- }
2191
- return rule;
2192
- }
2193
- const isValidLevel = (level) => !!level && typeof level == "string" && ["error", "warning", "info"].includes(level);
2194
- function stringToRegExp(str) {
2195
- const match = str.match(/^\/(.*)\/([gimuy]*)$/);
2196
- return match ? new RegExp(match[1], match[2]) : new RegExp(str);
2197
- }
2198
- const documentDefaultFields = (typeName) => ({
2199
- _id: {
2200
- type: "objectAttribute",
2201
- value: { type: "string" }
2202
- },
2203
- _type: {
2204
- type: "objectAttribute",
2205
- value: { type: "string", value: typeName }
2206
- },
2207
- _createdAt: {
2208
- type: "objectAttribute",
2209
- value: { type: "string" }
2210
- },
2211
- _updatedAt: {
2212
- type: "objectAttribute",
2213
- value: { type: "string" }
2214
- },
2215
- _rev: {
2216
- type: "objectAttribute",
2217
- value: { type: "string" }
2218
- }
2219
- }), typesMap = /* @__PURE__ */ new Map([
2220
- ["text", { type: "string" }],
2221
- ["url", { type: "string" }],
2222
- ["datetime", { type: "string" }],
2223
- ["date", { type: "string" }],
2224
- ["boolean", { type: "boolean" }],
2225
- ["email", { type: "string" }]
2226
- ]);
2227
- function extractSchema(schemaDef, extractOptions = {}) {
2228
- const inlineFields = /* @__PURE__ */ new Set(), documentTypes = /* @__PURE__ */ new Map(), schema = [], sortedSchemaTypeNames = sortByDependencies(schemaDef);
2229
- sortedSchemaTypeNames.forEach((typeName) => {
2230
- const schemaType = schemaDef.get(typeName);
2231
- if (schemaType === void 0)
2232
- return;
2233
- const base = convertBaseType(schemaType);
2234
- base !== null && (base.type === "type" && inlineFields.add(schemaType), base.type === "document" && documentTypes.set(typeName, base), schema.push(base));
2235
- });
2236
- function convertBaseType(schemaType) {
2237
- let typeName;
2238
- if (schemaType.type ? typeName = schemaType.type.name : "jsonType" in schemaType && (typeName = schemaType.jsonType), typeName === "document" && isObjectType(schemaType)) {
2239
- const defaultAttributes = documentDefaultFields(schemaType.name), object2 = createObject(schemaType);
2240
- return object2.type === "unknown" ? null : {
2241
- name: schemaType.name,
2242
- type: "document",
2243
- attributes: {
2244
- ...defaultAttributes,
2245
- ...object2.attributes
2246
- }
2247
- };
2248
- }
2249
- const value = convertSchemaType(schemaType);
2250
- return value.type === "unknown" ? null : value.type === "object" ? (value.attributes = {
2251
- _type: {
2252
- type: "objectAttribute",
2253
- value: {
2254
- type: "string",
2255
- value: schemaType.name
2256
- }
2257
- },
2258
- ...value.attributes
2259
- }, {
2260
- name: schemaType.name,
2261
- type: "type",
2262
- value
2263
- }) : {
2264
- name: schemaType.name,
2265
- type: "type",
2266
- value
2267
- };
2268
- }
2269
- function convertSchemaType(schemaType) {
2270
- if (inlineFields.has(schemaType.type))
2271
- return { type: "inline", name: schemaType.type.name };
2272
- if (schemaType.type?.name && sortedSchemaTypeNames.indexOf(schemaType.type?.name) > -1)
2273
- return { type: "inline", name: schemaType.name };
2274
- if (isStringType(schemaType))
2275
- return createStringTypeNodeDefintion(schemaType);
2276
- if (isNumberType(schemaType))
2277
- return createNumberTypeNodeDefintion(schemaType);
2278
- if (schemaType.type && typesMap.has(schemaType.type.name))
2279
- return typesMap.get(schemaType.type.name);
2280
- if (isCrossDatasetReferenceType(schemaType))
2281
- return { type: "unknown" };
2282
- if (isGlobalDocumentReferenceType(schemaType))
2283
- return { type: "unknown" };
2284
- if (isReferenceType(schemaType))
2285
- return createReferenceTypeNodeDefintion(schemaType);
2286
- if (isArrayType(schemaType))
2287
- return createArray(schemaType);
2288
- if (isObjectType(schemaType))
2289
- return createObject(schemaType);
2290
- if (lastType(schemaType)?.name === "document") {
2291
- const doc = documentTypes.get(schemaType.name);
2292
- return doc === void 0 ? { type: "unknown" } : { type: "object", attributes: doc?.attributes };
2293
- }
2294
- throw new Error(`Type "${schemaType.name}" not found`);
2295
- }
2296
- function createObject(schemaType) {
2297
- const attributes = {}, fields = gatherFields(schemaType);
2298
- for (const field of fields) {
2299
- const fieldIsRequired = isFieldRequired(field), value = convertSchemaType(field.type);
2300
- if (value === null)
2301
- continue;
2302
- hasAssetRequired(field) && value.type === "object" && (value.attributes.asset.optional = !1);
2303
- const optional = extractOptions.enforceRequiredFields ? fieldIsRequired === !1 : !0;
2304
- attributes[field.name] = {
2305
- type: "objectAttribute",
2306
- value,
2307
- optional
2308
- };
2309
- }
2310
- return Object.keys(attributes).length === 0 ? { type: "unknown" } : (schemaType.type?.name !== "document" && schemaType.name !== "object" && (attributes._type = {
2311
- type: "objectAttribute",
2312
- value: {
2313
- type: "string",
2314
- value: schemaType.name
2315
- }
2316
- }), {
2317
- type: "object",
2318
- attributes
2319
- });
2320
- }
2321
- function createArray(arraySchemaType) {
2322
- const of = [];
2323
- for (const item of arraySchemaType.of) {
2324
- const field = convertSchemaType(item);
2325
- field.type === "inline" ? of.push({
2326
- type: "object",
2327
- attributes: {
2328
- _key: createKeyField()
2329
- },
2330
- rest: field
2331
- }) : (field.type === "object" && (field.rest = {
2332
- type: "object",
2333
- attributes: {
2334
- _key: createKeyField()
2335
- }
2336
- }), of.push(field));
2337
- }
2338
- return of.length === 0 ? { type: "null" } : {
2339
- type: "array",
2340
- of: of.length > 1 ? {
2341
- type: "union",
2342
- of
2343
- } : of[0]
2344
- };
2345
- }
2346
- return schema;
2347
- }
2348
- function createKeyField() {
2349
- return {
2350
- type: "objectAttribute",
2351
- value: {
2352
- type: "string"
2353
- }
2354
- };
2355
- }
2356
- function isFieldRequired(field) {
2357
- const { validation } = field.type;
2358
- if (!validation)
2359
- return !1;
2360
- const rules = Array.isArray(validation) ? validation : [validation];
2361
- for (const rule of rules) {
2362
- let required = !1;
2363
- const proxy = new Proxy(
2364
- {},
2365
- {
2366
- get: (target, methodName) => () => (methodName === "required" && (required = !0), proxy)
2367
- }
2368
- );
2369
- if (typeof rule == "function" && (rule(proxy), required) || typeof rule == "object" && rule !== null && "_required" in rule && rule._required === "required")
2370
- return !0;
2371
- }
2372
- return !1;
2373
- }
2374
- function hasAssetRequired(field) {
2375
- const { validation } = field.type;
2376
- if (!validation)
2377
- return !1;
2378
- const rules = Array.isArray(validation) ? validation : [validation];
2379
- for (const rule of rules) {
2380
- let assetRequired = !1;
2381
- const proxy = new Proxy(
2382
- {},
2383
- {
2384
- get: (target, methodName) => () => (methodName === "assetRequired" && (assetRequired = !0), proxy)
2385
- }
2386
- );
2387
- if (typeof rule == "function" && (rule(proxy), assetRequired) || typeof rule == "object" && rule !== null && "_rules" in rule && Array.isArray(rule._rules) && rule._rules.some((r) => r.flag === "assetRequired"))
2388
- return !0;
2389
- }
2390
- return !1;
2391
- }
2392
- function isObjectType(typeDef) {
2393
- return isType(typeDef, "object") || typeDef.jsonType === "object" || "fields" in typeDef;
2394
- }
2395
- function isArrayType(typeDef) {
2396
- return isType(typeDef, "array");
2397
- }
2398
- function isReferenceType(typeDef) {
2399
- return isType(typeDef, "reference");
2400
- }
2401
- function isCrossDatasetReferenceType(typeDef) {
2402
- return isType(typeDef, "crossDatasetReference");
2403
- }
2404
- function isGlobalDocumentReferenceType(typeDef) {
2405
- return isType(typeDef, "globalDocumentReference");
2406
- }
2407
- function isStringType(typeDef) {
2408
- return isType(typeDef, "string");
2409
- }
2410
- function isNumberType(typeDef) {
2411
- return isType(typeDef, "number");
2412
- }
2413
- function createStringTypeNodeDefintion(stringSchemaType) {
2414
- const listOptions = stringSchemaType.options?.list;
2415
- return listOptions && Array.isArray(listOptions) ? {
2416
- type: "union",
2417
- of: listOptions.map((v) => ({
2418
- type: "string",
2419
- value: typeof v == "string" ? v : v.value
2420
- }))
2421
- } : {
2422
- type: "string"
2423
- };
2424
- }
2425
- function createNumberTypeNodeDefintion(numberSchemaType) {
2426
- const listOptions = numberSchemaType.options?.list;
2427
- return listOptions && Array.isArray(listOptions) ? {
2428
- type: "union",
2429
- of: listOptions.map((v) => ({
2430
- type: "number",
2431
- value: typeof v == "number" ? v : v.value
2432
- }))
2433
- } : {
2434
- type: "number"
2435
- };
2436
- }
2437
- function createReferenceTypeNodeDefintion(reference2) {
2438
- const references = gatherReferenceNames(reference2);
2439
- return references.length === 1 ? createReferenceTypeNode(references[0]) : {
2440
- type: "union",
2441
- of: references.map((name) => createReferenceTypeNode(name))
2442
- };
2443
- }
2444
- function gatherReferenceNames(type) {
2445
- const allReferences = gatherReferenceTypes(type);
2446
- return [...new Set(allReferences.map((ref) => ref.name))];
2447
- }
2448
- function gatherReferenceTypes(type) {
2449
- const refTo = "to" in type ? type.to : [];
2450
- return "type" in type && isReferenceType(type.type) ? [...gatherReferenceTypes(type.type), ...refTo] : refTo;
2451
- }
2452
- function gatherFields(type) {
2453
- return "fields" in type ? type.type ? gatherFields(type.type).concat(type.fields) : type.fields : [];
2454
- }
2455
- function isType(typeDef, typeName) {
2456
- let type = typeDef;
2457
- for (; type; ) {
2458
- if (type.name === typeName || type.type && type.type.name === typeName)
2459
- return !0;
2460
- type = type.type;
2461
- }
2462
- return !1;
2463
- }
2464
- function lastType(typeDef) {
2465
- let type = typeDef;
2466
- for (; type; ) {
2467
- if (!type.type)
2468
- return type;
2469
- type = type.type;
2470
- }
2471
- }
2472
- function sortByDependencies(compiledSchema) {
2473
- const seen = /* @__PURE__ */ new Set();
2474
- function walkDependencies(schemaType, dependencies) {
2475
- if (!seen.has(schemaType)) {
2476
- if (seen.add(schemaType), "fields" in schemaType)
2477
- for (const field of gatherFields(schemaType)) {
2478
- const last = lastType(field.type);
2479
- if (last.name === "document") {
2480
- dependencies.add(last);
2481
- continue;
2482
- }
2483
- let schemaTypeName;
2484
- schemaType.type.type ? schemaTypeName = field.type.type.name : "jsonType" in schemaType.type && (schemaTypeName = field.type.jsonType), schemaTypeName === "object" || schemaTypeName === "block" ? isReferenceType(field.type) ? field.type.to.forEach((ref) => dependencies.add(ref.type)) : dependencies.add(field.type) : field.type && dependencies.add(field.type), walkDependencies(field.type, dependencies);
2485
- }
2486
- else if ("of" in schemaType)
2487
- for (const item of schemaType.of)
2488
- walkDependencies(item, dependencies);
2489
- }
2490
- }
2491
- const dependencyMap = /* @__PURE__ */ new Map(), schemaTypeNames = compiledSchema.getTypeNames(), validSchemaNames = /* @__PURE__ */ new Set();
2492
- schemaTypeNames.forEach((typeName) => {
2493
- const schemaType = compiledSchema.get(typeName);
2494
- if (schemaType === void 0 || schemaType.type === null)
2495
- return;
2496
- validSchemaNames.add(typeName);
2497
- const dependencies = /* @__PURE__ */ new Set();
2498
- walkDependencies(schemaType, dependencies), dependencyMap.set(schemaType, dependencies), seen.clear();
2499
- });
2500
- const typeNames = [], currentlyVisiting = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
2501
- function visit(type) {
2502
- if (visited.has(type) || currentlyVisiting.has(type))
2503
- return;
2504
- currentlyVisiting.add(type);
2505
- const deps = dependencyMap.get(type);
2506
- deps !== void 0 && deps.forEach((dep) => visit(dep)), currentlyVisiting.delete(type), visited.add(type), typeNames.includes(type.name) && typeNames.splice(typeNames.indexOf(type.name), 1), typeNames.unshift(type.name);
2507
- }
2508
- for (const [type] of dependencyMap)
2509
- visit(type);
2510
- return typeNames.filter((typeName) => validSchemaNames.has(typeName));
2511
- }
2512
- function validateNoCallbacks(typeDef) {
2513
- const problems = [];
2514
- return problems.push(...validateConditionalProperties(typeDef)), problems.push(...validateValueProperties(typeDef)), problems.push(...validateComponents(typeDef)), problems.push(...validateOptions(typeDef)), problems.push(...validateFieldsetsAndGroups(typeDef)), problems.push(...validateBlockSpecific(typeDef)), problems;
2515
- }
2516
- function validateConditionalProperties(typeDef) {
2517
- const problems = [];
2518
- return typeof typeDef.hidden == "function" && problems.push(
2519
- error('The "hidden" property cannot be a function. Use a static boolean value instead.')
2520
- ), typeof typeDef.readOnly == "function" && problems.push(
2521
- error('The "readOnly" property cannot be a function. Use a static boolean value instead.')
2522
- ), problems;
2523
- }
2524
- function validateValueProperties(typeDef) {
2525
- const problems = [];
2526
- return typeof typeDef.initialValue == "function" && problems.push(
2527
- error('The "initialValue" property cannot be a function. Use a static value instead.')
2528
- ), typeof typeDef.validation == "function" && problems.push(
2529
- error('The "validation" property cannot be a function. Use static validation rules instead.')
2530
- ), typeDef.validation && typeof typeDef.validation == "object" && checkForCustomValidators(typeDef.validation) && problems.push(
2531
- error("Custom validation functions are not supported. Use only built-in validation rules.")
2532
- ), typeDef.preview?.prepare && typeof typeDef.preview.prepare == "function" && problems.push(error('The "preview.prepare" property cannot be a function.')), typeDef.blockEditor?.render && problems.push(error('The "blockEditor.render" property cannot be a function.')), problems;
2533
- }
2534
- function validateComponents(typeDef) {
2535
- const problems = [];
2536
- if (!typeDef.components)
2537
- return problems;
2538
- const componentProps = [
2539
- "input",
2540
- "field",
2541
- "item",
2542
- "preview",
2543
- "diff",
2544
- "block",
2545
- "inlineBlock",
2546
- "annotation"
2547
- ];
2548
- for (const prop of componentProps)
2549
- typeDef.components[prop] && isComponentLike(typeDef.components[prop]) && problems.push(error(`The "components.${prop}" property cannot be a component function.`));
2550
- return typeDef.components.portableText?.plugins && problems.push(
2551
- error('The "components.portableText.plugins" property cannot contain plugin functions.')
2552
- ), problems;
2553
- }
2554
- function validateOptions(typeDef) {
2555
- const problems = [];
2556
- return !typeDef.options || typeof typeDef.options != "object" || (problems.push(...validateCommonOptions(typeDef.options)), problems.push(...validateAssetSources(typeDef.options)), problems.push(...validateOtherFunctionOptions(typeDef.options))), problems;
2557
- }
2558
- function validateCommonOptions(options) {
2559
- const problems = [];
2560
- return typeof options.filter == "function" && problems.push(
2561
- error(
2562
- 'The "options.filter" property cannot be a function. Use a static GROQ filter string with filterParams instead.'
2563
- )
2564
- ), typeof options.source == "function" && problems.push(
2565
- error(
2566
- 'The "options.source" property cannot be a function. Use a static string path instead.'
2567
- )
2568
- ), typeof options.slugify == "function" && problems.push(error('The "options.slugify" property cannot be a function.')), typeof options.isUnique == "function" && problems.push(error('The "options.isUnique" property cannot be a function.')), problems;
2569
- }
2570
- function validateAssetSources(options) {
2571
- const problems = [];
2572
- if (!Array.isArray(options.sources))
2573
- return problems;
2574
- for (let i = 0; i < options.sources.length; i++) {
2575
- const source = options.sources[i];
2576
- source && (source.component && isComponentLike(source.component) && problems.push(
2577
- error(`Asset source at index ${i} has a "component" property that cannot be a function.`)
2578
- ), source.icon && isComponentLike(source.icon) && problems.push(
2579
- error(`Asset source at index ${i} has an "icon" property that cannot be a component.`)
2580
- ), (typeof source == "function" || source.Uploader) && problems.push(error(`Asset source at index ${i} contains functions or classes.`)));
2581
- }
2582
- return problems;
2583
- }
2584
- function validateOtherFunctionOptions(options) {
2585
- const problems = [], knownFunctionOptions = ["filter", "source", "slugify", "isUnique"];
2586
- for (const [key, value] of Object.entries(options))
2587
- typeof value == "function" && !knownFunctionOptions.includes(key) && problems.push(error(`The "options.${key}" property cannot be a function.`));
2588
- return problems;
2589
- }
2590
- function validateFieldsetsAndGroups(typeDef) {
2591
- const problems = [];
2592
- return problems.push(...validateFieldsets(typeDef.fieldsets)), problems.push(...validateGroups(typeDef.groups)), problems;
2593
- }
2594
- function validateFieldsets(fieldsets) {
2595
- const problems = [];
2596
- if (!Array.isArray(fieldsets))
2597
- return problems;
2598
- for (let i = 0; i < fieldsets.length; i++) {
2599
- const fieldset = fieldsets[i];
2600
- fieldset && (typeof fieldset.hidden == "function" && problems.push(
2601
- error(`Fieldset at index ${i} has a "hidden" property that cannot be a function.`)
2602
- ), typeof fieldset.readOnly == "function" && problems.push(
2603
- error(`Fieldset at index ${i} has a "readOnly" property that cannot be a function.`)
2604
- ));
2605
- }
2606
- return problems;
2607
- }
2608
- function validateGroups(groups) {
2609
- const problems = [];
2610
- if (!Array.isArray(groups))
2611
- return problems;
2612
- for (let i = 0; i < groups.length; i++) {
2613
- const group = groups[i];
2614
- group && (typeof group.hidden == "function" && problems.push(
2615
- error(`Field group at index ${i} has a "hidden" property that cannot be a function.`)
2616
- ), group.icon && isComponentLike(group.icon) && problems.push(
2617
- error(`Field group at index ${i} has an "icon" property that cannot be a component.`)
2618
- ));
2619
- }
2620
- return problems;
2621
- }
2622
- function validateBlockSpecific(typeDef) {
2623
- const problems = [];
2624
- return typeDef.type !== "block" || (problems.push(...validateBlockStyles(typeDef.styles)), problems.push(...validateBlockMarks(typeDef.marks))), problems;
2625
- }
2626
- function validateBlockStyles(styles) {
2627
- const problems = [];
2628
- if (!Array.isArray(styles))
2629
- return problems;
2630
- for (let i = 0; i < styles.length; i++) {
2631
- const style = styles[i];
2632
- style?.component && isComponentLike(style.component) && problems.push(
2633
- error(`Block style at index ${i} has a "component" property that cannot be a function.`)
2634
- );
2635
- }
2636
- return problems;
2637
- }
2638
- function validateBlockMarks(marks) {
2639
- const problems = [];
2640
- if (!marks)
2641
- return problems;
2642
- if (Array.isArray(marks.decorators))
2643
- for (let i = 0; i < marks.decorators.length; i++) {
2644
- const decorator = marks.decorators[i];
2645
- decorator?.component && isComponentLike(decorator.component) && problems.push(
2646
- error(
2647
- `Block decorator at index ${i} has a "component" property that cannot be a function.`
2648
- )
2649
- );
2650
- }
2651
- if (Array.isArray(marks.annotations))
2652
- for (let i = 0; i < marks.annotations.length; i++) {
2653
- const annotation = marks.annotations[i];
2654
- annotation?.component && isComponentLike(annotation.component) && problems.push(
2655
- error(
2656
- `Block annotation at index ${i} has a "component" property that cannot be a function.`
2657
- )
2658
- );
2659
- }
2660
- return problems;
2661
- }
2662
- function checkForCustomValidators(validation) {
2663
- if (!validation) return !1;
2664
- if (Array.isArray(validation))
2665
- return validation.some((v) => checkForCustomValidators(v));
2666
- if (typeof validation == "object") {
2667
- if (Array.isArray(validation._rules))
2668
- return validation._rules.some((rule) => rule.flag === "custom" && typeof rule.constraint == "function");
2669
- if (typeof validation.custom == "function")
2670
- return !0;
2671
- }
2672
- return !1;
2673
- }
2674
- function unsupportedTypeValidator(typeLabel) {
2675
- return function() {
2676
- return {
2677
- _problems: [
2678
- {
2679
- severity: "error",
2680
- message: `Type unsupported in Media Library aspects: ${typeLabel}.`
2681
- }
2682
- ]
2683
- };
2684
- };
2685
- }
2686
- function noCallbacksVisitor(typeDef, visitorContext) {
2687
- return {
2688
- ...typeDef,
2689
- _problems: validateNoCallbacks(typeDef)
2690
- };
2691
- }
2692
- function validateMediaLibraryAssetAspect(maybeAspect) {
2693
- const validated = validateSchema([maybeAspect], {
2694
- transformCommonVisitors: (visitors) => [...visitors, noCallbacksVisitor],
2695
- transformTypeVisitors: (typeVisitors2) => ({
2696
- ...typeVisitors2,
2697
- document: unsupportedTypeValidator("document"),
2698
- image: unsupportedTypeValidator("image"),
2699
- file: unsupportedTypeValidator("file"),
2700
- video: unsupportedTypeValidator("sanity.video"),
2701
- reference: unsupportedTypeValidator("reference"),
2702
- crossDatasetReference: unsupportedTypeValidator("cross dataset reference")
2703
- })
2704
- }), errors = groupProblems(validated.getTypes()).map((group) => group.problems.filter(({ severity }) => severity === "error")).filter((problems) => problems.length);
2705
- return [errors.length === 0, errors];
2706
- }
2707
- export {
2708
- ALL_FIELDS_GROUP_NAME,
2709
- DEFAULT_MAX_FIELD_DEPTH,
2710
- DescriptorConverter,
2711
- ValidationError,
2712
- builtinTypes,
2713
- createSchemaFromManifestTypes,
2714
- extractSchema,
2715
- groupProblems,
2716
- isActionEnabled,
2717
- processSchemaSynchronization,
2718
- resolveSearchConfig,
2719
- resolveSearchConfigForBaseFieldPaths,
2720
- validateMediaLibraryAssetAspect,
2721
- validateSchema
2722
- };
2723
- //# sourceMappingURL=_internal.mjs.map