@tinacms/schema-tools 0.0.0-00f6525-20241015065741

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