@valbuild/shared 0.63.5 → 0.65.0

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.
@@ -1,8 +1,9 @@
1
1
  import { Internal, VAL_EXTENSION, FILE_REF_PROP } from '@valbuild/core';
2
2
  import { z } from 'zod';
3
3
  import { result } from '@valbuild/core/fp';
4
+ import { fromZodError } from 'zod-validation-error';
4
5
 
5
- function toPrimitive(t, r) {
6
+ function _toPrimitive(t, r) {
6
7
  if ("object" != typeof t || !t) return t;
7
8
  var e = t[Symbol.toPrimitive];
8
9
  if (void 0 !== e) {
@@ -13,24 +14,18 @@ function toPrimitive(t, r) {
13
14
  return ("string" === r ? String : Number)(t);
14
15
  }
15
16
 
16
- function toPropertyKey(t) {
17
- var i = toPrimitive(t, "string");
18
- return "symbol" == typeof i ? i : String(i);
17
+ function _toPropertyKey(t) {
18
+ var i = _toPrimitive(t, "string");
19
+ return "symbol" == typeof i ? i : i + "";
19
20
  }
20
21
 
21
- function _defineProperty(obj, key, value) {
22
- key = toPropertyKey(key);
23
- if (key in obj) {
24
- Object.defineProperty(obj, key, {
25
- value: value,
26
- enumerable: true,
27
- configurable: true,
28
- writable: true
29
- });
30
- } else {
31
- obj[key] = value;
32
- }
33
- return obj;
22
+ function _defineProperty(e, r, t) {
23
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
24
+ value: t,
25
+ enumerable: !0,
26
+ configurable: !0,
27
+ writable: !0
28
+ }) : e[r] = t, e;
34
29
  }
35
30
 
36
31
  function ownKeys(e, r) {
@@ -55,840 +50,74 @@ function _objectSpread2(e) {
55
50
  return e;
56
51
  }
57
52
 
58
- function _arrayLikeToArray(arr, len) {
59
- if (len == null || len > arr.length) len = arr.length;
60
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
61
- return arr2;
53
+ function _arrayLikeToArray(r, a) {
54
+ (null == a || a > r.length) && (a = r.length);
55
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
56
+ return n;
62
57
  }
63
58
 
64
- function _unsupportedIterableToArray(o, minLen) {
65
- if (!o) return;
66
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
67
- var n = Object.prototype.toString.call(o).slice(8, -1);
68
- if (n === "Object" && o.constructor) n = o.constructor.name;
69
- if (n === "Map" || n === "Set") return Array.from(o);
70
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
59
+ function _unsupportedIterableToArray(r, a) {
60
+ if (r) {
61
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
62
+ var t = {}.toString.call(r).slice(8, -1);
63
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
64
+ }
71
65
  }
72
66
 
73
- function _createForOfIteratorHelper(o, allowArrayLike) {
74
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
75
- if (!it) {
76
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
77
- if (it) o = it;
78
- var i = 0;
79
- var F = function () {};
67
+ function _createForOfIteratorHelper(r, e) {
68
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
69
+ if (!t) {
70
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
71
+ t && (r = t);
72
+ var n = 0,
73
+ F = function () {};
80
74
  return {
81
75
  s: F,
82
76
  n: function () {
83
- if (i >= o.length) return {
84
- done: true
85
- };
86
- return {
87
- done: false,
88
- value: o[i++]
77
+ return n >= r.length ? {
78
+ done: !0
79
+ } : {
80
+ done: !1,
81
+ value: r[n++]
89
82
  };
90
83
  },
91
- e: function (e) {
92
- throw e;
84
+ e: function (r) {
85
+ throw r;
93
86
  },
94
87
  f: F
95
88
  };
96
89
  }
97
90
  throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
98
91
  }
99
- var normalCompletion = true,
100
- didErr = false,
101
- err;
92
+ var o,
93
+ a = !0,
94
+ u = !1;
102
95
  return {
103
96
  s: function () {
104
- it = it.call(o);
97
+ t = t.call(r);
105
98
  },
106
99
  n: function () {
107
- var step = it.next();
108
- normalCompletion = step.done;
109
- return step;
100
+ var r = t.next();
101
+ return a = r.done, r;
110
102
  },
111
- e: function (e) {
112
- didErr = true;
113
- err = e;
103
+ e: function (r) {
104
+ u = !0, o = r;
114
105
  },
115
106
  f: function () {
116
107
  try {
117
- if (!normalCompletion && it.return != null) it.return();
108
+ a || null == t.return || t.return();
118
109
  } finally {
119
- if (didErr) throw err;
110
+ if (u) throw o;
120
111
  }
121
112
  }
122
113
  };
123
114
  }
124
115
 
125
- function _arrayWithHoles(arr) {
126
- if (Array.isArray(arr)) return arr;
127
- }
128
-
129
- function _iterableToArrayLimit(r, l) {
130
- var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
131
- if (null != t) {
132
- var e,
133
- n,
134
- i,
135
- u,
136
- a = [],
137
- f = !0,
138
- o = !1;
139
- try {
140
- if (i = (t = t.call(r)).next, 0 === l) {
141
- if (Object(t) !== t) return;
142
- f = !1;
143
- } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
144
- } catch (r) {
145
- o = !0, n = r;
146
- } finally {
147
- try {
148
- if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
149
- } finally {
150
- if (o) throw n;
151
- }
152
- }
153
- return a;
154
- }
155
- }
156
-
157
- function _nonIterableRest() {
158
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
159
- }
160
-
161
- function _slicedToArray(arr, i) {
162
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
163
- }
164
-
165
- var EXT_TO_MIME_TYPES = {
166
- x3d: "application/vnd.hzn-3d-crossword",
167
- "3gp": "video/3gpp",
168
- "3g2": "video/3gpp2",
169
- mseq: "application/vnd.mseq",
170
- pwn: "application/vnd.3m.post-it-notes",
171
- plb: "application/vnd.3gpp.pic-bw-large",
172
- psb: "application/vnd.3gpp.pic-bw-small",
173
- pvb: "application/vnd.3gpp.pic-bw-var",
174
- tcap: "application/vnd.3gpp2.tcap",
175
- "7z": "application/x-7z-compressed",
176
- abw: "application/x-abiword",
177
- ace: "application/x-ace-compressed",
178
- acc: "application/vnd.americandynamics.acc",
179
- acu: "application/vnd.acucobol",
180
- atc: "application/vnd.acucorp",
181
- adp: "audio/adpcm",
182
- aab: "application/x-authorware-bin",
183
- aam: "application/x-authorware-map",
184
- aas: "application/x-authorware-seg",
185
- air: "application/vnd.adobe.air-application-installer-package+zip",
186
- swf: "application/x-shockwave-flash",
187
- fxp: "application/vnd.adobe.fxp",
188
- pdf: "application/pdf",
189
- ppd: "application/vnd.cups-ppd",
190
- dir: "application/x-director",
191
- xdp: "application/vnd.adobe.xdp+xml",
192
- xfdf: "application/vnd.adobe.xfdf",
193
- aac: "audio/x-aac",
194
- ahead: "application/vnd.ahead.space",
195
- azf: "application/vnd.airzip.filesecure.azf",
196
- azs: "application/vnd.airzip.filesecure.azs",
197
- azw: "application/vnd.amazon.ebook",
198
- ami: "application/vnd.amiga.ami",
199
- "N/A": "application/andrew-inset",
200
- apk: "application/vnd.android.package-archive",
201
- cii: "application/vnd.anser-web-certificate-issue-initiation",
202
- fti: "application/vnd.anser-web-funds-transfer-initiation",
203
- atx: "application/vnd.antix.game-component",
204
- dmg: "application/x-apple-diskimage",
205
- mpkg: "application/vnd.apple.installer+xml",
206
- aw: "application/applixware",
207
- mp3: "audio/mpeg",
208
- les: "application/vnd.hhe.lesson-player",
209
- swi: "application/vnd.aristanetworks.swi",
210
- s: "text/x-asm",
211
- atomcat: "application/atomcat+xml",
212
- atomsvc: "application/atomsvc+xml",
213
- atom: "application/atom+xml",
214
- ac: "application/pkix-attr-cert",
215
- aif: "audio/x-aiff",
216
- avi: "video/x-msvideo",
217
- aep: "application/vnd.audiograph",
218
- dxf: "image/vnd.dxf",
219
- dwf: "model/vnd.dwf",
220
- par: "text/plain-bas",
221
- bcpio: "application/x-bcpio",
222
- bin: "application/octet-stream",
223
- bmp: "image/bmp",
224
- torrent: "application/x-bittorrent",
225
- cod: "application/vnd.rim.cod",
226
- mpm: "application/vnd.blueice.multipass",
227
- bmi: "application/vnd.bmi",
228
- sh: "application/x-sh",
229
- btif: "image/prs.btif",
230
- rep: "application/vnd.businessobjects",
231
- bz: "application/x-bzip",
232
- bz2: "application/x-bzip2",
233
- csh: "application/x-csh",
234
- c: "text/x-c",
235
- cdxml: "application/vnd.chemdraw+xml",
236
- css: "text/css",
237
- cdx: "chemical/x-cdx",
238
- cml: "chemical/x-cml",
239
- csml: "chemical/x-csml",
240
- cdbcmsg: "application/vnd.contact.cmsg",
241
- cla: "application/vnd.claymore",
242
- c4g: "application/vnd.clonk.c4group",
243
- sub: "image/vnd.dvb.subtitle",
244
- cdmia: "application/cdmi-capability",
245
- cdmic: "application/cdmi-container",
246
- cdmid: "application/cdmi-domain",
247
- cdmio: "application/cdmi-object",
248
- cdmiq: "application/cdmi-queue",
249
- c11amc: "application/vnd.cluetrust.cartomobile-config",
250
- c11amz: "application/vnd.cluetrust.cartomobile-config-pkg",
251
- ras: "image/x-cmu-raster",
252
- dae: "model/vnd.collada+xml",
253
- csv: "text/csv",
254
- cpt: "application/mac-compactpro",
255
- wmlc: "application/vnd.wap.wmlc",
256
- cgm: "image/cgm",
257
- ice: "x-conference/x-cooltalk",
258
- cmx: "image/x-cmx",
259
- xar: "application/vnd.xara",
260
- cmc: "application/vnd.cosmocaller",
261
- cpio: "application/x-cpio",
262
- clkx: "application/vnd.crick.clicker",
263
- clkk: "application/vnd.crick.clicker.keyboard",
264
- clkp: "application/vnd.crick.clicker.palette",
265
- clkt: "application/vnd.crick.clicker.template",
266
- clkw: "application/vnd.crick.clicker.wordbank",
267
- wbs: "application/vnd.criticaltools.wbs+xml",
268
- cryptonote: "application/vnd.rig.cryptonote",
269
- cif: "chemical/x-cif",
270
- cmdf: "chemical/x-cmdf",
271
- cu: "application/cu-seeme",
272
- cww: "application/prs.cww",
273
- curl: "text/vnd.curl",
274
- dcurl: "text/vnd.curl.dcurl",
275
- mcurl: "text/vnd.curl.mcurl",
276
- scurl: "text/vnd.curl.scurl",
277
- car: "application/vnd.curl.car",
278
- pcurl: "application/vnd.curl.pcurl",
279
- cmp: "application/vnd.yellowriver-custom-menu",
280
- dssc: "application/dssc+der",
281
- xdssc: "application/dssc+xml",
282
- deb: "application/x-debian-package",
283
- uva: "audio/vnd.dece.audio",
284
- uvi: "image/vnd.dece.graphic",
285
- uvh: "video/vnd.dece.hd",
286
- uvm: "video/vnd.dece.mobile",
287
- uvu: "video/vnd.uvvu.mp4",
288
- uvp: "video/vnd.dece.pd",
289
- uvs: "video/vnd.dece.sd",
290
- uvv: "video/vnd.dece.video",
291
- dvi: "application/x-dvi",
292
- seed: "application/vnd.fdsn.seed",
293
- dtb: "application/x-dtbook+xml",
294
- res: "application/x-dtbresource+xml",
295
- ait: "application/vnd.dvb.ait",
296
- svc: "application/vnd.dvb.service",
297
- eol: "audio/vnd.digital-winds",
298
- djvu: "image/vnd.djvu",
299
- dtd: "application/xml-dtd",
300
- mlp: "application/vnd.dolby.mlp",
301
- wad: "application/x-doom",
302
- dpg: "application/vnd.dpgraph",
303
- dra: "audio/vnd.dra",
304
- dfac: "application/vnd.dreamfactory",
305
- dts: "audio/vnd.dts",
306
- dtshd: "audio/vnd.dts.hd",
307
- dwg: "image/vnd.dwg",
308
- geo: "application/vnd.dynageo",
309
- es: "application/ecmascript",
310
- mag: "application/vnd.ecowin.chart",
311
- mmr: "image/vnd.fujixerox.edmics-mmr",
312
- rlc: "image/vnd.fujixerox.edmics-rlc",
313
- exi: "application/exi",
314
- mgz: "application/vnd.proteus.magazine",
315
- epub: "application/epub+zip",
316
- eml: "message/rfc822",
317
- nml: "application/vnd.enliven",
318
- xpr: "application/vnd.is-xpr",
319
- xif: "image/vnd.xiff",
320
- xfdl: "application/vnd.xfdl",
321
- emma: "application/emma+xml",
322
- ez2: "application/vnd.ezpix-album",
323
- ez3: "application/vnd.ezpix-package",
324
- fst: "image/vnd.fst",
325
- fvt: "video/vnd.fvt",
326
- fbs: "image/vnd.fastbidsheet",
327
- fe_launch: "application/vnd.denovo.fcselayout-link",
328
- f4v: "video/x-f4v",
329
- flv: "video/x-flv",
330
- fpx: "image/vnd.fpx",
331
- npx: "image/vnd.net-fpx",
332
- flx: "text/vnd.fmi.flexstor",
333
- fli: "video/x-fli",
334
- ftc: "application/vnd.fluxtime.clip",
335
- fdf: "application/vnd.fdf",
336
- f: "text/x-fortran",
337
- mif: "application/vnd.mif",
338
- fm: "application/vnd.framemaker",
339
- fh: "image/x-freehand",
340
- fsc: "application/vnd.fsc.weblaunch",
341
- fnc: "application/vnd.frogans.fnc",
342
- ltf: "application/vnd.frogans.ltf",
343
- ddd: "application/vnd.fujixerox.ddd",
344
- xdw: "application/vnd.fujixerox.docuworks",
345
- xbd: "application/vnd.fujixerox.docuworks.binder",
346
- oas: "application/vnd.fujitsu.oasys",
347
- oa2: "application/vnd.fujitsu.oasys2",
348
- oa3: "application/vnd.fujitsu.oasys3",
349
- fg5: "application/vnd.fujitsu.oasysgp",
350
- bh2: "application/vnd.fujitsu.oasysprs",
351
- spl: "application/x-futuresplash",
352
- fzs: "application/vnd.fuzzysheet",
353
- g3: "image/g3fax",
354
- gmx: "application/vnd.gmx",
355
- gtw: "model/vnd.gtw",
356
- txd: "application/vnd.genomatix.tuxedo",
357
- ggb: "application/vnd.geogebra.file",
358
- ggt: "application/vnd.geogebra.tool",
359
- gdl: "model/vnd.gdl",
360
- gex: "application/vnd.geometry-explorer",
361
- gxt: "application/vnd.geonext",
362
- g2w: "application/vnd.geoplan",
363
- g3w: "application/vnd.geospace",
364
- gsf: "application/x-font-ghostscript",
365
- bdf: "application/x-font-bdf",
366
- gtar: "application/x-gtar",
367
- texinfo: "application/x-texinfo",
368
- gnumeric: "application/x-gnumeric",
369
- kml: "application/vnd.google-earth.kml+xml",
370
- kmz: "application/vnd.google-earth.kmz",
371
- gqf: "application/vnd.grafeq",
372
- gif: "image/gif",
373
- gv: "text/vnd.graphviz",
374
- gac: "application/vnd.groove-account",
375
- ghf: "application/vnd.groove-help",
376
- gim: "application/vnd.groove-identity-message",
377
- grv: "application/vnd.groove-injector",
378
- gtm: "application/vnd.groove-tool-message",
379
- tpl: "application/vnd.groove-tool-template",
380
- vcg: "application/vnd.groove-vcard",
381
- h261: "video/h261",
382
- h263: "video/h263",
383
- h264: "video/h264",
384
- hpid: "application/vnd.hp-hpid",
385
- hps: "application/vnd.hp-hps",
386
- hdf: "application/x-hdf",
387
- rip: "audio/vnd.rip",
388
- hbci: "application/vnd.hbci",
389
- jlt: "application/vnd.hp-jlyt",
390
- pcl: "application/vnd.hp-pcl",
391
- hpgl: "application/vnd.hp-hpgl",
392
- hvs: "application/vnd.yamaha.hv-script",
393
- hvd: "application/vnd.yamaha.hv-dic",
394
- hvp: "application/vnd.yamaha.hv-voice",
395
- "sfd-hdstx": "application/vnd.hydrostatix.sof-data",
396
- stk: "application/hyperstudio",
397
- hal: "application/vnd.hal+xml",
398
- html: "text/html",
399
- irm: "application/vnd.ibm.rights-management",
400
- sc: "application/vnd.ibm.secure-container",
401
- ics: "text/calendar",
402
- icc: "application/vnd.iccprofile",
403
- ico: "image/x-icon",
404
- igl: "application/vnd.igloader",
405
- ief: "image/ief",
406
- ivp: "application/vnd.immervision-ivp",
407
- ivu: "application/vnd.immervision-ivu",
408
- rif: "application/reginfo+xml",
409
- "3dml": "text/vnd.in3d.3dml",
410
- spot: "text/vnd.in3d.spot",
411
- igs: "model/iges",
412
- i2g: "application/vnd.intergeo",
413
- cdy: "application/vnd.cinderella",
414
- xpw: "application/vnd.intercon.formnet",
415
- fcs: "application/vnd.isac.fcs",
416
- ipfix: "application/ipfix",
417
- cer: "application/pkix-cert",
418
- pki: "application/pkixcmp",
419
- crl: "application/pkix-crl",
420
- pkipath: "application/pkix-pkipath",
421
- igm: "application/vnd.insors.igm",
422
- rcprofile: "application/vnd.ipunplugged.rcprofile",
423
- irp: "application/vnd.irepository.package+xml",
424
- jad: "text/vnd.sun.j2me.app-descriptor",
425
- jar: "application/java-archive",
426
- "class": "application/java-vm",
427
- jnlp: "application/x-java-jnlp-file",
428
- ser: "application/java-serialized-object",
429
- java: "text/x-java-source,java",
430
- js: "application/javascript",
431
- json: "application/json",
432
- joda: "application/vnd.joost.joda-archive",
433
- jpm: "video/jpm",
434
- jpeg: "image/jpeg",
435
- jpg: "image/jpeg",
436
- pjpeg: "image/pjpeg",
437
- jpgv: "video/jpeg",
438
- ktz: "application/vnd.kahootz",
439
- mmd: "application/vnd.chipnuts.karaoke-mmd",
440
- karbon: "application/vnd.kde.karbon",
441
- chrt: "application/vnd.kde.kchart",
442
- kfo: "application/vnd.kde.kformula",
443
- flw: "application/vnd.kde.kivio",
444
- kon: "application/vnd.kde.kontour",
445
- kpr: "application/vnd.kde.kpresenter",
446
- ksp: "application/vnd.kde.kspread",
447
- kwd: "application/vnd.kde.kword",
448
- htke: "application/vnd.kenameaapp",
449
- kia: "application/vnd.kidspiration",
450
- kne: "application/vnd.kinar",
451
- sse: "application/vnd.kodak-descriptor",
452
- lasxml: "application/vnd.las.las+xml",
453
- latex: "application/x-latex",
454
- lbd: "application/vnd.llamagraphics.life-balance.desktop",
455
- lbe: "application/vnd.llamagraphics.life-balance.exchange+xml",
456
- jam: "application/vnd.jam",
457
- "123": "application/vnd.lotus-1-2-3",
458
- apr: "application/vnd.lotus-approach",
459
- pre: "application/vnd.lotus-freelance",
460
- nsf: "application/vnd.lotus-notes",
461
- org: "application/vnd.lotus-organizer",
462
- scm: "application/vnd.lotus-screencam",
463
- lwp: "application/vnd.lotus-wordpro",
464
- lvp: "audio/vnd.lucent.voice",
465
- m3u: "audio/x-mpegurl",
466
- m4v: "video/x-m4v",
467
- hqx: "application/mac-binhex40",
468
- portpkg: "application/vnd.macports.portpkg",
469
- mgp: "application/vnd.osgeo.mapguide.package",
470
- mrc: "application/marc",
471
- mrcx: "application/marcxml+xml",
472
- mxf: "application/mxf",
473
- nbp: "application/vnd.wolfram.player",
474
- ma: "application/mathematica",
475
- mathml: "application/mathml+xml",
476
- mbox: "application/mbox",
477
- mc1: "application/vnd.medcalcdata",
478
- mscml: "application/mediaservercontrol+xml",
479
- cdkey: "application/vnd.mediastation.cdkey",
480
- mwf: "application/vnd.mfer",
481
- mfm: "application/vnd.mfmp",
482
- msh: "model/mesh",
483
- mads: "application/mads+xml",
484
- mets: "application/mets+xml",
485
- mods: "application/mods+xml",
486
- meta4: "application/metalink4+xml",
487
- mcd: "application/vnd.mcd",
488
- flo: "application/vnd.micrografx.flo",
489
- igx: "application/vnd.micrografx.igx",
490
- es3: "application/vnd.eszigno3+xml",
491
- mdb: "application/x-msaccess",
492
- asf: "video/x-ms-asf",
493
- exe: "application/x-msdownload",
494
- cil: "application/vnd.ms-artgalry",
495
- cab: "application/vnd.ms-cab-compressed",
496
- ims: "application/vnd.ms-ims",
497
- application: "application/x-ms-application",
498
- clp: "application/x-msclip",
499
- mdi: "image/vnd.ms-modi",
500
- eot: "application/vnd.ms-fontobject",
501
- xls: "application/vnd.ms-excel",
502
- xlam: "application/vnd.ms-excel.addin.macroenabled.12",
503
- xlsb: "application/vnd.ms-excel.sheet.binary.macroenabled.12",
504
- xltm: "application/vnd.ms-excel.template.macroenabled.12",
505
- xlsm: "application/vnd.ms-excel.sheet.macroenabled.12",
506
- chm: "application/vnd.ms-htmlhelp",
507
- crd: "application/x-mscardfile",
508
- lrm: "application/vnd.ms-lrm",
509
- mvb: "application/x-msmediaview",
510
- mny: "application/x-msmoney",
511
- pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
512
- sldx: "application/vnd.openxmlformats-officedocument.presentationml.slide",
513
- ppsx: "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
514
- potx: "application/vnd.openxmlformats-officedocument.presentationml.template",
515
- xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
516
- xltx: "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
517
- docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
518
- dotx: "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
519
- obd: "application/x-msbinder",
520
- thmx: "application/vnd.ms-officetheme",
521
- onetoc: "application/onenote",
522
- pya: "audio/vnd.ms-playready.media.pya",
523
- pyv: "video/vnd.ms-playready.media.pyv",
524
- ppt: "application/vnd.ms-powerpoint",
525
- ppam: "application/vnd.ms-powerpoint.addin.macroenabled.12",
526
- sldm: "application/vnd.ms-powerpoint.slide.macroenabled.12",
527
- pptm: "application/vnd.ms-powerpoint.presentation.macroenabled.12",
528
- ppsm: "application/vnd.ms-powerpoint.slideshow.macroenabled.12",
529
- potm: "application/vnd.ms-powerpoint.template.macroenabled.12",
530
- mpp: "application/vnd.ms-project",
531
- pub: "application/x-mspublisher",
532
- scd: "application/x-msschedule",
533
- xap: "application/x-silverlight-app",
534
- stl: "application/vnd.ms-pki.stl",
535
- cat: "application/vnd.ms-pki.seccat",
536
- vsd: "application/vnd.visio",
537
- vsdx: "application/vnd.visio2013",
538
- wm: "video/x-ms-wm",
539
- wma: "audio/x-ms-wma",
540
- wax: "audio/x-ms-wax",
541
- wmx: "video/x-ms-wmx",
542
- wmd: "application/x-ms-wmd",
543
- wpl: "application/vnd.ms-wpl",
544
- wmz: "application/x-ms-wmz",
545
- wmv: "video/x-ms-wmv",
546
- wvx: "video/x-ms-wvx",
547
- wmf: "application/x-msmetafile",
548
- trm: "application/x-msterminal",
549
- doc: "application/msword",
550
- docm: "application/vnd.ms-word.document.macroenabled.12",
551
- dotm: "application/vnd.ms-word.template.macroenabled.12",
552
- wri: "application/x-mswrite",
553
- wps: "application/vnd.ms-works",
554
- xbap: "application/x-ms-xbap",
555
- xps: "application/vnd.ms-xpsdocument",
556
- mid: "audio/midi",
557
- mpy: "application/vnd.ibm.minipay",
558
- afp: "application/vnd.ibm.modcap",
559
- rms: "application/vnd.jcp.javame.midlet-rms",
560
- tmo: "application/vnd.tmobile-livetv",
561
- prc: "application/x-mobipocket-ebook",
562
- mbk: "application/vnd.mobius.mbk",
563
- dis: "application/vnd.mobius.dis",
564
- plc: "application/vnd.mobius.plc",
565
- mqy: "application/vnd.mobius.mqy",
566
- msl: "application/vnd.mobius.msl",
567
- txf: "application/vnd.mobius.txf",
568
- daf: "application/vnd.mobius.daf",
569
- fly: "text/vnd.fly",
570
- mpc: "application/vnd.mophun.certificate",
571
- mpn: "application/vnd.mophun.application",
572
- mj2: "video/mj2",
573
- mpga: "audio/mpeg",
574
- mxu: "video/vnd.mpegurl",
575
- mpeg: "video/mpeg",
576
- m21: "application/mp21",
577
- mp4a: "audio/mp4",
578
- mp4: "video/mp4",
579
- m3u8: "application/vnd.apple.mpegurl",
580
- mus: "application/vnd.musician",
581
- msty: "application/vnd.muvee.style",
582
- mxml: "application/xv+xml",
583
- ngdat: "application/vnd.nokia.n-gage.data",
584
- "n-gage": "application/vnd.nokia.n-gage.symbian.install",
585
- ncx: "application/x-dtbncx+xml",
586
- nc: "application/x-netcdf",
587
- nlu: "application/vnd.neurolanguage.nlu",
588
- dna: "application/vnd.dna",
589
- nnd: "application/vnd.noblenet-directory",
590
- nns: "application/vnd.noblenet-sealer",
591
- nnw: "application/vnd.noblenet-web",
592
- rpst: "application/vnd.nokia.radio-preset",
593
- rpss: "application/vnd.nokia.radio-presets",
594
- n3: "text/n3",
595
- edm: "application/vnd.novadigm.edm",
596
- edx: "application/vnd.novadigm.edx",
597
- ext: "application/vnd.novadigm.ext",
598
- gph: "application/vnd.flographit",
599
- ecelp4800: "audio/vnd.nuera.ecelp4800",
600
- ecelp7470: "audio/vnd.nuera.ecelp7470",
601
- ecelp9600: "audio/vnd.nuera.ecelp9600",
602
- oda: "application/oda",
603
- ogx: "application/ogg",
604
- oga: "audio/ogg",
605
- ogv: "video/ogg",
606
- dd2: "application/vnd.oma.dd2+xml",
607
- oth: "application/vnd.oasis.opendocument.text-web",
608
- opf: "application/oebps-package+xml",
609
- qbo: "application/vnd.intu.qbo",
610
- oxt: "application/vnd.openofficeorg.extension",
611
- osf: "application/vnd.yamaha.openscoreformat",
612
- weba: "audio/webm",
613
- webm: "video/webm",
614
- odc: "application/vnd.oasis.opendocument.chart",
615
- otc: "application/vnd.oasis.opendocument.chart-template",
616
- odb: "application/vnd.oasis.opendocument.database",
617
- odf: "application/vnd.oasis.opendocument.formula",
618
- odft: "application/vnd.oasis.opendocument.formula-template",
619
- odg: "application/vnd.oasis.opendocument.graphics",
620
- otg: "application/vnd.oasis.opendocument.graphics-template",
621
- odi: "application/vnd.oasis.opendocument.image",
622
- oti: "application/vnd.oasis.opendocument.image-template",
623
- odp: "application/vnd.oasis.opendocument.presentation",
624
- otp: "application/vnd.oasis.opendocument.presentation-template",
625
- ods: "application/vnd.oasis.opendocument.spreadsheet",
626
- ots: "application/vnd.oasis.opendocument.spreadsheet-template",
627
- odt: "application/vnd.oasis.opendocument.text",
628
- odm: "application/vnd.oasis.opendocument.text-master",
629
- ott: "application/vnd.oasis.opendocument.text-template",
630
- ktx: "image/ktx",
631
- sxc: "application/vnd.sun.xml.calc",
632
- stc: "application/vnd.sun.xml.calc.template",
633
- sxd: "application/vnd.sun.xml.draw",
634
- std: "application/vnd.sun.xml.draw.template",
635
- sxi: "application/vnd.sun.xml.impress",
636
- sti: "application/vnd.sun.xml.impress.template",
637
- sxm: "application/vnd.sun.xml.math",
638
- sxw: "application/vnd.sun.xml.writer",
639
- sxg: "application/vnd.sun.xml.writer.global",
640
- stw: "application/vnd.sun.xml.writer.template",
641
- otf: "application/x-font-otf",
642
- osfpvg: "application/vnd.yamaha.openscoreformat.osfpvg+xml",
643
- dp: "application/vnd.osgi.dp",
644
- pdb: "application/vnd.palm",
645
- p: "text/x-pascal",
646
- paw: "application/vnd.pawaafile",
647
- pclxl: "application/vnd.hp-pclxl",
648
- efif: "application/vnd.picsel",
649
- pcx: "image/x-pcx",
650
- psd: "image/vnd.adobe.photoshop",
651
- prf: "application/pics-rules",
652
- pic: "image/x-pict",
653
- chat: "application/x-chat",
654
- p10: "application/pkcs10",
655
- p12: "application/x-pkcs12",
656
- p7m: "application/pkcs7-mime",
657
- p7s: "application/pkcs7-signature",
658
- p7r: "application/x-pkcs7-certreqresp",
659
- p7b: "application/x-pkcs7-certificates",
660
- p8: "application/pkcs8",
661
- plf: "application/vnd.pocketlearn",
662
- pnm: "image/x-portable-anymap",
663
- pbm: "image/x-portable-bitmap",
664
- pcf: "application/x-font-pcf",
665
- pfr: "application/font-tdpfr",
666
- pgn: "application/x-chess-pgn",
667
- pgm: "image/x-portable-graymap",
668
- png: "image/png",
669
- ppm: "image/x-portable-pixmap",
670
- pskcxml: "application/pskc+xml",
671
- pml: "application/vnd.ctc-posml",
672
- ai: "application/postscript",
673
- pfa: "application/x-font-type1",
674
- pbd: "application/vnd.powerbuilder6",
675
- pgp: "application/pgp-signature",
676
- box: "application/vnd.previewsystems.box",
677
- ptid: "application/vnd.pvi.ptid1",
678
- pls: "application/pls+xml",
679
- str: "application/vnd.pg.format",
680
- ei6: "application/vnd.pg.osasli",
681
- dsc: "text/prs.lines.tag",
682
- psf: "application/x-font-linux-psf",
683
- qps: "application/vnd.publishare-delta-tree",
684
- wg: "application/vnd.pmi.widget",
685
- qxd: "application/vnd.quark.quarkxpress",
686
- esf: "application/vnd.epson.esf",
687
- msf: "application/vnd.epson.msf",
688
- ssf: "application/vnd.epson.ssf",
689
- qam: "application/vnd.epson.quickanime",
690
- qfx: "application/vnd.intu.qfx",
691
- qt: "video/quicktime",
692
- rar: "application/x-rar-compressed",
693
- ram: "audio/x-pn-realaudio",
694
- rmp: "audio/x-pn-realaudio-plugin",
695
- rsd: "application/rsd+xml",
696
- rm: "application/vnd.rn-realmedia",
697
- bed: "application/vnd.realvnc.bed",
698
- mxl: "application/vnd.recordare.musicxml",
699
- musicxml: "application/vnd.recordare.musicxml+xml",
700
- rnc: "application/relax-ng-compact-syntax",
701
- rdz: "application/vnd.data-vision.rdz",
702
- rdf: "application/rdf+xml",
703
- rp9: "application/vnd.cloanto.rp9",
704
- jisp: "application/vnd.jisp",
705
- rtf: "application/rtf",
706
- rtx: "text/richtext",
707
- link66: "application/vnd.route66.link66+xml",
708
- rss: "application/rss+xml",
709
- shf: "application/shf+xml",
710
- st: "application/vnd.sailingtracker.track",
711
- svg: "image/svg+xml",
712
- sus: "application/vnd.sus-calendar",
713
- sru: "application/sru+xml",
714
- setpay: "application/set-payment-initiation",
715
- setreg: "application/set-registration-initiation",
716
- sema: "application/vnd.sema",
717
- semd: "application/vnd.semd",
718
- semf: "application/vnd.semf",
719
- see: "application/vnd.seemail",
720
- snf: "application/x-font-snf",
721
- spq: "application/scvp-vp-request",
722
- spp: "application/scvp-vp-response",
723
- scq: "application/scvp-cv-request",
724
- scs: "application/scvp-cv-response",
725
- sdp: "application/sdp",
726
- etx: "text/x-setext",
727
- movie: "video/x-sgi-movie",
728
- ifm: "application/vnd.shana.informed.formdata",
729
- itp: "application/vnd.shana.informed.formtemplate",
730
- iif: "application/vnd.shana.informed.interchange",
731
- ipk: "application/vnd.shana.informed.package",
732
- tfi: "application/thraud+xml",
733
- shar: "application/x-shar",
734
- rgb: "image/x-rgb",
735
- slt: "application/vnd.epson.salt",
736
- aso: "application/vnd.accpac.simply.aso",
737
- imp: "application/vnd.accpac.simply.imp",
738
- twd: "application/vnd.simtech-mindmapper",
739
- csp: "application/vnd.commonspace",
740
- saf: "application/vnd.yamaha.smaf-audio",
741
- mmf: "application/vnd.smaf",
742
- spf: "application/vnd.yamaha.smaf-phrase",
743
- teacher: "application/vnd.smart.teacher",
744
- svd: "application/vnd.svd",
745
- rq: "application/sparql-query",
746
- srx: "application/sparql-results+xml",
747
- gram: "application/srgs",
748
- grxml: "application/srgs+xml",
749
- ssml: "application/ssml+xml",
750
- skp: "application/vnd.koan",
751
- sgml: "text/sgml",
752
- sdc: "application/vnd.stardivision.calc",
753
- sda: "application/vnd.stardivision.draw",
754
- sdd: "application/vnd.stardivision.impress",
755
- smf: "application/vnd.stardivision.math",
756
- sdw: "application/vnd.stardivision.writer",
757
- sgl: "application/vnd.stardivision.writer-global",
758
- sm: "application/vnd.stepmania.stepchart",
759
- sit: "application/x-stuffit",
760
- sitx: "application/x-stuffitx",
761
- sdkm: "application/vnd.solent.sdkm+xml",
762
- xo: "application/vnd.olpc-sugar",
763
- au: "audio/basic",
764
- wqd: "application/vnd.wqd",
765
- sis: "application/vnd.symbian.install",
766
- smi: "application/smil+xml",
767
- xsm: "application/vnd.syncml+xml",
768
- bdm: "application/vnd.syncml.dm+wbxml",
769
- xdm: "application/vnd.syncml.dm+xml",
770
- sv4cpio: "application/x-sv4cpio",
771
- sv4crc: "application/x-sv4crc",
772
- sbml: "application/sbml+xml",
773
- tsv: "text/tab-separated-values",
774
- tiff: "image/tiff",
775
- tao: "application/vnd.tao.intent-module-archive",
776
- tar: "application/x-tar",
777
- tcl: "application/x-tcl",
778
- tex: "application/x-tex",
779
- tfm: "application/x-tex-tfm",
780
- tei: "application/tei+xml",
781
- txt: "text/plain",
782
- dxp: "application/vnd.spotfire.dxp",
783
- sfs: "application/vnd.spotfire.sfs",
784
- tsd: "application/timestamped-data",
785
- tpt: "application/vnd.trid.tpt",
786
- mxs: "application/vnd.triscape.mxs",
787
- t: "text/troff",
788
- tra: "application/vnd.trueapp",
789
- ttf: "application/x-font-ttf",
790
- ttl: "text/turtle",
791
- umj: "application/vnd.umajin",
792
- uoml: "application/vnd.uoml+xml",
793
- unityweb: "application/vnd.unity",
794
- ufd: "application/vnd.ufdl",
795
- uri: "text/uri-list",
796
- utz: "application/vnd.uiq.theme",
797
- ustar: "application/x-ustar",
798
- uu: "text/x-uuencode",
799
- vcs: "text/x-vcalendar",
800
- vcf: "text/x-vcard",
801
- vcd: "application/x-cdlink",
802
- vsf: "application/vnd.vsf",
803
- wrl: "model/vrml",
804
- vcx: "application/vnd.vcx",
805
- mts: "model/vnd.mts",
806
- vtu: "model/vnd.vtu",
807
- vis: "application/vnd.visionary",
808
- viv: "video/vnd.vivo",
809
- ccxml: "application/ccxml+xml,",
810
- vxml: "application/voicexml+xml",
811
- src: "application/x-wais-source",
812
- wbxml: "application/vnd.wap.wbxml",
813
- wbmp: "image/vnd.wap.wbmp",
814
- wav: "audio/x-wav",
815
- davmount: "application/davmount+xml",
816
- woff: "application/x-font-woff",
817
- wspolicy: "application/wspolicy+xml",
818
- webp: "image/webp",
819
- wtb: "application/vnd.webturbo",
820
- wgt: "application/widget",
821
- hlp: "application/winhlp",
822
- wml: "text/vnd.wap.wml",
823
- wmls: "text/vnd.wap.wmlscript",
824
- wmlsc: "application/vnd.wap.wmlscriptc",
825
- wpd: "application/vnd.wordperfect",
826
- stf: "application/vnd.wt.stf",
827
- wsdl: "application/wsdl+xml",
828
- xbm: "image/x-xbitmap",
829
- xpm: "image/x-xpixmap",
830
- xwd: "image/x-xwindowdump",
831
- der: "application/x-x509-ca-cert",
832
- fig: "application/x-xfig",
833
- xhtml: "application/xhtml+xml",
834
- xml: "application/xml",
835
- xdf: "application/xcap-diff+xml",
836
- xenc: "application/xenc+xml",
837
- xer: "application/patch-ops-error+xml",
838
- rl: "application/resource-lists+xml",
839
- rs: "application/rls-services+xml",
840
- rld: "application/resource-lists-diff+xml",
841
- xslt: "application/xslt+xml",
842
- xop: "application/xop+xml",
843
- xpi: "application/x-xpinstall",
844
- xspf: "application/xspf+xml",
845
- xul: "application/vnd.mozilla.xul+xml",
846
- xyz: "chemical/x-xyz",
847
- yaml: "text/yaml",
848
- yang: "application/yang",
849
- yin: "application/yin+xml",
850
- zir: "application/vnd.zul",
851
- zip: "application/zip",
852
- zmm: "application/vnd.handheld-entertainment+xml",
853
- zaz: "application/vnd.zzazz.deck+xml"
854
- };
855
-
856
- // TODO: write this out to avoid compute
857
- var MIME_TYPES_TO_EXT = Object.fromEntries(Object.entries(EXT_TO_MIME_TYPES).map(function (_ref) {
858
- var _ref2 = _slicedToArray(_ref, 2),
859
- k = _ref2[0],
860
- v = _ref2[1];
861
- return [v, k];
862
- }));
863
-
864
- var MIME_TYPE_REGEX = /^data:(.*?);base64,/;
865
- function getMimeType(base64Url) {
866
- var match = MIME_TYPE_REGEX.exec(base64Url);
867
- if (match && match[1]) {
868
- return match[1];
869
- }
870
- return;
871
- }
872
- function mimeTypeToFileExt(mimeType) {
873
- var recognizedMimeType = MIME_TYPES_TO_EXT[mimeType];
874
- if (recognizedMimeType) {
875
- return recognizedMimeType;
876
- }
877
- return mimeType.split("/")[1];
878
- }
879
- function filenameToMimeType(filename) {
880
- var ext = filename.split(".").pop();
881
- var recognizedExt = ext && EXT_TO_MIME_TYPES[ext];
882
- if (recognizedExt) {
883
- return recognizedExt;
884
- }
885
- }
886
-
887
116
  function remirrorToRichTextSource(node) {
888
117
  var files = {};
889
118
  var blocks = [];
890
119
  var i = 0;
891
- var _iterator = _createForOfIteratorHelper(node.content),
120
+ var _iterator = _createForOfIteratorHelper((node === null || node === void 0 ? void 0 : node.content) || []),
892
121
  _step;
893
122
  try {
894
123
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
@@ -1065,13 +294,16 @@ var textEncoder = new TextEncoder();
1065
294
  function convertImageNode(path, node, files) {
1066
295
  if (node.attrs && node.attrs.src.startsWith("data:")) {
1067
296
  var sha256 = Internal.getSHA256Hash(textEncoder.encode(node.attrs.src));
1068
- var mimeType = getMimeType(node.attrs.src);
297
+ var mimeType = Internal.getMimeType(node.attrs.src);
1069
298
  if (mimeType === undefined) {
1070
299
  throw new Error("Could not detect Mime Type for image: ".concat(node.attrs.src));
1071
300
  }
1072
- var fileExt = mimeTypeToFileExt(mimeType);
1073
- var fileName = node.attrs.fileName || "".concat(sha256, ".").concat(fileExt);
1074
- var filePath = "/public/".concat(fileName);
301
+ var fileName = Internal.createFilename(node.attrs.src, node.attrs.fileName || "", {
302
+ width: typeof node.attrs.width === "number" ? node.attrs.width : 0,
303
+ height: typeof node.attrs.height === "number" ? node.attrs.height : 0,
304
+ mimeType: mimeType
305
+ }, sha256);
306
+ var filePath = "/public/val/".concat(fileName);
1075
307
  var existingFilesEntry = files[filePath];
1076
308
  var thisPath = path
1077
309
  // file is added as src (see below):
@@ -1089,21 +321,32 @@ function convertImageNode(path, node, files) {
1089
321
  src: _defineProperty(_defineProperty(_defineProperty({}, VAL_EXTENSION, "file"), FILE_REF_PROP, filePath), "metadata", {
1090
322
  width: typeof node.attrs.width === "number" ? node.attrs.width : 0,
1091
323
  height: typeof node.attrs.height === "number" ? node.attrs.height : 0,
1092
- sha256: sha256 || "",
1093
324
  mimeType: mimeType
1094
325
  })
1095
326
  };
1096
327
  } else if (node.attrs) {
1097
- var _sha = getParam("sha256", node.attrs.src);
1098
- var patchId = getParam("patch_id", node.attrs.src);
1099
- var noParamsSrc = node.attrs.src.split("?")[0];
328
+ var url = node.attrs.src;
329
+ var patchId = getParam("patch_id", url);
330
+ var noParamsUrl = url.split("?")[0];
331
+ if (patchId) {
332
+ if (noParamsUrl.startsWith("/api/val/files/public")) {
333
+ noParamsUrl = noParamsUrl.slice("/api/val/files".length);
334
+ } else {
335
+ console.error("Patched image URL does not start with /api/val/files: " + url);
336
+ }
337
+ } else {
338
+ if (!noParamsUrl.startsWith("/public")) {
339
+ noParamsUrl = "/public".concat(noParamsUrl);
340
+ } else {
341
+ console.error("Unpatched image URL starts with /public: " + url);
342
+ }
343
+ }
1100
344
  var tag = {
1101
345
  tag: "img",
1102
- src: _objectSpread2(_defineProperty(_defineProperty(_defineProperty({}, VAL_EXTENSION, "file"), FILE_REF_PROP, "/public".concat(node.attrs.src.split("?")[0])), "metadata", {
346
+ src: _objectSpread2(_defineProperty(_defineProperty(_defineProperty({}, VAL_EXTENSION, "file"), FILE_REF_PROP, noParamsUrl), "metadata", {
1103
347
  width: typeof node.attrs.width === "number" ? node.attrs.width : 0,
1104
348
  height: typeof node.attrs.height === "number" ? node.attrs.height : 0,
1105
- sha256: _sha || "",
1106
- mimeType: noParamsSrc && filenameToMimeType(noParamsSrc) || ""
349
+ mimeType: noParamsUrl && Internal.filenameToMimeType(noParamsUrl) || ""
1107
350
  }), patchId ? {
1108
351
  patch_id: patchId
1109
352
  } : {})
@@ -1208,20 +451,20 @@ var RemirrorJSON = z.object({
1208
451
  content: z.array(z.union([RemirrorParagraph, RemirrorHeading, RemirrorBulletList, RemirrorOrderedList]))
1209
452
  });
1210
453
 
1211
- function _arrayWithoutHoles(arr) {
1212
- if (Array.isArray(arr)) return _arrayLikeToArray(arr);
454
+ function _arrayWithoutHoles(r) {
455
+ if (Array.isArray(r)) return _arrayLikeToArray(r);
1213
456
  }
1214
457
 
1215
- function _iterableToArray(iter) {
1216
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
458
+ function _iterableToArray(r) {
459
+ if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
1217
460
  }
1218
461
 
1219
462
  function _nonIterableSpread() {
1220
463
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1221
464
  }
1222
465
 
1223
- function _toConsumableArray(arr) {
1224
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
466
+ function _toConsumableArray(r) {
467
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
1225
468
  }
1226
469
 
1227
470
  function richTextToRemirror(richtext) {
@@ -1473,6 +716,46 @@ var VAL_SESSION_COOKIE = Internal.VAL_SESSION_COOKIE;
1473
716
  var VAL_STATE_COOKIE = Internal.VAL_STATE_COOKIE;
1474
717
  var VAL_ENABLE_COOKIE_NAME = Internal.VAL_ENABLE_COOKIE_NAME;
1475
718
 
719
+ function _arrayWithHoles(r) {
720
+ if (Array.isArray(r)) return r;
721
+ }
722
+
723
+ function _iterableToArrayLimit(r, l) {
724
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
725
+ if (null != t) {
726
+ var e,
727
+ n,
728
+ i,
729
+ u,
730
+ a = [],
731
+ f = !0,
732
+ o = !1;
733
+ try {
734
+ if (i = (t = t.call(r)).next, 0 === l) {
735
+ if (Object(t) !== t) return;
736
+ f = !1;
737
+ } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
738
+ } catch (r) {
739
+ o = !0, n = r;
740
+ } finally {
741
+ try {
742
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
743
+ } finally {
744
+ if (o) throw n;
745
+ }
746
+ }
747
+ return a;
748
+ }
749
+ }
750
+
751
+ function _nonIterableRest() {
752
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
753
+ }
754
+
755
+ function _slicedToArray(r, e) {
756
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
757
+ }
758
+
1476
759
  function _regeneratorRuntime() {
1477
760
  _regeneratorRuntime = function () {
1478
761
  return e;
@@ -1581,7 +864,7 @@ function _regeneratorRuntime() {
1581
864
  function makeInvokeMethod(e, r, n) {
1582
865
  var o = h;
1583
866
  return function (i, a) {
1584
- if (o === f) throw new Error("Generator is already running");
867
+ if (o === f) throw Error("Generator is already running");
1585
868
  if (o === s) {
1586
869
  if ("throw" === i) throw a;
1587
870
  return {
@@ -1723,7 +1006,7 @@ function _regeneratorRuntime() {
1723
1006
  } else if (c) {
1724
1007
  if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
1725
1008
  } else {
1726
- if (!u) throw new Error("try statement without catch or finally");
1009
+ if (!u) throw Error("try statement without catch or finally");
1727
1010
  if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
1728
1011
  }
1729
1012
  }
@@ -1763,7 +1046,7 @@ function _regeneratorRuntime() {
1763
1046
  return o;
1764
1047
  }
1765
1048
  }
1766
- throw new Error("illegal catch attempt");
1049
+ throw Error("illegal catch attempt");
1767
1050
  },
1768
1051
  delegateYield: function (e, r, n) {
1769
1052
  return this.delegate = {
@@ -1775,150 +1058,112 @@ function _regeneratorRuntime() {
1775
1058
  }, e;
1776
1059
  }
1777
1060
 
1778
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
1061
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
1779
1062
  try {
1780
- var info = gen[key](arg);
1781
- var value = info.value;
1782
- } catch (error) {
1783
- reject(error);
1784
- return;
1785
- }
1786
- if (info.done) {
1787
- resolve(value);
1788
- } else {
1789
- Promise.resolve(value).then(_next, _throw);
1063
+ var i = n[a](c),
1064
+ u = i.value;
1065
+ } catch (n) {
1066
+ return void e(n);
1790
1067
  }
1068
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
1791
1069
  }
1792
- function _asyncToGenerator(fn) {
1070
+ function _asyncToGenerator(n) {
1793
1071
  return function () {
1794
- var self = this,
1795
- args = arguments;
1796
- return new Promise(function (resolve, reject) {
1797
- var gen = fn.apply(self, args);
1798
- function _next(value) {
1799
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
1072
+ var t = this,
1073
+ e = arguments;
1074
+ return new Promise(function (r, o) {
1075
+ var a = n.apply(t, e);
1076
+ function _next(n) {
1077
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
1800
1078
  }
1801
- function _throw(err) {
1802
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
1079
+ function _throw(n) {
1080
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
1803
1081
  }
1804
- _next(undefined);
1082
+ _next(void 0);
1805
1083
  });
1806
1084
  };
1807
1085
  }
1808
1086
 
1809
- function _classCallCheck(instance, Constructor) {
1810
- if (!(instance instanceof Constructor)) {
1811
- throw new TypeError("Cannot call a class as a function");
1812
- }
1087
+ function _classCallCheck(a, n) {
1088
+ if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
1813
1089
  }
1814
1090
 
1815
- function _defineProperties(target, props) {
1816
- for (var i = 0; i < props.length; i++) {
1817
- var descriptor = props[i];
1818
- descriptor.enumerable = descriptor.enumerable || false;
1819
- descriptor.configurable = true;
1820
- if ("value" in descriptor) descriptor.writable = true;
1821
- Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);
1091
+ function _defineProperties(e, r) {
1092
+ for (var t = 0; t < r.length; t++) {
1093
+ var o = r[t];
1094
+ o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
1822
1095
  }
1823
1096
  }
1824
- function _createClass(Constructor, protoProps, staticProps) {
1825
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
1826
- if (staticProps) _defineProperties(Constructor, staticProps);
1827
- Object.defineProperty(Constructor, "prototype", {
1828
- writable: false
1829
- });
1830
- return Constructor;
1097
+ function _createClass(e, r, t) {
1098
+ return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
1099
+ writable: !1
1100
+ }), e;
1831
1101
  }
1832
1102
 
1833
- var ValStore = /*#__PURE__*/function () {
1834
- // uncertain whether this is the optimal way of returning
1835
-
1836
- function ValStore(api) {
1837
- var _this = this;
1838
- _classCallCheck(this, ValStore);
1839
- _defineProperty(this, "subscribe", function (paths) {
1840
- return function (listener) {
1841
- var subscriberId = createSubscriberId(paths);
1842
- if (!_this.listeners[subscriberId]) {
1843
- _this.listeners[subscriberId] = [];
1844
- _this.subscribers.set(subscriberId, {});
1845
- }
1846
- _this.listeners[subscriberId].push(listener);
1847
- return function () {
1848
- _this.listeners[subscriberId].splice(_this.listeners[subscriberId].indexOf(listener), 1);
1849
- };
1850
- };
1851
- });
1852
- _defineProperty(this, "getSnapshot", function (paths) {
1853
- return function () {
1854
- return _this.get(paths);
1855
- };
1856
- });
1857
- _defineProperty(this, "getServerSnapshot", function (paths) {
1858
- return function () {
1859
- return _this.get(paths);
1860
- };
1861
- });
1862
- _defineProperty(this, "get", function (paths) {
1863
- var subscriberId = createSubscriberId(paths);
1864
- return _this.subscribers.get(subscriberId);
1865
- });
1866
- this.api = api;
1867
- this.subscribers = new Map();
1868
- this.listeners = {};
1103
+ var ValCache = /*#__PURE__*/function () {
1104
+ function ValCache(client) {
1105
+ _classCallCheck(this, ValCache);
1106
+ this.client = client;
1869
1107
  this.drafts = {};
1870
1108
  this.schema = {};
1871
1109
  }
1872
- _createClass(ValStore, [{
1110
+ return _createClass(ValCache, [{
1873
1111
  key: "reloadPaths",
1874
1112
  value: function () {
1875
- var _reloadPaths = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(paths) {
1876
- var patches, filteredPatches, data, _i, _Object$keys, pathS, path, _i2, _Array$from, _Array$from$_i, subscriberId, subscriberModules;
1113
+ var _reloadPaths = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(paths) {
1114
+ var patchesResponse, patches, filteredPatches, treeRes, data, _i, _Object$keys, _data$modules, pathS, path;
1877
1115
  return _regeneratorRuntime().wrap(function _callee$(_context) {
1878
1116
  while (1) switch (_context.prev = _context.next) {
1879
1117
  case 0:
1880
1118
  _context.next = 2;
1881
- return this.api.getPatches({
1882
- omitPatches: true,
1883
- moduleFilePaths: paths
1119
+ return this.client("/patches/~", "GET", {
1120
+ query: {
1121
+ omit_patch: true,
1122
+ author: [],
1123
+ patch_id: [],
1124
+ module_file_path: paths
1125
+ }
1884
1126
  });
1885
1127
  case 2:
1886
- patches = _context.sent;
1887
- if (!result.isErr(patches)) {
1128
+ patchesResponse = _context.sent;
1129
+ if (!(patchesResponse.status !== 200)) {
1888
1130
  _context.next = 6;
1889
1131
  break;
1890
1132
  }
1891
- console.error("Val: failed to get patches", patches.error);
1133
+ console.error("Val: failed to get patches", patchesResponse.json.message, patchesResponse.json);
1892
1134
  return _context.abrupt("return");
1893
1135
  case 6:
1894
- filteredPatches = Object.keys(patches.value.patches);
1895
- _context.next = 9;
1896
- return this.api.putTree({
1897
- patchIds: filteredPatches
1136
+ patches = patchesResponse.json;
1137
+ filteredPatches = Object.keys(patches);
1138
+ _context.next = 10;
1139
+ return this.client("/sources", "PUT", {
1140
+ query: {
1141
+ validate_sources: true,
1142
+ validate_all: false,
1143
+ validate_binary_files: false
1144
+ },
1145
+ path: undefined,
1146
+ body: {
1147
+ patchIds: filteredPatches
1148
+ }
1898
1149
  });
1899
- case 9:
1900
- data = _context.sent;
1901
- _context.next = 12;
1150
+ case 10:
1151
+ treeRes = _context.sent;
1152
+ _context.next = 13;
1902
1153
  return this.initialize();
1903
- case 12:
1904
- if (result.isOk(data)) {
1905
- for (_i = 0, _Object$keys = Object.keys(data.value.modules); _i < _Object$keys.length; _i++) {
1154
+ case 13:
1155
+ if (treeRes.status === 200) {
1156
+ data = treeRes.json;
1157
+ for (_i = 0, _Object$keys = Object.keys(data.modules); _i < _Object$keys.length; _i++) {
1906
1158
  pathS = _Object$keys[_i];
1907
1159
  path = pathS;
1908
- this.drafts[path] = data.value.modules[path].source;
1160
+ this.drafts[path] = data === null || data === void 0 || (_data$modules = data.modules) === null || _data$modules === void 0 || (_data$modules = _data$modules[path]) === null || _data$modules === void 0 ? void 0 : _data$modules.source;
1909
1161
  this.emitEvent(path, this.drafts[path]);
1910
- for (_i2 = 0, _Array$from = Array.from(this.subscribers.entries()); _i2 < _Array$from.length; _i2++) {
1911
- _Array$from$_i = _slicedToArray(_Array$from[_i2], 2), subscriberId = _Array$from$_i[0], subscriberModules = _Array$from$_i[1];
1912
- if (subscriberModules[path]) {
1913
- this.subscribers.set(subscriberId, _objectSpread2(_objectSpread2({}, subscriberModules), {}, _defineProperty({}, path, this.drafts[path])));
1914
- this.emitChange(subscriberId);
1915
- }
1916
- }
1917
1162
  }
1918
1163
  } else {
1919
- console.error("Val: failed to reload paths", paths, data.error);
1164
+ console.error("Val: failed to reload paths", paths, treeRes.json);
1920
1165
  }
1921
- case 13:
1166
+ case 14:
1922
1167
  case "end":
1923
1168
  return _context.stop();
1924
1169
  }
@@ -1932,50 +1177,100 @@ var ValStore = /*#__PURE__*/function () {
1932
1177
  }, {
1933
1178
  key: "reset",
1934
1179
  value: function () {
1935
- var _reset = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
1936
- var patches, allPatches, data, _i3, _Object$keys2, pathS, path, _i4, _Array$from2, _Array$from2$_i, subscriberId, subscriberModules;
1180
+ var _reset = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
1181
+ var patchesRes, allPatches, treeRes, initRes, _i2, _Object$keys2, _treeRes$json, pathS, path;
1937
1182
  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1938
1183
  while (1) switch (_context2.prev = _context2.next) {
1939
1184
  case 0:
1940
1185
  _context2.next = 2;
1941
- return this.api.getPatches();
1186
+ return this.client("/patches/~", "GET", {
1187
+ query: {
1188
+ omit_patch: true,
1189
+ author: [],
1190
+ patch_id: [],
1191
+ module_file_path: []
1192
+ }
1193
+ });
1942
1194
  case 2:
1943
- patches = _context2.sent;
1944
- if (!result.isErr(patches)) {
1195
+ patchesRes = _context2.sent;
1196
+ if (!(patchesRes.status !== 200)) {
1945
1197
  _context2.next = 6;
1946
1198
  break;
1947
1199
  }
1948
- console.error("Val: failed to get patches", patches.error);
1949
- return _context2.abrupt("return");
1200
+ console.error("Val: failed to get patches", patchesRes.json);
1201
+ return _context2.abrupt("return", result.err({
1202
+ errorType: "other",
1203
+ message: "Failed to get patches"
1204
+ }));
1950
1205
  case 6:
1951
- allPatches = Object.keys(patches.value.patches);
1206
+ allPatches = Object.keys(patchesRes.json.patches);
1952
1207
  _context2.next = 9;
1953
- return this.api.putTree({
1954
- patchIds: allPatches
1208
+ return this.client("/sources", "PUT", {
1209
+ path: undefined,
1210
+ query: {
1211
+ validate_sources: false,
1212
+ validate_all: false,
1213
+ validate_binary_files: false
1214
+ },
1215
+ body: {
1216
+ patchIds: allPatches
1217
+ }
1955
1218
  });
1956
1219
  case 9:
1957
- data = _context2.sent;
1220
+ treeRes = _context2.sent;
1958
1221
  _context2.next = 12;
1959
1222
  return this.initialize();
1960
1223
  case 12:
1961
- if (result.isOk(data)) {
1962
- for (_i3 = 0, _Object$keys2 = Object.keys(data.value.modules); _i3 < _Object$keys2.length; _i3++) {
1963
- pathS = _Object$keys2[_i3];
1964
- path = pathS;
1965
- this.drafts[path] = data.value.modules[path].source;
1966
- this.emitEvent(path, this.drafts[path]);
1967
- for (_i4 = 0, _Array$from2 = Array.from(this.subscribers.entries()); _i4 < _Array$from2.length; _i4++) {
1968
- _Array$from2$_i = _slicedToArray(_Array$from2[_i4], 2), subscriberId = _Array$from2$_i[0], subscriberModules = _Array$from2$_i[1];
1969
- if (subscriberModules[path]) {
1970
- this.subscribers.set(subscriberId, _objectSpread2(_objectSpread2({}, subscriberModules), {}, _defineProperty({}, path, this.drafts[path])));
1971
- this.emitChange(subscriberId);
1972
- }
1973
- }
1974
- }
1975
- } else {
1976
- console.error("Val: failed to reset", data.error);
1224
+ initRes = _context2.sent;
1225
+ if (!result.isErr(initRes)) {
1226
+ _context2.next = 16;
1227
+ break;
1977
1228
  }
1978
- case 13:
1229
+ console.error("Failed to initialize inside reset", initRes.error);
1230
+ return _context2.abrupt("return", result.err({
1231
+ errorType: "other",
1232
+ message: initRes.error.message
1233
+ }));
1234
+ case 16:
1235
+ if (!(treeRes.status === 200)) {
1236
+ _context2.next = 21;
1237
+ break;
1238
+ }
1239
+ for (_i2 = 0, _Object$keys2 = Object.keys(treeRes.json.modules); _i2 < _Object$keys2.length; _i2++) {
1240
+ pathS = _Object$keys2[_i2];
1241
+ path = pathS;
1242
+ this.drafts[path] = (_treeRes$json = treeRes.json) === null || _treeRes$json === void 0 || (_treeRes$json = _treeRes$json.modules) === null || _treeRes$json === void 0 || (_treeRes$json = _treeRes$json[path]) === null || _treeRes$json === void 0 ? void 0 : _treeRes$json.source;
1243
+ this.emitEvent(path, this.drafts[path]);
1244
+ }
1245
+ return _context2.abrupt("return", result.ok(undefined));
1246
+ case 21:
1247
+ if (!(treeRes.status === 400 && "type" in treeRes.json)) {
1248
+ _context2.next = 25;
1249
+ break;
1250
+ }
1251
+ return _context2.abrupt("return", result.err({
1252
+ errorType: "patch-error",
1253
+ errors: Object.entries(treeRes.json.errors).flatMap(function (_ref) {
1254
+ var _ref2 = _slicedToArray(_ref, 2),
1255
+ moduleFilePath = _ref2[0],
1256
+ value = _ref2[1];
1257
+ return (value !== null && value !== void 0 ? value : []).map(function (item) {
1258
+ return {
1259
+ moduleFilePath: moduleFilePath,
1260
+ patchError: item.error.message,
1261
+ patchId: item.patchId,
1262
+ skipped: item.skipped
1263
+ };
1264
+ });
1265
+ })
1266
+ }));
1267
+ case 25:
1268
+ console.error("Val: failed to reset", treeRes.json);
1269
+ return _context2.abrupt("return", result.err({
1270
+ errorType: "other",
1271
+ message: "Failed to reset " + JSON.stringify(treeRes.json)
1272
+ }));
1273
+ case 27:
1979
1274
  case "end":
1980
1275
  return _context2.stop();
1981
1276
  }
@@ -1989,9 +1284,11 @@ var ValStore = /*#__PURE__*/function () {
1989
1284
  }, {
1990
1285
  key: "getModule",
1991
1286
  value: function () {
1992
- var _getModule = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(path) {
1287
+ var _getModule = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(path) {
1993
1288
  var refetch,
1994
- data,
1289
+ treeRes,
1290
+ _treeRes$json2,
1291
+ _treeRes$json3,
1995
1292
  fetchedSource,
1996
1293
  schema,
1997
1294
  _args3 = arguments;
@@ -2009,29 +1306,35 @@ var ValStore = /*#__PURE__*/function () {
2009
1306
  }));
2010
1307
  case 3:
2011
1308
  _context3.next = 5;
2012
- return this.api.putTree({
2013
- treePath: path
1309
+ return this.client("/sources", "PUT", {
1310
+ path: path,
1311
+ body: {},
1312
+ query: {
1313
+ validate_sources: false,
1314
+ validate_all: false,
1315
+ validate_binary_files: false
1316
+ }
2014
1317
  });
2015
1318
  case 5:
2016
- data = _context3.sent;
2017
- if (!result.isOk(data)) {
1319
+ treeRes = _context3.sent;
1320
+ if (!(treeRes.status === 200)) {
2018
1321
  _context3.next = 26;
2019
1322
  break;
2020
1323
  }
2021
- if (data.value.modules[path]) {
1324
+ if ((_treeRes$json2 = treeRes.json) !== null && _treeRes$json2 !== void 0 && (_treeRes$json2 = _treeRes$json2.modules) !== null && _treeRes$json2 !== void 0 && _treeRes$json2[path]) {
2022
1325
  _context3.next = 10;
2023
1326
  break;
2024
1327
  }
2025
1328
  console.error("Val: could not find the module", {
2026
- moduleIds: Object.keys(data.value.modules),
1329
+ moduleIds: Object.keys(treeRes.json.modules),
2027
1330
  moduleId: path,
2028
- data: data
1331
+ data: treeRes
2029
1332
  });
2030
1333
  return _context3.abrupt("return", result.err({
2031
1334
  message: "Could not fetch data.\nCould not find the module:\n" + path + "\n\nVerify that the val.modules file includes this module."
2032
1335
  }));
2033
1336
  case 10:
2034
- fetchedSource = data.value.modules[path].source;
1337
+ fetchedSource = (_treeRes$json3 = treeRes.json) === null || _treeRes$json3 === void 0 || (_treeRes$json3 = _treeRes$json3.modules) === null || _treeRes$json3 === void 0 || (_treeRes$json3 = _treeRes$json3[path]) === null || _treeRes$json3 === void 0 ? void 0 : _treeRes$json3.source;
2035
1338
  schema = this.schema[path];
2036
1339
  if (this.schema[path]) {
2037
1340
  _context3.next = 17;
@@ -2066,18 +1369,18 @@ var ValStore = /*#__PURE__*/function () {
2066
1369
  _context3.next = 33;
2067
1370
  break;
2068
1371
  case 26:
2069
- if (!(data.error.statusCode === 504)) {
1372
+ if (!(treeRes.status === 504)) {
2070
1373
  _context3.next = 31;
2071
1374
  break;
2072
1375
  }
2073
- console.error("Val: timeout", data.error);
1376
+ console.error("Val: timeout", treeRes.json);
2074
1377
  return _context3.abrupt("return", result.err({
2075
1378
  message: "Timed out while fetching data. Try again later."
2076
1379
  }));
2077
1380
  case 31:
2078
- console.error("Val: failed to get module", data.error);
1381
+ console.error("Val: failed to get module", treeRes.json);
2079
1382
  return _context3.abrupt("return", result.err({
2080
- message: "Could not fetch data. Verify that Val is correctly configured."
1383
+ message: "Could not fetch data. Verify that is correctly configured."
2081
1384
  }));
2082
1385
  case 33:
2083
1386
  case "end":
@@ -2091,78 +1394,140 @@ var ValStore = /*#__PURE__*/function () {
2091
1394
  return getModule;
2092
1395
  }()
2093
1396
  }, {
2094
- key: "applyPatch",
1397
+ key: "deletePatches",
2095
1398
  value: function () {
2096
- var _applyPatch = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(path, patchIds, patch) {
2097
- var data, newPatchId, fetchedSource, _data$value$modules$p, _i5, _Array$from3, _Array$from3$_i, subscriberId, subscriberModules;
1399
+ var _deletePatches = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(patchIds) {
1400
+ var patchesRes;
2098
1401
  return _regeneratorRuntime().wrap(function _callee4$(_context4) {
2099
1402
  while (1) switch (_context4.prev = _context4.next) {
2100
1403
  case 0:
2101
1404
  _context4.next = 2;
2102
- return this.api.putTree({
2103
- treePath: path,
2104
- patchIds: patchIds,
2105
- addPatch: {
2106
- path: path,
2107
- patch: patch
1405
+ return this.client("/patches/~", "DELETE", {
1406
+ query: {
1407
+ id: patchIds
1408
+ }
1409
+ });
1410
+ case 2:
1411
+ patchesRes = _context4.sent;
1412
+ if (!(patchesRes.status === 200)) {
1413
+ _context4.next = 7;
1414
+ break;
1415
+ }
1416
+ return _context4.abrupt("return", result.ok(patchesRes.json));
1417
+ case 7:
1418
+ console.error("Val: failed to delete patches", patchesRes.json);
1419
+ return _context4.abrupt("return", result.err({
1420
+ message: patchesRes.json.message
1421
+ }));
1422
+ case 9:
1423
+ case "end":
1424
+ return _context4.stop();
1425
+ }
1426
+ }, _callee4, this);
1427
+ }));
1428
+ function deletePatches(_x3) {
1429
+ return _deletePatches.apply(this, arguments);
1430
+ }
1431
+ return deletePatches;
1432
+ }()
1433
+ }, {
1434
+ key: "applyPatch",
1435
+ value: function () {
1436
+ var _applyPatch = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(path, patchIds, patch) {
1437
+ var treeRes, _treeRes$json4, newPatchIds, newPatchId, fetchedSource, _treeRes$json5;
1438
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1439
+ while (1) switch (_context5.prev = _context5.next) {
1440
+ case 0:
1441
+ _context5.next = 2;
1442
+ return this.client("/sources", "PUT", {
1443
+ path: path,
1444
+ query: {
1445
+ validate_sources: false,
1446
+ validate_all: false,
1447
+ validate_binary_files: false
1448
+ },
1449
+ body: {
1450
+ patchIds: patchIds,
1451
+ addPatches: [{
1452
+ path: path,
1453
+ patch: patch
1454
+ }]
2108
1455
  }
2109
1456
  });
2110
1457
  case 2:
2111
- data = _context4.sent;
2112
- if (!result.isOk(data)) {
2113
- _context4.next = 20;
1458
+ treeRes = _context5.sent;
1459
+ if (!(treeRes.status === 200)) {
1460
+ _context5.next = 20;
2114
1461
  break;
2115
1462
  }
2116
- newPatchId = data.value.newPatchId;
2117
- if (newPatchId) {
2118
- _context4.next = 8;
1463
+ newPatchIds = treeRes.json.newPatchIds;
1464
+ if (newPatchIds) {
1465
+ _context5.next = 8;
2119
1466
  break;
2120
1467
  }
2121
- console.error("Val: could create patch", data);
2122
- return _context4.abrupt("return", result.err({
2123
- message: "Val: could not create patch."
1468
+ console.error("Val: could create patch", treeRes);
1469
+ return _context5.abrupt("return", result.err({
1470
+ errorType: "other",
1471
+ message: "Val: could not create patch"
2124
1472
  }));
2125
1473
  case 8:
2126
- fetchedSource = data.value.modules[path].source;
1474
+ newPatchId = newPatchIds[0];
1475
+ fetchedSource = (_treeRes$json4 = treeRes.json) === null || _treeRes$json4 === void 0 || (_treeRes$json4 = _treeRes$json4.modules) === null || _treeRes$json4 === void 0 || (_treeRes$json4 = _treeRes$json4[path]) === null || _treeRes$json4 === void 0 ? void 0 : _treeRes$json4.source;
2127
1476
  if (!(fetchedSource !== undefined)) {
2128
- _context4.next = 16;
1477
+ _context5.next = 16;
2129
1478
  break;
2130
1479
  }
2131
1480
  this.drafts[path] = fetchedSource;
2132
1481
  this.emitEvent(path, fetchedSource);
2133
- for (_i5 = 0, _Array$from3 = Array.from(this.subscribers.entries()); _i5 < _Array$from3.length; _i5++) {
2134
- _Array$from3$_i = _slicedToArray(_Array$from3[_i5], 2), subscriberId = _Array$from3$_i[0], subscriberModules = _Array$from3$_i[1];
2135
- if (subscriberModules[path]) {
2136
- this.subscribers.set(subscriberId, _objectSpread2(_objectSpread2({}, subscriberModules), {}, _defineProperty({}, path, this.drafts[path])));
2137
- this.emitChange(subscriberId);
2138
- }
2139
- }
2140
- return _context4.abrupt("return", result.ok({
1482
+ return _context5.abrupt("return", result.ok({
2141
1483
  newPatchId: newPatchId,
2142
1484
  modules: _defineProperty({}, path, {
2143
- patchIds: ((_data$value$modules$p = data.value.modules[path].patches) === null || _data$value$modules$p === void 0 ? void 0 : _data$value$modules$p.applied) || []
1485
+ patchIds: ((_treeRes$json5 = treeRes.json) === null || _treeRes$json5 === void 0 || (_treeRes$json5 = _treeRes$json5.modules) === null || _treeRes$json5 === void 0 || (_treeRes$json5 = _treeRes$json5[path]) === null || _treeRes$json5 === void 0 || (_treeRes$json5 = _treeRes$json5.patches) === null || _treeRes$json5 === void 0 ? void 0 : _treeRes$json5.applied) || []
2144
1486
  })
2145
1487
  }));
2146
1488
  case 16:
2147
1489
  console.error("Val: could not patch");
2148
- return _context4.abrupt("return", result.err({
1490
+ return _context5.abrupt("return", result.err({
1491
+ errorType: "other",
2149
1492
  message: "Val: could not fetch data. Verify that the module exists."
2150
1493
  }));
2151
1494
  case 18:
2152
- _context4.next = 22;
1495
+ _context5.next = 26;
2153
1496
  break;
2154
1497
  case 20:
2155
- console.error("Val: failed to get module", data.error);
2156
- return _context4.abrupt("return", result.err({
2157
- message: "Val: could not fetch data. Verify that Val is correctly configured."
1498
+ if (!(treeRes.status === 400 && "type" in treeRes.json)) {
1499
+ _context5.next = 24;
1500
+ break;
1501
+ }
1502
+ return _context5.abrupt("return", result.err({
1503
+ errorType: "patch-error",
1504
+ errors: Object.entries(treeRes.json.errors).flatMap(function (_ref3) {
1505
+ var _ref4 = _slicedToArray(_ref3, 2),
1506
+ moduleFilePath = _ref4[0],
1507
+ value = _ref4[1];
1508
+ return (value !== null && value !== void 0 ? value : []).map(function (item) {
1509
+ return {
1510
+ moduleFilePath: moduleFilePath,
1511
+ patchError: item.error.message,
1512
+ patchId: item.patchId,
1513
+ skipped: item.skipped
1514
+ };
1515
+ });
1516
+ })
2158
1517
  }));
2159
- case 22:
1518
+ case 24:
1519
+ console.error("Val: failed to get module", treeRes.json);
1520
+ return _context5.abrupt("return", result.err({
1521
+ errorType: "other",
1522
+ message: "Val: could not fetch data. Verify that is correctly configured."
1523
+ }));
1524
+ case 26:
2160
1525
  case "end":
2161
- return _context4.stop();
1526
+ return _context5.stop();
2162
1527
  }
2163
- }, _callee4, this);
1528
+ }, _callee5, this);
2164
1529
  }));
2165
- function applyPatch(_x3, _x4, _x5) {
1530
+ function applyPatch(_x4, _x5, _x6) {
2166
1531
  return _applyPatch.apply(this, arguments);
2167
1532
  }
2168
1533
  return applyPatch;
@@ -2182,74 +1547,1005 @@ var ValStore = /*#__PURE__*/function () {
2182
1547
  }, {
2183
1548
  key: "initialize",
2184
1549
  value: function () {
2185
- var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
2186
- var data, paths, _i6, _arr, moduleId, schema, msg;
2187
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
2188
- while (1) switch (_context5.prev = _context5.next) {
1550
+ var _initialize = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
1551
+ var schemaRes, paths, _i3, _arr, moduleId, schema, msg;
1552
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1553
+ while (1) switch (_context6.prev = _context6.next) {
2189
1554
  case 0:
2190
- _context5.next = 2;
2191
- return this.api.getSchema({});
1555
+ _context6.next = 2;
1556
+ return this.client("/schema", "GET", {});
2192
1557
  case 2:
2193
- data = _context5.sent;
2194
- if (!result.isOk(data)) {
2195
- _context5.next = 9;
1558
+ schemaRes = _context6.sent;
1559
+ if (!(schemaRes.status === 200)) {
1560
+ _context6.next = 9;
2196
1561
  break;
2197
1562
  }
2198
1563
  paths = [];
2199
- for (_i6 = 0, _arr = Object.keys(data.value.schemas); _i6 < _arr.length; _i6++) {
2200
- moduleId = _arr[_i6];
2201
- schema = data.value.schemas[moduleId];
1564
+ for (_i3 = 0, _arr = Object.keys(schemaRes.json.schemas); _i3 < _arr.length; _i3++) {
1565
+ moduleId = _arr[_i3];
1566
+ schema = schemaRes.json.schemas[moduleId];
2202
1567
  if (schema) {
2203
1568
  paths.push(moduleId);
2204
1569
  this.schema[moduleId] = schema;
2205
1570
  }
2206
1571
  }
2207
- return _context5.abrupt("return", result.ok(paths));
1572
+ return _context6.abrupt("return", result.ok(paths));
2208
1573
  case 9:
2209
1574
  msg = "Failed to fetch content. ";
2210
- if (data.error.statusCode === 401) {
1575
+ if (schemaRes.status === 401) {
2211
1576
  msg += "Authorization failed - check that you are logged in.";
2212
1577
  } else {
2213
- msg += "Get a developer to verify that Val is correctly setup.";
1578
+ msg += "Get a developer to verify that is correctly setup.";
2214
1579
  }
2215
- return _context5.abrupt("return", result.err({
1580
+ return _context6.abrupt("return", result.err({
2216
1581
  message: msg,
2217
1582
  details: {
2218
- fetchError: data.error
1583
+ fetchError: schemaRes.json
2219
1584
  }
2220
1585
  }));
2221
1586
  case 12:
2222
1587
  case "end":
2223
- return _context5.stop();
1588
+ return _context6.stop();
2224
1589
  }
2225
- }, _callee5, this);
1590
+ }, _callee6, this);
2226
1591
  }));
2227
1592
  function initialize() {
2228
1593
  return _initialize.apply(this, arguments);
2229
1594
  }
2230
1595
  return initialize;
2231
1596
  }()
2232
- }, {
2233
- key: "emitChange",
2234
- value: function emitChange(subscriberId) {
2235
- var _iterator = _createForOfIteratorHelper(this.listeners[subscriberId]),
2236
- _step;
2237
- try {
2238
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
2239
- var listener = _step.value;
2240
- listener();
2241
- }
2242
- } catch (err) {
2243
- _iterator.e(err);
2244
- } finally {
2245
- _iterator.f();
2246
- }
2247
- }
2248
1597
  }]);
2249
- return ValStore;
2250
1598
  }();
2251
- function createSubscriberId(paths) {
2252
- return paths.slice().sort().join("&");
1599
+
1600
+ var JSONValueT = z.lazy(function () {
1601
+ return z.union([z.string(), z.number(), z["boolean"](), z["null"](), z.array(JSONValueT), z.record(JSONValueT)]);
1602
+ });
1603
+ var OperationT = z.discriminatedUnion("op", [z.object({
1604
+ op: z.literal("add"),
1605
+ path: z.array(z.string()),
1606
+ value: JSONValueT
1607
+ }).strict(), z.object({
1608
+ op: z.literal("remove"),
1609
+ path: z.array(z.string()).nonempty()
1610
+ }).strict(), z.object({
1611
+ op: z.literal("replace"),
1612
+ path: z.array(z.string()),
1613
+ value: JSONValueT
1614
+ }).strict(), z.object({
1615
+ op: z.literal("move"),
1616
+ from: z.array(z.string()).nonempty(),
1617
+ path: z.array(z.string())
1618
+ }).strict(), z.object({
1619
+ op: z.literal("copy"),
1620
+ from: z.array(z.string()),
1621
+ path: z.array(z.string())
1622
+ }).strict(), z.object({
1623
+ op: z.literal("test"),
1624
+ path: z.array(z.string()),
1625
+ value: JSONValueT
1626
+ }).strict(), z.object({
1627
+ op: z.literal("file"),
1628
+ path: z.array(z.string()),
1629
+ filePath: z.string(),
1630
+ nestedFilePath: z.array(z.string()).optional(),
1631
+ value: z.union([z.string(), z.object({
1632
+ sha256: z.string()
1633
+ })])
1634
+ }).strict()]);
1635
+ var Patch = z.array(OperationT);
1636
+
1637
+ var SourcePath = z.string().transform(function (path) {
1638
+ return path;
1639
+ });
1640
+
1641
+ var SerializedStringSchema = z.object({
1642
+ type: z.literal("string"),
1643
+ options: z.object({
1644
+ maxLength: z.number().optional(),
1645
+ minLength: z.number().optional(),
1646
+ regexp: z.object({
1647
+ source: z.string(),
1648
+ flags: z.string()
1649
+ }).optional()
1650
+ }).optional(),
1651
+ opt: z["boolean"](),
1652
+ raw: z["boolean"]()
1653
+ });
1654
+ var SerializedLiteralSchema = z.object({
1655
+ type: z.literal("literal"),
1656
+ value: z.string(),
1657
+ opt: z["boolean"]()
1658
+ });
1659
+ var SerializedBooleanSchema = z.object({
1660
+ type: z.literal("boolean"),
1661
+ opt: z["boolean"]()
1662
+ });
1663
+ var SerializedNumberSchema = z.object({
1664
+ type: z.literal("number"),
1665
+ options: z.object({
1666
+ max: z.number().optional(),
1667
+ min: z.number().optional()
1668
+ }).optional(),
1669
+ opt: z["boolean"]()
1670
+ });
1671
+ var SerializedObjectSchema = z.lazy(function () {
1672
+ return z.object({
1673
+ type: z.literal("object"),
1674
+ items: z.record(SerializedSchema),
1675
+ opt: z["boolean"]()
1676
+ });
1677
+ });
1678
+ var SerializedArraySchema = z.lazy(function () {
1679
+ return z.object({
1680
+ type: z.literal("array"),
1681
+ item: SerializedSchema,
1682
+ opt: z["boolean"]()
1683
+ });
1684
+ });
1685
+ var SerializedUnionSchema = z.lazy(function () {
1686
+ return z.union([z.object({
1687
+ type: z.literal("union"),
1688
+ key: SerializedLiteralSchema,
1689
+ items: z.array(SerializedLiteralSchema),
1690
+ opt: z["boolean"]()
1691
+ }), z.object({
1692
+ type: z.literal("union"),
1693
+ key: z.string(),
1694
+ items: z.array(SerializedObjectSchema),
1695
+ opt: z["boolean"]()
1696
+ })]);
1697
+ });
1698
+ var RichTextOptions = z.object({
1699
+ style: z.object({
1700
+ bold: z["boolean"]().optional(),
1701
+ italic: z["boolean"]().optional(),
1702
+ lineThrough: z["boolean"]().optional()
1703
+ }).optional(),
1704
+ block: z.object({
1705
+ h1: z["boolean"]().optional(),
1706
+ h2: z["boolean"]().optional(),
1707
+ h3: z["boolean"]().optional(),
1708
+ h4: z["boolean"]().optional(),
1709
+ h5: z["boolean"]().optional(),
1710
+ h6: z["boolean"]().optional(),
1711
+ ul: z["boolean"]().optional(),
1712
+ ol: z["boolean"]().optional()
1713
+ }).optional(),
1714
+ inline: z.object({
1715
+ a: z["boolean"]().optional(),
1716
+ img: z["boolean"]().optional()
1717
+ }).optional()
1718
+ });
1719
+ var SerializedRichTextSchema = z.object({
1720
+ type: z.literal("richtext"),
1721
+ options: RichTextOptions.optional(),
1722
+ opt: z["boolean"]()
1723
+ });
1724
+ var SerializedRecordSchema = z.lazy(function () {
1725
+ return z.object({
1726
+ type: z.literal("record"),
1727
+ item: SerializedSchema,
1728
+ opt: z["boolean"]()
1729
+ });
1730
+ });
1731
+ var SerializedKeyOfSchema = z.lazy(function () {
1732
+ return z.object({
1733
+ type: z.literal("keyOf"),
1734
+ path: SourcePath,
1735
+ schema: SerializedSchema,
1736
+ values: z.union([z.literal("string"), z.array(z.string())]),
1737
+ opt: z["boolean"]()
1738
+ });
1739
+ });
1740
+ var FileOptions = z.object({
1741
+ accept: z.string().optional()
1742
+ });
1743
+ var SerializedFileSchema = z.object({
1744
+ type: z.literal("file"),
1745
+ options: FileOptions.optional(),
1746
+ opt: z["boolean"]()
1747
+ });
1748
+ var SerializedDateSchema = z.object({
1749
+ type: z.literal("date"),
1750
+ opt: z["boolean"]()
1751
+ });
1752
+ var ImageOptions = z.object({
1753
+ ext: z.union([z.tuple([z.literal("jpg")]), z.tuple([z.literal("webp")])]).optional(),
1754
+ directory: z.string().optional(),
1755
+ prefix: z.string().optional(),
1756
+ accept: z.string().optional()
1757
+ });
1758
+ var SerializedImageSchema = z.object({
1759
+ type: z.literal("image"),
1760
+ options: ImageOptions.optional(),
1761
+ opt: z["boolean"]()
1762
+ });
1763
+ var SerializedSchema = z.union([SerializedStringSchema, SerializedLiteralSchema, SerializedBooleanSchema, SerializedNumberSchema, SerializedObjectSchema, SerializedArraySchema, SerializedUnionSchema, SerializedRichTextSchema, SerializedRecordSchema, SerializedKeyOfSchema, SerializedFileSchema, SerializedDateSchema, SerializedImageSchema]);
1764
+
1765
+ var PatchId = z.string().refine(function (_id) {
1766
+ return true;
1767
+ } // TODO:
1768
+ );
1769
+ var ModuleFilePath = z.string().refine(function (_path) {
1770
+ return true;
1771
+ } // TODO:
1772
+ );
1773
+ var ValConfig = z.object({
1774
+ project: z.string().optional(),
1775
+ root: z.string().optional(),
1776
+ files: z.object({
1777
+ directory: z.string() // TODO: validate that it is prefixed by /public/
1778
+ }).optional(),
1779
+ gitCommit: z.string().optional(),
1780
+ gitBranch: z.string().optional()
1781
+ });
1782
+ var ValidationFixZ = z.union([z.literal("image:add-metadata"), z.literal("image:replace-metadata"), z.literal("file:add-metadata"), z.literal("file:check-metadata"), z.literal("fix:deprecated-richtext")]);
1783
+ var ValidationError = z.object({
1784
+ message: z.string(),
1785
+ value: z.unknown().optional(),
1786
+ fatal: z["boolean"]().optional(),
1787
+ fixes: z.array(ValidationFixZ).optional()
1788
+ });
1789
+ var notFoundResponse = z.object({
1790
+ status: z.literal(401),
1791
+ json: z.object({
1792
+ message: z.string()
1793
+ })
1794
+ });
1795
+ var GenericError = z.object({
1796
+ message: z.string()
1797
+ });
1798
+ var ModulesError = z.object({
1799
+ message: z.string(),
1800
+ path: ModuleFilePath.optional()
1801
+ });
1802
+ z.union([z.literal("val_session"), z.literal("val_enable"), z.literal("val_state")]);
1803
+ var enableCookieValue = z.object({
1804
+ value: z.literal("true"),
1805
+ options: z.object({
1806
+ httpOnly: z.literal(false),
1807
+ sameSite: z.literal("lax")
1808
+ })
1809
+ });
1810
+ var Api = {
1811
+ "/draft/enable": {
1812
+ GET: {
1813
+ req: {
1814
+ query: {
1815
+ redirect_to: z.string().optional()
1816
+ },
1817
+ cookies: _defineProperty({}, VAL_SESSION_COOKIE, z.string().optional())
1818
+ },
1819
+ res: z.union([z.object({
1820
+ status: z.literal(401),
1821
+ json: GenericError
1822
+ }), z.object({
1823
+ status: z.literal(302),
1824
+ redirectTo: z.string()
1825
+ }), z.object({
1826
+ status: z.literal(400),
1827
+ json: z.object({
1828
+ message: z.string()
1829
+ })
1830
+ })])
1831
+ }
1832
+ },
1833
+ "/draft/disable": {
1834
+ GET: {
1835
+ req: {
1836
+ query: {
1837
+ redirect_to: z.string().optional()
1838
+ },
1839
+ cookies: _defineProperty({}, VAL_SESSION_COOKIE, z.string().optional())
1840
+ },
1841
+ res: z.union([z.object({
1842
+ status: z.literal(401),
1843
+ json: GenericError
1844
+ }), z.object({
1845
+ status: z.literal(302),
1846
+ redirectTo: z.string()
1847
+ }), z.object({
1848
+ status: z.literal(400),
1849
+ json: z.object({
1850
+ message: z.string()
1851
+ })
1852
+ })])
1853
+ }
1854
+ },
1855
+ "/draft/stat": {
1856
+ GET: {
1857
+ req: {
1858
+ cookies: _defineProperty({}, VAL_SESSION_COOKIE, z.string().optional())
1859
+ },
1860
+ res: z.union([z.object({
1861
+ status: z.literal(401),
1862
+ json: GenericError
1863
+ }), z.object({
1864
+ status: z.literal(200),
1865
+ json: z.object({
1866
+ draftMode: z["boolean"]()
1867
+ })
1868
+ })])
1869
+ }
1870
+ },
1871
+ "/enable": {
1872
+ GET: {
1873
+ req: {
1874
+ query: {
1875
+ redirect_to: z.string().optional()
1876
+ },
1877
+ cookies: _defineProperty({}, VAL_SESSION_COOKIE, z.string().optional())
1878
+ },
1879
+ res: z.union([z.object({
1880
+ status: z.literal(401),
1881
+ json: GenericError
1882
+ }), z.object({
1883
+ status: z.literal(302),
1884
+ redirectTo: z.string(),
1885
+ cookies: z.object(_defineProperty(_defineProperty({}, VAL_ENABLE_COOKIE_NAME, enableCookieValue), VAL_STATE_COOKIE, z.object({
1886
+ value: z.string(),
1887
+ options: z.object({
1888
+ httpOnly: z.literal(true),
1889
+ sameSite: z.literal("lax"),
1890
+ expires: z["instanceof"](Date)
1891
+ })
1892
+ })))
1893
+ }), z.object({
1894
+ status: z.literal(302),
1895
+ redirectTo: z.string(),
1896
+ cookies: z.object(_defineProperty({}, VAL_ENABLE_COOKIE_NAME, enableCookieValue))
1897
+ }), z.object({
1898
+ status: z.literal(400),
1899
+ json: z.object({
1900
+ message: z.string()
1901
+ })
1902
+ })])
1903
+ }
1904
+ },
1905
+ "/disable": {
1906
+ GET: {
1907
+ req: {
1908
+ query: {
1909
+ redirect_to: z.string().optional()
1910
+ },
1911
+ cookies: _defineProperty({}, VAL_SESSION_COOKIE, z.string().optional())
1912
+ },
1913
+ res: z.union([z.object({
1914
+ status: z.literal(401),
1915
+ json: GenericError
1916
+ }), z.object({
1917
+ status: z.literal(302),
1918
+ redirectTo: z.string(),
1919
+ cookies: z.object(_defineProperty({}, VAL_ENABLE_COOKIE_NAME, z.object({
1920
+ value: z.literal("false")
1921
+ })))
1922
+ }), z.object({
1923
+ status: z.literal(400),
1924
+ json: z.object({
1925
+ message: z.string()
1926
+ })
1927
+ })])
1928
+ }
1929
+ },
1930
+ "/authorize": {
1931
+ GET: {
1932
+ req: {
1933
+ query: {
1934
+ redirect_to: z.string().optional()
1935
+ }
1936
+ },
1937
+ res: z.union([z.object({
1938
+ status: z.literal(302),
1939
+ redirectTo: z.string(),
1940
+ cookies: z.object(_defineProperty(_defineProperty({}, VAL_ENABLE_COOKIE_NAME, enableCookieValue), VAL_STATE_COOKIE, z.object({
1941
+ value: z.string(),
1942
+ options: z.object({
1943
+ httpOnly: z.literal(true),
1944
+ sameSite: z.literal("lax"),
1945
+ expires: z["instanceof"](Date)
1946
+ })
1947
+ })))
1948
+ }), z.object({
1949
+ status: z.literal(400),
1950
+ json: z.object({
1951
+ message: z.string()
1952
+ })
1953
+ })])
1954
+ }
1955
+ },
1956
+ "/callback": {
1957
+ GET: {
1958
+ req: {
1959
+ query: {
1960
+ code: z.string().optional(),
1961
+ state: z.string().optional()
1962
+ },
1963
+ cookies: _defineProperty({}, VAL_STATE_COOKIE, z.string())
1964
+ },
1965
+ res: z.object({
1966
+ status: z.literal(302),
1967
+ redirectTo: z.string(),
1968
+ cookies: z.object(_defineProperty(_defineProperty(_defineProperty({}, VAL_STATE_COOKIE, z.object({
1969
+ value: z.literal(null)
1970
+ })), VAL_ENABLE_COOKIE_NAME, enableCookieValue.optional()), VAL_SESSION_COOKIE, z.object({
1971
+ value: z.string(),
1972
+ options: z.object({
1973
+ httpOnly: z.literal(true),
1974
+ sameSite: z.literal("strict"),
1975
+ path: z.string(),
1976
+ secure: z.literal(true),
1977
+ expires: z["instanceof"](Date)
1978
+ }).optional()
1979
+ }).optional()))
1980
+ })
1981
+ }
1982
+ },
1983
+ "/session": {
1984
+ GET: {
1985
+ req: {
1986
+ cookies: {
1987
+ val_session: z.string().optional()
1988
+ }
1989
+ },
1990
+ res: z.union([z.object({
1991
+ status: z.literal(200),
1992
+ json: z.object({
1993
+ mode: z.union([z.literal("local"), z.literal("proxy")]),
1994
+ enabled: z["boolean"]()
1995
+ })
1996
+ }), z.object({
1997
+ status: z.union([
1998
+ // TODO: Remove the ones we don't need.
1999
+ z.literal(400), z.literal(401), z.literal(403), z.literal(404), z.literal(500), z.literal(501)]),
2000
+ json: z.object({
2001
+ message: z.string()
2002
+ })
2003
+ }), z.object({
2004
+ status: z.literal(401),
2005
+ json: z.object({
2006
+ message: z.string(),
2007
+ details: z.union([z.string(), z.object({
2008
+ reason: z.string()
2009
+ }), z.object({
2010
+ sub: z.string(),
2011
+ exp: z.number(),
2012
+ token: z.string(),
2013
+ org: z.string(),
2014
+ project: z.string()
2015
+ })])
2016
+ })
2017
+ }), z.object({
2018
+ status: z.literal(500),
2019
+ json: z.object({
2020
+ message: z.string()
2021
+ })
2022
+ })])
2023
+ }
2024
+ },
2025
+ "/logout": {
2026
+ GET: {
2027
+ req: {},
2028
+ // TODO fix req types
2029
+ res: z.object({
2030
+ status: z.literal(200),
2031
+ cookies: z.object(_defineProperty(_defineProperty({}, VAL_SESSION_COOKIE, z.object({
2032
+ value: z.literal(null)
2033
+ })), VAL_STATE_COOKIE, z.object({
2034
+ value: z.literal(null)
2035
+ })))
2036
+ })
2037
+ }
2038
+ },
2039
+ "/stat": {
2040
+ POST: {
2041
+ req: {
2042
+ body: z.object({
2043
+ schemaSha: z.string(),
2044
+ baseSha: z.string(),
2045
+ patches: z.array(z.string()).optional()
2046
+ }).nullable(),
2047
+ cookies: {
2048
+ val_session: z.string().optional()
2049
+ }
2050
+ },
2051
+ res: z.union([z.object({
2052
+ status: z.literal(401),
2053
+ json: GenericError
2054
+ }), z.object({
2055
+ status: z.literal(500),
2056
+ json: GenericError
2057
+ }), z.object({
2058
+ status: z.literal(200),
2059
+ json: z.union([z.object({
2060
+ type: z.union([z.literal("request-again"), z.literal("no-change"), z.literal("did-change")]),
2061
+ baseSha: z.string(),
2062
+ schemaSha: z.string(),
2063
+ patches: z.array(PatchId),
2064
+ config: ValConfig
2065
+ }), z.object({
2066
+ type: z.literal("use-websocket"),
2067
+ url: z.string(),
2068
+ nonce: z.string(),
2069
+ baseSha: z.string(),
2070
+ schemaSha: z.string(),
2071
+ commitSha: z.string(),
2072
+ patches: z.array(PatchId),
2073
+ config: ValConfig
2074
+ })])
2075
+ })])
2076
+ }
2077
+ },
2078
+ "/patches/~": {
2079
+ DELETE: {
2080
+ req: {
2081
+ query: {
2082
+ id: z.array(PatchId)
2083
+ },
2084
+ cookies: {
2085
+ val_session: z.string().optional()
2086
+ }
2087
+ },
2088
+ res: z.union([notFoundResponse, z.object({
2089
+ status: z.literal(500),
2090
+ json: z.object({
2091
+ message: z.string(),
2092
+ details: z.record(PatchId, GenericError)
2093
+ })
2094
+ }), z.object({
2095
+ status: z.literal(200),
2096
+ json: z.array(PatchId)
2097
+ })])
2098
+ },
2099
+ GET: {
2100
+ req: {
2101
+ query: {
2102
+ author: z.array(z.string()).optional(),
2103
+ patch_id: z.array(PatchId).optional(),
2104
+ module_file_path: z.array(ModuleFilePath).optional(),
2105
+ omit_patch: z["boolean"]().optional() // TODO: rename! we mean that we are not including the actual patch / operations in the response
2106
+ },
2107
+ cookies: {
2108
+ val_session: z.string().optional()
2109
+ }
2110
+ },
2111
+ res: z.union([notFoundResponse, z.object({
2112
+ status: z.literal(500),
2113
+ json: z.object({
2114
+ message: z.string(),
2115
+ details: z.record(PatchId, GenericError)
2116
+ })
2117
+ }), z.object({
2118
+ status: z.literal(200),
2119
+ json: z.object({
2120
+ patches: z.record(PatchId, z.object({
2121
+ path: ModuleFilePath,
2122
+ patch: Patch.optional(),
2123
+ createdAt: z.string(),
2124
+ authorId: z.string().nullable(),
2125
+ appliedAt: z.object({
2126
+ baseSha: z.string(),
2127
+ git: z.object({
2128
+ commitSha: z.string()
2129
+ }).optional(),
2130
+ timestamp: z.string()
2131
+ }).nullable()
2132
+ })),
2133
+ error: GenericError.optional(),
2134
+ errors: z.record(PatchId, GenericError).optional()
2135
+ })
2136
+ })])
2137
+ }
2138
+ },
2139
+ "/schema": {
2140
+ GET: {
2141
+ req: {
2142
+ cookies: {
2143
+ val_session: z.string().optional()
2144
+ }
2145
+ },
2146
+ res: z.union([notFoundResponse, z.object({
2147
+ status: z.literal(500),
2148
+ json: z.object({
2149
+ message: z.string(),
2150
+ details: z.array(ModulesError)
2151
+ })
2152
+ }), z.object({
2153
+ status: z.literal(500),
2154
+ json: z.object({
2155
+ message: z.string(),
2156
+ details: z.array(GenericError)
2157
+ })
2158
+ }), z.object({
2159
+ status: z.literal(200),
2160
+ json: z.object({
2161
+ schemaSha: z.string(),
2162
+ schemas: z.record(ModuleFilePath, SerializedSchema)
2163
+ })
2164
+ })])
2165
+ }
2166
+ },
2167
+ "/sources": {
2168
+ PUT: {
2169
+ req: {
2170
+ path: z.string().optional(),
2171
+ body: z.object({
2172
+ patchIds: z.array(PatchId).optional(),
2173
+ addPatches: z.array(z.object({
2174
+ path: ModuleFilePath,
2175
+ patch: Patch
2176
+ })).optional()
2177
+ }).optional(),
2178
+ query: {
2179
+ validate_all: z["boolean"]().optional(),
2180
+ validate_sources: z["boolean"]().optional(),
2181
+ validate_binary_files: z["boolean"]().optional()
2182
+ },
2183
+ cookies: {
2184
+ val_session: z.string().optional()
2185
+ }
2186
+ },
2187
+ res: z.union([notFoundResponse, z.object({
2188
+ status: z.literal(401),
2189
+ json: GenericError
2190
+ }), z.object({
2191
+ status: z.literal(409),
2192
+ // conflict: i.e. not a head of patches
2193
+ json: GenericError
2194
+ }), z.object({
2195
+ status: z.literal(500),
2196
+ json: z.object({
2197
+ message: z.string(),
2198
+ details: z.union([z.array(ModulesError), GenericError])
2199
+ })
2200
+ }), z.object({
2201
+ status: z.literal(400),
2202
+ json: z.object({
2203
+ message: z.string(),
2204
+ details: z.array(ModulesError)
2205
+ })
2206
+ }), z.object({
2207
+ status: z.literal(400),
2208
+ json: z.object({
2209
+ type: z.literal("patch-error"),
2210
+ message: z.string(),
2211
+ schemaSha: z.string(),
2212
+ modules: z.record(ModuleFilePath, z.object({
2213
+ source: z.any(),
2214
+ //.optional(), // TODO: Json zod type
2215
+ patches: z.object({
2216
+ applied: z.array(PatchId),
2217
+ skipped: z.array(PatchId).optional(),
2218
+ errors: z.record(PatchId, GenericError).optional()
2219
+ }).optional(),
2220
+ validationErrors: z.record(SourcePath, z.array(ValidationError)).optional()
2221
+ })),
2222
+ errors: z.record(ModuleFilePath, z.array(z.object({
2223
+ patchId: PatchId,
2224
+ skipped: z["boolean"](),
2225
+ error: GenericError
2226
+ })))
2227
+ })
2228
+ }), z.object({
2229
+ status: z.literal(200),
2230
+ json: z.object({
2231
+ schemaSha: z.string(),
2232
+ modules: z.record(ModuleFilePath, z.object({
2233
+ source: z.any(),
2234
+ //.optional(), // TODO: Json zod type
2235
+ patches: z.object({
2236
+ applied: z.array(PatchId),
2237
+ skipped: z.array(PatchId).optional(),
2238
+ errors: z.record(PatchId, GenericError).optional()
2239
+ }).optional(),
2240
+ validationErrors: z.record(SourcePath, z.array(ValidationError)).optional()
2241
+ })),
2242
+ newPatchIds: z.array(PatchId).optional()
2243
+ })
2244
+ })])
2245
+ }
2246
+ },
2247
+ "/save": {
2248
+ POST: {
2249
+ req: {
2250
+ body: z.object({
2251
+ patchIds: z.array(PatchId)
2252
+ }),
2253
+ cookies: {
2254
+ val_session: z.string().optional()
2255
+ }
2256
+ },
2257
+ res: z.union([notFoundResponse, z.object({
2258
+ status: z.literal(200),
2259
+ json: z.object({}) // TODO:
2260
+ }), z.object({
2261
+ status: z.literal(409),
2262
+ json: z.object({
2263
+ message: z.string(),
2264
+ isNotFastForward: z.literal(true)
2265
+ })
2266
+ }), z.object({
2267
+ status: z.literal(400),
2268
+ json: z.object({
2269
+ message: z.string(),
2270
+ details: z.union([z.object({
2271
+ sourceFilePatchErrors: z.record(ModuleFilePath, z.array(GenericError)),
2272
+ binaryFilePatchErrors: z.record(GenericError)
2273
+ }), z.array(GenericError)])
2274
+ })
2275
+ })])
2276
+ }
2277
+ },
2278
+ "/files": {
2279
+ GET: {
2280
+ req: {
2281
+ path: z.string(),
2282
+ query: {
2283
+ patch_id: PatchId.optional()
2284
+ }
2285
+ },
2286
+ res: z.union([z.object({
2287
+ status: z.literal(200),
2288
+ body: z["instanceof"](ReadableStream)
2289
+ }), z.object({
2290
+ status: z.literal(404),
2291
+ json: z.object({
2292
+ message: z.string()
2293
+ })
2294
+ })])
2295
+ }
2296
+ }
2297
+ };
2298
+
2299
+ // Types and helper types:
2300
+
2301
+ /**
2302
+ * Extracts the keys of an object where the value is not undefined.
2303
+ */
2304
+
2305
+ /**
2306
+ * Extracts the keys of an object where the value is not undefined.
2307
+ * Then picks the keys from the object.
2308
+ * This is useful for creating a new object type with only the defined keys.
2309
+ * @example
2310
+ * type A = { a: string; b?: number };
2311
+ * type B = DefinedObject<A>; // { a: string }
2312
+ */
2313
+
2314
+ /**
2315
+ * This schema supports:
2316
+ * 1. multiple query params with the same name
2317
+ * 2. simple API route definitions where:
2318
+ * 2.1. z.array means at least one query params this name is required
2319
+ * 2.2. z.optional means no query param of this name is accepted
2320
+ * 2.3. z.array(...).optional() means zero or more query params of this name is accepted
2321
+ *
2322
+ * Do not change this without updating the ValRouter query parsing logic
2323
+ * */
2324
+
2325
+ var createValClient = function createValClient(host) {
2326
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2327
+ var anyApi = Api;
2328
+ return /*#__PURE__*/function () {
2329
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(path, method, req) {
2330
+ var _anyApi$path, _apiEndpoint$req$body;
2331
+ var anyReq, fullPath, params, _i, _Object$keys, _anyReq$query, key, _anyReq$query2, _iterator, _step, value, _anyReq$query3, apiEndpoint, reqBodyResult, res;
2332
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
2333
+ while (1) switch (_context2.prev = _context2.next) {
2334
+ case 0:
2335
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2336
+ anyReq = req;
2337
+ fullPath = path;
2338
+ if (anyReq !== null && anyReq !== void 0 && anyReq.path && anyReq.path.length > 0) {
2339
+ fullPath += anyReq.path;
2340
+ }
2341
+ if (anyReq.query) {
2342
+ params = [];
2343
+ for (_i = 0, _Object$keys = Object.keys(anyReq.query); _i < _Object$keys.length; _i++) {
2344
+ key = _Object$keys[_i];
2345
+ if (Array.isArray((_anyReq$query = anyReq.query) === null || _anyReq$query === void 0 ? void 0 : _anyReq$query[key])) {
2346
+ _iterator = _createForOfIteratorHelper(((_anyReq$query2 = anyReq.query) === null || _anyReq$query2 === void 0 ? void 0 : _anyReq$query2[key]) || []);
2347
+ try {
2348
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
2349
+ value = _step.value;
2350
+ params.push([key, value.toString()]);
2351
+ }
2352
+ } catch (err) {
2353
+ _iterator.e(err);
2354
+ } finally {
2355
+ _iterator.f();
2356
+ }
2357
+ } else {
2358
+ params.push([key, anyReq === null || anyReq === void 0 || (_anyReq$query3 = anyReq.query) === null || _anyReq$query3 === void 0 ? void 0 : _anyReq$query3[key]]);
2359
+ }
2360
+ }
2361
+ if (anyReq !== null && anyReq !== void 0 && anyReq.query && params.length > 0) {
2362
+ fullPath += "?".concat(new URLSearchParams(params).toString());
2363
+ }
2364
+ }
2365
+ apiEndpoint = anyApi === null || anyApi === void 0 || (_anyApi$path = anyApi[path]) === null || _anyApi$path === void 0 ? void 0 : _anyApi$path[method];
2366
+ if (apiEndpoint) {
2367
+ _context2.next = 7;
2368
+ break;
2369
+ }
2370
+ return _context2.abrupt("return", {
2371
+ status: null,
2372
+ json: {
2373
+ message: "Invalid route ".concat(path, " with method ").concat(method, ". This is most likely a Val bug."),
2374
+ type: "client_side_validation_error",
2375
+ details: {
2376
+ validationError: "Route ".concat(path, " with method ").concat(method, " not found."),
2377
+ data: {
2378
+ routes: Object.keys(anyApi || {}),
2379
+ methods: Object.keys((anyApi === null || anyApi === void 0 ? void 0 : anyApi[path]) || {}),
2380
+ route: path,
2381
+ method: method
2382
+ }
2383
+ }
2384
+ }
2385
+ });
2386
+ case 7:
2387
+ reqBodyResult = (_apiEndpoint$req$body = apiEndpoint.req.body) === null || _apiEndpoint$req$body === void 0 ? void 0 : _apiEndpoint$req$body.safeParse(anyReq.body);
2388
+ if (!(reqBodyResult && !reqBodyResult.success)) {
2389
+ _context2.next = 10;
2390
+ break;
2391
+ }
2392
+ return _context2.abrupt("return", {
2393
+ status: null,
2394
+ json: {
2395
+ message: "Invalid request body. This is most likely a Val bug.",
2396
+ type: "client_side_validation_error",
2397
+ details: {
2398
+ validationError: fromZodError(reqBodyResult.error).toString(),
2399
+ data: anyReq.body
2400
+ }
2401
+ }
2402
+ });
2403
+ case 10:
2404
+ _context2.prev = 10;
2405
+ _context2.next = 13;
2406
+ return fetch("".concat(host).concat(fullPath), {
2407
+ method: method,
2408
+ headers: {
2409
+ "Content-Type": "application/json"
2410
+ },
2411
+ body: anyReq.body !== undefined ? JSON.stringify(anyReq.body) : undefined
2412
+ }).then(/*#__PURE__*/function () {
2413
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(res) {
2414
+ var _apiEndpoint$res;
2415
+ var contentTypeHeaders, json, valClientResult, responseResult;
2416
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2417
+ while (1) switch (_context.prev = _context.next) {
2418
+ case 0:
2419
+ contentTypeHeaders = res.headers.get("content-type");
2420
+ if (contentTypeHeaders !== null && contentTypeHeaders !== void 0 && contentTypeHeaders.includes("application/json")) {
2421
+ _context.next = 3;
2422
+ break;
2423
+ }
2424
+ return _context.abrupt("return", {
2425
+ status: null,
2426
+ json: {
2427
+ type: "client_side_validation_error",
2428
+ message: "Invalid content type header in response. Could not find application/json in ".concat(Array.from(res.headers.entries()), ". This could be a result of mismatched Val versions."),
2429
+ details: {
2430
+ validationError: "Invalid content type",
2431
+ data: {
2432
+ status: res.status,
2433
+ contentType: contentTypeHeaders
2434
+ }
2435
+ }
2436
+ }
2437
+ });
2438
+ case 3:
2439
+ _context.next = 5;
2440
+ return res.json();
2441
+ case 5:
2442
+ json = _context.sent;
2443
+ valClientResult = {
2444
+ status: res.status,
2445
+ json: json
2446
+ };
2447
+ if (!(res.status === 500)) {
2448
+ _context.next = 10;
2449
+ break;
2450
+ }
2451
+ console.log("Server responded with an error", json);
2452
+ return _context.abrupt("return", {
2453
+ status: 500,
2454
+ json: {
2455
+ message: json.message,
2456
+ type: "unknown"
2457
+ }
2458
+ });
2459
+ case 10:
2460
+ responseResult = (_apiEndpoint$res = apiEndpoint.res) === null || _apiEndpoint$res === void 0 ? void 0 : _apiEndpoint$res.safeParse(valClientResult);
2461
+ if (!(responseResult && !responseResult.success)) {
2462
+ _context.next = 13;
2463
+ break;
2464
+ }
2465
+ return _context.abrupt("return", {
2466
+ status: null,
2467
+ json: {
2468
+ message: "Response could not be validated. This could also be a result of mismatched Val versions.",
2469
+ type: "client_side_validation_error",
2470
+ details: {
2471
+ validationError: fromZodError(responseResult.error).toString(),
2472
+ data: valClientResult
2473
+ }
2474
+ }
2475
+ });
2476
+ case 13:
2477
+ return _context.abrupt("return", {
2478
+ status: res.status,
2479
+ json: json
2480
+ });
2481
+ case 14:
2482
+ case "end":
2483
+ return _context.stop();
2484
+ }
2485
+ }, _callee);
2486
+ }));
2487
+ return function (_x4) {
2488
+ return _ref2.apply(this, arguments);
2489
+ };
2490
+ }());
2491
+ case 13:
2492
+ res = _context2.sent;
2493
+ return _context2.abrupt("return", res);
2494
+ case 17:
2495
+ _context2.prev = 17;
2496
+ _context2.t0 = _context2["catch"](10);
2497
+ return _context2.abrupt("return", {
2498
+ status: null,
2499
+ json: {
2500
+ message: "Failed to fetch data",
2501
+ type: "network_error",
2502
+ retryable: isRetryable(_context2.t0),
2503
+ details: _context2.t0 instanceof Error ? _context2.t0.message : JSON.stringify(_context2.t0)
2504
+ }
2505
+ });
2506
+ case 20:
2507
+ case "end":
2508
+ return _context2.stop();
2509
+ }
2510
+ }, _callee2, null, [[10, 17]]);
2511
+ }));
2512
+ return function (_x, _x2, _x3) {
2513
+ return _ref.apply(this, arguments);
2514
+ };
2515
+ }();
2516
+ };
2517
+ function isRetryable(error) {
2518
+ if (error instanceof TypeError) {
2519
+ // TypeError is usually thrown by fetch when the network request fails.
2520
+ return true;
2521
+ }
2522
+ if (error instanceof Error && "code" in error) {
2523
+ var errorCode = error.code;
2524
+
2525
+ // Network-specific errors (Node.js specific)
2526
+ var retryableErrorCodes = ["ECONNRESET", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN"];
2527
+ return retryableErrorCodes.includes(errorCode);
2528
+ }
2529
+ return false;
2253
2530
  }
2254
2531
 
2255
- export { EXT_TO_MIME_TYPES, MIME_TYPES_TO_EXT, RemirrorBr, RemirrorBulletList, RemirrorHeading, RemirrorImage, RemirrorJSON, RemirrorLinkMark, RemirrorListItem, RemirrorOrderedList, RemirrorParagraph, RemirrorText, RemirrorTextMark, VAL_ENABLE_COOKIE_NAME, VAL_SESSION_COOKIE, VAL_STATE_COOKIE, ValStore, filenameToMimeType, getMimeType, mimeTypeToFileExt, remirrorToRichTextSource, richTextToRemirror };
2532
+ var urlOf = function urlOf() {
2533
+ var route = arguments.length <= 0 ? undefined : arguments[0];
2534
+ var query = arguments.length <= 1 ? undefined : arguments[1];
2535
+ if (query) {
2536
+ var params = Object.entries(query).flatMap(function (_ref) {
2537
+ var _ref2 = _slicedToArray(_ref, 2),
2538
+ key = _ref2[0],
2539
+ value = _ref2[1];
2540
+ if (!value) {
2541
+ return [];
2542
+ }
2543
+ return [[key, value.toString()]];
2544
+ });
2545
+ var searchParams = new URLSearchParams(params);
2546
+ return "".concat(route + "?" + searchParams.toString());
2547
+ }
2548
+ return "".concat(route);
2549
+ };
2550
+
2551
+ export { Api, RemirrorBr, RemirrorBulletList, RemirrorHeading, RemirrorImage, RemirrorJSON, RemirrorLinkMark, RemirrorListItem, RemirrorOrderedList, RemirrorParagraph, RemirrorText, RemirrorTextMark, VAL_ENABLE_COOKIE_NAME, VAL_SESSION_COOKIE, VAL_STATE_COOKIE, ValCache, createValClient, remirrorToRichTextSource, richTextToRemirror, urlOf };