@coffre/cli 0.1.13 → 0.1.15

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.
@@ -0,0 +1,1456 @@
1
+ import { r as isEmpty } from "./init-2xGelVG1.js";
2
+ import { spawn } from "node:child_process";
3
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js
6
+ /**
7
+ * Creates a JSON scanner on the given text.
8
+ * If ignoreTrivia is set, whitespaces or comments are ignored.
9
+ */
10
+ function createScanner(text, ignoreTrivia = false) {
11
+ const len = text.length;
12
+ let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
13
+ function scanHexDigits(count, exact) {
14
+ let digits = 0;
15
+ let value = 0;
16
+ while (digits < count || !exact) {
17
+ let ch = text.charCodeAt(pos);
18
+ if (ch >= 48 && ch <= 57) value = value * 16 + ch - 48;
19
+ else if (ch >= 65 && ch <= 70) value = value * 16 + ch - 65 + 10;
20
+ else if (ch >= 97 && ch <= 102) value = value * 16 + ch - 97 + 10;
21
+ else break;
22
+ pos++;
23
+ digits++;
24
+ }
25
+ if (digits < count) value = -1;
26
+ return value;
27
+ }
28
+ function setPosition(newPosition) {
29
+ pos = newPosition;
30
+ value = "";
31
+ tokenOffset = 0;
32
+ token = 16;
33
+ scanError = 0;
34
+ }
35
+ function scanNumber() {
36
+ let start = pos;
37
+ if (text.charCodeAt(pos) === 48) pos++;
38
+ else {
39
+ pos++;
40
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
41
+ }
42
+ if (pos < text.length && text.charCodeAt(pos) === 46) {
43
+ pos++;
44
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
45
+ pos++;
46
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
47
+ } else {
48
+ scanError = 3;
49
+ return text.substring(start, pos);
50
+ }
51
+ }
52
+ let end = pos;
53
+ if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
54
+ pos++;
55
+ if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++;
56
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
57
+ pos++;
58
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
59
+ end = pos;
60
+ } else scanError = 3;
61
+ }
62
+ return text.substring(start, end);
63
+ }
64
+ function scanString() {
65
+ let result = "", start = pos;
66
+ while (true) {
67
+ if (pos >= len) {
68
+ result += text.substring(start, pos);
69
+ scanError = 2;
70
+ break;
71
+ }
72
+ const ch = text.charCodeAt(pos);
73
+ if (ch === 34) {
74
+ result += text.substring(start, pos);
75
+ pos++;
76
+ break;
77
+ }
78
+ if (ch === 92) {
79
+ result += text.substring(start, pos);
80
+ pos++;
81
+ if (pos >= len) {
82
+ scanError = 2;
83
+ break;
84
+ }
85
+ switch (text.charCodeAt(pos++)) {
86
+ case 34:
87
+ result += "\"";
88
+ break;
89
+ case 92:
90
+ result += "\\";
91
+ break;
92
+ case 47:
93
+ result += "/";
94
+ break;
95
+ case 98:
96
+ result += "\b";
97
+ break;
98
+ case 102:
99
+ result += "\f";
100
+ break;
101
+ case 110:
102
+ result += "\n";
103
+ break;
104
+ case 114:
105
+ result += "\r";
106
+ break;
107
+ case 116:
108
+ result += " ";
109
+ break;
110
+ case 117:
111
+ const ch3 = scanHexDigits(4, true);
112
+ if (ch3 >= 0) result += String.fromCharCode(ch3);
113
+ else scanError = 4;
114
+ break;
115
+ default: scanError = 5;
116
+ }
117
+ start = pos;
118
+ continue;
119
+ }
120
+ if (ch >= 0 && ch <= 31) {
121
+ if (isLineBreak(ch)) {
122
+ result += text.substring(start, pos);
123
+ scanError = 2;
124
+ break;
125
+ } else scanError = 6;
126
+ }
127
+ pos++;
128
+ }
129
+ return result;
130
+ }
131
+ function scanNext() {
132
+ value = "";
133
+ scanError = 0;
134
+ tokenOffset = pos;
135
+ lineStartOffset = lineNumber;
136
+ prevTokenLineStartOffset = tokenLineStartOffset;
137
+ if (pos >= len) {
138
+ tokenOffset = len;
139
+ return token = 17;
140
+ }
141
+ let code = text.charCodeAt(pos);
142
+ if (isWhiteSpace(code)) {
143
+ do {
144
+ pos++;
145
+ value += String.fromCharCode(code);
146
+ code = text.charCodeAt(pos);
147
+ } while (isWhiteSpace(code));
148
+ return token = 15;
149
+ }
150
+ if (isLineBreak(code)) {
151
+ pos++;
152
+ value += String.fromCharCode(code);
153
+ if (code === 13 && text.charCodeAt(pos) === 10) {
154
+ pos++;
155
+ value += "\n";
156
+ }
157
+ lineNumber++;
158
+ tokenLineStartOffset = pos;
159
+ return token = 14;
160
+ }
161
+ switch (code) {
162
+ case 123:
163
+ pos++;
164
+ return token = 1;
165
+ case 125:
166
+ pos++;
167
+ return token = 2;
168
+ case 91:
169
+ pos++;
170
+ return token = 3;
171
+ case 93:
172
+ pos++;
173
+ return token = 4;
174
+ case 58:
175
+ pos++;
176
+ return token = 6;
177
+ case 44:
178
+ pos++;
179
+ return token = 5;
180
+ case 34:
181
+ pos++;
182
+ value = scanString();
183
+ return token = 10;
184
+ case 47:
185
+ const start = pos - 1;
186
+ if (text.charCodeAt(pos + 1) === 47) {
187
+ pos += 2;
188
+ while (pos < len) {
189
+ if (isLineBreak(text.charCodeAt(pos))) break;
190
+ pos++;
191
+ }
192
+ value = text.substring(start, pos);
193
+ return token = 12;
194
+ }
195
+ if (text.charCodeAt(pos + 1) === 42) {
196
+ pos += 2;
197
+ const safeLength = len - 1;
198
+ let commentClosed = false;
199
+ while (pos < safeLength) {
200
+ const ch = text.charCodeAt(pos);
201
+ if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
202
+ pos += 2;
203
+ commentClosed = true;
204
+ break;
205
+ }
206
+ pos++;
207
+ if (isLineBreak(ch)) {
208
+ if (ch === 13 && text.charCodeAt(pos) === 10) pos++;
209
+ lineNumber++;
210
+ tokenLineStartOffset = pos;
211
+ }
212
+ }
213
+ if (!commentClosed) {
214
+ pos++;
215
+ scanError = 1;
216
+ }
217
+ value = text.substring(start, pos);
218
+ return token = 13;
219
+ }
220
+ value += String.fromCharCode(code);
221
+ pos++;
222
+ return token = 16;
223
+ case 45:
224
+ value += String.fromCharCode(code);
225
+ pos++;
226
+ if (pos === len || !isDigit(text.charCodeAt(pos))) return token = 16;
227
+ case 48:
228
+ case 49:
229
+ case 50:
230
+ case 51:
231
+ case 52:
232
+ case 53:
233
+ case 54:
234
+ case 55:
235
+ case 56:
236
+ case 57:
237
+ value += scanNumber();
238
+ return token = 11;
239
+ default:
240
+ while (pos < len && isUnknownContentCharacter(code)) {
241
+ pos++;
242
+ code = text.charCodeAt(pos);
243
+ }
244
+ if (tokenOffset !== pos) {
245
+ value = text.substring(tokenOffset, pos);
246
+ switch (value) {
247
+ case "true": return token = 8;
248
+ case "false": return token = 9;
249
+ case "null": return token = 7;
250
+ }
251
+ return token = 16;
252
+ }
253
+ value += String.fromCharCode(code);
254
+ pos++;
255
+ return token = 16;
256
+ }
257
+ }
258
+ function isUnknownContentCharacter(code) {
259
+ if (isWhiteSpace(code) || isLineBreak(code)) return false;
260
+ switch (code) {
261
+ case 125:
262
+ case 93:
263
+ case 123:
264
+ case 91:
265
+ case 34:
266
+ case 58:
267
+ case 44:
268
+ case 47: return false;
269
+ }
270
+ return true;
271
+ }
272
+ function scanNextNonTrivia() {
273
+ let result;
274
+ do
275
+ result = scanNext();
276
+ while (result >= 12 && result <= 15);
277
+ return result;
278
+ }
279
+ return {
280
+ setPosition,
281
+ getPosition: () => pos,
282
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
283
+ getToken: () => token,
284
+ getTokenValue: () => value,
285
+ getTokenOffset: () => tokenOffset,
286
+ getTokenLength: () => pos - tokenOffset,
287
+ getTokenStartLine: () => lineStartOffset,
288
+ getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
289
+ getTokenError: () => scanError
290
+ };
291
+ }
292
+ function isWhiteSpace(ch) {
293
+ return ch === 32 || ch === 9;
294
+ }
295
+ function isLineBreak(ch) {
296
+ return ch === 10 || ch === 13;
297
+ }
298
+ function isDigit(ch) {
299
+ return ch >= 48 && ch <= 57;
300
+ }
301
+ var CharacterCodes;
302
+ (function(CharacterCodes) {
303
+ CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
304
+ CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
305
+ CharacterCodes[CharacterCodes["space"] = 32] = "space";
306
+ CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
307
+ CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
308
+ CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
309
+ CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
310
+ CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
311
+ CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
312
+ CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
313
+ CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
314
+ CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
315
+ CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
316
+ CharacterCodes[CharacterCodes["a"] = 97] = "a";
317
+ CharacterCodes[CharacterCodes["b"] = 98] = "b";
318
+ CharacterCodes[CharacterCodes["c"] = 99] = "c";
319
+ CharacterCodes[CharacterCodes["d"] = 100] = "d";
320
+ CharacterCodes[CharacterCodes["e"] = 101] = "e";
321
+ CharacterCodes[CharacterCodes["f"] = 102] = "f";
322
+ CharacterCodes[CharacterCodes["g"] = 103] = "g";
323
+ CharacterCodes[CharacterCodes["h"] = 104] = "h";
324
+ CharacterCodes[CharacterCodes["i"] = 105] = "i";
325
+ CharacterCodes[CharacterCodes["j"] = 106] = "j";
326
+ CharacterCodes[CharacterCodes["k"] = 107] = "k";
327
+ CharacterCodes[CharacterCodes["l"] = 108] = "l";
328
+ CharacterCodes[CharacterCodes["m"] = 109] = "m";
329
+ CharacterCodes[CharacterCodes["n"] = 110] = "n";
330
+ CharacterCodes[CharacterCodes["o"] = 111] = "o";
331
+ CharacterCodes[CharacterCodes["p"] = 112] = "p";
332
+ CharacterCodes[CharacterCodes["q"] = 113] = "q";
333
+ CharacterCodes[CharacterCodes["r"] = 114] = "r";
334
+ CharacterCodes[CharacterCodes["s"] = 115] = "s";
335
+ CharacterCodes[CharacterCodes["t"] = 116] = "t";
336
+ CharacterCodes[CharacterCodes["u"] = 117] = "u";
337
+ CharacterCodes[CharacterCodes["v"] = 118] = "v";
338
+ CharacterCodes[CharacterCodes["w"] = 119] = "w";
339
+ CharacterCodes[CharacterCodes["x"] = 120] = "x";
340
+ CharacterCodes[CharacterCodes["y"] = 121] = "y";
341
+ CharacterCodes[CharacterCodes["z"] = 122] = "z";
342
+ CharacterCodes[CharacterCodes["A"] = 65] = "A";
343
+ CharacterCodes[CharacterCodes["B"] = 66] = "B";
344
+ CharacterCodes[CharacterCodes["C"] = 67] = "C";
345
+ CharacterCodes[CharacterCodes["D"] = 68] = "D";
346
+ CharacterCodes[CharacterCodes["E"] = 69] = "E";
347
+ CharacterCodes[CharacterCodes["F"] = 70] = "F";
348
+ CharacterCodes[CharacterCodes["G"] = 71] = "G";
349
+ CharacterCodes[CharacterCodes["H"] = 72] = "H";
350
+ CharacterCodes[CharacterCodes["I"] = 73] = "I";
351
+ CharacterCodes[CharacterCodes["J"] = 74] = "J";
352
+ CharacterCodes[CharacterCodes["K"] = 75] = "K";
353
+ CharacterCodes[CharacterCodes["L"] = 76] = "L";
354
+ CharacterCodes[CharacterCodes["M"] = 77] = "M";
355
+ CharacterCodes[CharacterCodes["N"] = 78] = "N";
356
+ CharacterCodes[CharacterCodes["O"] = 79] = "O";
357
+ CharacterCodes[CharacterCodes["P"] = 80] = "P";
358
+ CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
359
+ CharacterCodes[CharacterCodes["R"] = 82] = "R";
360
+ CharacterCodes[CharacterCodes["S"] = 83] = "S";
361
+ CharacterCodes[CharacterCodes["T"] = 84] = "T";
362
+ CharacterCodes[CharacterCodes["U"] = 85] = "U";
363
+ CharacterCodes[CharacterCodes["V"] = 86] = "V";
364
+ CharacterCodes[CharacterCodes["W"] = 87] = "W";
365
+ CharacterCodes[CharacterCodes["X"] = 88] = "X";
366
+ CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
367
+ CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
368
+ CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
369
+ CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
370
+ CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
371
+ CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
372
+ CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
373
+ CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
374
+ CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
375
+ CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
376
+ CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
377
+ CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
378
+ CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
379
+ CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
380
+ CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
381
+ CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
382
+ CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
383
+ })(CharacterCodes || (CharacterCodes = {}));
384
+ //#endregion
385
+ //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js
386
+ const cachedSpaces = new Array(20).fill(0).map((_, index) => {
387
+ return " ".repeat(index);
388
+ });
389
+ const maxCachedValues = 200;
390
+ const cachedBreakLinesWithSpaces = {
391
+ " ": {
392
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
393
+ return "\n" + " ".repeat(index);
394
+ }),
395
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
396
+ return "\r" + " ".repeat(index);
397
+ }),
398
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
399
+ return "\r\n" + " ".repeat(index);
400
+ })
401
+ },
402
+ " ": {
403
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
404
+ return "\n" + " ".repeat(index);
405
+ }),
406
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
407
+ return "\r" + " ".repeat(index);
408
+ }),
409
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
410
+ return "\r\n" + " ".repeat(index);
411
+ })
412
+ }
413
+ };
414
+ const supportedEols = [
415
+ "\n",
416
+ "\r",
417
+ "\r\n"
418
+ ];
419
+ //#endregion
420
+ //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js
421
+ function format(documentText, range, options) {
422
+ let initialIndentLevel;
423
+ let formatText;
424
+ let formatTextStart;
425
+ let rangeStart;
426
+ let rangeEnd;
427
+ if (range) {
428
+ rangeStart = range.offset;
429
+ rangeEnd = rangeStart + range.length;
430
+ formatTextStart = rangeStart;
431
+ while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) formatTextStart--;
432
+ let endOffset = rangeEnd;
433
+ while (endOffset < documentText.length && !isEOL(documentText, endOffset)) endOffset++;
434
+ formatText = documentText.substring(formatTextStart, endOffset);
435
+ initialIndentLevel = computeIndentLevel(formatText, options);
436
+ } else {
437
+ formatText = documentText;
438
+ initialIndentLevel = 0;
439
+ formatTextStart = 0;
440
+ rangeStart = 0;
441
+ rangeEnd = documentText.length;
442
+ }
443
+ const eol = getEOL(options, documentText);
444
+ const eolFastPathSupported = supportedEols.includes(eol);
445
+ let numberLineBreaks = 0;
446
+ let indentLevel = 0;
447
+ let indentValue;
448
+ if (options.insertSpaces) indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);
449
+ else indentValue = " ";
450
+ const indentType = indentValue === " " ? " " : " ";
451
+ let scanner = createScanner(formatText, false);
452
+ let hasError = false;
453
+ function newLinesAndIndent() {
454
+ if (numberLineBreaks > 1) return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
455
+ const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);
456
+ if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) return eol + repeat(indentValue, initialIndentLevel + indentLevel);
457
+ if (amountOfSpaces <= 0) return eol;
458
+ return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];
459
+ }
460
+ function scanNext() {
461
+ let token = scanner.scan();
462
+ numberLineBreaks = 0;
463
+ while (token === 15 || token === 14) {
464
+ if (token === 14 && options.keepLines) numberLineBreaks += 1;
465
+ else if (token === 14) numberLineBreaks = 1;
466
+ token = scanner.scan();
467
+ }
468
+ hasError = token === 16 || scanner.getTokenError() !== 0;
469
+ return token;
470
+ }
471
+ const editOperations = [];
472
+ function addEdit(text, startOffset, endOffset) {
473
+ if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) editOperations.push({
474
+ offset: startOffset,
475
+ length: endOffset - startOffset,
476
+ content: text
477
+ });
478
+ }
479
+ let firstToken = scanNext();
480
+ if (options.keepLines && numberLineBreaks > 0) addEdit(repeat(eol, numberLineBreaks), 0, 0);
481
+ if (firstToken !== 17) {
482
+ let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
483
+ addEdit(indentValue.length * initialIndentLevel < 20 && options.insertSpaces ? cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel), formatTextStart, firstTokenStart);
484
+ }
485
+ while (firstToken !== 17) {
486
+ let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
487
+ let secondToken = scanNext();
488
+ let replaceContent = "";
489
+ let needsLineBreak = false;
490
+ while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
491
+ let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
492
+ addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);
493
+ firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
494
+ needsLineBreak = secondToken === 12;
495
+ replaceContent = needsLineBreak ? newLinesAndIndent() : "";
496
+ secondToken = scanNext();
497
+ }
498
+ if (secondToken === 2) {
499
+ if (firstToken !== 1) indentLevel--;
500
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) replaceContent = newLinesAndIndent();
501
+ else if (options.keepLines) replaceContent = cachedSpaces[1];
502
+ } else if (secondToken === 4) {
503
+ if (firstToken !== 3) indentLevel--;
504
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) replaceContent = newLinesAndIndent();
505
+ else if (options.keepLines) replaceContent = cachedSpaces[1];
506
+ } else {
507
+ switch (firstToken) {
508
+ case 3:
509
+ case 1:
510
+ indentLevel++;
511
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) replaceContent = newLinesAndIndent();
512
+ else replaceContent = cachedSpaces[1];
513
+ break;
514
+ case 5:
515
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) replaceContent = newLinesAndIndent();
516
+ else replaceContent = cachedSpaces[1];
517
+ break;
518
+ case 12:
519
+ replaceContent = newLinesAndIndent();
520
+ break;
521
+ case 13:
522
+ if (numberLineBreaks > 0) replaceContent = newLinesAndIndent();
523
+ else if (!needsLineBreak) replaceContent = cachedSpaces[1];
524
+ break;
525
+ case 6:
526
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
527
+ else if (!needsLineBreak) replaceContent = cachedSpaces[1];
528
+ break;
529
+ case 10:
530
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
531
+ else if (secondToken === 6 && !needsLineBreak) replaceContent = "";
532
+ break;
533
+ case 7:
534
+ case 8:
535
+ case 9:
536
+ case 11:
537
+ case 2:
538
+ case 4:
539
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
540
+ else if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) replaceContent = cachedSpaces[1];
541
+ else if (secondToken !== 5 && secondToken !== 17) hasError = true;
542
+ break;
543
+ case 16: hasError = true;
544
+ }
545
+ if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) replaceContent = newLinesAndIndent();
546
+ }
547
+ if (secondToken === 17) {
548
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
549
+ else replaceContent = options.insertFinalNewline ? eol : "";
550
+ }
551
+ const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
552
+ addEdit(replaceContent, firstTokenEnd, secondTokenStart);
553
+ firstToken = secondToken;
554
+ }
555
+ return editOperations;
556
+ }
557
+ function repeat(s, count) {
558
+ let result = "";
559
+ for (let i = 0; i < count; i++) result += s;
560
+ return result;
561
+ }
562
+ function computeIndentLevel(content, options) {
563
+ let i = 0;
564
+ let nChars = 0;
565
+ const tabSize = options.tabSize || 4;
566
+ while (i < content.length) {
567
+ let ch = content.charAt(i);
568
+ if (ch === cachedSpaces[1]) nChars++;
569
+ else if (ch === " ") nChars += tabSize;
570
+ else break;
571
+ i++;
572
+ }
573
+ return Math.floor(nChars / tabSize);
574
+ }
575
+ function getEOL(options, text) {
576
+ for (let i = 0; i < text.length; i++) {
577
+ const ch = text.charAt(i);
578
+ if (ch === "\r") {
579
+ if (i + 1 < text.length && text.charAt(i + 1) === "\n") return "\r\n";
580
+ return "\r";
581
+ } else if (ch === "\n") return "\n";
582
+ }
583
+ return options && options.eol || "\n";
584
+ }
585
+ function isEOL(text, offset) {
586
+ return "\r\n".indexOf(text.charAt(offset)) !== -1;
587
+ }
588
+ //#endregion
589
+ //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js
590
+ var ParseOptions;
591
+ (function(ParseOptions) {
592
+ ParseOptions.DEFAULT = { allowTrailingComma: false };
593
+ })(ParseOptions || (ParseOptions = {}));
594
+ /**
595
+ * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
596
+ * Therefore always check the errors list to find out if the input was valid.
597
+ */
598
+ function parse$1(text, errors = [], options = ParseOptions.DEFAULT) {
599
+ let currentProperty = null;
600
+ let currentParent = [];
601
+ const previousParents = [];
602
+ function onValue(value) {
603
+ if (Array.isArray(currentParent)) currentParent.push(value);
604
+ else if (currentProperty !== null) currentParent[currentProperty] = value;
605
+ }
606
+ visit(text, {
607
+ onObjectBegin: () => {
608
+ const object = {};
609
+ onValue(object);
610
+ previousParents.push(currentParent);
611
+ currentParent = object;
612
+ currentProperty = null;
613
+ },
614
+ onObjectProperty: (name) => {
615
+ currentProperty = name;
616
+ },
617
+ onObjectEnd: () => {
618
+ currentParent = previousParents.pop();
619
+ },
620
+ onArrayBegin: () => {
621
+ const array = [];
622
+ onValue(array);
623
+ previousParents.push(currentParent);
624
+ currentParent = array;
625
+ currentProperty = null;
626
+ },
627
+ onArrayEnd: () => {
628
+ currentParent = previousParents.pop();
629
+ },
630
+ onLiteralValue: onValue,
631
+ onError: (error, offset, length) => {
632
+ errors.push({
633
+ error,
634
+ offset,
635
+ length
636
+ });
637
+ }
638
+ }, options);
639
+ return currentParent[0];
640
+ }
641
+ /**
642
+ * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
643
+ */
644
+ function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
645
+ let currentParent = {
646
+ type: "array",
647
+ offset: -1,
648
+ length: -1,
649
+ children: [],
650
+ parent: void 0
651
+ };
652
+ function ensurePropertyComplete(endOffset) {
653
+ if (currentParent.type === "property") {
654
+ currentParent.length = endOffset - currentParent.offset;
655
+ currentParent = currentParent.parent;
656
+ }
657
+ }
658
+ function onValue(valueNode) {
659
+ currentParent.children.push(valueNode);
660
+ return valueNode;
661
+ }
662
+ visit(text, {
663
+ onObjectBegin: (offset) => {
664
+ currentParent = onValue({
665
+ type: "object",
666
+ offset,
667
+ length: -1,
668
+ parent: currentParent,
669
+ children: []
670
+ });
671
+ },
672
+ onObjectProperty: (name, offset, length) => {
673
+ currentParent = onValue({
674
+ type: "property",
675
+ offset,
676
+ length: -1,
677
+ parent: currentParent,
678
+ children: []
679
+ });
680
+ currentParent.children.push({
681
+ type: "string",
682
+ value: name,
683
+ offset,
684
+ length,
685
+ parent: currentParent
686
+ });
687
+ },
688
+ onObjectEnd: (offset, length) => {
689
+ ensurePropertyComplete(offset + length);
690
+ currentParent.length = offset + length - currentParent.offset;
691
+ currentParent = currentParent.parent;
692
+ ensurePropertyComplete(offset + length);
693
+ },
694
+ onArrayBegin: (offset, length) => {
695
+ currentParent = onValue({
696
+ type: "array",
697
+ offset,
698
+ length: -1,
699
+ parent: currentParent,
700
+ children: []
701
+ });
702
+ },
703
+ onArrayEnd: (offset, length) => {
704
+ currentParent.length = offset + length - currentParent.offset;
705
+ currentParent = currentParent.parent;
706
+ ensurePropertyComplete(offset + length);
707
+ },
708
+ onLiteralValue: (value, offset, length) => {
709
+ onValue({
710
+ type: getNodeType(value),
711
+ offset,
712
+ length,
713
+ parent: currentParent,
714
+ value
715
+ });
716
+ ensurePropertyComplete(offset + length);
717
+ },
718
+ onSeparator: (sep, offset, length) => {
719
+ if (currentParent.type === "property") {
720
+ if (sep === ":") currentParent.colonOffset = offset;
721
+ else if (sep === ",") ensurePropertyComplete(offset);
722
+ }
723
+ },
724
+ onError: (error, offset, length) => {
725
+ errors.push({
726
+ error,
727
+ offset,
728
+ length
729
+ });
730
+ }
731
+ }, options);
732
+ const result = currentParent.children[0];
733
+ if (result) delete result.parent;
734
+ return result;
735
+ }
736
+ /**
737
+ * Finds the node at the given path in a JSON DOM.
738
+ */
739
+ function findNodeAtLocation(root, path) {
740
+ if (!root) return;
741
+ let node = root;
742
+ for (let segment of path) if (typeof segment === "string") {
743
+ if (node.type !== "object" || !Array.isArray(node.children)) return;
744
+ let found = false;
745
+ for (const propertyNode of node.children) if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
746
+ node = propertyNode.children[1];
747
+ found = true;
748
+ break;
749
+ }
750
+ if (!found) return;
751
+ } else {
752
+ const index = segment;
753
+ if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) return;
754
+ node = node.children[index];
755
+ }
756
+ return node;
757
+ }
758
+ /**
759
+ * Parses the given text and invokes the visitor functions for each object, array and literal reached.
760
+ */
761
+ function visit(text, visitor, options = ParseOptions.DEFAULT) {
762
+ const _scanner = createScanner(text, false);
763
+ const _jsonPath = [];
764
+ let suppressedCallbacks = 0;
765
+ function toNoArgVisit(visitFunction) {
766
+ return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
767
+ }
768
+ function toOneArgVisit(visitFunction) {
769
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
770
+ }
771
+ function toOneArgVisitWithPath(visitFunction) {
772
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
773
+ }
774
+ function toBeginVisit(visitFunction) {
775
+ return visitFunction ? () => {
776
+ if (suppressedCallbacks > 0) suppressedCallbacks++;
777
+ else if (visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) === false) suppressedCallbacks = 1;
778
+ } : () => true;
779
+ }
780
+ function toEndVisit(visitFunction) {
781
+ return visitFunction ? () => {
782
+ if (suppressedCallbacks > 0) suppressedCallbacks--;
783
+ if (suppressedCallbacks === 0) visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());
784
+ } : () => true;
785
+ }
786
+ const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
787
+ const disallowComments = options && options.disallowComments;
788
+ const allowTrailingComma = options && options.allowTrailingComma;
789
+ function scanNext() {
790
+ while (true) {
791
+ const token = _scanner.scan();
792
+ switch (_scanner.getTokenError()) {
793
+ case 4:
794
+ handleError(14);
795
+ break;
796
+ case 5:
797
+ handleError(15);
798
+ break;
799
+ case 3:
800
+ handleError(13);
801
+ break;
802
+ case 1:
803
+ if (!disallowComments) handleError(11);
804
+ break;
805
+ case 2:
806
+ handleError(12);
807
+ break;
808
+ case 6: handleError(16);
809
+ }
810
+ switch (token) {
811
+ case 12:
812
+ case 13:
813
+ if (disallowComments) handleError(10);
814
+ else onComment();
815
+ break;
816
+ case 16:
817
+ handleError(1);
818
+ break;
819
+ case 15:
820
+ case 14: break;
821
+ default: return token;
822
+ }
823
+ }
824
+ }
825
+ function handleError(error, skipUntilAfter = [], skipUntil = []) {
826
+ onError(error);
827
+ if (skipUntilAfter.length + skipUntil.length > 0) {
828
+ let token = _scanner.getToken();
829
+ while (token !== 17) {
830
+ if (skipUntilAfter.indexOf(token) !== -1) {
831
+ scanNext();
832
+ break;
833
+ } else if (skipUntil.indexOf(token) !== -1) break;
834
+ token = scanNext();
835
+ }
836
+ }
837
+ }
838
+ function parseString(isValue) {
839
+ const value = _scanner.getTokenValue();
840
+ if (isValue) onLiteralValue(value);
841
+ else {
842
+ onObjectProperty(value);
843
+ _jsonPath.push(value);
844
+ }
845
+ scanNext();
846
+ return true;
847
+ }
848
+ function parseLiteral() {
849
+ switch (_scanner.getToken()) {
850
+ case 11:
851
+ const tokenValue = _scanner.getTokenValue();
852
+ let value = Number(tokenValue);
853
+ if (isNaN(value)) {
854
+ handleError(2);
855
+ value = 0;
856
+ }
857
+ onLiteralValue(value);
858
+ break;
859
+ case 7:
860
+ onLiteralValue(null);
861
+ break;
862
+ case 8:
863
+ onLiteralValue(true);
864
+ break;
865
+ case 9:
866
+ onLiteralValue(false);
867
+ break;
868
+ default: return false;
869
+ }
870
+ scanNext();
871
+ return true;
872
+ }
873
+ function parseProperty() {
874
+ if (_scanner.getToken() !== 10) {
875
+ handleError(3, [], [2, 5]);
876
+ return false;
877
+ }
878
+ parseString(false);
879
+ if (_scanner.getToken() === 6) {
880
+ onSeparator(":");
881
+ scanNext();
882
+ if (!parseValue()) handleError(4, [], [2, 5]);
883
+ } else handleError(5, [], [2, 5]);
884
+ _jsonPath.pop();
885
+ return true;
886
+ }
887
+ function parseObject() {
888
+ onObjectBegin();
889
+ scanNext();
890
+ let needsComma = false;
891
+ while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
892
+ if (_scanner.getToken() === 5) {
893
+ if (!needsComma) handleError(4, [], []);
894
+ onSeparator(",");
895
+ scanNext();
896
+ if (_scanner.getToken() === 2 && allowTrailingComma) break;
897
+ } else if (needsComma) handleError(6, [], []);
898
+ if (!parseProperty()) handleError(4, [], [2, 5]);
899
+ needsComma = true;
900
+ }
901
+ onObjectEnd();
902
+ if (_scanner.getToken() !== 2) handleError(7, [2], []);
903
+ else scanNext();
904
+ return true;
905
+ }
906
+ function parseArray() {
907
+ onArrayBegin();
908
+ scanNext();
909
+ let isFirstElement = true;
910
+ let needsComma = false;
911
+ while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
912
+ if (_scanner.getToken() === 5) {
913
+ if (!needsComma) handleError(4, [], []);
914
+ onSeparator(",");
915
+ scanNext();
916
+ if (_scanner.getToken() === 4 && allowTrailingComma) break;
917
+ } else if (needsComma) handleError(6, [], []);
918
+ if (isFirstElement) {
919
+ _jsonPath.push(0);
920
+ isFirstElement = false;
921
+ } else _jsonPath[_jsonPath.length - 1]++;
922
+ if (!parseValue()) handleError(4, [], [4, 5]);
923
+ needsComma = true;
924
+ }
925
+ onArrayEnd();
926
+ if (!isFirstElement) _jsonPath.pop();
927
+ if (_scanner.getToken() !== 4) handleError(8, [4], []);
928
+ else scanNext();
929
+ return true;
930
+ }
931
+ function parseValue() {
932
+ switch (_scanner.getToken()) {
933
+ case 3: return parseArray();
934
+ case 1: return parseObject();
935
+ case 10: return parseString(true);
936
+ default: return parseLiteral();
937
+ }
938
+ }
939
+ scanNext();
940
+ if (_scanner.getToken() === 17) {
941
+ if (options.allowEmptyContent) return true;
942
+ handleError(4, [], []);
943
+ return false;
944
+ }
945
+ if (!parseValue()) {
946
+ handleError(4, [], []);
947
+ return false;
948
+ }
949
+ if (_scanner.getToken() !== 17) handleError(9, [], []);
950
+ return true;
951
+ }
952
+ function getNodeType(value) {
953
+ switch (typeof value) {
954
+ case "boolean": return "boolean";
955
+ case "number": return "number";
956
+ case "string": return "string";
957
+ case "object":
958
+ if (!value) return "null";
959
+ else if (Array.isArray(value)) return "array";
960
+ return "object";
961
+ default: return "null";
962
+ }
963
+ }
964
+ //#endregion
965
+ //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js
966
+ function setProperty(text, originalPath, value, options) {
967
+ const path = originalPath.slice();
968
+ const root = parseTree(text, []);
969
+ let parent = void 0;
970
+ let lastSegment = void 0;
971
+ while (path.length > 0) {
972
+ lastSegment = path.pop();
973
+ parent = findNodeAtLocation(root, path);
974
+ if (parent === void 0 && value !== void 0) {
975
+ if (typeof lastSegment === "string") value = { [lastSegment]: value };
976
+ else value = [value];
977
+ } else break;
978
+ }
979
+ if (!parent) {
980
+ if (value === void 0) throw new Error("Can not delete in empty document");
981
+ return withFormatting(text, {
982
+ offset: root ? root.offset : 0,
983
+ length: root ? root.length : 0,
984
+ content: JSON.stringify(value)
985
+ }, options);
986
+ } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
987
+ const existing = findNodeAtLocation(parent, [lastSegment]);
988
+ if (existing !== void 0) {
989
+ if (value === void 0) {
990
+ if (!existing.parent) throw new Error("Malformed AST");
991
+ const propertyIndex = parent.children.indexOf(existing.parent);
992
+ let removeBegin;
993
+ let removeEnd = existing.parent.offset + existing.parent.length;
994
+ if (propertyIndex > 0) {
995
+ let previous = parent.children[propertyIndex - 1];
996
+ removeBegin = previous.offset + previous.length;
997
+ } else {
998
+ removeBegin = parent.offset + 1;
999
+ if (parent.children.length > 1) removeEnd = parent.children[1].offset;
1000
+ }
1001
+ return withFormatting(text, {
1002
+ offset: removeBegin,
1003
+ length: removeEnd - removeBegin,
1004
+ content: ""
1005
+ }, options);
1006
+ } else return withFormatting(text, {
1007
+ offset: existing.offset,
1008
+ length: existing.length,
1009
+ content: JSON.stringify(value)
1010
+ }, options);
1011
+ } else {
1012
+ if (value === void 0) return [];
1013
+ const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
1014
+ const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p) => p.children[0].value)) : parent.children.length;
1015
+ let edit;
1016
+ if (index > 0) {
1017
+ let previous = parent.children[index - 1];
1018
+ edit = {
1019
+ offset: previous.offset + previous.length,
1020
+ length: 0,
1021
+ content: "," + newProperty
1022
+ };
1023
+ } else if (parent.children.length === 0) edit = {
1024
+ offset: parent.offset + 1,
1025
+ length: 0,
1026
+ content: newProperty
1027
+ };
1028
+ else edit = {
1029
+ offset: parent.offset + 1,
1030
+ length: 0,
1031
+ content: newProperty + ","
1032
+ };
1033
+ return withFormatting(text, edit, options);
1034
+ }
1035
+ } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
1036
+ const insertIndex = lastSegment;
1037
+ if (insertIndex === -1) {
1038
+ const newProperty = `${JSON.stringify(value)}`;
1039
+ let edit;
1040
+ if (parent.children.length === 0) edit = {
1041
+ offset: parent.offset + 1,
1042
+ length: 0,
1043
+ content: newProperty
1044
+ };
1045
+ else {
1046
+ const previous = parent.children[parent.children.length - 1];
1047
+ edit = {
1048
+ offset: previous.offset + previous.length,
1049
+ length: 0,
1050
+ content: "," + newProperty
1051
+ };
1052
+ }
1053
+ return withFormatting(text, edit, options);
1054
+ } else if (value === void 0 && parent.children.length >= 0) {
1055
+ const removalIndex = lastSegment;
1056
+ const toRemove = parent.children[removalIndex];
1057
+ let edit;
1058
+ if (parent.children.length === 1) edit = {
1059
+ offset: parent.offset + 1,
1060
+ length: parent.length - 2,
1061
+ content: ""
1062
+ };
1063
+ else if (parent.children.length - 1 === removalIndex) {
1064
+ let previous = parent.children[removalIndex - 1];
1065
+ let offset = previous.offset + previous.length;
1066
+ edit = {
1067
+ offset,
1068
+ length: parent.offset + parent.length - 2 - offset,
1069
+ content: ""
1070
+ };
1071
+ } else edit = {
1072
+ offset: toRemove.offset,
1073
+ length: parent.children[removalIndex + 1].offset - toRemove.offset,
1074
+ content: ""
1075
+ };
1076
+ return withFormatting(text, edit, options);
1077
+ } else if (value !== void 0) {
1078
+ let edit;
1079
+ const newProperty = `${JSON.stringify(value)}`;
1080
+ if (!options.isArrayInsertion && parent.children.length > lastSegment) {
1081
+ const toModify = parent.children[lastSegment];
1082
+ edit = {
1083
+ offset: toModify.offset,
1084
+ length: toModify.length,
1085
+ content: newProperty
1086
+ };
1087
+ } else if (parent.children.length === 0 || lastSegment === 0) edit = {
1088
+ offset: parent.offset + 1,
1089
+ length: 0,
1090
+ content: parent.children.length === 0 ? newProperty : newProperty + ","
1091
+ };
1092
+ else {
1093
+ const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
1094
+ const previous = parent.children[index - 1];
1095
+ edit = {
1096
+ offset: previous.offset + previous.length,
1097
+ length: 0,
1098
+ content: "," + newProperty
1099
+ };
1100
+ }
1101
+ return withFormatting(text, edit, options);
1102
+ } else throw new Error(`Can not ${value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
1103
+ } else throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
1104
+ }
1105
+ function withFormatting(text, edit, options) {
1106
+ if (!options.formattingOptions) return [edit];
1107
+ let newText = applyEdit(text, edit);
1108
+ let begin = edit.offset;
1109
+ let end = edit.offset + edit.content.length;
1110
+ if (edit.length === 0 || edit.content.length === 0) {
1111
+ while (begin > 0 && !isEOL(newText, begin - 1)) begin--;
1112
+ while (end < newText.length && !isEOL(newText, end)) end++;
1113
+ }
1114
+ const edits = format(newText, {
1115
+ offset: begin,
1116
+ length: end - begin
1117
+ }, {
1118
+ ...options.formattingOptions,
1119
+ keepLines: false
1120
+ });
1121
+ for (let i = edits.length - 1; i >= 0; i--) {
1122
+ const edit = edits[i];
1123
+ newText = applyEdit(newText, edit);
1124
+ begin = Math.min(begin, edit.offset);
1125
+ end = Math.max(end, edit.offset + edit.length);
1126
+ end += edit.content.length - edit.length;
1127
+ }
1128
+ const editLength = text.length - (newText.length - end) - begin;
1129
+ return [{
1130
+ offset: begin,
1131
+ length: editLength,
1132
+ content: newText.substring(begin, end)
1133
+ }];
1134
+ }
1135
+ function applyEdit(text, edit) {
1136
+ return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
1137
+ }
1138
+ //#endregion
1139
+ //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js
1140
+ var ScanError;
1141
+ (function(ScanError) {
1142
+ ScanError[ScanError["None"] = 0] = "None";
1143
+ ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
1144
+ ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
1145
+ ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
1146
+ ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode";
1147
+ ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
1148
+ ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter";
1149
+ })(ScanError || (ScanError = {}));
1150
+ var SyntaxKind;
1151
+ (function(SyntaxKind) {
1152
+ SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken";
1153
+ SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken";
1154
+ SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken";
1155
+ SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken";
1156
+ SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken";
1157
+ SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken";
1158
+ SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword";
1159
+ SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword";
1160
+ SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword";
1161
+ SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
1162
+ SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral";
1163
+ SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia";
1164
+ SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
1165
+ SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia";
1166
+ SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia";
1167
+ SyntaxKind[SyntaxKind["Unknown"] = 16] = "Unknown";
1168
+ SyntaxKind[SyntaxKind["EOF"] = 17] = "EOF";
1169
+ })(SyntaxKind || (SyntaxKind = {}));
1170
+ /**
1171
+ * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
1172
+ * Therefore, always check the errors list to find out if the input was valid.
1173
+ */
1174
+ const parse = parse$1;
1175
+ var ParseErrorCode;
1176
+ (function(ParseErrorCode) {
1177
+ ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 1] = "InvalidSymbol";
1178
+ ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
1179
+ ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 3] = "PropertyNameExpected";
1180
+ ParseErrorCode[ParseErrorCode["ValueExpected"] = 4] = "ValueExpected";
1181
+ ParseErrorCode[ParseErrorCode["ColonExpected"] = 5] = "ColonExpected";
1182
+ ParseErrorCode[ParseErrorCode["CommaExpected"] = 6] = "CommaExpected";
1183
+ ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 7] = "CloseBraceExpected";
1184
+ ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 8] = "CloseBracketExpected";
1185
+ ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 9] = "EndOfFileExpected";
1186
+ ParseErrorCode[ParseErrorCode["InvalidCommentToken"] = 10] = "InvalidCommentToken";
1187
+ ParseErrorCode[ParseErrorCode["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
1188
+ ParseErrorCode[ParseErrorCode["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
1189
+ ParseErrorCode[ParseErrorCode["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
1190
+ ParseErrorCode[ParseErrorCode["InvalidUnicode"] = 14] = "InvalidUnicode";
1191
+ ParseErrorCode[ParseErrorCode["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
1192
+ ParseErrorCode[ParseErrorCode["InvalidCharacter"] = 16] = "InvalidCharacter";
1193
+ })(ParseErrorCode || (ParseErrorCode = {}));
1194
+ function printParseErrorCode(code) {
1195
+ switch (code) {
1196
+ case 1: return "InvalidSymbol";
1197
+ case 2: return "InvalidNumberFormat";
1198
+ case 3: return "PropertyNameExpected";
1199
+ case 4: return "ValueExpected";
1200
+ case 5: return "ColonExpected";
1201
+ case 6: return "CommaExpected";
1202
+ case 7: return "CloseBraceExpected";
1203
+ case 8: return "CloseBracketExpected";
1204
+ case 9: return "EndOfFileExpected";
1205
+ case 10: return "InvalidCommentToken";
1206
+ case 11: return "UnexpectedEndOfComment";
1207
+ case 12: return "UnexpectedEndOfString";
1208
+ case 13: return "UnexpectedEndOfNumber";
1209
+ case 14: return "InvalidUnicode";
1210
+ case 15: return "InvalidEscapeCharacter";
1211
+ case 16: return "InvalidCharacter";
1212
+ }
1213
+ return "<unknown ParseErrorCode>";
1214
+ }
1215
+ /**
1216
+ * Computes the edit operations needed to modify a value in the JSON document.
1217
+ *
1218
+ * @param documentText The input text
1219
+ * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
1220
+ * If the path points to an non-existing property or item, it will be created.
1221
+ * @param value The new value for the specified property or item. If the value is undefined,
1222
+ * the property or item will be removed.
1223
+ * @param options Options
1224
+ * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.
1225
+ * To apply the edit operations to the input, use {@linkcode applyEdits}.
1226
+ */
1227
+ function modify(text, path, value, options) {
1228
+ return setProperty(text, path, value, options);
1229
+ }
1230
+ /**
1231
+ * Applies edits to an input string.
1232
+ * @param text The input text
1233
+ * @param edits Edit operations following the format described in {@linkcode EditResult}.
1234
+ * @returns The text with the applied edits.
1235
+ * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.
1236
+ */
1237
+ function applyEdits(text, edits) {
1238
+ let sortedEdits = edits.slice(0).sort((a, b) => {
1239
+ const diff = a.offset - b.offset;
1240
+ if (diff === 0) return a.length - b.length;
1241
+ return diff;
1242
+ });
1243
+ let lastModifiedOffset = text.length;
1244
+ for (let i = sortedEdits.length - 1; i >= 0; i--) {
1245
+ let e = sortedEdits[i];
1246
+ if (e.offset + e.length <= lastModifiedOffset) text = applyEdit(text, e);
1247
+ else throw new Error("Overlapping edit");
1248
+ lastModifiedOffset = e.offset;
1249
+ }
1250
+ return text;
1251
+ }
1252
+ //#endregion
1253
+ //#region src/deployment.ts
1254
+ /** What a directory holds: a deployment of either kind, nothing yet (`isEmpty`), or something else. */
1255
+ function deploymentKind(dir) {
1256
+ if (isEmpty(dir)) return "empty";
1257
+ if (existsSync(join(dir, "app", "wrangler.jsonc")) && existsSync(join(dir, "vault", "wrangler.jsonc"))) return "workers";
1258
+ if (existsSync(join(dir, "src", "vault.ts")) && existsSync(join(dir, "vault.env.example"))) return "node";
1259
+ return "other";
1260
+ }
1261
+ /** Install a new deployment's packages, as its README says: pnpm, through corepack when pnpm itself is missing. */
1262
+ function install(dir) {
1263
+ const attempt = (command, args) => new Promise((resolve) => {
1264
+ const child = spawn(command, args, {
1265
+ cwd: dir,
1266
+ stdio: [
1267
+ "ignore",
1268
+ "pipe",
1269
+ "pipe"
1270
+ ],
1271
+ env: {
1272
+ ...process.env,
1273
+ COREPACK_ENABLE_DOWNLOAD_PROMPT: "0"
1274
+ }
1275
+ });
1276
+ let output = "";
1277
+ child.stdout.setEncoding("utf8").on("data", (chunk) => output += chunk);
1278
+ child.stderr.setEncoding("utf8").on("data", (chunk) => output += chunk);
1279
+ child.on("error", () => resolve(null));
1280
+ child.on("close", (code) => resolve({
1281
+ code,
1282
+ output
1283
+ }));
1284
+ });
1285
+ return (async () => {
1286
+ const ran = await attempt("pnpm", ["install"]) ?? await attempt("corepack", ["pnpm", "install"]);
1287
+ if (ran === null) throw new Error("pnpm is not installed: corepack enable, or npm install -g pnpm, then run setup again");
1288
+ if (ran.code !== 0) {
1289
+ const held = heldBack(ran.output);
1290
+ throw held.length > 0 ? new HeldBack(held, installFailure(ran.output)) : new Error(installFailure(ran.output));
1291
+ }
1292
+ })();
1293
+ }
1294
+ /** A deployment's `@coffre/*` pins, as its package.json has them. */
1295
+ function coffrePins(dir) {
1296
+ const manifest = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
1297
+ const pins = {};
1298
+ for (const field of ["dependencies", "devDependencies"]) for (const [name, version] of Object.entries(manifest[field] ?? {})) if (name.startsWith("@coffre/")) pins[name] = version;
1299
+ return pins;
1300
+ }
1301
+ /**
1302
+ * Every `@coffre/*` pin in `dir`'s package.json, moved to `version`; the
1303
+ * rest left as it is. What `pnpm bump` does to the examples, which `coffre
1304
+ * init` copies.
1305
+ */
1306
+ function bumpPins(dir, version) {
1307
+ const path = join(dir, "package.json");
1308
+ const manifest = JSON.parse(readFileSync(path, "utf8"));
1309
+ for (const field of ["dependencies", "devDependencies"]) for (const name of Object.keys(manifest[field] ?? {})) if (name.startsWith("@coffre/")) manifest[field][name] = version;
1310
+ writeFileSync(path, `${JSON.stringify(manifest, null, 2)}\n`);
1311
+ }
1312
+ /** pnpm install refused packages younger than the deployment's minimumReleaseAge. */
1313
+ var HeldBack = class extends Error {
1314
+ held;
1315
+ constructor(held, message) {
1316
+ super(message);
1317
+ this.held = held;
1318
+ }
1319
+ };
1320
+ /** The packages pnpm held back, as its error names them. */
1321
+ function heldBack(output) {
1322
+ if (!output.includes("MINIMUM_RELEASE_AGE")) return [];
1323
+ return [...output.matchAll(/^\s*(\S+@\d\S*) was published at (\S+?),?\s/gm)].map((match) => ({
1324
+ spec: match[1],
1325
+ publishedAt: new Date(match[2])
1326
+ }));
1327
+ }
1328
+ /** The deployment's minimumReleaseAge, in minutes, as its pnpm-workspace.yaml sets it; pnpm's own default, none, without one. */
1329
+ function minimumReleaseAge(dir) {
1330
+ const path = join(dir, "pnpm-workspace.yaml");
1331
+ const match = existsSync(path) ? /^minimumReleaseAge:\s*(\d+)/m.exec(readFileSync(path, "utf8")) : null;
1332
+ return match === null ? 0 : Number(match[1]);
1333
+ }
1334
+ /** How every temporary exclusion `coffre update` writes ends: with when it lapses. */
1335
+ const EXCLUDED = /^\s*- '([^']+)' # coffre update: until (\S+)/;
1336
+ /**
1337
+ * Exclude `held` from minimumReleaseAge, each until it clears, named in the
1338
+ * deployment's pnpm-workspace.yaml with that date: never silently, and
1339
+ * removed by `removeCleared` once the date has passed.
1340
+ */
1341
+ function excludeUntil(dir, held, reason) {
1342
+ const path = join(dir, "pnpm-workspace.yaml");
1343
+ const lines = (existsSync(path) ? readFileSync(path, "utf8") : "").replace(/\n*$/, "").split("\n");
1344
+ const entries = held.map(({ spec, clears }) => ` - '${spec}' # coffre update: until ${clears.toISOString()}, ${reason}`);
1345
+ const key = lines.findIndex((line) => /^minimumReleaseAgeExclude:/.test(line));
1346
+ if (key === -1) lines.push("minimumReleaseAgeExclude:", ...entries);
1347
+ else {
1348
+ let end = key + 1;
1349
+ while (end < lines.length && /^\s+(-|#)/.test(lines[end])) end++;
1350
+ lines.splice(end, 0, ...entries);
1351
+ }
1352
+ writeFileSync(path, `${lines.join("\n")}\n`);
1353
+ }
1354
+ /** Remove the exclusions `excludeUntil` wrote whose date has passed; the packages they named. */
1355
+ function removeCleared(dir, now) {
1356
+ const path = join(dir, "pnpm-workspace.yaml");
1357
+ if (!existsSync(path)) return [];
1358
+ const removed = [];
1359
+ const kept = readFileSync(path, "utf8").split("\n").filter((line) => {
1360
+ const match = EXCLUDED.exec(line);
1361
+ if (match === null || new Date(match[2].replace(/,$/, "")) > now) return true;
1362
+ removed.push(match[1]);
1363
+ return false;
1364
+ });
1365
+ if (removed.length > 0) writeFileSync(path, kept.join("\n"));
1366
+ return removed;
1367
+ }
1368
+ /**
1369
+ * The pnpm a deployment runs, `packageManager` in its package.json, set to
1370
+ * `wanted`, coffre's: then a laptop, CI and Workers Builds all install with
1371
+ * one pnpm, which holds minimumReleaseAge alike. The value it had, when it
1372
+ * changed; null when it was right already.
1373
+ */
1374
+ function pinPackageManager(dir, wanted) {
1375
+ const path = join(dir, "package.json");
1376
+ const manifest = JSON.parse(readFileSync(path, "utf8"));
1377
+ if (manifest.packageManager === wanted) return null;
1378
+ const was = manifest.packageManager;
1379
+ let next;
1380
+ if (was !== void 0) next = {
1381
+ ...manifest,
1382
+ packageManager: wanted
1383
+ };
1384
+ else {
1385
+ const after = "private" in manifest ? "private" : "name";
1386
+ next = {};
1387
+ for (const [field, value] of Object.entries(manifest)) {
1388
+ next[field] = value;
1389
+ if (field === after) next.packageManager = wanted;
1390
+ }
1391
+ next.packageManager ??= wanted;
1392
+ }
1393
+ writeFileSync(path, `${JSON.stringify(next, null, 2)}\n`);
1394
+ return was;
1395
+ }
1396
+ /**
1397
+ * Why pnpm install failed, in a sentence. The deployment's minimumReleaseAge
1398
+ * holds back every package published within the week, coffre's own
1399
+ * excepted, and that includes what coffre's packages depend on: say which,
1400
+ * and what to do, rather than pnpm's last lines.
1401
+ */
1402
+ function installFailure(output) {
1403
+ if (output.includes("MINIMUM_RELEASE_AGE")) {
1404
+ const held = [...output.matchAll(/^\s*(\S+@\d\S*) was published at/gm)].map((match) => match[1]);
1405
+ return `pnpm held back ${held.length === 0 ? "packages" : held.join(", ")}: published within this deployment's minimumReleaseAge (pnpm-workspace.yaml), a week. Install again once they are a week old, or add them to minimumReleaseAgeExclude if you trust them`;
1406
+ }
1407
+ return `pnpm install failed: ${output.trim().split("\n").slice(-3).join(" ")}`;
1408
+ }
1409
+ /** A value the examples ship, standing for the operator's own. */
1410
+ function placeholder(value) {
1411
+ return value === void 0 || value === null || value === "" || /^replace-with-|example\.com\b/.test(value);
1412
+ }
1413
+ function readWorker(dir, path) {
1414
+ const errors = [];
1415
+ const config = parse(readFileSync(join(dir, path), "utf8"), errors, { allowTrailingComma: true });
1416
+ if (errors.length > 0) throw new Error(`${path} is not valid: ${printParseErrorCode(errors[0].error)} at offset ${errors[0].offset}`);
1417
+ if (typeof config.name !== "string") throw new Error(`${path} names no Worker`);
1418
+ const route = config.routes?.[0];
1419
+ return {
1420
+ path,
1421
+ name: config.name,
1422
+ accountId: config.account_id ?? null,
1423
+ vars: Object.fromEntries(Object.entries(config.vars ?? {}).filter((entry) => typeof entry[1] === "string")),
1424
+ hyperdrive: placeholder(config.hyperdrive?.[0]?.id) ? null : config.hyperdrive[0].id,
1425
+ route: typeof route === "string" ? route : route?.pattern ?? null
1426
+ };
1427
+ }
1428
+ /** A value as the examples write one on a single line: `[{ "pattern": "…", "custom_domain": true }]`. */
1429
+ function inline(value) {
1430
+ return JSON.stringify(value, null, 1).replace(/\n\s*/g, " ").replace(/\[ /g, "[").replace(/ \]/g, "]");
1431
+ }
1432
+ /** Make `changes` to the file at `path`, leaving the rest as it is, comments and all. Says which changed anything. */
1433
+ function editWorker(dir, path, changes) {
1434
+ const MARK = "\0coffre\0";
1435
+ let text = readFileSync(join(dir, path), "utf8");
1436
+ const changed = changes.map((change) => {
1437
+ const edits = modify(text, change.path, MARK, {
1438
+ formattingOptions: {
1439
+ insertSpaces: true,
1440
+ tabSize: 2,
1441
+ eol: "\n"
1442
+ },
1443
+ getInsertionIndex: change.after === void 0 ? void 0 : (properties) => properties.indexOf(change.after) + 1
1444
+ });
1445
+ const before = text;
1446
+ text = applyEdits(text, edits.map((edit) => ({
1447
+ ...edit,
1448
+ content: edit.content.replace(JSON.stringify(MARK), inline(change.value))
1449
+ })));
1450
+ return text !== before;
1451
+ });
1452
+ writeFileSync(join(dir, path), text);
1453
+ return changed;
1454
+ }
1455
+ //#endregion
1456
+ export { editWorker as a, minimumReleaseAge as c, readWorker as d, removeCleared as f, deploymentKind as i, pinPackageManager as l, bumpPins as n, excludeUntil as o, coffrePins as r, install as s, HeldBack as t, placeholder as u };