@tinacms/schema-tools 0.0.0-00d7b85-20251222014449

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2789 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
7
+ import * as yup from "yup";
8
+ import UrlPattern from "url-pattern";
9
+ import z$1, { z, ZodError } from "zod";
10
+ function addNamespaceToSchema(maybeNode, namespace = []) {
11
+ if (typeof maybeNode !== "object" || maybeNode === null) {
12
+ return maybeNode;
13
+ }
14
+ const newNode = { ...maybeNode, namespace: [...namespace] };
15
+ Object.entries(maybeNode).forEach(([key, value]) => {
16
+ if (Array.isArray(value)) {
17
+ newNode[key] = value.map((element) => {
18
+ if (element && typeof element === "object" && "name" in element) {
19
+ const valueName = element.name || element.value;
20
+ return addNamespaceToSchema(element, [...namespace, valueName]);
21
+ }
22
+ return element;
23
+ });
24
+ } else if (value && typeof value === "object" && "name" in value) {
25
+ newNode[key] = addNamespaceToSchema(value, [...namespace, value.name]);
26
+ } else {
27
+ newNode[key] = value;
28
+ }
29
+ });
30
+ return newNode;
31
+ }
32
+ function getDefaultExportFromCjs(x) {
33
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
34
+ }
35
+ var utils$4 = {};
36
+ const WIN_SLASH = "\\\\/";
37
+ const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
38
+ const DOT_LITERAL = "\\.";
39
+ const PLUS_LITERAL = "\\+";
40
+ const QMARK_LITERAL = "\\?";
41
+ const SLASH_LITERAL = "\\/";
42
+ const ONE_CHAR = "(?=.)";
43
+ const QMARK = "[^/]";
44
+ const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
45
+ const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
46
+ const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
47
+ const NO_DOT = `(?!${DOT_LITERAL})`;
48
+ const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
49
+ const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
50
+ const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
51
+ const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
52
+ const STAR = `${QMARK}*?`;
53
+ const SEP = "/";
54
+ const POSIX_CHARS = {
55
+ DOT_LITERAL,
56
+ PLUS_LITERAL,
57
+ QMARK_LITERAL,
58
+ SLASH_LITERAL,
59
+ ONE_CHAR,
60
+ QMARK,
61
+ END_ANCHOR,
62
+ DOTS_SLASH,
63
+ NO_DOT,
64
+ NO_DOTS,
65
+ NO_DOT_SLASH,
66
+ NO_DOTS_SLASH,
67
+ QMARK_NO_DOT,
68
+ STAR,
69
+ START_ANCHOR,
70
+ SEP
71
+ };
72
+ const WINDOWS_CHARS = {
73
+ ...POSIX_CHARS,
74
+ SLASH_LITERAL: `[${WIN_SLASH}]`,
75
+ QMARK: WIN_NO_SLASH,
76
+ STAR: `${WIN_NO_SLASH}*?`,
77
+ DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
78
+ NO_DOT: `(?!${DOT_LITERAL})`,
79
+ NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
80
+ NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
81
+ NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
82
+ QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
83
+ START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
84
+ END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
85
+ SEP: "\\"
86
+ };
87
+ const POSIX_REGEX_SOURCE$1 = {
88
+ alnum: "a-zA-Z0-9",
89
+ alpha: "a-zA-Z",
90
+ ascii: "\\x00-\\x7F",
91
+ blank: " \\t",
92
+ cntrl: "\\x00-\\x1F\\x7F",
93
+ digit: "0-9",
94
+ graph: "\\x21-\\x7E",
95
+ lower: "a-z",
96
+ print: "\\x20-\\x7E ",
97
+ punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
98
+ space: " \\t\\r\\n\\v\\f",
99
+ upper: "A-Z",
100
+ word: "A-Za-z0-9_",
101
+ xdigit: "A-Fa-f0-9"
102
+ };
103
+ var constants$2 = {
104
+ MAX_LENGTH: 1024 * 64,
105
+ POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
106
+ // regular expressions
107
+ REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
108
+ REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
109
+ REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
110
+ REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
111
+ REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
112
+ REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
113
+ // Replace globs with equivalent patterns to reduce parsing time.
114
+ REPLACEMENTS: {
115
+ __proto__: null,
116
+ "***": "*",
117
+ "**/**": "**",
118
+ "**/**/**": "**"
119
+ },
120
+ // Digits
121
+ CHAR_0: 48,
122
+ /* 0 */
123
+ CHAR_9: 57,
124
+ /* 9 */
125
+ // Alphabet chars.
126
+ CHAR_UPPERCASE_A: 65,
127
+ /* A */
128
+ CHAR_LOWERCASE_A: 97,
129
+ /* a */
130
+ CHAR_UPPERCASE_Z: 90,
131
+ /* Z */
132
+ CHAR_LOWERCASE_Z: 122,
133
+ /* z */
134
+ CHAR_LEFT_PARENTHESES: 40,
135
+ /* ( */
136
+ CHAR_RIGHT_PARENTHESES: 41,
137
+ /* ) */
138
+ CHAR_ASTERISK: 42,
139
+ /* * */
140
+ // Non-alphabetic chars.
141
+ CHAR_AMPERSAND: 38,
142
+ /* & */
143
+ CHAR_AT: 64,
144
+ /* @ */
145
+ CHAR_BACKWARD_SLASH: 92,
146
+ /* \ */
147
+ CHAR_CARRIAGE_RETURN: 13,
148
+ /* \r */
149
+ CHAR_CIRCUMFLEX_ACCENT: 94,
150
+ /* ^ */
151
+ CHAR_COLON: 58,
152
+ /* : */
153
+ CHAR_COMMA: 44,
154
+ /* , */
155
+ CHAR_DOT: 46,
156
+ /* . */
157
+ CHAR_DOUBLE_QUOTE: 34,
158
+ /* " */
159
+ CHAR_EQUAL: 61,
160
+ /* = */
161
+ CHAR_EXCLAMATION_MARK: 33,
162
+ /* ! */
163
+ CHAR_FORM_FEED: 12,
164
+ /* \f */
165
+ CHAR_FORWARD_SLASH: 47,
166
+ /* / */
167
+ CHAR_GRAVE_ACCENT: 96,
168
+ /* ` */
169
+ CHAR_HASH: 35,
170
+ /* # */
171
+ CHAR_HYPHEN_MINUS: 45,
172
+ /* - */
173
+ CHAR_LEFT_ANGLE_BRACKET: 60,
174
+ /* < */
175
+ CHAR_LEFT_CURLY_BRACE: 123,
176
+ /* { */
177
+ CHAR_LEFT_SQUARE_BRACKET: 91,
178
+ /* [ */
179
+ CHAR_LINE_FEED: 10,
180
+ /* \n */
181
+ CHAR_NO_BREAK_SPACE: 160,
182
+ /* \u00A0 */
183
+ CHAR_PERCENT: 37,
184
+ /* % */
185
+ CHAR_PLUS: 43,
186
+ /* + */
187
+ CHAR_QUESTION_MARK: 63,
188
+ /* ? */
189
+ CHAR_RIGHT_ANGLE_BRACKET: 62,
190
+ /* > */
191
+ CHAR_RIGHT_CURLY_BRACE: 125,
192
+ /* } */
193
+ CHAR_RIGHT_SQUARE_BRACKET: 93,
194
+ /* ] */
195
+ CHAR_SEMICOLON: 59,
196
+ /* ; */
197
+ CHAR_SINGLE_QUOTE: 39,
198
+ /* ' */
199
+ CHAR_SPACE: 32,
200
+ /* */
201
+ CHAR_TAB: 9,
202
+ /* \t */
203
+ CHAR_UNDERSCORE: 95,
204
+ /* _ */
205
+ CHAR_VERTICAL_LINE: 124,
206
+ /* | */
207
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
208
+ /* \uFEFF */
209
+ /**
210
+ * Create EXTGLOB_CHARS
211
+ */
212
+ extglobChars(chars) {
213
+ return {
214
+ "!": { type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})` },
215
+ "?": { type: "qmark", open: "(?:", close: ")?" },
216
+ "+": { type: "plus", open: "(?:", close: ")+" },
217
+ "*": { type: "star", open: "(?:", close: ")*" },
218
+ "@": { type: "at", open: "(?:", close: ")" }
219
+ };
220
+ },
221
+ /**
222
+ * Create GLOB_CHARS
223
+ */
224
+ globChars(win32) {
225
+ return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
226
+ }
227
+ };
228
+ (function(exports) {
229
+ const {
230
+ REGEX_BACKSLASH,
231
+ REGEX_REMOVE_BACKSLASH,
232
+ REGEX_SPECIAL_CHARS,
233
+ REGEX_SPECIAL_CHARS_GLOBAL
234
+ } = constants$2;
235
+ exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
236
+ exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
237
+ exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
238
+ exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
239
+ exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
240
+ exports.isWindows = () => {
241
+ if (typeof navigator !== "undefined" && navigator.platform) {
242
+ const platform = navigator.platform.toLowerCase();
243
+ return platform === "win32" || platform === "windows";
244
+ }
245
+ if (typeof process !== "undefined" && process.platform) {
246
+ return process.platform === "win32";
247
+ }
248
+ return false;
249
+ };
250
+ exports.removeBackslashes = (str) => {
251
+ return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
252
+ return match === "\\" ? "" : match;
253
+ });
254
+ };
255
+ exports.escapeLast = (input, char, lastIdx) => {
256
+ const idx = input.lastIndexOf(char, lastIdx);
257
+ if (idx === -1)
258
+ return input;
259
+ if (input[idx - 1] === "\\")
260
+ return exports.escapeLast(input, char, idx - 1);
261
+ return `${input.slice(0, idx)}\\${input.slice(idx)}`;
262
+ };
263
+ exports.removePrefix = (input, state = {}) => {
264
+ let output = input;
265
+ if (output.startsWith("./")) {
266
+ output = output.slice(2);
267
+ state.prefix = "./";
268
+ }
269
+ return output;
270
+ };
271
+ exports.wrapOutput = (input, state = {}, options = {}) => {
272
+ const prepend = options.contains ? "" : "^";
273
+ const append = options.contains ? "" : "$";
274
+ let output = `${prepend}(?:${input})${append}`;
275
+ if (state.negated === true) {
276
+ output = `(?:^(?!${output}).*$)`;
277
+ }
278
+ return output;
279
+ };
280
+ exports.basename = (path, { windows } = {}) => {
281
+ const segs = path.split(windows ? /[\\/]/ : "/");
282
+ const last = segs[segs.length - 1];
283
+ if (last === "") {
284
+ return segs[segs.length - 2];
285
+ }
286
+ return last;
287
+ };
288
+ })(utils$4);
289
+ const utils$3 = utils$4;
290
+ const {
291
+ CHAR_ASTERISK,
292
+ /* * */
293
+ CHAR_AT,
294
+ /* @ */
295
+ CHAR_BACKWARD_SLASH,
296
+ /* \ */
297
+ CHAR_COMMA,
298
+ /* , */
299
+ CHAR_DOT,
300
+ /* . */
301
+ CHAR_EXCLAMATION_MARK,
302
+ /* ! */
303
+ CHAR_FORWARD_SLASH,
304
+ /* / */
305
+ CHAR_LEFT_CURLY_BRACE,
306
+ /* { */
307
+ CHAR_LEFT_PARENTHESES,
308
+ /* ( */
309
+ CHAR_LEFT_SQUARE_BRACKET,
310
+ /* [ */
311
+ CHAR_PLUS,
312
+ /* + */
313
+ CHAR_QUESTION_MARK,
314
+ /* ? */
315
+ CHAR_RIGHT_CURLY_BRACE,
316
+ /* } */
317
+ CHAR_RIGHT_PARENTHESES,
318
+ /* ) */
319
+ CHAR_RIGHT_SQUARE_BRACKET
320
+ /* ] */
321
+ } = constants$2;
322
+ const isPathSeparator = (code) => {
323
+ return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
324
+ };
325
+ const depth = (token) => {
326
+ if (token.isPrefix !== true) {
327
+ token.depth = token.isGlobstar ? Infinity : 1;
328
+ }
329
+ };
330
+ const scan$1 = (input, options) => {
331
+ const opts = options || {};
332
+ const length = input.length - 1;
333
+ const scanToEnd = opts.parts === true || opts.scanToEnd === true;
334
+ const slashes = [];
335
+ const tokens = [];
336
+ const parts = [];
337
+ let str = input;
338
+ let index = -1;
339
+ let start = 0;
340
+ let lastIndex = 0;
341
+ let isBrace = false;
342
+ let isBracket = false;
343
+ let isGlob = false;
344
+ let isExtglob = false;
345
+ let isGlobstar = false;
346
+ let braceEscaped = false;
347
+ let backslashes = false;
348
+ let negated = false;
349
+ let negatedExtglob = false;
350
+ let finished = false;
351
+ let braces = 0;
352
+ let prev;
353
+ let code;
354
+ let token = { value: "", depth: 0, isGlob: false };
355
+ const eos = () => index >= length;
356
+ const peek = () => str.charCodeAt(index + 1);
357
+ const advance = () => {
358
+ prev = code;
359
+ return str.charCodeAt(++index);
360
+ };
361
+ while (index < length) {
362
+ code = advance();
363
+ let next;
364
+ if (code === CHAR_BACKWARD_SLASH) {
365
+ backslashes = token.backslashes = true;
366
+ code = advance();
367
+ if (code === CHAR_LEFT_CURLY_BRACE) {
368
+ braceEscaped = true;
369
+ }
370
+ continue;
371
+ }
372
+ if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
373
+ braces++;
374
+ while (eos() !== true && (code = advance())) {
375
+ if (code === CHAR_BACKWARD_SLASH) {
376
+ backslashes = token.backslashes = true;
377
+ advance();
378
+ continue;
379
+ }
380
+ if (code === CHAR_LEFT_CURLY_BRACE) {
381
+ braces++;
382
+ continue;
383
+ }
384
+ if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
385
+ isBrace = token.isBrace = true;
386
+ isGlob = token.isGlob = true;
387
+ finished = true;
388
+ if (scanToEnd === true) {
389
+ continue;
390
+ }
391
+ break;
392
+ }
393
+ if (braceEscaped !== true && code === CHAR_COMMA) {
394
+ isBrace = token.isBrace = true;
395
+ isGlob = token.isGlob = true;
396
+ finished = true;
397
+ if (scanToEnd === true) {
398
+ continue;
399
+ }
400
+ break;
401
+ }
402
+ if (code === CHAR_RIGHT_CURLY_BRACE) {
403
+ braces--;
404
+ if (braces === 0) {
405
+ braceEscaped = false;
406
+ isBrace = token.isBrace = true;
407
+ finished = true;
408
+ break;
409
+ }
410
+ }
411
+ }
412
+ if (scanToEnd === true) {
413
+ continue;
414
+ }
415
+ break;
416
+ }
417
+ if (code === CHAR_FORWARD_SLASH) {
418
+ slashes.push(index);
419
+ tokens.push(token);
420
+ token = { value: "", depth: 0, isGlob: false };
421
+ if (finished === true)
422
+ continue;
423
+ if (prev === CHAR_DOT && index === start + 1) {
424
+ start += 2;
425
+ continue;
426
+ }
427
+ lastIndex = index + 1;
428
+ continue;
429
+ }
430
+ if (opts.noext !== true) {
431
+ const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
432
+ if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
433
+ isGlob = token.isGlob = true;
434
+ isExtglob = token.isExtglob = true;
435
+ finished = true;
436
+ if (code === CHAR_EXCLAMATION_MARK && index === start) {
437
+ negatedExtglob = true;
438
+ }
439
+ if (scanToEnd === true) {
440
+ while (eos() !== true && (code = advance())) {
441
+ if (code === CHAR_BACKWARD_SLASH) {
442
+ backslashes = token.backslashes = true;
443
+ code = advance();
444
+ continue;
445
+ }
446
+ if (code === CHAR_RIGHT_PARENTHESES) {
447
+ isGlob = token.isGlob = true;
448
+ finished = true;
449
+ break;
450
+ }
451
+ }
452
+ continue;
453
+ }
454
+ break;
455
+ }
456
+ }
457
+ if (code === CHAR_ASTERISK) {
458
+ if (prev === CHAR_ASTERISK)
459
+ isGlobstar = token.isGlobstar = true;
460
+ isGlob = token.isGlob = true;
461
+ finished = true;
462
+ if (scanToEnd === true) {
463
+ continue;
464
+ }
465
+ break;
466
+ }
467
+ if (code === CHAR_QUESTION_MARK) {
468
+ isGlob = token.isGlob = true;
469
+ finished = true;
470
+ if (scanToEnd === true) {
471
+ continue;
472
+ }
473
+ break;
474
+ }
475
+ if (code === CHAR_LEFT_SQUARE_BRACKET) {
476
+ while (eos() !== true && (next = advance())) {
477
+ if (next === CHAR_BACKWARD_SLASH) {
478
+ backslashes = token.backslashes = true;
479
+ advance();
480
+ continue;
481
+ }
482
+ if (next === CHAR_RIGHT_SQUARE_BRACKET) {
483
+ isBracket = token.isBracket = true;
484
+ isGlob = token.isGlob = true;
485
+ finished = true;
486
+ break;
487
+ }
488
+ }
489
+ if (scanToEnd === true) {
490
+ continue;
491
+ }
492
+ break;
493
+ }
494
+ if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
495
+ negated = token.negated = true;
496
+ start++;
497
+ continue;
498
+ }
499
+ if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
500
+ isGlob = token.isGlob = true;
501
+ if (scanToEnd === true) {
502
+ while (eos() !== true && (code = advance())) {
503
+ if (code === CHAR_LEFT_PARENTHESES) {
504
+ backslashes = token.backslashes = true;
505
+ code = advance();
506
+ continue;
507
+ }
508
+ if (code === CHAR_RIGHT_PARENTHESES) {
509
+ finished = true;
510
+ break;
511
+ }
512
+ }
513
+ continue;
514
+ }
515
+ break;
516
+ }
517
+ if (isGlob === true) {
518
+ finished = true;
519
+ if (scanToEnd === true) {
520
+ continue;
521
+ }
522
+ break;
523
+ }
524
+ }
525
+ if (opts.noext === true) {
526
+ isExtglob = false;
527
+ isGlob = false;
528
+ }
529
+ let base = str;
530
+ let prefix = "";
531
+ let glob = "";
532
+ if (start > 0) {
533
+ prefix = str.slice(0, start);
534
+ str = str.slice(start);
535
+ lastIndex -= start;
536
+ }
537
+ if (base && isGlob === true && lastIndex > 0) {
538
+ base = str.slice(0, lastIndex);
539
+ glob = str.slice(lastIndex);
540
+ } else if (isGlob === true) {
541
+ base = "";
542
+ glob = str;
543
+ } else {
544
+ base = str;
545
+ }
546
+ if (base && base !== "" && base !== "/" && base !== str) {
547
+ if (isPathSeparator(base.charCodeAt(base.length - 1))) {
548
+ base = base.slice(0, -1);
549
+ }
550
+ }
551
+ if (opts.unescape === true) {
552
+ if (glob)
553
+ glob = utils$3.removeBackslashes(glob);
554
+ if (base && backslashes === true) {
555
+ base = utils$3.removeBackslashes(base);
556
+ }
557
+ }
558
+ const state = {
559
+ prefix,
560
+ input,
561
+ start,
562
+ base,
563
+ glob,
564
+ isBrace,
565
+ isBracket,
566
+ isGlob,
567
+ isExtglob,
568
+ isGlobstar,
569
+ negated,
570
+ negatedExtglob
571
+ };
572
+ if (opts.tokens === true) {
573
+ state.maxDepth = 0;
574
+ if (!isPathSeparator(code)) {
575
+ tokens.push(token);
576
+ }
577
+ state.tokens = tokens;
578
+ }
579
+ if (opts.parts === true || opts.tokens === true) {
580
+ let prevIndex;
581
+ for (let idx = 0; idx < slashes.length; idx++) {
582
+ const n = prevIndex ? prevIndex + 1 : start;
583
+ const i = slashes[idx];
584
+ const value = input.slice(n, i);
585
+ if (opts.tokens) {
586
+ if (idx === 0 && start !== 0) {
587
+ tokens[idx].isPrefix = true;
588
+ tokens[idx].value = prefix;
589
+ } else {
590
+ tokens[idx].value = value;
591
+ }
592
+ depth(tokens[idx]);
593
+ state.maxDepth += tokens[idx].depth;
594
+ }
595
+ if (idx !== 0 || value !== "") {
596
+ parts.push(value);
597
+ }
598
+ prevIndex = i;
599
+ }
600
+ if (prevIndex && prevIndex + 1 < input.length) {
601
+ const value = input.slice(prevIndex + 1);
602
+ parts.push(value);
603
+ if (opts.tokens) {
604
+ tokens[tokens.length - 1].value = value;
605
+ depth(tokens[tokens.length - 1]);
606
+ state.maxDepth += tokens[tokens.length - 1].depth;
607
+ }
608
+ }
609
+ state.slashes = slashes;
610
+ state.parts = parts;
611
+ }
612
+ return state;
613
+ };
614
+ var scan_1 = scan$1;
615
+ const constants$1 = constants$2;
616
+ const utils$2 = utils$4;
617
+ const {
618
+ MAX_LENGTH,
619
+ POSIX_REGEX_SOURCE,
620
+ REGEX_NON_SPECIAL_CHARS,
621
+ REGEX_SPECIAL_CHARS_BACKREF,
622
+ REPLACEMENTS
623
+ } = constants$1;
624
+ const expandRange = (args, options) => {
625
+ if (typeof options.expandRange === "function") {
626
+ return options.expandRange(...args, options);
627
+ }
628
+ args.sort();
629
+ const value = `[${args.join("-")}]`;
630
+ try {
631
+ new RegExp(value);
632
+ } catch (ex) {
633
+ return args.map((v) => utils$2.escapeRegex(v)).join("..");
634
+ }
635
+ return value;
636
+ };
637
+ const syntaxError = (type, char) => {
638
+ return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
639
+ };
640
+ const parse$1 = (input, options) => {
641
+ if (typeof input !== "string") {
642
+ throw new TypeError("Expected a string");
643
+ }
644
+ input = REPLACEMENTS[input] || input;
645
+ const opts = { ...options };
646
+ const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
647
+ let len = input.length;
648
+ if (len > max) {
649
+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
650
+ }
651
+ const bos = { type: "bos", value: "", output: opts.prepend || "" };
652
+ const tokens = [bos];
653
+ const capture = opts.capture ? "" : "?:";
654
+ const PLATFORM_CHARS = constants$1.globChars(opts.windows);
655
+ const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
656
+ const {
657
+ DOT_LITERAL: DOT_LITERAL2,
658
+ PLUS_LITERAL: PLUS_LITERAL2,
659
+ SLASH_LITERAL: SLASH_LITERAL2,
660
+ ONE_CHAR: ONE_CHAR2,
661
+ DOTS_SLASH: DOTS_SLASH2,
662
+ NO_DOT: NO_DOT2,
663
+ NO_DOT_SLASH: NO_DOT_SLASH2,
664
+ NO_DOTS_SLASH: NO_DOTS_SLASH2,
665
+ QMARK: QMARK2,
666
+ QMARK_NO_DOT: QMARK_NO_DOT2,
667
+ STAR: STAR2,
668
+ START_ANCHOR: START_ANCHOR2
669
+ } = PLATFORM_CHARS;
670
+ const globstar = (opts2) => {
671
+ return `(${capture}(?:(?!${START_ANCHOR2}${opts2.dot ? DOTS_SLASH2 : DOT_LITERAL2}).)*?)`;
672
+ };
673
+ const nodot = opts.dot ? "" : NO_DOT2;
674
+ const qmarkNoDot = opts.dot ? QMARK2 : QMARK_NO_DOT2;
675
+ let star = opts.bash === true ? globstar(opts) : STAR2;
676
+ if (opts.capture) {
677
+ star = `(${star})`;
678
+ }
679
+ if (typeof opts.noext === "boolean") {
680
+ opts.noextglob = opts.noext;
681
+ }
682
+ const state = {
683
+ input,
684
+ index: -1,
685
+ start: 0,
686
+ dot: opts.dot === true,
687
+ consumed: "",
688
+ output: "",
689
+ prefix: "",
690
+ backtrack: false,
691
+ negated: false,
692
+ brackets: 0,
693
+ braces: 0,
694
+ parens: 0,
695
+ quotes: 0,
696
+ globstar: false,
697
+ tokens
698
+ };
699
+ input = utils$2.removePrefix(input, state);
700
+ len = input.length;
701
+ const extglobs = [];
702
+ const braces = [];
703
+ const stack = [];
704
+ let prev = bos;
705
+ let value;
706
+ const eos = () => state.index === len - 1;
707
+ const peek = state.peek = (n = 1) => input[state.index + n];
708
+ const advance = state.advance = () => input[++state.index] || "";
709
+ const remaining = () => input.slice(state.index + 1);
710
+ const consume = (value2 = "", num = 0) => {
711
+ state.consumed += value2;
712
+ state.index += num;
713
+ };
714
+ const append = (token) => {
715
+ state.output += token.output != null ? token.output : token.value;
716
+ consume(token.value);
717
+ };
718
+ const negate = () => {
719
+ let count = 1;
720
+ while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
721
+ advance();
722
+ state.start++;
723
+ count++;
724
+ }
725
+ if (count % 2 === 0) {
726
+ return false;
727
+ }
728
+ state.negated = true;
729
+ state.start++;
730
+ return true;
731
+ };
732
+ const increment = (type) => {
733
+ state[type]++;
734
+ stack.push(type);
735
+ };
736
+ const decrement = (type) => {
737
+ state[type]--;
738
+ stack.pop();
739
+ };
740
+ const push = (tok) => {
741
+ if (prev.type === "globstar") {
742
+ const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace");
743
+ const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
744
+ if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) {
745
+ state.output = state.output.slice(0, -prev.output.length);
746
+ prev.type = "star";
747
+ prev.value = "*";
748
+ prev.output = star;
749
+ state.output += prev.output;
750
+ }
751
+ }
752
+ if (extglobs.length && tok.type !== "paren") {
753
+ extglobs[extglobs.length - 1].inner += tok.value;
754
+ }
755
+ if (tok.value || tok.output)
756
+ append(tok);
757
+ if (prev && prev.type === "text" && tok.type === "text") {
758
+ prev.output = (prev.output || prev.value) + tok.value;
759
+ prev.value += tok.value;
760
+ return;
761
+ }
762
+ tok.prev = prev;
763
+ tokens.push(tok);
764
+ prev = tok;
765
+ };
766
+ const extglobOpen = (type, value2) => {
767
+ const token = { ...EXTGLOB_CHARS[value2], conditions: 1, inner: "" };
768
+ token.prev = prev;
769
+ token.parens = state.parens;
770
+ token.output = state.output;
771
+ const output = (opts.capture ? "(" : "") + token.open;
772
+ increment("parens");
773
+ push({ type, value: value2, output: state.output ? "" : ONE_CHAR2 });
774
+ push({ type: "paren", extglob: true, value: advance(), output });
775
+ extglobs.push(token);
776
+ };
777
+ const extglobClose = (token) => {
778
+ let output = token.close + (opts.capture ? ")" : "");
779
+ let rest;
780
+ if (token.type === "negate") {
781
+ let extglobStar = star;
782
+ if (token.inner && token.inner.length > 1 && token.inner.includes("/")) {
783
+ extglobStar = globstar(opts);
784
+ }
785
+ if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
786
+ output = token.close = `)$))${extglobStar}`;
787
+ }
788
+ if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
789
+ const expression = parse$1(rest, { ...options, fastpaths: false }).output;
790
+ output = token.close = `)${expression})${extglobStar})`;
791
+ }
792
+ if (token.prev.type === "bos") {
793
+ state.negatedExtglob = true;
794
+ }
795
+ }
796
+ push({ type: "paren", extglob: true, value, output });
797
+ decrement("parens");
798
+ };
799
+ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
800
+ let backslashes = false;
801
+ let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
802
+ if (first === "\\") {
803
+ backslashes = true;
804
+ return m;
805
+ }
806
+ if (first === "?") {
807
+ if (esc) {
808
+ return esc + first + (rest ? QMARK2.repeat(rest.length) : "");
809
+ }
810
+ if (index === 0) {
811
+ return qmarkNoDot + (rest ? QMARK2.repeat(rest.length) : "");
812
+ }
813
+ return QMARK2.repeat(chars.length);
814
+ }
815
+ if (first === ".") {
816
+ return DOT_LITERAL2.repeat(chars.length);
817
+ }
818
+ if (first === "*") {
819
+ if (esc) {
820
+ return esc + first + (rest ? star : "");
821
+ }
822
+ return star;
823
+ }
824
+ return esc ? m : `\\${m}`;
825
+ });
826
+ if (backslashes === true) {
827
+ if (opts.unescape === true) {
828
+ output = output.replace(/\\/g, "");
829
+ } else {
830
+ output = output.replace(/\\+/g, (m) => {
831
+ return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
832
+ });
833
+ }
834
+ }
835
+ if (output === input && opts.contains === true) {
836
+ state.output = input;
837
+ return state;
838
+ }
839
+ state.output = utils$2.wrapOutput(output, state, options);
840
+ return state;
841
+ }
842
+ while (!eos()) {
843
+ value = advance();
844
+ if (value === "\0") {
845
+ continue;
846
+ }
847
+ if (value === "\\") {
848
+ const next = peek();
849
+ if (next === "/" && opts.bash !== true) {
850
+ continue;
851
+ }
852
+ if (next === "." || next === ";") {
853
+ continue;
854
+ }
855
+ if (!next) {
856
+ value += "\\";
857
+ push({ type: "text", value });
858
+ continue;
859
+ }
860
+ const match = /^\\+/.exec(remaining());
861
+ let slashes = 0;
862
+ if (match && match[0].length > 2) {
863
+ slashes = match[0].length;
864
+ state.index += slashes;
865
+ if (slashes % 2 !== 0) {
866
+ value += "\\";
867
+ }
868
+ }
869
+ if (opts.unescape === true) {
870
+ value = advance();
871
+ } else {
872
+ value += advance();
873
+ }
874
+ if (state.brackets === 0) {
875
+ push({ type: "text", value });
876
+ continue;
877
+ }
878
+ }
879
+ if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
880
+ if (opts.posix !== false && value === ":") {
881
+ const inner = prev.value.slice(1);
882
+ if (inner.includes("[")) {
883
+ prev.posix = true;
884
+ if (inner.includes(":")) {
885
+ const idx = prev.value.lastIndexOf("[");
886
+ const pre = prev.value.slice(0, idx);
887
+ const rest2 = prev.value.slice(idx + 2);
888
+ const posix = POSIX_REGEX_SOURCE[rest2];
889
+ if (posix) {
890
+ prev.value = pre + posix;
891
+ state.backtrack = true;
892
+ advance();
893
+ if (!bos.output && tokens.indexOf(prev) === 1) {
894
+ bos.output = ONE_CHAR2;
895
+ }
896
+ continue;
897
+ }
898
+ }
899
+ }
900
+ }
901
+ if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") {
902
+ value = `\\${value}`;
903
+ }
904
+ if (value === "]" && (prev.value === "[" || prev.value === "[^")) {
905
+ value = `\\${value}`;
906
+ }
907
+ if (opts.posix === true && value === "!" && prev.value === "[") {
908
+ value = "^";
909
+ }
910
+ prev.value += value;
911
+ append({ value });
912
+ continue;
913
+ }
914
+ if (state.quotes === 1 && value !== '"') {
915
+ value = utils$2.escapeRegex(value);
916
+ prev.value += value;
917
+ append({ value });
918
+ continue;
919
+ }
920
+ if (value === '"') {
921
+ state.quotes = state.quotes === 1 ? 0 : 1;
922
+ if (opts.keepQuotes === true) {
923
+ push({ type: "text", value });
924
+ }
925
+ continue;
926
+ }
927
+ if (value === "(") {
928
+ increment("parens");
929
+ push({ type: "paren", value });
930
+ continue;
931
+ }
932
+ if (value === ")") {
933
+ if (state.parens === 0 && opts.strictBrackets === true) {
934
+ throw new SyntaxError(syntaxError("opening", "("));
935
+ }
936
+ const extglob = extglobs[extglobs.length - 1];
937
+ if (extglob && state.parens === extglob.parens + 1) {
938
+ extglobClose(extglobs.pop());
939
+ continue;
940
+ }
941
+ push({ type: "paren", value, output: state.parens ? ")" : "\\)" });
942
+ decrement("parens");
943
+ continue;
944
+ }
945
+ if (value === "[") {
946
+ if (opts.nobracket === true || !remaining().includes("]")) {
947
+ if (opts.nobracket !== true && opts.strictBrackets === true) {
948
+ throw new SyntaxError(syntaxError("closing", "]"));
949
+ }
950
+ value = `\\${value}`;
951
+ } else {
952
+ increment("brackets");
953
+ }
954
+ push({ type: "bracket", value });
955
+ continue;
956
+ }
957
+ if (value === "]") {
958
+ if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
959
+ push({ type: "text", value, output: `\\${value}` });
960
+ continue;
961
+ }
962
+ if (state.brackets === 0) {
963
+ if (opts.strictBrackets === true) {
964
+ throw new SyntaxError(syntaxError("opening", "["));
965
+ }
966
+ push({ type: "text", value, output: `\\${value}` });
967
+ continue;
968
+ }
969
+ decrement("brackets");
970
+ const prevValue = prev.value.slice(1);
971
+ if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) {
972
+ value = `/${value}`;
973
+ }
974
+ prev.value += value;
975
+ append({ value });
976
+ if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) {
977
+ continue;
978
+ }
979
+ const escaped = utils$2.escapeRegex(prev.value);
980
+ state.output = state.output.slice(0, -prev.value.length);
981
+ if (opts.literalBrackets === true) {
982
+ state.output += escaped;
983
+ prev.value = escaped;
984
+ continue;
985
+ }
986
+ prev.value = `(${capture}${escaped}|${prev.value})`;
987
+ state.output += prev.value;
988
+ continue;
989
+ }
990
+ if (value === "{" && opts.nobrace !== true) {
991
+ increment("braces");
992
+ const open = {
993
+ type: "brace",
994
+ value,
995
+ output: "(",
996
+ outputIndex: state.output.length,
997
+ tokensIndex: state.tokens.length
998
+ };
999
+ braces.push(open);
1000
+ push(open);
1001
+ continue;
1002
+ }
1003
+ if (value === "}") {
1004
+ const brace = braces[braces.length - 1];
1005
+ if (opts.nobrace === true || !brace) {
1006
+ push({ type: "text", value, output: value });
1007
+ continue;
1008
+ }
1009
+ let output = ")";
1010
+ if (brace.dots === true) {
1011
+ const arr = tokens.slice();
1012
+ const range = [];
1013
+ for (let i = arr.length - 1; i >= 0; i--) {
1014
+ tokens.pop();
1015
+ if (arr[i].type === "brace") {
1016
+ break;
1017
+ }
1018
+ if (arr[i].type !== "dots") {
1019
+ range.unshift(arr[i].value);
1020
+ }
1021
+ }
1022
+ output = expandRange(range, opts);
1023
+ state.backtrack = true;
1024
+ }
1025
+ if (brace.comma !== true && brace.dots !== true) {
1026
+ const out = state.output.slice(0, brace.outputIndex);
1027
+ const toks = state.tokens.slice(brace.tokensIndex);
1028
+ brace.value = brace.output = "\\{";
1029
+ value = output = "\\}";
1030
+ state.output = out;
1031
+ for (const t of toks) {
1032
+ state.output += t.output || t.value;
1033
+ }
1034
+ }
1035
+ push({ type: "brace", value, output });
1036
+ decrement("braces");
1037
+ braces.pop();
1038
+ continue;
1039
+ }
1040
+ if (value === "|") {
1041
+ if (extglobs.length > 0) {
1042
+ extglobs[extglobs.length - 1].conditions++;
1043
+ }
1044
+ push({ type: "text", value });
1045
+ continue;
1046
+ }
1047
+ if (value === ",") {
1048
+ let output = value;
1049
+ const brace = braces[braces.length - 1];
1050
+ if (brace && stack[stack.length - 1] === "braces") {
1051
+ brace.comma = true;
1052
+ output = "|";
1053
+ }
1054
+ push({ type: "comma", value, output });
1055
+ continue;
1056
+ }
1057
+ if (value === "/") {
1058
+ if (prev.type === "dot" && state.index === state.start + 1) {
1059
+ state.start = state.index + 1;
1060
+ state.consumed = "";
1061
+ state.output = "";
1062
+ tokens.pop();
1063
+ prev = bos;
1064
+ continue;
1065
+ }
1066
+ push({ type: "slash", value, output: SLASH_LITERAL2 });
1067
+ continue;
1068
+ }
1069
+ if (value === ".") {
1070
+ if (state.braces > 0 && prev.type === "dot") {
1071
+ if (prev.value === ".")
1072
+ prev.output = DOT_LITERAL2;
1073
+ const brace = braces[braces.length - 1];
1074
+ prev.type = "dots";
1075
+ prev.output += value;
1076
+ prev.value += value;
1077
+ brace.dots = true;
1078
+ continue;
1079
+ }
1080
+ if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
1081
+ push({ type: "text", value, output: DOT_LITERAL2 });
1082
+ continue;
1083
+ }
1084
+ push({ type: "dot", value, output: DOT_LITERAL2 });
1085
+ continue;
1086
+ }
1087
+ if (value === "?") {
1088
+ const isGroup = prev && prev.value === "(";
1089
+ if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1090
+ extglobOpen("qmark", value);
1091
+ continue;
1092
+ }
1093
+ if (prev && prev.type === "paren") {
1094
+ const next = peek();
1095
+ let output = value;
1096
+ if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) {
1097
+ output = `\\${value}`;
1098
+ }
1099
+ push({ type: "text", value, output });
1100
+ continue;
1101
+ }
1102
+ if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
1103
+ push({ type: "qmark", value, output: QMARK_NO_DOT2 });
1104
+ continue;
1105
+ }
1106
+ push({ type: "qmark", value, output: QMARK2 });
1107
+ continue;
1108
+ }
1109
+ if (value === "!") {
1110
+ if (opts.noextglob !== true && peek() === "(") {
1111
+ if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
1112
+ extglobOpen("negate", value);
1113
+ continue;
1114
+ }
1115
+ }
1116
+ if (opts.nonegate !== true && state.index === 0) {
1117
+ negate();
1118
+ continue;
1119
+ }
1120
+ }
1121
+ if (value === "+") {
1122
+ if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1123
+ extglobOpen("plus", value);
1124
+ continue;
1125
+ }
1126
+ if (prev && prev.value === "(" || opts.regex === false) {
1127
+ push({ type: "plus", value, output: PLUS_LITERAL2 });
1128
+ continue;
1129
+ }
1130
+ if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
1131
+ push({ type: "plus", value });
1132
+ continue;
1133
+ }
1134
+ push({ type: "plus", value: PLUS_LITERAL2 });
1135
+ continue;
1136
+ }
1137
+ if (value === "@") {
1138
+ if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1139
+ push({ type: "at", extglob: true, value, output: "" });
1140
+ continue;
1141
+ }
1142
+ push({ type: "text", value });
1143
+ continue;
1144
+ }
1145
+ if (value !== "*") {
1146
+ if (value === "$" || value === "^") {
1147
+ value = `\\${value}`;
1148
+ }
1149
+ const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
1150
+ if (match) {
1151
+ value += match[0];
1152
+ state.index += match[0].length;
1153
+ }
1154
+ push({ type: "text", value });
1155
+ continue;
1156
+ }
1157
+ if (prev && (prev.type === "globstar" || prev.star === true)) {
1158
+ prev.type = "star";
1159
+ prev.star = true;
1160
+ prev.value += value;
1161
+ prev.output = star;
1162
+ state.backtrack = true;
1163
+ state.globstar = true;
1164
+ consume(value);
1165
+ continue;
1166
+ }
1167
+ let rest = remaining();
1168
+ if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
1169
+ extglobOpen("star", value);
1170
+ continue;
1171
+ }
1172
+ if (prev.type === "star") {
1173
+ if (opts.noglobstar === true) {
1174
+ consume(value);
1175
+ continue;
1176
+ }
1177
+ const prior = prev.prev;
1178
+ const before = prior.prev;
1179
+ const isStart = prior.type === "slash" || prior.type === "bos";
1180
+ const afterStar = before && (before.type === "star" || before.type === "globstar");
1181
+ if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
1182
+ push({ type: "star", value, output: "" });
1183
+ continue;
1184
+ }
1185
+ const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace");
1186
+ const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
1187
+ if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
1188
+ push({ type: "star", value, output: "" });
1189
+ continue;
1190
+ }
1191
+ while (rest.slice(0, 3) === "/**") {
1192
+ const after = input[state.index + 4];
1193
+ if (after && after !== "/") {
1194
+ break;
1195
+ }
1196
+ rest = rest.slice(3);
1197
+ consume("/**", 3);
1198
+ }
1199
+ if (prior.type === "bos" && eos()) {
1200
+ prev.type = "globstar";
1201
+ prev.value += value;
1202
+ prev.output = globstar(opts);
1203
+ state.output = prev.output;
1204
+ state.globstar = true;
1205
+ consume(value);
1206
+ continue;
1207
+ }
1208
+ if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
1209
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
1210
+ prior.output = `(?:${prior.output}`;
1211
+ prev.type = "globstar";
1212
+ prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
1213
+ prev.value += value;
1214
+ state.globstar = true;
1215
+ state.output += prior.output + prev.output;
1216
+ consume(value);
1217
+ continue;
1218
+ }
1219
+ if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
1220
+ const end = rest[1] !== void 0 ? "|$" : "";
1221
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
1222
+ prior.output = `(?:${prior.output}`;
1223
+ prev.type = "globstar";
1224
+ prev.output = `${globstar(opts)}${SLASH_LITERAL2}|${SLASH_LITERAL2}${end})`;
1225
+ prev.value += value;
1226
+ state.output += prior.output + prev.output;
1227
+ state.globstar = true;
1228
+ consume(value + advance());
1229
+ push({ type: "slash", value: "/", output: "" });
1230
+ continue;
1231
+ }
1232
+ if (prior.type === "bos" && rest[0] === "/") {
1233
+ prev.type = "globstar";
1234
+ prev.value += value;
1235
+ prev.output = `(?:^|${SLASH_LITERAL2}|${globstar(opts)}${SLASH_LITERAL2})`;
1236
+ state.output = prev.output;
1237
+ state.globstar = true;
1238
+ consume(value + advance());
1239
+ push({ type: "slash", value: "/", output: "" });
1240
+ continue;
1241
+ }
1242
+ state.output = state.output.slice(0, -prev.output.length);
1243
+ prev.type = "globstar";
1244
+ prev.output = globstar(opts);
1245
+ prev.value += value;
1246
+ state.output += prev.output;
1247
+ state.globstar = true;
1248
+ consume(value);
1249
+ continue;
1250
+ }
1251
+ const token = { type: "star", value, output: star };
1252
+ if (opts.bash === true) {
1253
+ token.output = ".*?";
1254
+ if (prev.type === "bos" || prev.type === "slash") {
1255
+ token.output = nodot + token.output;
1256
+ }
1257
+ push(token);
1258
+ continue;
1259
+ }
1260
+ if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
1261
+ token.output = value;
1262
+ push(token);
1263
+ continue;
1264
+ }
1265
+ if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
1266
+ if (prev.type === "dot") {
1267
+ state.output += NO_DOT_SLASH2;
1268
+ prev.output += NO_DOT_SLASH2;
1269
+ } else if (opts.dot === true) {
1270
+ state.output += NO_DOTS_SLASH2;
1271
+ prev.output += NO_DOTS_SLASH2;
1272
+ } else {
1273
+ state.output += nodot;
1274
+ prev.output += nodot;
1275
+ }
1276
+ if (peek() !== "*") {
1277
+ state.output += ONE_CHAR2;
1278
+ prev.output += ONE_CHAR2;
1279
+ }
1280
+ }
1281
+ push(token);
1282
+ }
1283
+ while (state.brackets > 0) {
1284
+ if (opts.strictBrackets === true)
1285
+ throw new SyntaxError(syntaxError("closing", "]"));
1286
+ state.output = utils$2.escapeLast(state.output, "[");
1287
+ decrement("brackets");
1288
+ }
1289
+ while (state.parens > 0) {
1290
+ if (opts.strictBrackets === true)
1291
+ throw new SyntaxError(syntaxError("closing", ")"));
1292
+ state.output = utils$2.escapeLast(state.output, "(");
1293
+ decrement("parens");
1294
+ }
1295
+ while (state.braces > 0) {
1296
+ if (opts.strictBrackets === true)
1297
+ throw new SyntaxError(syntaxError("closing", "}"));
1298
+ state.output = utils$2.escapeLast(state.output, "{");
1299
+ decrement("braces");
1300
+ }
1301
+ if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) {
1302
+ push({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL2}?` });
1303
+ }
1304
+ if (state.backtrack === true) {
1305
+ state.output = "";
1306
+ for (const token of state.tokens) {
1307
+ state.output += token.output != null ? token.output : token.value;
1308
+ if (token.suffix) {
1309
+ state.output += token.suffix;
1310
+ }
1311
+ }
1312
+ }
1313
+ return state;
1314
+ };
1315
+ parse$1.fastpaths = (input, options) => {
1316
+ const opts = { ...options };
1317
+ const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
1318
+ const len = input.length;
1319
+ if (len > max) {
1320
+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
1321
+ }
1322
+ input = REPLACEMENTS[input] || input;
1323
+ const {
1324
+ DOT_LITERAL: DOT_LITERAL2,
1325
+ SLASH_LITERAL: SLASH_LITERAL2,
1326
+ ONE_CHAR: ONE_CHAR2,
1327
+ DOTS_SLASH: DOTS_SLASH2,
1328
+ NO_DOT: NO_DOT2,
1329
+ NO_DOTS: NO_DOTS2,
1330
+ NO_DOTS_SLASH: NO_DOTS_SLASH2,
1331
+ STAR: STAR2,
1332
+ START_ANCHOR: START_ANCHOR2
1333
+ } = constants$1.globChars(opts.windows);
1334
+ const nodot = opts.dot ? NO_DOTS2 : NO_DOT2;
1335
+ const slashDot = opts.dot ? NO_DOTS_SLASH2 : NO_DOT2;
1336
+ const capture = opts.capture ? "" : "?:";
1337
+ const state = { negated: false, prefix: "" };
1338
+ let star = opts.bash === true ? ".*?" : STAR2;
1339
+ if (opts.capture) {
1340
+ star = `(${star})`;
1341
+ }
1342
+ const globstar = (opts2) => {
1343
+ if (opts2.noglobstar === true)
1344
+ return star;
1345
+ return `(${capture}(?:(?!${START_ANCHOR2}${opts2.dot ? DOTS_SLASH2 : DOT_LITERAL2}).)*?)`;
1346
+ };
1347
+ const create = (str) => {
1348
+ switch (str) {
1349
+ case "*":
1350
+ return `${nodot}${ONE_CHAR2}${star}`;
1351
+ case ".*":
1352
+ return `${DOT_LITERAL2}${ONE_CHAR2}${star}`;
1353
+ case "*.*":
1354
+ return `${nodot}${star}${DOT_LITERAL2}${ONE_CHAR2}${star}`;
1355
+ case "*/*":
1356
+ return `${nodot}${star}${SLASH_LITERAL2}${ONE_CHAR2}${slashDot}${star}`;
1357
+ case "**":
1358
+ return nodot + globstar(opts);
1359
+ case "**/*":
1360
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL2})?${slashDot}${ONE_CHAR2}${star}`;
1361
+ case "**/*.*":
1362
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL2})?${slashDot}${star}${DOT_LITERAL2}${ONE_CHAR2}${star}`;
1363
+ case "**/.*":
1364
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL2})?${DOT_LITERAL2}${ONE_CHAR2}${star}`;
1365
+ default: {
1366
+ const match = /^(.*?)\.(\w+)$/.exec(str);
1367
+ if (!match)
1368
+ return;
1369
+ const source2 = create(match[1]);
1370
+ if (!source2)
1371
+ return;
1372
+ return source2 + DOT_LITERAL2 + match[2];
1373
+ }
1374
+ }
1375
+ };
1376
+ const output = utils$2.removePrefix(input, state);
1377
+ let source = create(output);
1378
+ if (source && opts.strictSlashes !== true) {
1379
+ source += `${SLASH_LITERAL2}?`;
1380
+ }
1381
+ return source;
1382
+ };
1383
+ var parse_1 = parse$1;
1384
+ const scan = scan_1;
1385
+ const parse = parse_1;
1386
+ const utils$1 = utils$4;
1387
+ const constants = constants$2;
1388
+ const isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
1389
+ const picomatch$2 = (glob, options, returnState = false) => {
1390
+ if (Array.isArray(glob)) {
1391
+ const fns = glob.map((input) => picomatch$2(input, options, returnState));
1392
+ const arrayMatcher = (str) => {
1393
+ for (const isMatch of fns) {
1394
+ const state2 = isMatch(str);
1395
+ if (state2)
1396
+ return state2;
1397
+ }
1398
+ return false;
1399
+ };
1400
+ return arrayMatcher;
1401
+ }
1402
+ const isState = isObject(glob) && glob.tokens && glob.input;
1403
+ if (glob === "" || typeof glob !== "string" && !isState) {
1404
+ throw new TypeError("Expected pattern to be a non-empty string");
1405
+ }
1406
+ const opts = options || {};
1407
+ const posix = opts.windows;
1408
+ const regex = isState ? picomatch$2.compileRe(glob, options) : picomatch$2.makeRe(glob, options, false, true);
1409
+ const state = regex.state;
1410
+ delete regex.state;
1411
+ let isIgnored = () => false;
1412
+ if (opts.ignore) {
1413
+ const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
1414
+ isIgnored = picomatch$2(opts.ignore, ignoreOpts, returnState);
1415
+ }
1416
+ const matcher = (input, returnObject = false) => {
1417
+ const { isMatch, match, output } = picomatch$2.test(input, regex, options, { glob, posix });
1418
+ const result = { glob, state, regex, posix, input, output, match, isMatch };
1419
+ if (typeof opts.onResult === "function") {
1420
+ opts.onResult(result);
1421
+ }
1422
+ if (isMatch === false) {
1423
+ result.isMatch = false;
1424
+ return returnObject ? result : false;
1425
+ }
1426
+ if (isIgnored(input)) {
1427
+ if (typeof opts.onIgnore === "function") {
1428
+ opts.onIgnore(result);
1429
+ }
1430
+ result.isMatch = false;
1431
+ return returnObject ? result : false;
1432
+ }
1433
+ if (typeof opts.onMatch === "function") {
1434
+ opts.onMatch(result);
1435
+ }
1436
+ return returnObject ? result : true;
1437
+ };
1438
+ if (returnState) {
1439
+ matcher.state = state;
1440
+ }
1441
+ return matcher;
1442
+ };
1443
+ picomatch$2.test = (input, regex, options, { glob, posix } = {}) => {
1444
+ if (typeof input !== "string") {
1445
+ throw new TypeError("Expected input to be a string");
1446
+ }
1447
+ if (input === "") {
1448
+ return { isMatch: false, output: "" };
1449
+ }
1450
+ const opts = options || {};
1451
+ const format = opts.format || (posix ? utils$1.toPosixSlashes : null);
1452
+ let match = input === glob;
1453
+ let output = match && format ? format(input) : input;
1454
+ if (match === false) {
1455
+ output = format ? format(input) : input;
1456
+ match = output === glob;
1457
+ }
1458
+ if (match === false || opts.capture === true) {
1459
+ if (opts.matchBase === true || opts.basename === true) {
1460
+ match = picomatch$2.matchBase(input, regex, options, posix);
1461
+ } else {
1462
+ match = regex.exec(output);
1463
+ }
1464
+ }
1465
+ return { isMatch: Boolean(match), match, output };
1466
+ };
1467
+ picomatch$2.matchBase = (input, glob, options) => {
1468
+ const regex = glob instanceof RegExp ? glob : picomatch$2.makeRe(glob, options);
1469
+ return regex.test(utils$1.basename(input));
1470
+ };
1471
+ picomatch$2.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str);
1472
+ picomatch$2.parse = (pattern, options) => {
1473
+ if (Array.isArray(pattern))
1474
+ return pattern.map((p) => picomatch$2.parse(p, options));
1475
+ return parse(pattern, { ...options, fastpaths: false });
1476
+ };
1477
+ picomatch$2.scan = (input, options) => scan(input, options);
1478
+ picomatch$2.compileRe = (state, options, returnOutput = false, returnState = false) => {
1479
+ if (returnOutput === true) {
1480
+ return state.output;
1481
+ }
1482
+ const opts = options || {};
1483
+ const prepend = opts.contains ? "" : "^";
1484
+ const append = opts.contains ? "" : "$";
1485
+ let source = `${prepend}(?:${state.output})${append}`;
1486
+ if (state && state.negated === true) {
1487
+ source = `^(?!${source}).*$`;
1488
+ }
1489
+ const regex = picomatch$2.toRegex(source, options);
1490
+ if (returnState === true) {
1491
+ regex.state = state;
1492
+ }
1493
+ return regex;
1494
+ };
1495
+ picomatch$2.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
1496
+ if (!input || typeof input !== "string") {
1497
+ throw new TypeError("Expected a non-empty string");
1498
+ }
1499
+ let parsed = { negated: false, fastpaths: true };
1500
+ if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) {
1501
+ parsed.output = parse.fastpaths(input, options);
1502
+ }
1503
+ if (!parsed.output) {
1504
+ parsed = parse(input, options);
1505
+ }
1506
+ return picomatch$2.compileRe(parsed, options, returnOutput, returnState);
1507
+ };
1508
+ picomatch$2.toRegex = (source, options) => {
1509
+ try {
1510
+ const opts = options || {};
1511
+ return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
1512
+ } catch (err) {
1513
+ if (options && options.debug === true)
1514
+ throw err;
1515
+ return /$^/;
1516
+ }
1517
+ };
1518
+ picomatch$2.constants = constants;
1519
+ var picomatch_1$1 = picomatch$2;
1520
+ const pico = picomatch_1$1;
1521
+ const utils = utils$4;
1522
+ function picomatch(glob, options, returnState = false) {
1523
+ if (options && (options.windows === null || options.windows === void 0)) {
1524
+ options = { ...options, windows: utils.isWindows() };
1525
+ }
1526
+ return pico(glob, options, returnState);
1527
+ }
1528
+ Object.assign(picomatch, pico);
1529
+ var picomatch_1 = picomatch;
1530
+ const picomatch$1 = /* @__PURE__ */ getDefaultExportFromCjs(picomatch_1);
1531
+ function assertShape(value, yupSchema, errorMessage) {
1532
+ const shape = yupSchema(yup);
1533
+ try {
1534
+ shape.validateSync(value);
1535
+ } catch (e) {
1536
+ const message = errorMessage || `Failed to assertShape - ${e.message}`;
1537
+ throw new Error(message);
1538
+ }
1539
+ }
1540
+ const lastItem = (arr) => {
1541
+ if (typeof arr === "undefined") {
1542
+ throw new Error("Can not call lastItem when arr is undefined");
1543
+ }
1544
+ return arr[arr.length - 1];
1545
+ };
1546
+ const capitalize = (s) => {
1547
+ if (typeof s !== "string")
1548
+ return "";
1549
+ return s.charAt(0).toUpperCase() + s.slice(1);
1550
+ };
1551
+ const generateNamespacedFieldName = (names, suffix = "") => {
1552
+ return (suffix ? [...names, suffix] : names).map(capitalize).join("");
1553
+ };
1554
+ const NAMER = {
1555
+ dataFilterTypeNameOn: (namespace) => {
1556
+ return generateNamespacedFieldName(namespace, "_FilterOn");
1557
+ },
1558
+ dataFilterTypeName: (namespace) => {
1559
+ return generateNamespacedFieldName(namespace, "Filter");
1560
+ },
1561
+ dataMutationTypeNameOn: (namespace) => {
1562
+ return generateNamespacedFieldName(namespace, "_MutationOn");
1563
+ },
1564
+ dataMutationTypeName: (namespace) => {
1565
+ return generateNamespacedFieldName(namespace, "Mutation");
1566
+ },
1567
+ updateName: (namespace) => {
1568
+ return "update" + generateNamespacedFieldName(namespace, "Document");
1569
+ },
1570
+ createName: (namespace) => {
1571
+ return "create" + generateNamespacedFieldName(namespace, "Document");
1572
+ },
1573
+ queryName: (namespace) => {
1574
+ return "get" + generateNamespacedFieldName(namespace, "Document");
1575
+ },
1576
+ generateQueryListName: (namespace) => {
1577
+ return "get" + generateNamespacedFieldName(namespace, "List");
1578
+ },
1579
+ fragmentName: (namespace) => {
1580
+ return generateNamespacedFieldName(namespace, "") + "Parts";
1581
+ },
1582
+ collectionTypeName: (namespace) => {
1583
+ return generateNamespacedFieldName(namespace, "Collection");
1584
+ },
1585
+ documentTypeName: (namespace) => {
1586
+ return generateNamespacedFieldName(namespace, "Document");
1587
+ },
1588
+ dataTypeName: (namespace) => {
1589
+ return generateNamespacedFieldName(namespace, "");
1590
+ },
1591
+ referenceConnectionType: (namespace) => {
1592
+ return generateNamespacedFieldName(namespace, "Connection");
1593
+ },
1594
+ referenceConnectionEdgesTypeName: (namespace) => {
1595
+ return generateNamespacedFieldName(namespace, "ConnectionEdges");
1596
+ }
1597
+ };
1598
+ function findDuplicates(array = []) {
1599
+ const duplicates = [
1600
+ ...new Set(array.filter((item, index) => array.indexOf(item) !== index))
1601
+ ].map((x) => `"${x}"`);
1602
+ if (duplicates.length) {
1603
+ return duplicates.join(", ");
1604
+ } else
1605
+ return void 0;
1606
+ }
1607
+ const TINA_HOST = "content.tinajs.io";
1608
+ const parseURL = (url) => {
1609
+ if (url.startsWith("/")) {
1610
+ return {
1611
+ branch: null,
1612
+ isLocalClient: false,
1613
+ clientId: null,
1614
+ host: null
1615
+ };
1616
+ }
1617
+ if (url.includes("localhost")) {
1618
+ return {
1619
+ branch: null,
1620
+ isLocalClient: true,
1621
+ clientId: null,
1622
+ host: "localhost"
1623
+ };
1624
+ }
1625
+ const params = new URL(url);
1626
+ const isTinaCloud = params.host.includes("tinajs.dev") || params.host.includes("tina.io") || params.host.includes("tinajs.io");
1627
+ if (!isTinaCloud) {
1628
+ return {
1629
+ branch: null,
1630
+ isLocalClient: true,
1631
+ clientId: null,
1632
+ host: params.host
1633
+ };
1634
+ }
1635
+ const pattern = new UrlPattern("/:v/content/:clientId/github/*", {
1636
+ escapeChar: " ",
1637
+ // extend to allow `.` in version
1638
+ segmentValueCharset: "a-zA-Z0-9-_~ %."
1639
+ });
1640
+ const result = pattern.match(params.pathname);
1641
+ const branch = result == null ? void 0 : result._;
1642
+ const clientId = result == null ? void 0 : result.clientId;
1643
+ if (!branch || !clientId) {
1644
+ throw new Error(
1645
+ `Invalid URL format provided. Expected: https://content.tinajs.io/<Version>/content/<ClientID>/github/<Branch> but but received ${url}`
1646
+ );
1647
+ }
1648
+ return {
1649
+ host: params.host,
1650
+ branch,
1651
+ clientId,
1652
+ isLocalClient: false
1653
+ };
1654
+ };
1655
+ const normalizePath = (filepath) => filepath.replace(/\\/g, "/");
1656
+ const canonicalPath = (filepath) => {
1657
+ return normalizePath(filepath).split("/").filter((name2) => name2 !== "").join("/");
1658
+ };
1659
+ class TinaSchema {
1660
+ /**
1661
+ * Create a schema class from a user defined schema object
1662
+ */
1663
+ constructor(config) {
1664
+ __publicField(this, "schema");
1665
+ __publicField(this, "getIsTitleFieldName", (collection) => {
1666
+ var _a;
1667
+ const col = this.getCollection(collection);
1668
+ const field = (_a = col == null ? void 0 : col.fields) == null ? void 0 : _a.find((x) => x.type === "string" && x.isTitle);
1669
+ return field == null ? void 0 : field.name;
1670
+ });
1671
+ __publicField(this, "getCollectionsByName", (collectionNames) => {
1672
+ return this.schema.collections.filter(
1673
+ (collection) => collectionNames.includes(collection.name)
1674
+ );
1675
+ });
1676
+ __publicField(this, "getCollection", (collectionName) => {
1677
+ const collection = this.schema.collections.find(
1678
+ (collection2) => collection2.name === collectionName
1679
+ );
1680
+ if (!collection) {
1681
+ throw new Error(`Expected to find collection named ${collectionName}`);
1682
+ }
1683
+ const extraFields = {};
1684
+ const templateInfo = this.getTemplatesForCollectable(collection);
1685
+ switch (templateInfo.type) {
1686
+ case "object":
1687
+ extraFields.fields = templateInfo.template.fields;
1688
+ break;
1689
+ case "union":
1690
+ extraFields.templates = templateInfo.templates;
1691
+ break;
1692
+ }
1693
+ return {
1694
+ // @ts-ignore FIXME: backwards compatibility, using `slug` should probably be deprecated
1695
+ slug: collection.name,
1696
+ ...extraFields,
1697
+ ...collection,
1698
+ format: collection.format || "md"
1699
+ };
1700
+ });
1701
+ __publicField(this, "getCollections", () => {
1702
+ return this.schema.collections.map(
1703
+ (collection) => this.getCollection(collection.name)
1704
+ ) || [];
1705
+ });
1706
+ __publicField(this, "getCollectionByFullPath", (filepath) => {
1707
+ const fileExtension = filepath.split(".").pop();
1708
+ const canonicalFilepath = canonicalPath(filepath);
1709
+ const possibleCollections = this.getCollections().filter((collection) => {
1710
+ var _a, _b;
1711
+ if (!canonicalFilepath.endsWith(`.gitkeep.${collection.format || "md"}`) && fileExtension !== (collection.format || "md")) {
1712
+ return false;
1713
+ }
1714
+ if (((_a = collection == null ? void 0 : collection.match) == null ? void 0 : _a.include) || ((_b = collection == null ? void 0 : collection.match) == null ? void 0 : _b.exclude)) {
1715
+ const matches = this.getMatches({ collection });
1716
+ const match = picomatch$1.isMatch(canonicalFilepath, matches);
1717
+ if (!match) {
1718
+ return false;
1719
+ }
1720
+ }
1721
+ const collectionPath = canonicalPath(collection.path);
1722
+ return collectionPath === "" || canonicalFilepath.startsWith(`${collectionPath}/`);
1723
+ });
1724
+ if (possibleCollections.length === 0) {
1725
+ throw new Error(`Unable to find collection for file at ${filepath}`);
1726
+ }
1727
+ if (possibleCollections.length === 1) {
1728
+ return possibleCollections[0];
1729
+ }
1730
+ if (possibleCollections.length > 1) {
1731
+ const longestMatch = possibleCollections.reduce((acc, collection) => {
1732
+ if (collection.path.length > acc.path.length) {
1733
+ return collection;
1734
+ }
1735
+ return acc;
1736
+ });
1737
+ return longestMatch;
1738
+ }
1739
+ });
1740
+ __publicField(this, "getCollectionAndTemplateByFullPath", (filepath, templateName) => {
1741
+ const collection = this.getCollectionByFullPath(filepath);
1742
+ if (!collection) {
1743
+ return void 0;
1744
+ }
1745
+ let template;
1746
+ const templates = this.getTemplatesForCollectable(collection);
1747
+ if (templates.type === "union") {
1748
+ if (templateName) {
1749
+ template = templates.templates.find(
1750
+ (template2) => lastItem(template2.namespace) === templateName
1751
+ );
1752
+ if (!template) {
1753
+ throw new Error(
1754
+ `Unable to determine template for item at ${filepath}`
1755
+ );
1756
+ }
1757
+ } else {
1758
+ throw new Error(
1759
+ `Unable to determine template for item at ${filepath}, no template name provided for collection with multiple templates`
1760
+ );
1761
+ }
1762
+ }
1763
+ if (templates.type === "object") {
1764
+ template = templates.template;
1765
+ }
1766
+ if (!template) {
1767
+ throw new Error(
1768
+ `Something went wrong while trying to determine template for ${filepath}`
1769
+ );
1770
+ }
1771
+ return { collection, template };
1772
+ });
1773
+ __publicField(this, "getTemplateForData", ({
1774
+ data,
1775
+ collection
1776
+ }) => {
1777
+ const templateInfo = this.getTemplatesForCollectable(collection);
1778
+ switch (templateInfo.type) {
1779
+ case "object":
1780
+ return templateInfo.template;
1781
+ case "union": {
1782
+ assertShape(
1783
+ data,
1784
+ (yup2) => yup2.object({ _template: yup2.string().required() })
1785
+ );
1786
+ const template = templateInfo.templates.find(
1787
+ (template2) => template2.namespace[template2.namespace.length - 1] === data._template
1788
+ );
1789
+ if (!template) {
1790
+ throw new Error(
1791
+ `Expected to find template named '${data._template}' for collection '${lastItem(collection.namespace)}'`
1792
+ );
1793
+ }
1794
+ return template;
1795
+ }
1796
+ }
1797
+ });
1798
+ __publicField(this, "transformPayload", (collectionName, payload) => {
1799
+ const collection = this.getCollection(collectionName);
1800
+ if (collection.templates) {
1801
+ const template = collection.templates.find((template2) => {
1802
+ if (typeof template2 === "string") {
1803
+ throw new Error("Global templates not supported");
1804
+ }
1805
+ return (payload == null ? void 0 : payload._template) === template2.name;
1806
+ });
1807
+ if (!template) {
1808
+ console.error(payload);
1809
+ throw new Error("Unable to find template for payload");
1810
+ }
1811
+ if (typeof template === "string") {
1812
+ throw new Error("Global templates not supported");
1813
+ }
1814
+ return {
1815
+ [collectionName]: {
1816
+ [template.name]: this.transformCollectablePayload(payload, template)
1817
+ }
1818
+ };
1819
+ }
1820
+ return {
1821
+ [collectionName]: this.transformCollectablePayload(payload, collection)
1822
+ };
1823
+ });
1824
+ __publicField(this, "transformCollectablePayload", (payload, collection) => {
1825
+ const accumulator = {};
1826
+ Object.entries(payload).forEach(([key, value]) => {
1827
+ var _a;
1828
+ if (typeof collection.fields === "string") {
1829
+ throw new Error("Global templates not supported");
1830
+ }
1831
+ const field = (_a = collection == null ? void 0 : collection.fields) == null ? void 0 : _a.find((field2) => {
1832
+ if (typeof field2 === "string") {
1833
+ throw new Error("Global templates not supported");
1834
+ }
1835
+ return field2.name === key;
1836
+ });
1837
+ if (field) {
1838
+ accumulator[key] = this.transformField(field, value);
1839
+ }
1840
+ });
1841
+ return accumulator;
1842
+ });
1843
+ __publicField(this, "transformField", (field, value) => {
1844
+ if (field.type === "object")
1845
+ if (field.templates) {
1846
+ if (field.list) {
1847
+ assertShape(
1848
+ value,
1849
+ (yup2) => yup2.array(yup2.object({ _template: yup2.string().required() }))
1850
+ );
1851
+ return value.map((item) => {
1852
+ const { _template, ...rest } = item;
1853
+ const template = field.templates.find((template2) => {
1854
+ if (typeof template2 === "string") {
1855
+ return false;
1856
+ }
1857
+ return template2.name === _template;
1858
+ });
1859
+ if (typeof template === "string") {
1860
+ throw new Error("Global templates not supported");
1861
+ }
1862
+ if (!template) {
1863
+ throw new Error(`Expected to find template named '${_template}'`);
1864
+ }
1865
+ return {
1866
+ [_template]: this.transformCollectablePayload(rest, template)
1867
+ };
1868
+ });
1869
+ } else {
1870
+ assertShape(
1871
+ value,
1872
+ (yup2) => yup2.object({ _template: yup2.string().required() })
1873
+ );
1874
+ const { _template, ...rest } = value;
1875
+ return { [_template]: this.transformCollectablePayload(rest, field) };
1876
+ }
1877
+ } else {
1878
+ if (field.list) {
1879
+ assertShape(value, (yup2) => yup2.array(yup2.object()));
1880
+ return value.map((item) => {
1881
+ return this.transformCollectablePayload(item, field);
1882
+ });
1883
+ } else {
1884
+ assertShape(value, (yup2) => yup2.object());
1885
+ return this.transformCollectablePayload(value, field);
1886
+ }
1887
+ }
1888
+ else {
1889
+ return value;
1890
+ }
1891
+ });
1892
+ __publicField(this, "isMarkdownCollection", (collectionName) => {
1893
+ const collection = this.getCollection(collectionName);
1894
+ const format = collection.format;
1895
+ if (!format) {
1896
+ return true;
1897
+ }
1898
+ if (["markdown", "md"].includes(format)) {
1899
+ return true;
1900
+ }
1901
+ return false;
1902
+ });
1903
+ /**
1904
+ * Gets the template or templates from the item.
1905
+ * Both `object` fields and collections support
1906
+ * the ability for an object to be polymorphic,
1907
+ * and if it is, we need to build unions, which
1908
+ * are more of a headache for non-polymorphic
1909
+ * needs, so we also need the ability to just
1910
+ * build object types
1911
+ *
1912
+ *
1913
+ */
1914
+ __publicField(this, "getTemplatesForCollectable", (collection) => {
1915
+ const extraFields = [];
1916
+ if (collection == null ? void 0 : collection.fields) {
1917
+ const template = collection;
1918
+ if (typeof template.fields === "string" || typeof template.fields === "undefined") {
1919
+ throw new Error("Expected template to have fields but none were found");
1920
+ }
1921
+ return {
1922
+ namespace: collection.namespace,
1923
+ type: "object",
1924
+ template: {
1925
+ ...template,
1926
+ fields: [...template.fields, ...extraFields]
1927
+ }
1928
+ };
1929
+ } else {
1930
+ if (collection == null ? void 0 : collection.templates) {
1931
+ return {
1932
+ namespace: collection.namespace,
1933
+ type: "union",
1934
+ templates: collection.templates.map((templateOrTemplateString) => {
1935
+ const template = templateOrTemplateString;
1936
+ return {
1937
+ ...template,
1938
+ fields: [...template.fields, ...extraFields]
1939
+ };
1940
+ })
1941
+ };
1942
+ } else {
1943
+ throw new Error(
1944
+ `Expected either fields or templates array to be defined on collection ${collection.namespace.join(
1945
+ "_"
1946
+ )}`
1947
+ );
1948
+ }
1949
+ }
1950
+ });
1951
+ /**
1952
+ * Walk all fields in Tina Schema
1953
+ *
1954
+ * This is a legacy version to preserve backwards compatibility for the tina generated schema. It does not
1955
+ * traverse fields in object lists in rich-text templates.
1956
+ *
1957
+ * @param cb callback function invoked for each field
1958
+ */
1959
+ __publicField(this, "legacyWalkFields", (cb) => {
1960
+ const walk = (collectionOrObject, collection, path) => {
1961
+ if (collectionOrObject.templates) {
1962
+ collectionOrObject.templates.forEach((template) => {
1963
+ template.fields.forEach((field) => {
1964
+ cb({ field, collection, path: [...path, template.name] });
1965
+ });
1966
+ });
1967
+ }
1968
+ if (collectionOrObject.fields) {
1969
+ collectionOrObject.fields.forEach((field) => {
1970
+ cb({ field, collection, path: [...path, field.name] });
1971
+ if (field.type === "rich-text" || field.type === "object") {
1972
+ walk(field, collection, [...path, field.name]);
1973
+ }
1974
+ });
1975
+ }
1976
+ };
1977
+ const collections = this.getCollections();
1978
+ collections.forEach((collection) => walk(collection, collection, []));
1979
+ });
1980
+ this.config = config;
1981
+ this.schema = config;
1982
+ this.legacyWalkFields(({ field, collection }) => {
1983
+ if (!("searchable" in field)) {
1984
+ if (field.type === "image") {
1985
+ field.searchable = false;
1986
+ } else {
1987
+ field.searchable = true;
1988
+ }
1989
+ }
1990
+ if (field.type === "rich-text") {
1991
+ if (field.parser) {
1992
+ return;
1993
+ }
1994
+ if (collection.format === "mdx") {
1995
+ field.parser = { type: "mdx" };
1996
+ } else {
1997
+ field.parser = { type: "markdown" };
1998
+ }
1999
+ }
2000
+ field.uid = field.uid || false;
2001
+ });
2002
+ }
2003
+ findReferencesFromCollection(name2) {
2004
+ const result = {};
2005
+ this.walkFields(({ field, collection: c, path }) => {
2006
+ if (c.name !== name2) {
2007
+ return;
2008
+ }
2009
+ if (field.type === "reference") {
2010
+ field.collections.forEach((name22) => {
2011
+ if (result[name22] === void 0) {
2012
+ result[name22] = [];
2013
+ }
2014
+ result[name22].push(path);
2015
+ });
2016
+ }
2017
+ });
2018
+ return result;
2019
+ }
2020
+ /**
2021
+ * Walk all fields in tina schema
2022
+ *
2023
+ * @param cb callback function invoked for each field
2024
+ */
2025
+ walkFields(cb) {
2026
+ const walk = (collectionOrObject, collection, path = "$") => {
2027
+ if (collectionOrObject.templates) {
2028
+ collectionOrObject.templates.forEach((template) => {
2029
+ const templatePath = `${path}.${template.name}`;
2030
+ template.fields.forEach((field) => {
2031
+ const fieldPath = field.list ? `${templatePath}[*].${field.name}` : `${templatePath}.${field.name}`;
2032
+ cb({ field, collection, path: fieldPath });
2033
+ if (field.type === "object") {
2034
+ walk(field, collection, fieldPath);
2035
+ }
2036
+ });
2037
+ });
2038
+ }
2039
+ if (collectionOrObject.fields) {
2040
+ collectionOrObject.fields.forEach((field) => {
2041
+ const fieldPath = field.list ? `${path}.${field.name}[*]` : `${path}.${field.name}`;
2042
+ cb({ field, collection, path: fieldPath });
2043
+ if (field.type === "object" && field.fields) {
2044
+ walk(field, collection, fieldPath);
2045
+ } else if (field.templates) {
2046
+ field.templates.forEach((template) => {
2047
+ const templatePath = `${fieldPath}.${template.name}`;
2048
+ template.fields.forEach((field2) => {
2049
+ const fieldPath2 = field2.list ? `${templatePath}[*].${field2.name}` : `${templatePath}.${field2.name}`;
2050
+ cb({ field: field2, collection, path: fieldPath2 });
2051
+ if (field2.type === "object") {
2052
+ walk(field2, collection, fieldPath2);
2053
+ }
2054
+ });
2055
+ });
2056
+ }
2057
+ });
2058
+ }
2059
+ };
2060
+ this.getCollections().forEach((collection) => {
2061
+ walk(collection, collection);
2062
+ });
2063
+ }
2064
+ /**
2065
+ * This function returns an array of glob matches for a given collection.
2066
+ *
2067
+ * @param collection The collection to get the matches for. Can be a string or a collection object.
2068
+ * @returns An array of glob matches.
2069
+ */
2070
+ getMatches({
2071
+ collection: collectionOrString
2072
+ }) {
2073
+ var _a, _b;
2074
+ const collection = typeof collectionOrString === "string" ? this.getCollection(collectionOrString) : collectionOrString;
2075
+ const collectionPath = canonicalPath(collection.path);
2076
+ const pathSuffix = collectionPath ? "/" : "";
2077
+ const format = collection.format || "md";
2078
+ const matches = [];
2079
+ if ((_a = collection == null ? void 0 : collection.match) == null ? void 0 : _a.include) {
2080
+ const match = `${collectionPath}${pathSuffix}${collection.match.include}.${format}`;
2081
+ matches.push(match);
2082
+ }
2083
+ if ((_b = collection == null ? void 0 : collection.match) == null ? void 0 : _b.exclude) {
2084
+ const exclude = `!(${collectionPath}${pathSuffix}${collection.match.exclude}.${format})`;
2085
+ matches.push(exclude);
2086
+ }
2087
+ return matches;
2088
+ }
2089
+ matchFiles({
2090
+ collection,
2091
+ files
2092
+ }) {
2093
+ const matches = this.getMatches({ collection });
2094
+ const matcher = picomatch$1(matches);
2095
+ const matchedFiles = files.filter((file) => matcher(file));
2096
+ return matchedFiles;
2097
+ }
2098
+ }
2099
+ const resolveField = (field, schema) => {
2100
+ var _a;
2101
+ const extraFields = field.ui || {};
2102
+ switch (field.type) {
2103
+ case "number":
2104
+ return {
2105
+ component: "number",
2106
+ ...field,
2107
+ ...extraFields
2108
+ };
2109
+ case "datetime":
2110
+ return {
2111
+ component: "date",
2112
+ ...field,
2113
+ ...extraFields
2114
+ };
2115
+ case "boolean":
2116
+ return {
2117
+ component: "toggle",
2118
+ ...field,
2119
+ ...extraFields
2120
+ };
2121
+ case "image":
2122
+ if (field.list) {
2123
+ return {
2124
+ component: "list",
2125
+ field: {
2126
+ component: "image"
2127
+ },
2128
+ ...field,
2129
+ ...extraFields
2130
+ };
2131
+ }
2132
+ return {
2133
+ component: "image",
2134
+ clearable: true,
2135
+ ...field,
2136
+ ...extraFields
2137
+ };
2138
+ case "string":
2139
+ if (field.options) {
2140
+ if (field.list) {
2141
+ return {
2142
+ component: "checkbox-group",
2143
+ ...field,
2144
+ ...extraFields,
2145
+ options: field.options
2146
+ };
2147
+ }
2148
+ if (field.options[0] && typeof field.options[0] === "object" && field.options[0].icon) {
2149
+ return {
2150
+ component: "button-toggle",
2151
+ ...field,
2152
+ ...extraFields,
2153
+ options: field.options
2154
+ };
2155
+ }
2156
+ return {
2157
+ component: "select",
2158
+ ...field,
2159
+ ...extraFields,
2160
+ options: field.ui && field.ui.component !== "select" ? field.options : [{ label: "Choose an option", value: "" }, ...field.options]
2161
+ };
2162
+ }
2163
+ if (field.list) {
2164
+ return {
2165
+ // Allows component to be overridden for scalars
2166
+ component: "list",
2167
+ field: {
2168
+ component: "text"
2169
+ },
2170
+ ...field,
2171
+ ...extraFields
2172
+ };
2173
+ }
2174
+ return {
2175
+ // Allows component to be overridden for scalars
2176
+ component: "text",
2177
+ ...field,
2178
+ ...extraFields
2179
+ };
2180
+ case "object": {
2181
+ const templateInfo = schema.getTemplatesForCollectable(field);
2182
+ if (templateInfo.type === "object") {
2183
+ return {
2184
+ ...field,
2185
+ component: field.list ? "group-list" : "group",
2186
+ fields: templateInfo.template.fields.map(
2187
+ (field2) => resolveField(field2, schema)
2188
+ ),
2189
+ ...extraFields
2190
+ };
2191
+ } else if (templateInfo.type === "union") {
2192
+ const templates2 = {};
2193
+ const typeMap2 = {};
2194
+ templateInfo.templates.forEach((template) => {
2195
+ const extraFields2 = template.ui || {};
2196
+ const templateName = lastItem(template.namespace);
2197
+ typeMap2[templateName] = NAMER.dataTypeName(template.namespace);
2198
+ templates2[lastItem(template.namespace)] = {
2199
+ label: template.label || templateName,
2200
+ key: templateName,
2201
+ namespace: [...field.namespace, templateName],
2202
+ fields: template.fields.map((field2) => resolveField(field2, schema)),
2203
+ ...extraFields2
2204
+ };
2205
+ return true;
2206
+ });
2207
+ return {
2208
+ ...field,
2209
+ typeMap: typeMap2,
2210
+ namespace: field.namespace,
2211
+ component: field.list ? "blocks" : "not-implemented",
2212
+ templates: templates2,
2213
+ ...extraFields
2214
+ };
2215
+ } else {
2216
+ throw new Error(`Unknown object for resolveField function`);
2217
+ }
2218
+ }
2219
+ case "rich-text":
2220
+ const templates = {};
2221
+ (_a = field.templates) == null ? void 0 : _a.forEach((template) => {
2222
+ if (typeof template === "string") {
2223
+ throw new Error(`Global templates not yet supported for rich-text`);
2224
+ } else {
2225
+ const extraFields2 = template.ui || {};
2226
+ const templateName = lastItem(template.namespace);
2227
+ NAMER.dataTypeName(template.namespace);
2228
+ templates[lastItem(template.namespace)] = {
2229
+ label: template.label || templateName,
2230
+ key: templateName,
2231
+ inline: template.inline,
2232
+ name: templateName,
2233
+ match: template.match,
2234
+ fields: template.fields.map((field2) => resolveField(field2, schema)),
2235
+ ...extraFields2
2236
+ };
2237
+ return true;
2238
+ }
2239
+ });
2240
+ return {
2241
+ ...field,
2242
+ templates: Object.values(templates),
2243
+ component: "rich-text",
2244
+ ...extraFields
2245
+ };
2246
+ case "password":
2247
+ return {
2248
+ component: "password",
2249
+ ...field,
2250
+ ...extraFields
2251
+ };
2252
+ case "reference":
2253
+ return {
2254
+ ...field,
2255
+ component: "reference",
2256
+ ...extraFields
2257
+ };
2258
+ default:
2259
+ throw new Error(`Unknown field type ${field.type}`);
2260
+ }
2261
+ };
2262
+ const resolveForm = ({
2263
+ collection,
2264
+ basename,
2265
+ template,
2266
+ schema
2267
+ }) => {
2268
+ return {
2269
+ id: basename,
2270
+ label: collection.label,
2271
+ name: basename,
2272
+ fields: template.fields.map((field) => {
2273
+ return resolveField(field, schema);
2274
+ })
2275
+ };
2276
+ };
2277
+ const CONTENT_FORMATS = [
2278
+ "mdx",
2279
+ "md",
2280
+ "markdown",
2281
+ "json",
2282
+ "yaml",
2283
+ "yml",
2284
+ "toml"
2285
+ ];
2286
+ const parseZodError = ({ zodError }) => {
2287
+ var _a, _b, _c, _d;
2288
+ const errors = zodError.flatten((issue) => {
2289
+ const moreInfo = [];
2290
+ if (issue.code === "invalid_union") {
2291
+ issue.unionErrors.map((unionError) => {
2292
+ moreInfo.push(parseZodError({ zodError: unionError }));
2293
+ });
2294
+ }
2295
+ const errorMessage = `${issue == null ? void 0 : issue.message}
2296
+ Additional information:
2297
+ - Error found at path ${issue.path.join(
2298
+ "."
2299
+ )}
2300
+ `;
2301
+ const errorMessages = [errorMessage, ...moreInfo];
2302
+ return {
2303
+ errors: errorMessages
2304
+ };
2305
+ });
2306
+ const formErrors = errors.formErrors.flatMap((x) => x.errors);
2307
+ const parsedErrors = [
2308
+ ...((_b = (_a = errors.fieldErrors) == null ? void 0 : _a.collections) == null ? void 0 : _b.flatMap((x) => x.errors)) || [],
2309
+ ...((_d = (_c = errors.fieldErrors) == null ? void 0 : _c.config) == null ? void 0 : _d.flatMap((x) => x.errors)) || [],
2310
+ ...formErrors
2311
+ ];
2312
+ return parsedErrors;
2313
+ };
2314
+ const name = z.string({
2315
+ required_error: "Name is required but not provided",
2316
+ invalid_type_error: "Name must be a string"
2317
+ }).superRefine((val, ctx) => {
2318
+ if (val.match(/^[a-zA-Z0-9_]*$/) === null) {
2319
+ ctx.addIssue({
2320
+ code: "custom",
2321
+ message: `name, "${val}" must be alphanumeric and can only contain underscores. (No spaces, dashes, special characters, etc.)
2322
+ If you only want to display this value in the CMS UI, you can use the label property to customize it.
2323
+
2324
+ If you need to use this value in your content you can use the \`nameOverride\` property to customize the value. For example:
2325
+ \`\`\`
2326
+ {
2327
+ "name": ${val.replace(/[^a-zA-Z0-9]/g, "_")},
2328
+ "nameOverride": ${val},
2329
+ // ...
2330
+ }
2331
+ \`\`\``
2332
+ });
2333
+ }
2334
+ });
2335
+ const duplicateFieldErrorMessage = (fields) => `Fields must have unique names. Found duplicate field names: [${fields}]`;
2336
+ const duplicateTemplateErrorMessage = (templates) => `Templates must have unique names. Found duplicate template names: [${templates}]`;
2337
+ const duplicateCollectionErrorMessage = (collection) => `Collections must have unique names. Found duplicate collection names: [${collection}]`;
2338
+ const TypeName = [
2339
+ "string",
2340
+ "boolean",
2341
+ "number",
2342
+ "datetime",
2343
+ "image",
2344
+ "object",
2345
+ "reference",
2346
+ "rich-text"
2347
+ ];
2348
+ const formattedTypes = ` - ${TypeName.join("\n - ")}`;
2349
+ const typeTypeError = `Invalid \`type\` property. \`type\` expected to be one of the following values:
2350
+ ${formattedTypes}`;
2351
+ const typeRequiredError = `Missing \`type\` property. Please add a \`type\` property with one of the following:
2352
+ ${formattedTypes}`;
2353
+ const Option = z.union(
2354
+ [
2355
+ z.string(),
2356
+ z.object({ label: z.string(), value: z.string() }),
2357
+ z.object({ icon: z.any(), value: z.string() })
2358
+ ],
2359
+ {
2360
+ errorMap: () => {
2361
+ return {
2362
+ message: "Invalid option array. Must be a string[] or {label: string, value: string}[] or {icon: React.ComponentType<any>, value: string}[]"
2363
+ };
2364
+ }
2365
+ }
2366
+ );
2367
+ const TinaField = z.object({
2368
+ name,
2369
+ label: z.string().or(z.boolean()).optional(),
2370
+ description: z.string().optional(),
2371
+ required: z.boolean().optional()
2372
+ });
2373
+ const FieldWithList = TinaField.extend({ list: z.boolean().optional() });
2374
+ const TinaScalerBase = FieldWithList.extend({
2375
+ options: z.array(Option).optional(),
2376
+ uid: z.boolean().optional()
2377
+ });
2378
+ const StringField = TinaScalerBase.extend({
2379
+ type: z.literal("string", {
2380
+ invalid_type_error: typeTypeError,
2381
+ required_error: typeRequiredError
2382
+ }),
2383
+ isTitle: z.boolean().optional()
2384
+ });
2385
+ const PasswordField = TinaScalerBase.extend({
2386
+ type: z.literal("password", {
2387
+ invalid_type_error: typeTypeError,
2388
+ required_error: typeRequiredError
2389
+ })
2390
+ });
2391
+ const BooleanField = TinaScalerBase.extend({
2392
+ type: z.literal("boolean", {
2393
+ invalid_type_error: typeTypeError,
2394
+ required_error: typeRequiredError
2395
+ })
2396
+ });
2397
+ const NumberField = TinaScalerBase.extend({
2398
+ type: z.literal("number", {
2399
+ invalid_type_error: typeTypeError,
2400
+ required_error: typeRequiredError
2401
+ })
2402
+ });
2403
+ const ImageField = TinaScalerBase.extend({
2404
+ type: z.literal("image", {
2405
+ invalid_type_error: typeTypeError,
2406
+ required_error: typeRequiredError
2407
+ }),
2408
+ uploadDir: z.function().args(z.any()).returns(z.string()).optional()
2409
+ });
2410
+ const DateTimeField = TinaScalerBase.extend({
2411
+ type: z.literal("datetime", {
2412
+ invalid_type_error: typeTypeError,
2413
+ required_error: typeRequiredError
2414
+ }),
2415
+ dateFormat: z.string().optional(),
2416
+ timeFormat: z.string().optional()
2417
+ });
2418
+ const ReferenceField = FieldWithList.extend({
2419
+ type: z.literal("reference", {
2420
+ invalid_type_error: typeTypeError,
2421
+ required_error: typeRequiredError
2422
+ })
2423
+ });
2424
+ const TinaFieldZod = z.lazy(() => {
2425
+ const TemplateTemp = z.object({
2426
+ label: z.string().optional(),
2427
+ name,
2428
+ fields: z.array(TinaFieldZod),
2429
+ match: z.object({
2430
+ start: z.string(),
2431
+ end: z.string(),
2432
+ name: z.string().optional()
2433
+ }).optional()
2434
+ }).superRefine((val, ctx) => {
2435
+ const dups = findDuplicates(val == null ? void 0 : val.fields.map((x) => x.name));
2436
+ if (dups) {
2437
+ ctx.addIssue({
2438
+ code: z.ZodIssueCode.custom,
2439
+ message: duplicateFieldErrorMessage(dups)
2440
+ });
2441
+ }
2442
+ });
2443
+ const ObjectField = FieldWithList.extend({
2444
+ // needs to be redefined here to avoid circle deps
2445
+ type: z.literal("object", {
2446
+ invalid_type_error: typeTypeError,
2447
+ required_error: typeRequiredError
2448
+ }),
2449
+ fields: z.array(TinaFieldZod).min(1, "Property `fields` cannot be empty.").optional().superRefine((val, ctx) => {
2450
+ const dups = findDuplicates(val == null ? void 0 : val.map((x) => x.name));
2451
+ if (dups) {
2452
+ ctx.addIssue({
2453
+ code: z.ZodIssueCode.custom,
2454
+ message: duplicateFieldErrorMessage(dups)
2455
+ });
2456
+ }
2457
+ }),
2458
+ templates: z.array(TemplateTemp).min(1, "Property `templates` cannot be empty.").optional().superRefine((val, ctx) => {
2459
+ const dups = findDuplicates(val == null ? void 0 : val.map((x) => x.name));
2460
+ if (dups) {
2461
+ ctx.addIssue({
2462
+ code: z.ZodIssueCode.custom,
2463
+ message: duplicateTemplateErrorMessage(dups)
2464
+ });
2465
+ }
2466
+ })
2467
+ });
2468
+ const RichTextField = FieldWithList.extend({
2469
+ type: z.literal("rich-text", {
2470
+ invalid_type_error: typeTypeError,
2471
+ required_error: typeRequiredError
2472
+ }),
2473
+ templates: z.array(TemplateTemp).optional().superRefine((val, ctx) => {
2474
+ const dups = findDuplicates(val == null ? void 0 : val.map((x) => x.name));
2475
+ if (dups) {
2476
+ ctx.addIssue({
2477
+ code: z.ZodIssueCode.custom,
2478
+ message: duplicateTemplateErrorMessage(dups)
2479
+ });
2480
+ }
2481
+ })
2482
+ });
2483
+ return z.discriminatedUnion(
2484
+ "type",
2485
+ [
2486
+ StringField,
2487
+ BooleanField,
2488
+ NumberField,
2489
+ ImageField,
2490
+ DateTimeField,
2491
+ ReferenceField,
2492
+ ObjectField,
2493
+ RichTextField,
2494
+ PasswordField
2495
+ ],
2496
+ {
2497
+ errorMap: (issue, ctx) => {
2498
+ var _a, _b;
2499
+ if (issue.code === "invalid_union_discriminator") {
2500
+ if (!((_a = ctx.data) == null ? void 0 : _a.type)) {
2501
+ return {
2502
+ message: `Missing \`type\` property in field \`${ctx.data.name}\`. Please add a \`type\` property with one of the following:
2503
+ ${formattedTypes}`
2504
+ };
2505
+ }
2506
+ return {
2507
+ message: `Invalid \`type\` property in field \`${ctx.data.name}\`. In the schema is 'type: ${(_b = ctx.data) == null ? void 0 : _b.type}' but expected one of the following:
2508
+ ${formattedTypes}`
2509
+ };
2510
+ }
2511
+ return {
2512
+ message: issue.message || ""
2513
+ };
2514
+ }
2515
+ }
2516
+ ).superRefine((val, ctx) => {
2517
+ if (val.type === "string") {
2518
+ const stringifiedField = JSON.stringify(val, null, 2);
2519
+ if (val.isTitle && val.list) {
2520
+ ctx.addIssue({
2521
+ code: z.ZodIssueCode.custom,
2522
+ message: `\`list: true\` is not allowed when using \`isTitle\` for fields of \`type: string\`. Error found in field:
2523
+ ${stringifiedField}`
2524
+ });
2525
+ }
2526
+ if (val.isTitle && !val.required) {
2527
+ ctx.addIssue({
2528
+ code: z.ZodIssueCode.custom,
2529
+ message: `Property \`required: true\` is required when using \`isTitle\` for fields of \`type: string\`. Error found in field:
2530
+ ${stringifiedField}`
2531
+ });
2532
+ }
2533
+ if (val.uid && val.list) {
2534
+ if (val.list) {
2535
+ ctx.addIssue({
2536
+ code: z.ZodIssueCode.custom,
2537
+ message: `\`list: true\` is not allowed when using \`uid\` for fields of \`type: string\`. Error found in field:
2538
+ ${stringifiedField}`
2539
+ });
2540
+ }
2541
+ }
2542
+ if (val.uid && !val.required) {
2543
+ ctx.addIssue({
2544
+ code: z.ZodIssueCode.custom,
2545
+ message: `Property \`required: true\` is required when using \`uid\` for fields of \`type: string\`. Error found in field:
2546
+ ${stringifiedField}`
2547
+ });
2548
+ }
2549
+ }
2550
+ if (val.type === "object") {
2551
+ if (!(val == null ? void 0 : val.templates) && !(val == null ? void 0 : val.fields)) {
2552
+ ctx.addIssue({
2553
+ code: z.ZodIssueCode.custom,
2554
+ message: "Fields of `type: object` must have either `templates` or `fields` property."
2555
+ });
2556
+ return false;
2557
+ }
2558
+ if ((val == null ? void 0 : val.templates) && (val == null ? void 0 : val.fields)) {
2559
+ ctx.addIssue({
2560
+ code: z.ZodIssueCode.custom,
2561
+ message: "Fields of `type: object` must have either `templates` or `fields` property, not both."
2562
+ });
2563
+ return false;
2564
+ }
2565
+ }
2566
+ return true;
2567
+ });
2568
+ });
2569
+ const tinaConfigKey = z$1.object({
2570
+ publicFolder: z$1.string(),
2571
+ mediaRoot: z$1.string(),
2572
+ static: z$1.boolean().nullish()
2573
+ }).strict().optional();
2574
+ const tinaSearchKey = z$1.object({
2575
+ indexerToken: z$1.string().optional(),
2576
+ stopwordLanguages: z$1.array(z$1.string()).nonempty().optional(),
2577
+ tokenSplitRegex: z$1.string().optional(),
2578
+ fuzzyEnabled: z$1.boolean().optional(),
2579
+ fuzzyOptions: z$1.object({
2580
+ maxDistance: z$1.number().optional(),
2581
+ minSimilarity: z$1.number().optional(),
2582
+ maxResults: z$1.number().optional(),
2583
+ useTranspositions: z$1.boolean().optional(),
2584
+ caseSensitive: z$1.boolean().optional()
2585
+ }).strict().optional()
2586
+ }).strict().optional();
2587
+ const tinaConfigZod = z$1.object({
2588
+ client: z$1.object({ referenceDepth: z$1.number().optional() }).optional(),
2589
+ media: z$1.object({
2590
+ tina: tinaConfigKey,
2591
+ loadCustomStore: z$1.function().optional()
2592
+ }).optional(),
2593
+ search: z$1.object({
2594
+ tina: tinaSearchKey,
2595
+ searchClient: z$1.any().optional(),
2596
+ indexBatchSize: z$1.number().gte(1).optional(),
2597
+ maxSearchIndexFieldLength: z$1.number().gte(1).optional()
2598
+ }).optional(),
2599
+ ui: z$1.object({
2600
+ previewUrl: z$1.function().optional(),
2601
+ optOutOfUpdateCheck: z$1.boolean().optional(),
2602
+ regexValidation: z$1.object({
2603
+ folderNameRegex: z$1.string().refine(
2604
+ (val) => {
2605
+ try {
2606
+ new RegExp(val);
2607
+ return true;
2608
+ } catch (error) {
2609
+ return false;
2610
+ }
2611
+ },
2612
+ { message: "folderNameRegex is not a valid regex pattern" }
2613
+ ).optional()
2614
+ }).optional()
2615
+ }).optional()
2616
+ });
2617
+ const validateTinaCloudSchemaConfig = (config) => {
2618
+ const newConfig = tinaConfigZod.parse(config);
2619
+ return newConfig;
2620
+ };
2621
+ const Template = z.object({
2622
+ label: z.string({
2623
+ invalid_type_error: "Invalid data type for property `label`. Must be of type `string`",
2624
+ required_error: "Missing `label` property. Property `label` is required."
2625
+ }),
2626
+ name,
2627
+ fields: z.array(TinaFieldZod)
2628
+ }).superRefine((val, ctx) => {
2629
+ var _a;
2630
+ const dups = findDuplicates((_a = val.fields) == null ? void 0 : _a.map((x) => x.name));
2631
+ if (dups) {
2632
+ ctx.addIssue({
2633
+ code: z.ZodIssueCode.custom,
2634
+ message: duplicateFieldErrorMessage(dups)
2635
+ });
2636
+ }
2637
+ });
2638
+ const CollectionBaseSchema = z.object({
2639
+ label: z.string().optional(),
2640
+ name: name.superRefine((val, ctx) => {
2641
+ if (val === "relativePath") {
2642
+ ctx.addIssue({
2643
+ code: z.ZodIssueCode.custom,
2644
+ message: "Invalid `name` property. `name` cannot be 'relativePath' as it is a reserved field name."
2645
+ });
2646
+ }
2647
+ }),
2648
+ path: z.string().transform((val) => val.replace(/^\/|\/$/g, "")).superRefine((val, ctx) => {
2649
+ if (val === ".") {
2650
+ ctx.addIssue({
2651
+ code: z.ZodIssueCode.custom,
2652
+ message: "Invalid `path` property. `path` cannot be '.'. Please use '/' or '' instead."
2653
+ });
2654
+ }
2655
+ }),
2656
+ format: z.enum(CONTENT_FORMATS).optional(),
2657
+ isAuthCollection: z.boolean().optional(),
2658
+ isDetached: z.boolean().optional()
2659
+ });
2660
+ const TinaCloudCollection = CollectionBaseSchema.extend({
2661
+ fields: z.array(TinaFieldZod).min(1, "Property `fields` cannot be empty.").optional().superRefine((val, ctx) => {
2662
+ const dups = findDuplicates(val == null ? void 0 : val.map((x) => x.name));
2663
+ if (dups) {
2664
+ ctx.addIssue({
2665
+ code: z.ZodIssueCode.custom,
2666
+ message: duplicateFieldErrorMessage(dups)
2667
+ });
2668
+ }
2669
+ }).superRefine((val, ctx) => {
2670
+ const arr = (val == null ? void 0 : val.filter((x) => x.type === "string" && x.isTitle)) || [];
2671
+ if (arr.length > 1) {
2672
+ ctx.addIssue({
2673
+ code: z.ZodIssueCode.custom,
2674
+ message: `The following fields have the property \`isTitle\`: [${arr.map((field) => field.name).join(", ")}]. Only one can contain the property \`isTitle\`.`
2675
+ });
2676
+ }
2677
+ }).superRefine((val, ctx) => {
2678
+ const arr = (val == null ? void 0 : val.filter((x) => x.uid)) || [];
2679
+ if (arr.length > 2) {
2680
+ ctx.addIssue({
2681
+ code: z.ZodIssueCode.custom,
2682
+ message: `The following fields have the property \`uid\`: [${arr.map((field) => field.name).join(", ")}]. Only one can contain the property \`uid\`.`
2683
+ });
2684
+ }
2685
+ }).superRefine((val, ctx) => {
2686
+ const arr = (val == null ? void 0 : val.filter((x) => x.type === "password")) || [];
2687
+ if (arr.length > 2) {
2688
+ ctx.addIssue({
2689
+ code: z.ZodIssueCode.custom,
2690
+ message: `The following fields have \`type: password\`: [${arr.map((field) => field.name).join(", ")}]. Only one can be of \`type: password\`.`
2691
+ });
2692
+ }
2693
+ }),
2694
+ templates: z.array(Template).min(1, "Property `templates` cannot be empty.").optional().superRefine((val, ctx) => {
2695
+ const dups = findDuplicates(val == null ? void 0 : val.map((x) => x.name));
2696
+ if (dups) {
2697
+ ctx.addIssue({
2698
+ code: z.ZodIssueCode.custom,
2699
+ message: duplicateFieldErrorMessage(dups)
2700
+ });
2701
+ }
2702
+ })
2703
+ }).superRefine((val, ctx) => {
2704
+ if (!(val == null ? void 0 : val.templates) && !(val == null ? void 0 : val.fields)) {
2705
+ ctx.addIssue({
2706
+ code: z.ZodIssueCode.custom,
2707
+ message: "Fields of `type: object` must have either `templates` or `fields` property."
2708
+ });
2709
+ return false;
2710
+ }
2711
+ if ((val == null ? void 0 : val.templates) && (val == null ? void 0 : val.fields)) {
2712
+ ctx.addIssue({
2713
+ code: z.ZodIssueCode.custom,
2714
+ message: "Fields of `type: object` must have either `templates` or `fields` property, not both."
2715
+ });
2716
+ return false;
2717
+ }
2718
+ });
2719
+ const TinaCloudSchemaZod = z.object({
2720
+ collections: z.array(TinaCloudCollection),
2721
+ config: tinaConfigZod.optional()
2722
+ }).superRefine((val, ctx) => {
2723
+ var _a, _b, _c, _d;
2724
+ const dups = findDuplicates((_a = val.collections) == null ? void 0 : _a.map((x) => x.name));
2725
+ if (dups) {
2726
+ ctx.addIssue({
2727
+ code: z.ZodIssueCode.custom,
2728
+ message: duplicateCollectionErrorMessage(dups),
2729
+ fatal: true
2730
+ });
2731
+ }
2732
+ if (((_b = val.collections) == null ? void 0 : _b.filter((x) => x.isAuthCollection).length) > 1) {
2733
+ ctx.addIssue({
2734
+ code: z.ZodIssueCode.custom,
2735
+ message: "Only one collection can be marked as `isAuthCollection`.",
2736
+ fatal: true
2737
+ });
2738
+ }
2739
+ const media = (_c = val == null ? void 0 : val.config) == null ? void 0 : _c.media;
2740
+ if (media && media.tina && media.loadCustomStore) {
2741
+ ctx.addIssue({
2742
+ code: z.ZodIssueCode.custom,
2743
+ message: "Cannot have both `loadCustomStore` and `tina`. Must use one or the other.",
2744
+ fatal: true,
2745
+ path: ["config", "media"]
2746
+ });
2747
+ }
2748
+ const search = (_d = val == null ? void 0 : val.config) == null ? void 0 : _d.search;
2749
+ if (search && search.tina && search.searchClient) {
2750
+ ctx.addIssue({
2751
+ code: z.ZodIssueCode.custom,
2752
+ message: "Cannot have both `searchClient` and `tina`. Must use one or the other.",
2753
+ fatal: true,
2754
+ path: ["config", "search"]
2755
+ });
2756
+ }
2757
+ });
2758
+ class TinaSchemaValidationError extends Error {
2759
+ constructor(message) {
2760
+ super(message);
2761
+ this.name = "TinaSchemaValidationError";
2762
+ }
2763
+ }
2764
+ const validateSchema = ({ schema }) => {
2765
+ try {
2766
+ TinaCloudSchemaZod.parse(schema);
2767
+ } catch (e) {
2768
+ if (e instanceof ZodError) {
2769
+ const errors = parseZodError({ zodError: e });
2770
+ throw new TinaSchemaValidationError(errors.join("\n"));
2771
+ }
2772
+ throw new Error(e);
2773
+ }
2774
+ };
2775
+ export {
2776
+ CONTENT_FORMATS,
2777
+ NAMER,
2778
+ TINA_HOST,
2779
+ TinaSchema,
2780
+ TinaSchemaValidationError,
2781
+ addNamespaceToSchema,
2782
+ canonicalPath,
2783
+ normalizePath,
2784
+ parseURL,
2785
+ resolveField,
2786
+ resolveForm,
2787
+ validateSchema,
2788
+ validateTinaCloudSchemaConfig
2789
+ };