@vite-hub/cli 0.7.0 → 0.8.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.
@@ -0,0 +1,2813 @@
1
+ import { C as invariant, d as cliErrorDiagnostics } from "./provision-9QsGgeiq.js";
2
+ import { c as __exportAll, o as writeSetupError, r as setupExitCodes, s as writeSetupJson } from "./envelope-BJQ7xPyX.js";
3
+ import { createRequire } from "node:module";
4
+ import { existsSync, realpathSync } from "node:fs";
5
+ import process$1 from "node:process";
6
+ import { dirname, join, resolve } from "pathe";
7
+ import { chmod, mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
8
+ import { delimiter, dirname as dirname$1, join as join$1, sep } from "node:path";
9
+ import { homedir, hostname } from "node:os";
10
+ import { parse as parse$1 } from "@babel/parser";
11
+ import { parseArgs } from "node:util";
12
+ import { parseDocument } from "yaml";
13
+ import { parse as parse$2 } from "rc9";
14
+ import { Range, minVersion, subset, validRange } from "semver";
15
+ // ../internal/dist/ast.js
16
+ /** Parses JavaScript or TypeScript. `jsx` adds JSX syntax. */
17
+ function parseProgram(code, options = {}) {
18
+ const plugins = [];
19
+ if (options.typescript !== false) plugins.push("typescript");
20
+ if (options.jsx) plugins.push("jsx");
21
+ return parse$1(code, {
22
+ sourceType: "module",
23
+ plugins,
24
+ allowAwaitOutsideFunction: true,
25
+ allowReturnOutsideFunction: true
26
+ });
27
+ }
28
+ function isNode(value) {
29
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string" && "start" in value && typeof value.start === "number";
30
+ }
31
+ const skippedKeys = /* @__PURE__ */ new Set([
32
+ "leadingComments",
33
+ "trailingComments",
34
+ "innerComments",
35
+ "loc",
36
+ "extra"
37
+ ]);
38
+ /** Visits every node depth first. `ancestors` ends with the direct parent. */
39
+ function walk(root, visit) {
40
+ const ancestors = [];
41
+ const visitNode = (node) => {
42
+ visit(node, ancestors);
43
+ ancestors.push(node);
44
+ for (const [key, child] of Object.entries(node)) {
45
+ if (skippedKeys.has(key)) continue;
46
+ const value = child;
47
+ if (Array.isArray(value)) {
48
+ for (const item of value) if (isNode(item)) visitNode(item);
49
+ } else if (isNode(value)) visitNode(value);
50
+ }
51
+ ancestors.pop();
52
+ };
53
+ visitNode(root);
54
+ }
55
+ function start(node) {
56
+ invariant(typeof node.start === "number", `the parser gives every node a start position (${node.type})`);
57
+ return node.start;
58
+ }
59
+ function end(node) {
60
+ invariant(typeof node.end === "number", `the parser gives every node an end position (${node.type})`);
61
+ return node.end;
62
+ }
63
+ function line(node) {
64
+ return node.loc?.start.line ?? 1;
65
+ }
66
+ /** The static name of a property key, or `undefined` for a computed key. */
67
+ function keyName(key, computed = false) {
68
+ if (key.type === "Identifier" && !computed) return key.name;
69
+ if (key.type === "StringLiteral") return key.value;
70
+ }
71
+ /** The range that removes a list item: the node, its leading comments, one separator comma, and its line when it stands alone. */
72
+ function listItemRemoval(code, node) {
73
+ let from = Math.min(start(node), ...(node.leadingComments ?? []).map((comment) => comment.start ?? start(node)));
74
+ let to = end(node);
75
+ let cursor = to;
76
+ while (cursor < code.length && /[ \t]/.test(code[cursor] ?? "")) cursor++;
77
+ const trailingComma = code[cursor] === ",";
78
+ if (trailingComma) to = cursor + 1;
79
+ const lineStart = code.lastIndexOf("\n", from - 1) + 1;
80
+ const ownLineBefore = /^[ \t]*$/.test(code.slice(lineStart, from));
81
+ let lineEnd = to;
82
+ while (lineEnd < code.length && /[ \t]/.test(code[lineEnd] ?? "")) lineEnd++;
83
+ const lineBreak = code[lineEnd] === "\r" && code[lineEnd + 1] === "\n" ? 2 : code[lineEnd] === "\n" ? 1 : 0;
84
+ const ownLineAfter = lineBreak > 0 || lineEnd === code.length;
85
+ if (ownLineBefore && ownLineAfter) return [lineStart, Math.min(lineEnd + Math.max(lineBreak, 1), code.length)];
86
+ if (!trailingComma) {
87
+ let before = from;
88
+ while (before > 0 && /\s/.test(code[before - 1] ?? "")) before--;
89
+ if (code[before - 1] === ",") from = before - 1;
90
+ } else while (to < code.length && /[ \t]/.test(code[to] ?? "")) to++;
91
+ return [from, to];
92
+ }
93
+ /** Column indentation of the line that holds `position`. */
94
+ function indentAt(code, position) {
95
+ const lineStart = code.lastIndexOf("\n", position - 1) + 1;
96
+ return /^[ \t]*/.exec(code.slice(lineStart))?.[0] ?? "";
97
+ }
98
+ function detectStyle(code, program) {
99
+ let quote;
100
+ walk(program, (node) => {
101
+ if (!quote && node.type === "StringLiteral") quote = code[start(node)] === "'" ? "'" : "\"";
102
+ });
103
+ const statements = program.program.body;
104
+ const semicolons = statements.length ? statements.some((statement) => code[end(statement) - 1] === ";") : false;
105
+ const indentLine = /^([ \t]+)\S/m.exec(code);
106
+ return {
107
+ quote: quote ?? "\"",
108
+ semicolons,
109
+ indent: indentLine?.[1]?.startsWith(" ") ? " " : indentLine?.[1] ?? " "
110
+ };
111
+ }
112
+ function quoteString(value, style) {
113
+ const json = JSON.stringify(value);
114
+ if (style.quote === "\"") return json;
115
+ return `'${json.slice(1, -1).replaceAll("\\\"", "\"").replaceAll("'", "\\'")}'`;
116
+ }
117
+ // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.6.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
118
+ var comma = ",".charCodeAt(0);
119
+ var semicolon = ";".charCodeAt(0);
120
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
121
+ var intToChar$1 = /* @__PURE__ */ new Uint8Array(64);
122
+ var charToInt = /* @__PURE__ */ new Uint8Array(128);
123
+ for (let i = 0; i < chars.length; i++) {
124
+ const c = chars.charCodeAt(i);
125
+ intToChar$1[i] = c;
126
+ charToInt[c] = i;
127
+ }
128
+ function encodeInteger(builder, num) {
129
+ do {
130
+ let clamped = num & 31;
131
+ num >>>= 5;
132
+ if (num > 0) clamped |= 32;
133
+ builder.write(intToChar$1[clamped]);
134
+ } while (num > 0);
135
+ }
136
+ function encodeSign(num) {
137
+ return num < 0 ? -num << 1 | 1 : num << 1;
138
+ }
139
+ var bufLength = 16384;
140
+ var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
141
+ return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
142
+ } } : { decode(buf) {
143
+ let out = "";
144
+ for (let i = 0; i < buf.length; i++) out += String.fromCharCode(buf[i]);
145
+ return out;
146
+ } };
147
+ var StringWriter = class {
148
+ constructor() {
149
+ this.pos = 0;
150
+ this.out = "";
151
+ this.buffer = new Uint8Array(bufLength);
152
+ }
153
+ write(v) {
154
+ const { buffer } = this;
155
+ buffer[this.pos++] = v;
156
+ if (this.pos === bufLength) {
157
+ this.out += td.decode(buffer);
158
+ this.pos = 0;
159
+ }
160
+ }
161
+ flush() {
162
+ const { buffer, out, pos } = this;
163
+ return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
164
+ }
165
+ };
166
+ function encodeRangeMappings(decoded) {
167
+ if (decoded.length === 0) return "";
168
+ const writer = new StringWriter();
169
+ for (let i = 0; i < decoded.length; i++) {
170
+ const indices = decoded[i];
171
+ if (i > 0) writer.write(semicolon);
172
+ let index = 0;
173
+ for (let j = 0; j < indices.length; j++) {
174
+ const offset = indices[j];
175
+ encodeInteger(writer, offset - index);
176
+ index = offset;
177
+ }
178
+ }
179
+ return writer.flush();
180
+ }
181
+ function encode(decoded) {
182
+ const writer = new StringWriter();
183
+ let sourcesIndex = 0;
184
+ let sourceLine = 0;
185
+ let sourceColumn = 0;
186
+ let namesIndex = 0;
187
+ for (let i = 0; i < decoded.length; i++) {
188
+ const line = decoded[i];
189
+ if (i > 0) writer.write(semicolon);
190
+ if (line.length === 0) continue;
191
+ let genColumn = 0;
192
+ for (let j = 0; j < line.length; j++) {
193
+ const segment = line[j];
194
+ if (j > 0) writer.write(comma);
195
+ encodeInteger(writer, encodeSign(segment[0] - genColumn));
196
+ genColumn = segment[0];
197
+ if (segment.length === 1) continue;
198
+ encodeInteger(writer, encodeSign(segment[1] - sourcesIndex));
199
+ encodeInteger(writer, encodeSign(segment[2] - sourceLine));
200
+ encodeInteger(writer, encodeSign(segment[3] - sourceColumn));
201
+ sourcesIndex = segment[1];
202
+ sourceLine = segment[2];
203
+ sourceColumn = segment[3];
204
+ if (segment.length === 4) continue;
205
+ encodeInteger(writer, encodeSign(segment[4] - namesIndex));
206
+ namesIndex = segment[4];
207
+ }
208
+ }
209
+ return writer.flush();
210
+ }
211
+ // ../../node_modules/.pnpm/magic-string@1.4.5/node_modules/magic-string/dist/index.mjs
212
+ var BitSet = class BitSet {
213
+ constructor(arg) {
214
+ this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
215
+ }
216
+ add(n) {
217
+ this.bits[n >> 5] |= 1 << (n & 31);
218
+ }
219
+ has(n) {
220
+ return !!(this.bits[n >> 5] & 1 << (n & 31));
221
+ }
222
+ forEach(fn) {
223
+ const bits = this.bits;
224
+ for (let w = 0; w < bits.length; w++) {
225
+ let word = bits[w];
226
+ while (word) {
227
+ const lowest = word & -word;
228
+ fn((w << 5) + 31 - Math.clz32(lowest));
229
+ word ^= lowest;
230
+ }
231
+ }
232
+ }
233
+ };
234
+ var Chunk = class Chunk {
235
+ constructor(start, end, content) {
236
+ this.start = start;
237
+ this.end = end;
238
+ this.original = content;
239
+ this.intro = "";
240
+ this.outro = "";
241
+ this.content = content;
242
+ this.storeName = false;
243
+ this.edited = false;
244
+ this.replacesUntil = -1;
245
+ this.replacedFrom = -1;
246
+ this.previous = null;
247
+ this.next = null;
248
+ }
249
+ appendLeft(content) {
250
+ this.outro += content;
251
+ }
252
+ appendRight(content) {
253
+ this.intro = this.intro + content;
254
+ }
255
+ clone() {
256
+ const chunk = new Chunk(this.start, this.end, this.original);
257
+ chunk.intro = this.intro;
258
+ chunk.outro = this.outro;
259
+ chunk.content = this.content;
260
+ chunk.storeName = this.storeName;
261
+ chunk.edited = this.edited;
262
+ chunk.replacesUntil = this.replacesUntil;
263
+ chunk.replacedFrom = this.replacedFrom;
264
+ return chunk;
265
+ }
266
+ contains(index) {
267
+ return this.start < index && index < this.end;
268
+ }
269
+ eachNext(fn) {
270
+ fn(this);
271
+ let chunk = this.next;
272
+ while (chunk) {
273
+ fn(chunk);
274
+ chunk = chunk.next;
275
+ }
276
+ }
277
+ eachPrevious(fn) {
278
+ fn(this);
279
+ let chunk = this.previous;
280
+ while (chunk) {
281
+ fn(chunk);
282
+ chunk = chunk.previous;
283
+ }
284
+ }
285
+ edit(content, storeName, contentOnly) {
286
+ this.content = content;
287
+ if (!contentOnly) {
288
+ this.intro = "";
289
+ this.outro = "";
290
+ }
291
+ this.storeName = storeName;
292
+ this.edited = true;
293
+ return this;
294
+ }
295
+ prependLeft(content) {
296
+ this.outro = content + this.outro;
297
+ }
298
+ prependRight(content) {
299
+ this.intro = content + this.intro;
300
+ }
301
+ reset() {
302
+ this.intro = "";
303
+ this.outro = "";
304
+ this.replacesUntil = -1;
305
+ this.replacedFrom = -1;
306
+ if (this.edited) {
307
+ this.content = this.original;
308
+ this.storeName = false;
309
+ this.edited = false;
310
+ }
311
+ }
312
+ split(index) {
313
+ const sliceIndex = index - this.start;
314
+ const originalBefore = this.original.slice(0, sliceIndex);
315
+ const originalAfter = this.original.slice(sliceIndex);
316
+ this.original = originalBefore;
317
+ const newChunk = new Chunk(index, this.end, originalAfter);
318
+ newChunk.outro = this.outro;
319
+ this.outro = "";
320
+ this.end = index;
321
+ if (this.edited) {
322
+ newChunk.edit("", false, true);
323
+ newChunk.replacedFrom = this.replacedFrom;
324
+ } else this.content = originalBefore;
325
+ newChunk.next = this.next;
326
+ if (newChunk.next) newChunk.next.previous = newChunk;
327
+ newChunk.previous = this;
328
+ this.next = newChunk;
329
+ return newChunk;
330
+ }
331
+ toString() {
332
+ return this.intro + this.content + this.outro;
333
+ }
334
+ trimEnd(rx) {
335
+ this.outro = this.outro.replace(rx, "");
336
+ if (this.outro.length) return true;
337
+ const trimmed = this.content.replace(rx, "");
338
+ if (trimmed.length) {
339
+ if (trimmed !== this.content) {
340
+ if (this.edited) this.edit(trimmed, this.storeName, true);
341
+ else this.split(this.start + trimmed.length).edit("", void 0, true);
342
+ }
343
+ return true;
344
+ } else {
345
+ this.edit("", void 0, true);
346
+ this.intro = this.intro.replace(rx, "");
347
+ if (this.intro.length) return true;
348
+ }
349
+ }
350
+ trimStart(rx) {
351
+ this.intro = this.intro.replace(rx, "");
352
+ if (this.intro.length) return true;
353
+ const trimmed = this.content.replace(rx, "");
354
+ if (trimmed.length) {
355
+ if (trimmed !== this.content) {
356
+ if (this.edited) this.edit(trimmed, this.storeName, true);
357
+ else {
358
+ this.split(this.end - trimmed.length);
359
+ this.edit("", void 0, true);
360
+ }
361
+ }
362
+ return true;
363
+ } else {
364
+ this.edit("", void 0, true);
365
+ this.outro = this.outro.replace(rx, "");
366
+ if (this.outro.length) return true;
367
+ }
368
+ }
369
+ };
370
+ /**
371
+ * The single error type thrown by MagicString.
372
+ *
373
+ * Every message is prefixed with `[MagicString]` so its source is obvious at a
374
+ * glance, and is kept short and consistent in tone.
375
+ */
376
+ var MagicStringError = class extends Error {
377
+ name = "MagicStringError";
378
+ constructor(message, options) {
379
+ super(`[MagicString] ${message}`, options);
380
+ }
381
+ };
382
+ function getBtoa() {
383
+ /* v8 ignore next -- environment fallback, unreachable when `btoa` is present */
384
+ if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
385
+ const buffer = globalThis["Buffer"];
386
+ if (buffer) return (str) => buffer.from(str, "utf-8").toString("base64");
387
+ return () => {
388
+ throw new MagicStringError("unsupported environment: `btoa` or `Buffer` is required");
389
+ };
390
+ /* v8 ignore stop */
391
+ }
392
+ const btoa = /* #__PURE__ */ getBtoa();
393
+ var SourceMap = class {
394
+ constructor(properties) {
395
+ this.version = 3;
396
+ this.file = properties.file;
397
+ this.sources = properties.sources;
398
+ this.sourcesContent = properties.sourcesContent;
399
+ this.names = properties.names;
400
+ this.mappings = typeof properties.mappings === "string" ? properties.mappings : encode(properties.mappings);
401
+ if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList;
402
+ if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId;
403
+ if (typeof properties.rangeMappings !== "undefined") {
404
+ let shouldOutputRangeMapping = false;
405
+ for (const line of properties.rangeMappings) if (line.length !== 0) {
406
+ shouldOutputRangeMapping = true;
407
+ break;
408
+ }
409
+ if (shouldOutputRangeMapping) this.rangeMappings = encodeRangeMappings(properties.rangeMappings);
410
+ }
411
+ }
412
+ /**
413
+ * Returns the equivalent of `JSON.stringify(map)`
414
+ */
415
+ toString() {
416
+ return JSON.stringify(this);
417
+ }
418
+ /**
419
+ * Returns a DataURI containing the sourcemap. Useful for doing this sort of thing:
420
+ * `generateMap(options?: SourceMapOptions): SourceMap;`
421
+ */
422
+ toUrl() {
423
+ return `data:application/json;charset=utf-8;base64,${btoa(this.toString())}`;
424
+ }
425
+ };
426
+ function getLocator(source) {
427
+ const lineOffsets = [0];
428
+ for (let i = source.indexOf("\n"); i !== -1; i = source.indexOf("\n", i + 1)) lineOffsets.push(i + 1);
429
+ return function locate(index) {
430
+ let i = 0;
431
+ let j = lineOffsets.length;
432
+ while (i < j) {
433
+ const m = i + j >> 1;
434
+ if (index < lineOffsets[m]) j = m;
435
+ else i = m + 1;
436
+ }
437
+ const line = i - 1;
438
+ return {
439
+ line,
440
+ column: index - lineOffsets[line]
441
+ };
442
+ };
443
+ }
444
+ function getRelativePath(from, to) {
445
+ const fromParts = from.split(/[/\\]/);
446
+ const toParts = to.split(/[/\\]/);
447
+ fromParts.pop();
448
+ while (fromParts[0] === toParts[0]) {
449
+ fromParts.shift();
450
+ toParts.shift();
451
+ }
452
+ if (fromParts.length) {
453
+ let i = fromParts.length;
454
+ while (i--) fromParts[i] = "..";
455
+ }
456
+ return fromParts.concat(toParts).join("/");
457
+ }
458
+ function guessIndent(code) {
459
+ const lines = code.split("\n");
460
+ const tabbed = lines.filter((line) => /^\t+/.test(line));
461
+ const spaced = lines.filter((line) => /^ {2,}/.test(line));
462
+ if (tabbed.length === 0 && spaced.length === 0) return null;
463
+ if (tabbed.length >= spaced.length) return " ";
464
+ const min = spaced.reduce((previous, current) => {
465
+ const numSpaces = /^ +/.exec(current)[0].length;
466
+ return Math.min(numSpaces, previous);
467
+ }, Infinity);
468
+ return " ".repeat(min);
469
+ }
470
+ const toString = Object.prototype.toString;
471
+ function isObject(thing) {
472
+ return toString.call(thing) === "[object Object]";
473
+ }
474
+ const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
475
+ const intToChar = /* #__PURE__ */ (() => {
476
+ const chars = /* @__PURE__ */ new Uint8Array(64);
477
+ for (let i = 0; i < 64; i++) chars[i] = BASE64_CHARS.charCodeAt(i);
478
+ return chars;
479
+ })();
480
+ const COMMA = 44;
481
+ const SEMICOLON = 59;
482
+ const BUFFER_SIZE = 16384;
483
+ const FLUSH_THRESHOLD = 16348;
484
+ const scratch = /* #__PURE__ */ new Uint8Array(BUFFER_SIZE);
485
+ function writeVlq(pos, num) {
486
+ num = num < 0 ? -num << 1 | 1 : num << 1;
487
+ do {
488
+ let clamped = num & 31;
489
+ num >>>= 5;
490
+ if (num > 0) clamped |= 32;
491
+ scratch[pos++] = intToChar[clamped];
492
+ } while (num > 0);
493
+ return pos;
494
+ }
495
+ const decoder = /* #__PURE__ */ new TextDecoder();
496
+ var MappingsEncoder = class {
497
+ constructor() {
498
+ this.out = "";
499
+ this.pos = 0;
500
+ this.lines = [];
501
+ this.buffered = 0;
502
+ this.needsComma = false;
503
+ this.prevGenColumn = 0;
504
+ this.prevSourceIndex = 0;
505
+ this.prevSourceLine = 0;
506
+ this.prevSourceColumn = 0;
507
+ this.prevNameIndex = 0;
508
+ }
509
+ endLine(segments) {
510
+ this.lines.push(segments);
511
+ this.buffered += segments.length + 1;
512
+ if (this.buffered >= 4096) this.drain(null);
513
+ }
514
+ segments(segments) {
515
+ this.drain(segments);
516
+ }
517
+ finish(segments) {
518
+ this.drain(segments);
519
+ this.flush();
520
+ return this.out;
521
+ }
522
+ drain(trailing) {
523
+ const lines = this.lines;
524
+ const lineCount = lines.length;
525
+ for (let l = 0; l <= lineCount; l++) {
526
+ const line = l < lineCount ? lines[l] : trailing;
527
+ if (line === null) break;
528
+ for (let i = 0; i < line.length; i++) {
529
+ if (this.pos > FLUSH_THRESHOLD) this.flush();
530
+ const segment = line[i];
531
+ if (this.needsComma) scratch[this.pos++] = COMMA;
532
+ this.needsComma = true;
533
+ this.pos = writeVlq(this.pos, segment[0] - this.prevGenColumn);
534
+ this.prevGenColumn = segment[0];
535
+ this.pos = writeVlq(this.pos, segment[1] - this.prevSourceIndex);
536
+ this.prevSourceIndex = segment[1];
537
+ this.pos = writeVlq(this.pos, segment[2] - this.prevSourceLine);
538
+ this.prevSourceLine = segment[2];
539
+ this.pos = writeVlq(this.pos, segment[3] - this.prevSourceColumn);
540
+ this.prevSourceColumn = segment[3];
541
+ if (segment.length === 5) {
542
+ this.pos = writeVlq(this.pos, segment[4] - this.prevNameIndex);
543
+ this.prevNameIndex = segment[4];
544
+ }
545
+ }
546
+ if (l < lineCount) {
547
+ if (this.pos > FLUSH_THRESHOLD) this.flush();
548
+ scratch[this.pos++] = SEMICOLON;
549
+ this.needsComma = false;
550
+ this.prevGenColumn = 0;
551
+ }
552
+ }
553
+ lines.length = 0;
554
+ this.buffered = 0;
555
+ this.flush();
556
+ }
557
+ flush() {
558
+ this.out += decoder.decode(scratch.subarray(0, this.pos));
559
+ this.pos = 0;
560
+ }
561
+ };
562
+ const NEWLINE_CHAR$1 = 10;
563
+ function isWordCode(code) {
564
+ return code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 95;
565
+ }
566
+ var Mappings = class {
567
+ constructor(hires, encoder = null) {
568
+ this.hires = hires;
569
+ this.generatedCodeLine = 0;
570
+ this.generatedCodeColumn = 0;
571
+ this.raw = [];
572
+ this.rawSegments = this.raw[this.generatedCodeLine] = [];
573
+ this.rawRangeMappingsIndices = [];
574
+ this.rawRangeMappings = hires === "experimental-range" ? [this.rawRangeMappingsIndices] : void 0;
575
+ this.encoder = encoder;
576
+ }
577
+ nextLine() {
578
+ if (this.encoder === null) {
579
+ this.generatedCodeLine += 1;
580
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
581
+ } else {
582
+ this.encoder.endLine(this.rawSegments);
583
+ this.rawSegments = [];
584
+ this.generatedCodeLine += 1;
585
+ }
586
+ this.generatedCodeColumn = 0;
587
+ if (this.rawRangeMappings) this.rawRangeMappings[this.generatedCodeLine] = this.rawRangeMappingsIndices = [];
588
+ }
589
+ /**
590
+ * Emits the mappings for one MagicString: its intro, every chunk (with the
591
+ * chunk's own intro/outro) and its outro. `sourceIndex === -1` means the
592
+ * string has no source of its own, so its content only advances the
593
+ * generated position without mapping anything.
594
+ */
595
+ addMagicString(magicString, sourceIndex, nameIndex) {
596
+ const { original } = magicString;
597
+ const locate = getLocator(original);
598
+ if (magicString.intro) this.advance(magicString.intro);
599
+ magicString.firstChunk.eachNext((chunk) => {
600
+ if (chunk.intro.length) this.advance(chunk.intro);
601
+ if (sourceIndex === -1) this.advance(chunk.content);
602
+ else if (chunk.edited) {
603
+ const name = chunk.storeName ? nameIndex.get(original.slice(chunk.start, chunk.replacesUntil)) : void 0;
604
+ this.addEdit(sourceIndex, chunk.content, locate(chunk.start), name ?? -1);
605
+ } else this.addUneditedChunk(sourceIndex, chunk, original, locate(chunk.start), magicString.sourcemapLocations);
606
+ if (chunk.outro.length) this.advance(chunk.outro);
607
+ });
608
+ if (magicString.outro) this.advance(magicString.outro);
609
+ }
610
+ addEdit(sourceIndex, content, loc, nameIndex) {
611
+ if (content.length) {
612
+ const contentLengthMinusOne = content.length - 1;
613
+ let contentLineEnd = content.indexOf("\n", 0);
614
+ let previousContentLineEnd = -1;
615
+ while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
616
+ const segment = [
617
+ this.generatedCodeColumn,
618
+ sourceIndex,
619
+ loc.line,
620
+ loc.column
621
+ ];
622
+ if (nameIndex >= 0) segment.push(nameIndex);
623
+ this.rawSegments.push(segment);
624
+ this.nextLine();
625
+ previousContentLineEnd = contentLineEnd;
626
+ contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
627
+ }
628
+ const segment = [
629
+ this.generatedCodeColumn,
630
+ sourceIndex,
631
+ loc.line,
632
+ loc.column
633
+ ];
634
+ if (nameIndex >= 0) segment.push(nameIndex);
635
+ this.rawSegments.push(segment);
636
+ this.advance(content.slice(previousContentLineEnd + 1));
637
+ }
638
+ }
639
+ addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
640
+ const end = chunk.end;
641
+ let i = chunk.start;
642
+ if (this.hires) {
643
+ const boundary = this.hires === "boundary";
644
+ const experimentalRange = this.hires === "experimental-range";
645
+ const encoder = experimentalRange ? null : this.encoder;
646
+ let charInHiresBoundary = false;
647
+ while (i < end) {
648
+ if (encoder !== null && this.rawSegments.length >= 4096) {
649
+ encoder.segments(this.rawSegments);
650
+ this.rawSegments.length = 0;
651
+ }
652
+ if (experimentalRange && i + 1 >= end) this.rawSegments.push([
653
+ this.generatedCodeColumn,
654
+ sourceIndex,
655
+ loc.line,
656
+ loc.column
657
+ ]);
658
+ const code = original.charCodeAt(i);
659
+ if (code === NEWLINE_CHAR$1) {
660
+ loc.line += 1;
661
+ loc.column = 0;
662
+ this.nextLine();
663
+ charInHiresBoundary = false;
664
+ } else {
665
+ if (boundary) {
666
+ if (isWordCode(code)) {
667
+ if (!charInHiresBoundary) {
668
+ this.rawSegments.push([
669
+ this.generatedCodeColumn,
670
+ sourceIndex,
671
+ loc.line,
672
+ loc.column
673
+ ]);
674
+ charInHiresBoundary = true;
675
+ }
676
+ } else {
677
+ this.rawSegments.push([
678
+ this.generatedCodeColumn,
679
+ sourceIndex,
680
+ loc.line,
681
+ loc.column
682
+ ]);
683
+ charInHiresBoundary = false;
684
+ }
685
+ } else if (experimentalRange) {
686
+ if (i === chunk.start) {
687
+ this.rawRangeMappingsIndices.push(this.rawSegments.length);
688
+ this.rawSegments.push([
689
+ this.generatedCodeColumn,
690
+ sourceIndex,
691
+ loc.line,
692
+ loc.column
693
+ ]);
694
+ }
695
+ } else this.rawSegments.push([
696
+ this.generatedCodeColumn,
697
+ sourceIndex,
698
+ loc.line,
699
+ loc.column
700
+ ]);
701
+ loc.column += 1;
702
+ this.generatedCodeColumn += 1;
703
+ }
704
+ i += 1;
705
+ }
706
+ } else {
707
+ const bits = sourcemapLocations.bits;
708
+ while (i < end) {
709
+ let newline = original.indexOf("\n", i);
710
+ if (newline === -1 || newline > end) newline = end;
711
+ if (newline > i) {
712
+ this.rawSegments.push([
713
+ this.generatedCodeColumn,
714
+ sourceIndex,
715
+ loc.line,
716
+ loc.column
717
+ ]);
718
+ for (let w = i + 1 >> 5, last = newline - 1 >> 5; w <= last; w++) {
719
+ let word = bits[w];
720
+ if (!word) continue;
721
+ const base = w << 5;
722
+ while (word) {
723
+ const lowest = word & -word;
724
+ const index = base + 31 - Math.clz32(lowest);
725
+ if (index > i && index < newline) {
726
+ const offset = index - i;
727
+ this.rawSegments.push([
728
+ this.generatedCodeColumn + offset,
729
+ sourceIndex,
730
+ loc.line,
731
+ loc.column + offset
732
+ ]);
733
+ }
734
+ word ^= lowest;
735
+ }
736
+ }
737
+ loc.column += newline - i;
738
+ this.generatedCodeColumn += newline - i;
739
+ }
740
+ if (newline === end) break;
741
+ loc.line += 1;
742
+ loc.column = 0;
743
+ this.nextLine();
744
+ i = newline + 1;
745
+ }
746
+ }
747
+ }
748
+ advance(str) {
749
+ if (!str) return;
750
+ const lastNewline = str.lastIndexOf("\n");
751
+ for (let i = str.indexOf("\n"); i !== -1; i = str.indexOf("\n", i + 1)) this.nextLine();
752
+ this.generatedCodeColumn += str.length - lastNewline - 1;
753
+ }
754
+ };
755
+ const n = "\n";
756
+ const NEWLINE_CHAR = "\n".charCodeAt(0);
757
+ const CR_CHAR = "\r".charCodeAt(0);
758
+ const warned = {
759
+ insertLeft: false,
760
+ insertRight: false,
761
+ storeName: false
762
+ };
763
+ /**
764
+ * Expands the `$` substitution patterns that `String.prototype.replace` accepts
765
+ * in a string replacement.
766
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
767
+ *
768
+ * `captures` holds the capture groups in order, so `captures[0]` is `$1`.
769
+ * `namedCaptures` is `undefined` when the pattern has no named groups, and
770
+ * `$<name>` is then literal text - which is also the case for a string search
771
+ * value, where there are no groups of either kind.
772
+ */
773
+ function expandReplacement(replacement, matched, position, str, captures, namedCaptures) {
774
+ if (!replacement.includes("$")) return replacement;
775
+ let result = "";
776
+ let index = 0;
777
+ while (index < replacement.length) {
778
+ const dollar = replacement.indexOf("$", index);
779
+ if (dollar === -1) {
780
+ result += replacement.slice(index);
781
+ break;
782
+ }
783
+ result += replacement.slice(index, dollar);
784
+ const char = replacement[dollar + 1];
785
+ let expansion = "$";
786
+ let consumed = 1;
787
+ if (char === "$") consumed = 2;
788
+ else if (char === "&") {
789
+ expansion = matched;
790
+ consumed = 2;
791
+ } else if (char === "`") {
792
+ expansion = str.slice(0, position);
793
+ consumed = 2;
794
+ } else if (char === "'") {
795
+ expansion = str.slice(position + matched.length);
796
+ consumed = 2;
797
+ } else if (char === "<" && namedCaptures !== void 0) {
798
+ const close = replacement.indexOf(">", dollar + 2);
799
+ if (close !== -1) {
800
+ expansion = namedCaptures[replacement.slice(dollar + 2, close)] ?? "";
801
+ consumed = close + 1 - dollar;
802
+ }
803
+ } else if (char >= "0" && char <= "9") {
804
+ const second = replacement[dollar + 2];
805
+ const double = second >= "0" && second <= "9" ? Number(char + second) : NaN;
806
+ const single = Number(char);
807
+ if (double >= 1 && double <= captures.length) {
808
+ expansion = captures[double - 1] ?? "";
809
+ consumed = 3;
810
+ } else if (single >= 1 && single <= captures.length) {
811
+ expansion = captures[single - 1] ?? "";
812
+ consumed = 2;
813
+ }
814
+ }
815
+ result += expansion;
816
+ index = dollar + consumed;
817
+ }
818
+ return result;
819
+ }
820
+ var MagicString = class MagicString {
821
+ /**
822
+ * Wraps `string` for editing; every index passed to the editing methods refers to this original string.
823
+ */
824
+ constructor(string, options = {}) {
825
+ const chunk = new Chunk(0, string.length, string);
826
+ Object.defineProperties(this, {
827
+ original: {
828
+ writable: true,
829
+ value: string
830
+ },
831
+ outro: {
832
+ writable: true,
833
+ value: ""
834
+ },
835
+ intro: {
836
+ writable: true,
837
+ value: ""
838
+ },
839
+ firstChunk: {
840
+ writable: true,
841
+ value: chunk
842
+ },
843
+ lastChunk: {
844
+ writable: true,
845
+ value: chunk
846
+ },
847
+ lastSearchedChunk: {
848
+ writable: true,
849
+ value: chunk
850
+ },
851
+ byStart: {
852
+ writable: true,
853
+ value: /* @__PURE__ */ new Map([[0, chunk]])
854
+ },
855
+ byEnd: {
856
+ writable: true,
857
+ value: /* @__PURE__ */ new Map([[string.length, chunk]])
858
+ },
859
+ filename: {
860
+ writable: true,
861
+ value: options.filename
862
+ },
863
+ indentExclusionRanges: {
864
+ writable: true,
865
+ value: options.indentExclusionRanges
866
+ },
867
+ sourcemapLocations: {
868
+ writable: true,
869
+ value: new BitSet()
870
+ },
871
+ storedNames: {
872
+ writable: true,
873
+ value: /* @__PURE__ */ new Set()
874
+ },
875
+ indentStr: {
876
+ writable: true,
877
+ value: void 0
878
+ },
879
+ ignoreList: {
880
+ writable: true,
881
+ value: options.ignoreList
882
+ },
883
+ offset: {
884
+ writable: true,
885
+ value: options.offset || 0
886
+ },
887
+ hasMovedChunks: {
888
+ writable: true,
889
+ value: false
890
+ }
891
+ });
892
+ }
893
+ /**
894
+ * Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is false.
895
+ */
896
+ addSourcemapLocation(char) {
897
+ this.sourcemapLocations.add(char);
898
+ }
899
+ /**
900
+ * Appends the specified content to the end of the string.
901
+ */
902
+ append(content) {
903
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
904
+ this.outro += content;
905
+ return this;
906
+ }
907
+ /**
908
+ * Appends the specified content at the index in the original string.
909
+ * If a range *ending* with index is subsequently moved, the insert will be moved with it.
910
+ * See also `s.prependLeft(...)`.
911
+ */
912
+ appendLeft(index, content) {
913
+ index = this._resolveIndex(index);
914
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
915
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
916
+ this._split(index);
917
+ const chunk = this.byEnd.get(index);
918
+ if (chunk) chunk.appendLeft(content);
919
+ else this.intro += content;
920
+ return this;
921
+ }
922
+ /**
923
+ * Appends the specified content at the index in the original string.
924
+ * If a range *starting* with index is subsequently moved, the insert will be moved with it.
925
+ * See also `s.prependRight(...)`.
926
+ */
927
+ appendRight(index, content) {
928
+ index = this._resolveIndex(index);
929
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
930
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
931
+ this._split(index);
932
+ const chunk = this.byStart.get(index);
933
+ if (chunk) chunk.appendRight(content);
934
+ else this.outro += content;
935
+ return this;
936
+ }
937
+ /**
938
+ * Returns an independent copy: the chunk list, string-level intro/outro,
939
+ * sourcemap locations, stored names, indent exclusion ranges, `offset`,
940
+ * `filename` and `ignoreList` are all copied; later edits to either string
941
+ * do not affect the other.
942
+ */
943
+ clone() {
944
+ const cloned = new MagicString(this.original, {
945
+ filename: this.filename,
946
+ ignoreList: this.ignoreList,
947
+ offset: this.offset
948
+ });
949
+ let originalChunk = this.firstChunk;
950
+ let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
951
+ while (originalChunk) {
952
+ cloned.byStart.set(clonedChunk.start, clonedChunk);
953
+ cloned.byEnd.set(clonedChunk.end, clonedChunk);
954
+ const nextOriginalChunk = originalChunk.next;
955
+ const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
956
+ if (nextClonedChunk) {
957
+ clonedChunk.next = nextClonedChunk;
958
+ nextClonedChunk.previous = clonedChunk;
959
+ clonedChunk = nextClonedChunk;
960
+ }
961
+ originalChunk = nextOriginalChunk;
962
+ }
963
+ cloned.lastChunk = clonedChunk;
964
+ if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
965
+ cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
966
+ cloned.storedNames = new Set(this.storedNames);
967
+ cloned.intro = this.intro;
968
+ cloned.outro = this.outro;
969
+ cloned.hasMovedChunks = this.hasMovedChunks;
970
+ return cloned;
971
+ }
972
+ /**
973
+ * Generates a sourcemap object with raw mappings in array form, rather than encoded as a string.
974
+ * Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead.
975
+ */
976
+ generateDecodedMap(options) {
977
+ options = options || {};
978
+ const mappings = new Mappings(options.hires);
979
+ const names = this._generateMappings(mappings);
980
+ return {
981
+ ...this._mapProperties(options, names),
982
+ mappings: mappings.raw,
983
+ rangeMappings: mappings.rawRangeMappings
984
+ };
985
+ }
986
+ /**
987
+ * Generates a version 3 sourcemap.
988
+ */
989
+ generateMap(options) {
990
+ options = options || {};
991
+ const encoder = new MappingsEncoder();
992
+ const mappings = new Mappings(options.hires, encoder);
993
+ const names = this._generateMappings(mappings);
994
+ return new SourceMap({
995
+ ...this._mapProperties(options, names),
996
+ mappings: encoder.finish(mappings.rawSegments),
997
+ rangeMappings: mappings.rawRangeMappings
998
+ });
999
+ }
1000
+ /** @internal */
1001
+ _generateMappings(mappings) {
1002
+ const names = [...this.storedNames];
1003
+ mappings.addMagicString(this, 0, new Map(names.map((name, i) => [name, i])));
1004
+ return names;
1005
+ }
1006
+ /** @internal */
1007
+ _mapProperties(options, names) {
1008
+ return {
1009
+ file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
1010
+ sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
1011
+ sourcesContent: options.includeContent ? [this.original] : void 0,
1012
+ names,
1013
+ x_google_ignoreList: this.ignoreList ? [0] : void 0
1014
+ };
1015
+ }
1016
+ /** @internal */
1017
+ _ensureindentStr() {
1018
+ if (this.indentStr === void 0) this.indentStr = guessIndent(this.original);
1019
+ }
1020
+ /** @internal */
1021
+ _getRawIndentString() {
1022
+ this._ensureindentStr();
1023
+ return this.indentStr;
1024
+ }
1025
+ /**
1026
+ * Returns the indentation string guessed from the original content, falling back to a single tab character.
1027
+ * This is the value `s.indent()` uses when no prefix is supplied.
1028
+ */
1029
+ getIndentString() {
1030
+ this._ensureindentStr();
1031
+ return this.indentStr ?? " ";
1032
+ }
1033
+ indent(indentStr, options) {
1034
+ const pattern = /^[^\r\n]/gm;
1035
+ if (isObject(indentStr)) {
1036
+ options = indentStr;
1037
+ indentStr = void 0;
1038
+ }
1039
+ if (indentStr === void 0) {
1040
+ this._ensureindentStr();
1041
+ indentStr = this.indentStr || " ";
1042
+ }
1043
+ if (indentStr === "") return this;
1044
+ const resolvedIndentStr = indentStr;
1045
+ options = options || {};
1046
+ const isExcluded = new BitSet();
1047
+ if (options.exclude) (typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude).forEach((exclusion) => {
1048
+ for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded.add(i);
1049
+ });
1050
+ let shouldIndentNextCharacter = options.indentStart !== false;
1051
+ const indentPiece = (str) => {
1052
+ if (str === "") return str;
1053
+ const indented = str.replace(pattern, (match, offset) => offset > 0 || shouldIndentNextCharacter ? `${resolvedIndentStr}${match}` : match);
1054
+ shouldIndentNextCharacter = str[str.length - 1] === "\n";
1055
+ return indented;
1056
+ };
1057
+ this.intro = indentPiece(this.intro);
1058
+ let charIndex = 0;
1059
+ let chunk = this.firstChunk;
1060
+ const indentAt = (index) => {
1061
+ shouldIndentNextCharacter = false;
1062
+ if (index === chunk.start) chunk.appendRight(resolvedIndentStr);
1063
+ else {
1064
+ this._splitChunk(chunk, index);
1065
+ chunk = chunk.next;
1066
+ chunk.prependRight(resolvedIndentStr);
1067
+ }
1068
+ };
1069
+ while (chunk) {
1070
+ const end = chunk.end;
1071
+ if (!isExcluded.has(chunk.start)) chunk.intro = indentPiece(chunk.intro);
1072
+ if (chunk.edited) {
1073
+ if (!isExcluded.has(chunk.start)) chunk.content = indentPiece(chunk.content);
1074
+ else if (chunk.content) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
1075
+ } else if (options.exclude) {
1076
+ charIndex = chunk.start;
1077
+ while (charIndex < end) {
1078
+ if (!isExcluded.has(charIndex)) {
1079
+ const char = this.original.charCodeAt(charIndex);
1080
+ if (char === NEWLINE_CHAR) shouldIndentNextCharacter = true;
1081
+ else if (char !== CR_CHAR && shouldIndentNextCharacter) indentAt(charIndex);
1082
+ }
1083
+ charIndex += 1;
1084
+ }
1085
+ } else {
1086
+ charIndex = chunk.start;
1087
+ while (charIndex < end) {
1088
+ if (!shouldIndentNextCharacter) {
1089
+ const nextLine = this.original.indexOf(n, charIndex);
1090
+ if (nextLine === -1 || nextLine >= end) break;
1091
+ shouldIndentNextCharacter = true;
1092
+ charIndex = nextLine + 1;
1093
+ continue;
1094
+ }
1095
+ const char = this.original.charCodeAt(charIndex);
1096
+ if (char === NEWLINE_CHAR || char === CR_CHAR) {
1097
+ charIndex += 1;
1098
+ continue;
1099
+ }
1100
+ indentAt(charIndex);
1101
+ charIndex += 1;
1102
+ }
1103
+ }
1104
+ if (!isExcluded.has(chunk.end - 1)) chunk.outro = indentPiece(chunk.outro);
1105
+ charIndex = chunk.end;
1106
+ chunk = chunk.next;
1107
+ }
1108
+ this.outro = indentPiece(this.outro);
1109
+ return this;
1110
+ }
1111
+ /** @internal */
1112
+ insert() {
1113
+ throw new MagicStringError("insert() is deprecated, use appendLeft() or prependRight()");
1114
+ }
1115
+ /** @internal */
1116
+ insertLeft(index, content) {
1117
+ if (!warned.insertLeft) {
1118
+ console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
1119
+ warned.insertLeft = true;
1120
+ }
1121
+ return this.appendLeft(index, content);
1122
+ }
1123
+ /** @internal */
1124
+ insertRight(index, content) {
1125
+ if (!warned.insertRight) {
1126
+ console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
1127
+ warned.insertRight = true;
1128
+ }
1129
+ return this.prependRight(index, content);
1130
+ }
1131
+ /**
1132
+ * Moves the characters from `start` and `end` to `index`.
1133
+ *
1134
+ * `affinity` controls where the range is anchored at `index`. With the
1135
+ * default `'right'`, it is inserted before the content that starts at `index`;
1136
+ * with `'left'`, it is inserted after the content that ends at `index`. The
1137
+ * two differ only when other content has already been moved to that boundary,
1138
+ * mirroring the `appendLeft`/`appendRight` distinction.
1139
+ */
1140
+ move(start, end, index, affinity = "right") {
1141
+ start = this._resolveIndex(start);
1142
+ end = this._resolveIndex(end);
1143
+ index = this._resolveIndex(index);
1144
+ if (start === end) return this;
1145
+ if (start < 0 || end > this.original.length || index < 0 || index > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1146
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
1147
+ if (index >= start && index <= end) throw new MagicStringError("cannot move a selection inside itself");
1148
+ this._split(start);
1149
+ this._split(end);
1150
+ this._split(index);
1151
+ const first = this.byStart.get(start);
1152
+ const last = this.byEnd.get(end);
1153
+ if (!first || !last) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1154
+ if (this.hasMovedChunks) {
1155
+ let cursor = first;
1156
+ while (cursor !== last) {
1157
+ cursor = cursor.next;
1158
+ if (!cursor || cursor.start < start || cursor.end > end) throw new MagicStringError(`cannot move ${start} to ${end} because an earlier move split that range`);
1159
+ }
1160
+ }
1161
+ const oldLeft = first.previous;
1162
+ const oldRight = last.next;
1163
+ let newLeft;
1164
+ let newRight;
1165
+ if (affinity === "left") {
1166
+ newLeft = this.byEnd.get(index) ?? null;
1167
+ if (!newLeft) {
1168
+ if (first === this.firstChunk) return this;
1169
+ newRight = this.firstChunk;
1170
+ } else {
1171
+ if (newLeft.next === first) return this;
1172
+ newRight = newLeft.next;
1173
+ }
1174
+ } else {
1175
+ newRight = this.byStart.get(index) ?? null;
1176
+ if (!newRight) {
1177
+ if (last === this.lastChunk) return this;
1178
+ newLeft = this.lastChunk;
1179
+ } else {
1180
+ if (newRight.previous === last) return this;
1181
+ newLeft = newRight.previous;
1182
+ }
1183
+ }
1184
+ if (oldLeft) oldLeft.next = oldRight;
1185
+ if (oldRight) oldRight.previous = oldLeft;
1186
+ if (newLeft) newLeft.next = first;
1187
+ if (newRight) newRight.previous = last;
1188
+ if (!oldLeft) this.firstChunk = oldRight;
1189
+ if (!oldRight) {
1190
+ this.lastChunk = oldLeft;
1191
+ this.lastChunk.next = null;
1192
+ }
1193
+ first.previous = newLeft;
1194
+ last.next = newRight || null;
1195
+ if (!newLeft) this.firstChunk = first;
1196
+ if (!newRight) this.lastChunk = last;
1197
+ this.hasMovedChunks = true;
1198
+ return this;
1199
+ }
1200
+ /**
1201
+ * Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in
1202
+ * that range. The same restrictions as `s.remove()` apply.
1203
+ *
1204
+ * The fourth argument is optional. It can have a storeName property - if true, the original name will be stored
1205
+ * for later inclusion in a sourcemap's names array - and a contentOnly property which determines whether only
1206
+ * the content is overwritten, or anything that was appended/prepended to the range as well.
1207
+ *
1208
+ * It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content.
1209
+ */
1210
+ overwrite(start, end, content, options) {
1211
+ if (options === true) {
1212
+ if (!warned.storeName) {
1213
+ console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
1214
+ warned.storeName = true;
1215
+ }
1216
+ return this.update(start, end, content, {
1217
+ storeName: true,
1218
+ overwrite: true
1219
+ });
1220
+ }
1221
+ const optionObject = typeof options === "object" && options ? options : {};
1222
+ return this.update(start, end, content, {
1223
+ ...optionObject,
1224
+ overwrite: !optionObject.contentOnly
1225
+ });
1226
+ }
1227
+ /**
1228
+ * Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply.
1229
+ *
1230
+ * The fourth argument is optional. It can have a storeName property - if true, the original name will be stored
1231
+ * for later inclusion in a sourcemap's names array - and an overwrite property which determines whether only
1232
+ * the content is overwritten, or anything that was appended/prepended to the range as well.
1233
+ */
1234
+ update(start, end, content, options) {
1235
+ start = this._resolveIndex(start);
1236
+ end = this._resolveIndex(end);
1237
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
1238
+ if (start < 0) throw new MagicStringError(`start ${start} is out of bounds`);
1239
+ if (end > this.original.length) throw new MagicStringError(`end ${end} is out of bounds`);
1240
+ if (start === end) throw new MagicStringError(`cannot overwrite a zero-length range at ${start}, use appendLeft() or prependRight()`);
1241
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
1242
+ this._split(start);
1243
+ this._split(end);
1244
+ if (options === true) {
1245
+ if (!warned.storeName) {
1246
+ console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
1247
+ warned.storeName = true;
1248
+ }
1249
+ options = { storeName: true };
1250
+ }
1251
+ const optionObject = typeof options === "object" && options ? options : {};
1252
+ const storeName = optionObject.storeName || false;
1253
+ const overwrite = optionObject.overwrite || false;
1254
+ if (storeName) this.storedNames.add(this.original.slice(start, end));
1255
+ const first = this.byStart.get(start);
1256
+ for (let chunk = first; chunk.end < end;) {
1257
+ const next = chunk.next;
1258
+ if (next === null || next !== this.byStart.get(chunk.end)) throw new MagicStringError("cannot overwrite across a split point");
1259
+ chunk = next;
1260
+ }
1261
+ for (let chunk = first.next; chunk !== null && chunk.start < end; chunk = chunk.next) {
1262
+ chunk.edit("", false, !overwrite);
1263
+ chunk.replacesUntil = -1;
1264
+ chunk.replacedFrom = start;
1265
+ }
1266
+ first.edit(content, storeName, !overwrite);
1267
+ first.replacesUntil = end;
1268
+ first.replacedFrom = -1;
1269
+ return this;
1270
+ }
1271
+ /**
1272
+ * Prepends the string with the specified content.
1273
+ */
1274
+ prepend(content) {
1275
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
1276
+ this.intro = content + this.intro;
1277
+ return this;
1278
+ }
1279
+ /**
1280
+ * Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at index
1281
+ */
1282
+ prependLeft(index, content) {
1283
+ index = this._resolveIndex(index);
1284
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
1285
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
1286
+ this._split(index);
1287
+ const chunk = this.byEnd.get(index);
1288
+ if (chunk) chunk.prependLeft(content);
1289
+ else this.intro = content + this.intro;
1290
+ return this;
1291
+ }
1292
+ /**
1293
+ * Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
1294
+ */
1295
+ prependRight(index, content) {
1296
+ index = this._resolveIndex(index);
1297
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
1298
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
1299
+ this._split(index);
1300
+ const chunk = this.byStart.get(index);
1301
+ if (chunk) chunk.prependRight(content);
1302
+ else this.outro = content + this.outro;
1303
+ return this;
1304
+ }
1305
+ /**
1306
+ * Removes the characters from `start` to `end` (of the original string, **not** the generated string).
1307
+ * Content appended or prepended at positions strictly inside the range is removed with it, while
1308
+ * content attached at `start` or `end` is preserved — use `s.overwrite(start, end, '')` to remove
1309
+ * the range including its edge inserts.
1310
+ * Repeated removals and removals with partially overlapping ranges are allowed.
1311
+ */
1312
+ remove(start, end) {
1313
+ start = this._resolveIndex(start);
1314
+ end = this._resolveIndex(end);
1315
+ if (start === end) return this;
1316
+ if (start < 0 || end > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1317
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
1318
+ this._split(start);
1319
+ this._split(end);
1320
+ let chunk = this.byStart.get(start);
1321
+ while (chunk) {
1322
+ if (chunk.start > start) chunk.intro = "";
1323
+ if (chunk.end < end) chunk.outro = "";
1324
+ chunk.edit("", false, true);
1325
+ chunk.replacesUntil = -1;
1326
+ chunk.replacedFrom = -1;
1327
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : void 0;
1328
+ }
1329
+ return this;
1330
+ }
1331
+ /**
1332
+ * Reset the modified characters from `start` to `end` (of the original string, **not** the generated string).
1333
+ */
1334
+ reset(start, end) {
1335
+ start = this._resolveIndex(start);
1336
+ end = this._resolveIndex(end);
1337
+ if (start === end) return this;
1338
+ if (start < 0 || end > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1339
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
1340
+ this._split(start);
1341
+ this._split(end);
1342
+ let chunk = this.byStart.get(start);
1343
+ while (chunk) {
1344
+ chunk.reset();
1345
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : void 0;
1346
+ }
1347
+ return this;
1348
+ }
1349
+ /**
1350
+ * Returns the last character of the generated string, or `''` if it is empty.
1351
+ */
1352
+ lastChar() {
1353
+ if (this.outro.length) return this.outro[this.outro.length - 1];
1354
+ let chunk = this.lastChunk;
1355
+ while (chunk) {
1356
+ if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
1357
+ if (chunk.content.length) return chunk.content[chunk.content.length - 1];
1358
+ if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
1359
+ chunk = chunk.previous;
1360
+ }
1361
+ if (this.intro.length) return this.intro[this.intro.length - 1];
1362
+ return "";
1363
+ }
1364
+ /**
1365
+ * Returns everything after the last newline in the generated string, or the whole string if there is no newline.
1366
+ */
1367
+ lastLine() {
1368
+ let lineIndex = this.outro.lastIndexOf(n);
1369
+ if (lineIndex !== -1) return this.outro.slice(lineIndex + 1);
1370
+ let lineStr = this.outro;
1371
+ let chunk = this.lastChunk;
1372
+ while (chunk) {
1373
+ if (chunk.outro.length > 0) {
1374
+ lineIndex = chunk.outro.lastIndexOf(n);
1375
+ if (lineIndex !== -1) return chunk.outro.slice(lineIndex + 1) + lineStr;
1376
+ lineStr = chunk.outro + lineStr;
1377
+ }
1378
+ if (chunk.content.length > 0) {
1379
+ lineIndex = chunk.content.lastIndexOf(n);
1380
+ if (lineIndex !== -1) return chunk.content.slice(lineIndex + 1) + lineStr;
1381
+ lineStr = chunk.content + lineStr;
1382
+ }
1383
+ if (chunk.intro.length > 0) {
1384
+ lineIndex = chunk.intro.lastIndexOf(n);
1385
+ if (lineIndex !== -1) return chunk.intro.slice(lineIndex + 1) + lineStr;
1386
+ lineStr = chunk.intro + lineStr;
1387
+ }
1388
+ chunk = chunk.previous;
1389
+ }
1390
+ lineIndex = this.intro.lastIndexOf(n);
1391
+ if (lineIndex !== -1) return this.intro.slice(lineIndex + 1) + lineStr;
1392
+ return this.intro + lineStr;
1393
+ }
1394
+ /**
1395
+ * Returns the content of the generated string that corresponds to the slice
1396
+ * between `start` and `end` of the original string, walking the generated
1397
+ * string from the chunk holding `start` to the chunk holding `end`. Throws
1398
+ * if either index falls inside replaced content. After `move()`, a range
1399
+ * whose end now comes before its start in the output yields `''`.
1400
+ */
1401
+ slice(start = 0, end = this.original.length - this.offset) {
1402
+ start = this._resolveIndex(start);
1403
+ end = this._resolveIndex(end);
1404
+ let result = "";
1405
+ let chunk;
1406
+ if (this.hasMovedChunks) {
1407
+ chunk = this.firstChunk;
1408
+ while (chunk && (chunk.start > start || chunk.end <= start)) {
1409
+ if (chunk.start < end && chunk.end >= end || end === 0 && chunk.start === 0) return result;
1410
+ chunk = chunk.next;
1411
+ }
1412
+ } else {
1413
+ if (start >= end) return result;
1414
+ chunk = this._chunkAt(start);
1415
+ }
1416
+ if (chunk && chunk.edited && chunk.start !== start) throw new MagicStringError(`cannot use edited character ${start} as slice start anchor`);
1417
+ const startChunk = chunk;
1418
+ while (chunk) {
1419
+ if (end === 0 && chunk.start === 0) break;
1420
+ if (chunk.intro && (startChunk !== chunk || chunk.start === start)) result += chunk.intro;
1421
+ const containsEnd = chunk.start < end && chunk.end >= end;
1422
+ if (containsEnd && chunk.edited && chunk.end !== end) throw new MagicStringError(`cannot use edited character ${end} as slice end anchor`);
1423
+ const sliceStart = startChunk === chunk ? start - chunk.start : 0;
1424
+ const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1425
+ result += chunk.content.slice(sliceStart, sliceEnd);
1426
+ if (chunk.outro && (!containsEnd || chunk.end === end)) result += chunk.outro;
1427
+ if (containsEnd) break;
1428
+ chunk = chunk.next;
1429
+ }
1430
+ return result;
1431
+ }
1432
+ /**
1433
+ * Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed.
1434
+ */
1435
+ snip(start, end) {
1436
+ const clone = this.clone();
1437
+ clone.remove(-clone.offset, start);
1438
+ clone.remove(end, clone.original.length - clone.offset);
1439
+ return clone;
1440
+ }
1441
+ /**
1442
+ * Applies `offset`, resolves a negative index from the end of `original` as
1443
+ * `update`/`remove` always have, and rejects anything that is not an integer.
1444
+ * Bounds are checked by the caller, because the methods report them differently.
1445
+ *
1446
+ * @internal
1447
+ */
1448
+ _resolveIndex(index) {
1449
+ const resolved = index + this.offset;
1450
+ if (!Number.isInteger(resolved)) throw new MagicStringError(`index must be an integer, got ${index}`);
1451
+ if (resolved < 0 && this.original.length !== 0) return Math.max(0, resolved + this.original.length);
1452
+ return resolved;
1453
+ }
1454
+ /**
1455
+ * The chunk whose original range holds `index` (`chunk.start <= index < chunk.end`),
1456
+ * or `undefined` when `index` is at or past the end. Searches from the last
1457
+ * visited chunk so that scans over nearby indices stay cheap.
1458
+ *
1459
+ * @internal
1460
+ */
1461
+ _chunkAt(index) {
1462
+ let chunk = this.byStart.get(index);
1463
+ if (chunk) return chunk;
1464
+ chunk = this.lastSearchedChunk;
1465
+ const searchForward = index >= chunk.end;
1466
+ while (chunk && !chunk.contains(index)) chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
1467
+ if (chunk) this.lastSearchedChunk = chunk;
1468
+ return chunk;
1469
+ }
1470
+ /** @internal */
1471
+ _split(index) {
1472
+ if (this.byStart.get(index) || this.byEnd.get(index)) return;
1473
+ let chunk = this.lastSearchedChunk;
1474
+ let previousChunk = chunk;
1475
+ const searchForward = index > chunk.end;
1476
+ while (chunk) {
1477
+ if (chunk.contains(index)) return this._splitChunk(chunk, index);
1478
+ chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
1479
+ if (chunk === previousChunk) return;
1480
+ previousChunk = chunk;
1481
+ }
1482
+ }
1483
+ /** @internal */
1484
+ _splitChunk(chunk, index) {
1485
+ if (chunk.edited && chunk.content.length) {
1486
+ const loc = getLocator(this.original)(index);
1487
+ throw new MagicStringError(`cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`);
1488
+ }
1489
+ const newChunk = chunk.split(index);
1490
+ this.byEnd.set(index, chunk);
1491
+ this.byStart.set(index, newChunk);
1492
+ this.byEnd.set(newChunk.end, newChunk);
1493
+ if (chunk === this.lastChunk) this.lastChunk = newChunk;
1494
+ this.lastSearchedChunk = chunk;
1495
+ return true;
1496
+ }
1497
+ /**
1498
+ * Returns the generated string.
1499
+ */
1500
+ toString() {
1501
+ let str = this.intro;
1502
+ let chunk = this.firstChunk;
1503
+ while (chunk) {
1504
+ str += chunk.toString();
1505
+ chunk = chunk.next;
1506
+ }
1507
+ return str + this.outro;
1508
+ }
1509
+ /**
1510
+ * Returns true if the resulting source is empty (disregarding white space).
1511
+ */
1512
+ isEmpty() {
1513
+ if (this.intro.length && this.intro.trim()) return false;
1514
+ let chunk = this.firstChunk;
1515
+ while (chunk) {
1516
+ if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return false;
1517
+ chunk = chunk.next;
1518
+ }
1519
+ if (this.outro.length && this.outro.trim()) return false;
1520
+ return true;
1521
+ }
1522
+ /**
1523
+ * Returns the length of the generated string, counting only content attached to the original characters.
1524
+ * Content outside the string body (`s.prepend()`/`s.append()`, and inserts before the first or after the last
1525
+ * character) is not counted, so this can differ from `s.toString().length`.
1526
+ */
1527
+ length() {
1528
+ let chunk = this.firstChunk;
1529
+ let length = 0;
1530
+ while (chunk) {
1531
+ length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1532
+ chunk = chunk.next;
1533
+ }
1534
+ return length;
1535
+ }
1536
+ /**
1537
+ * Removes empty lines from the start and end.
1538
+ */
1539
+ trimLines() {
1540
+ return this.trim("[\\r\\n]");
1541
+ }
1542
+ /**
1543
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end.
1544
+ */
1545
+ trim(charType) {
1546
+ return this.trimStart(charType).trimEnd(charType);
1547
+ }
1548
+ /** @internal */
1549
+ trimEndAborted(charType) {
1550
+ const rx = new RegExp(`${charType || "\\s"}+$`);
1551
+ this.outro = this.outro.replace(rx, "");
1552
+ if (this.outro.length) return true;
1553
+ let chunk = this.lastChunk;
1554
+ do {
1555
+ const end = chunk.end;
1556
+ const aborted = chunk.trimEnd(rx);
1557
+ if (chunk.end !== end) {
1558
+ const next = chunk.next;
1559
+ if (this.lastChunk === chunk) this.lastChunk = next;
1560
+ this.byEnd.set(chunk.end, chunk);
1561
+ this.byStart.set(next.start, next);
1562
+ this.byEnd.set(next.end, next);
1563
+ }
1564
+ if (aborted) return true;
1565
+ chunk = chunk.previous;
1566
+ } while (chunk);
1567
+ this.intro = this.intro.replace(rx, "");
1568
+ return this.intro.length > 0;
1569
+ }
1570
+ /**
1571
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end.
1572
+ */
1573
+ trimEnd(charType) {
1574
+ this.trimEndAborted(charType);
1575
+ return this;
1576
+ }
1577
+ /** @internal */
1578
+ trimStartAborted(charType) {
1579
+ const rx = new RegExp(`^${charType || "\\s"}+`);
1580
+ this.intro = this.intro.replace(rx, "");
1581
+ if (this.intro.length) return true;
1582
+ let chunk = this.firstChunk;
1583
+ do {
1584
+ const end = chunk.end;
1585
+ const aborted = chunk.trimStart(rx);
1586
+ if (chunk.end !== end) {
1587
+ const next = chunk.next;
1588
+ if (chunk === this.lastChunk) this.lastChunk = next;
1589
+ this.byEnd.set(chunk.end, chunk);
1590
+ this.byStart.set(next.start, next);
1591
+ this.byEnd.set(next.end, next);
1592
+ }
1593
+ if (aborted) return true;
1594
+ chunk = chunk.next;
1595
+ } while (chunk);
1596
+ this.outro = this.outro.replace(rx, "");
1597
+ return this.outro.length > 0;
1598
+ }
1599
+ /**
1600
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start.
1601
+ */
1602
+ trimStart(charType) {
1603
+ this.trimStartAborted(charType);
1604
+ return this;
1605
+ }
1606
+ /**
1607
+ * Indicates if the string has been changed.
1608
+ */
1609
+ hasChanged() {
1610
+ if (this.intro || this.outro) return true;
1611
+ let outputIndex = 0;
1612
+ let chunk = this.firstChunk;
1613
+ while (chunk) {
1614
+ if (chunk.intro || chunk.outro) return true;
1615
+ if (!chunk.edited && chunk.start === outputIndex) outputIndex = chunk.end;
1616
+ else {
1617
+ if (!this.original.startsWith(chunk.content, outputIndex)) return true;
1618
+ outputIndex += chunk.content.length;
1619
+ }
1620
+ chunk = chunk.next;
1621
+ }
1622
+ return outputIndex !== this.original.length;
1623
+ }
1624
+ /**
1625
+ * Whether the original range [start, end) has had any of its characters
1626
+ * removed. `replace`/`replaceAll` search `original`, so a match can land on
1627
+ * text that is no longer in the output - overwriting it would resurrect the
1628
+ * removed characters, so such matches are skipped instead.
1629
+ *
1630
+ * @internal
1631
+ */
1632
+ _hasRemovedContent(start, end) {
1633
+ const atBoundary = this.byStart.get(start);
1634
+ if (atBoundary && start === end) {
1635
+ const previous = this.byEnd.get(start);
1636
+ return !!previous && previous.content === "" && atBoundary.content === "";
1637
+ }
1638
+ let chunk = this._chunkAt(start);
1639
+ while (chunk && chunk.start < end) {
1640
+ if (chunk.content === "" && (chunk.replacedFrom < start || this.byStart.get(chunk.replacedFrom).replacesUntil < chunk.end)) return true;
1641
+ chunk = this.byStart.get(chunk.end);
1642
+ }
1643
+ return false;
1644
+ }
1645
+ /** @internal */
1646
+ _replaceRegexp(searchValue, replacement) {
1647
+ function getReplacement(match, index, str) {
1648
+ if (typeof replacement === "string") return expandReplacement(replacement, match[0], index, str, match.slice(1), match.groups);
1649
+ else return match.groups === void 0 ? replacement(match[0], ...match.slice(1), index, str) : replacement(match[0], ...match.slice(1), index, str, match.groups);
1650
+ }
1651
+ const replaceMatch = (match) => {
1652
+ /* v8 ignore next 2 -- `match.index` is always defined for matches from `matchAll` */
1653
+ if (match.index == null) return false;
1654
+ if (this._hasRemovedContent(match.index, match.index + match[0].length)) return false;
1655
+ const replacement = getReplacement(match, match.index, this.original);
1656
+ if (replacement === match[0]) return true;
1657
+ if (match[0].length === 0) this.appendRight(match.index - this.offset, replacement);
1658
+ else this.overwrite(match.index - this.offset, match.index + match[0].length - this.offset, replacement);
1659
+ return true;
1660
+ };
1661
+ if (searchValue.global) {
1662
+ searchValue.lastIndex = 0;
1663
+ for (const match of this.original.matchAll(searchValue)) replaceMatch(match);
1664
+ } else {
1665
+ const match = this.original.match(searchValue);
1666
+ if (match && !replaceMatch(match)) {
1667
+ const global = new RegExp(searchValue.source, `${searchValue.flags}g`);
1668
+ for (const next of this.original.matchAll(global)) if (replaceMatch(next)) break;
1669
+ }
1670
+ }
1671
+ return this;
1672
+ }
1673
+ /** @internal */
1674
+ _replaceString(string, replacement) {
1675
+ const { original } = this;
1676
+ let index = original.indexOf(string);
1677
+ while (index !== -1) {
1678
+ if (this._hasRemovedContent(index, index + string.length)) {
1679
+ index = original.indexOf(string, index + string.length);
1680
+ continue;
1681
+ }
1682
+ if (typeof replacement === "function") replacement = replacement(string, index, original);
1683
+ else replacement = expandReplacement(replacement, string, index, original, [], void 0);
1684
+ if (string !== replacement) {
1685
+ if (string.length === 0) this.appendRight(index - this.offset, replacement);
1686
+ else this.overwrite(index - this.offset, index + string.length - this.offset, replacement);
1687
+ }
1688
+ break;
1689
+ }
1690
+ return this;
1691
+ }
1692
+ /**
1693
+ * String replacement with RegExp or string.
1694
+ */
1695
+ replace(searchValue, replacement) {
1696
+ if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
1697
+ return this._replaceRegexp(searchValue, replacement);
1698
+ }
1699
+ /** @internal */
1700
+ _replaceAllString(string, replacement) {
1701
+ const { original } = this;
1702
+ const stringLength = string.length;
1703
+ if (stringLength === 0) {
1704
+ for (let index = 0; index <= original.length; index += 1) {
1705
+ if (this._hasRemovedContent(index, index)) continue;
1706
+ const _replacement = typeof replacement === "function" ? replacement("", index, original) : expandReplacement(replacement, "", index, original, [], void 0);
1707
+ if (_replacement !== "") this.appendRight(index - this.offset, _replacement);
1708
+ }
1709
+ return this;
1710
+ }
1711
+ for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
1712
+ if (this._hasRemovedContent(index, index + stringLength)) continue;
1713
+ const previous = original.slice(index, index + stringLength);
1714
+ const _replacement = typeof replacement === "function" ? replacement(previous, index, original) : expandReplacement(replacement, previous, index, original, [], void 0);
1715
+ if (previous !== _replacement) this.overwrite(index - this.offset, index + stringLength - this.offset, _replacement);
1716
+ }
1717
+ return this;
1718
+ }
1719
+ /**
1720
+ * Same as `s.replace`, but replace all matched strings instead of just one.
1721
+ */
1722
+ replaceAll(searchValue, replacement) {
1723
+ if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement);
1724
+ if (!searchValue.global) throw new MagicStringError("replaceAll() requires a global RegExp");
1725
+ return this._replaceRegexp(searchValue, replacement);
1726
+ }
1727
+ };
1728
+ // ../internal/dist/config-edit.js
1729
+ const viteModule = "vite-hub";
1730
+ const nuxtModule = "vite-hub/nuxt";
1731
+ function fail(reason, at) {
1732
+ if (at === void 0) return {
1733
+ ok: false,
1734
+ reason
1735
+ };
1736
+ return {
1737
+ ok: false,
1738
+ reason,
1739
+ line: typeof at === "number" ? at : line(at)
1740
+ };
1741
+ }
1742
+ function isNuxtFile(file) {
1743
+ return /(?:^|[/\\])nuxt\.config\.[cm]?[jt]s$/.test(file);
1744
+ }
1745
+ function importedNames(program, source, accept) {
1746
+ const names = /* @__PURE__ */ new Set();
1747
+ for (const statement of program.program.body) {
1748
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== source || statement.importKind === "type") continue;
1749
+ for (const specifier of statement.specifiers) {
1750
+ if (specifier.type === "ImportNamespaceSpecifier") continue;
1751
+ if (specifier.type === "ImportSpecifier" && specifier.importKind === "type") continue;
1752
+ if (accept(specifier.type === "ImportDefaultSpecifier" ? void 0 : specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value)) names.add(specifier.local.name);
1753
+ }
1754
+ }
1755
+ return names;
1756
+ }
1757
+ function importedNamespaces(program, source) {
1758
+ const namespaces = /* @__PURE__ */ new Set();
1759
+ for (const statement of program.program.body) {
1760
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== source || statement.importKind === "type") continue;
1761
+ for (const specifier of statement.specifiers) if (specifier.type === "ImportNamespaceSpecifier") namespaces.add(specifier.local.name);
1762
+ }
1763
+ return namespaces;
1764
+ }
1765
+ function defaultExport(program) {
1766
+ const exported = program.program.body.find((statement) => statement.type === "ExportDefaultDeclaration");
1767
+ let declaration = exported?.type === "ExportDefaultDeclaration" ? exported.declaration : void 0;
1768
+ if (!declaration) {
1769
+ const named = program.program.body.flatMap((statement) => statement.type === "ExportNamedDeclaration" && !statement.source && statement.exportKind !== "type" ? statement.specifiers : []).find((specifier) => specifier.type === "ExportSpecifier" && specifier.exportKind !== "type" && keyName(specifier.exported) === "default");
1770
+ if (named?.type === "ExportSpecifier") declaration = named.local;
1771
+ }
1772
+ if (declaration?.type !== "Identifier") return declaration;
1773
+ for (const statement of program.program.body) {
1774
+ const variables = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
1775
+ if (variables?.type !== "VariableDeclaration") continue;
1776
+ for (const declarator of variables.declarations) if (declarator.id.type === "Identifier" && declarator.id.name === declaration.name && declarator.init) return declarator.init;
1777
+ }
1778
+ return declaration;
1779
+ }
1780
+ function unwrap(node) {
1781
+ let current = node;
1782
+ while (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "ParenthesizedExpression" || current.type === "TSNonNullExpression") current = current.expression;
1783
+ return current;
1784
+ }
1785
+ function knownProperty(properties, name) {
1786
+ for (let index = properties.length - 1; index >= 0; index--) {
1787
+ const member = properties[index];
1788
+ if (member.type === "SpreadElement") return;
1789
+ const key = keyName(member.key, member.computed);
1790
+ if (key === void 0) return;
1791
+ if (key === name) return member.type === "ObjectProperty" && !member.shorthand ? unwrap(member.value) : void 0;
1792
+ }
1793
+ }
1794
+ function literalOf(node) {
1795
+ switch (node.type) {
1796
+ case "NullLiteral": return { value: null };
1797
+ case "BooleanLiteral":
1798
+ case "StringLiteral": return { value: node.value };
1799
+ case "NumericLiteral": return { value: node.value };
1800
+ case "TemplateLiteral": {
1801
+ const quasi = node.quasis[0];
1802
+ return node.expressions.length === 0 && quasi?.value.cooked != null ? { value: quasi.value.cooked } : void 0;
1803
+ }
1804
+ case "UnaryExpression":
1805
+ if (node.operator === "-" && node.argument.type === "NumericLiteral") return { value: -node.argument.value };
1806
+ return;
1807
+ case "ArrayExpression": {
1808
+ const items = [];
1809
+ for (const element of node.elements) {
1810
+ const item = element && element.type !== "SpreadElement" ? literalOf(element) : void 0;
1811
+ if (!item) return void 0;
1812
+ items.push(item.value);
1813
+ }
1814
+ return { value: items };
1815
+ }
1816
+ case "ObjectExpression": {
1817
+ const object = {};
1818
+ for (const property of node.properties) {
1819
+ if (property.type !== "ObjectProperty" || property.shorthand) return void 0;
1820
+ const key = keyName(property.key, property.computed);
1821
+ const value = literalOf(property.value);
1822
+ if (key === void 0 || key === "__proto__" || !value) return void 0;
1823
+ object[key] = value.value;
1824
+ }
1825
+ return { value: object };
1826
+ }
1827
+ default: return;
1828
+ }
1829
+ }
1830
+ function readKeys(code, object) {
1831
+ const keys = {};
1832
+ let spread = false;
1833
+ for (const member of object.properties) {
1834
+ if (member.type === "SpreadElement") {
1835
+ spread = true;
1836
+ for (const key of Object.keys(keys)) keys[key] = {
1837
+ kind: "expression",
1838
+ source: code.slice(start(member), end(member)),
1839
+ line: line(member)
1840
+ };
1841
+ continue;
1842
+ }
1843
+ const key = keyName(member.key, member.computed);
1844
+ if (key === void 0) return fail("computed-key", member);
1845
+ const value = member.type === "ObjectProperty" && !member.shorthand ? member.value : member;
1846
+ const literal = member.type === "ObjectProperty" && !member.shorthand ? literalOf(member.value) : void 0;
1847
+ keys[key] = literal ? {
1848
+ kind: "literal",
1849
+ value: literal.value
1850
+ } : {
1851
+ kind: "expression",
1852
+ source: code.slice(start(value), end(value)),
1853
+ line: line(value)
1854
+ };
1855
+ }
1856
+ return {
1857
+ keys,
1858
+ spread
1859
+ };
1860
+ }
1861
+ function siteFor(code, form, options, container, program) {
1862
+ if (!options) return {
1863
+ site: {
1864
+ form,
1865
+ keys: {},
1866
+ spread: false
1867
+ },
1868
+ container,
1869
+ program
1870
+ };
1871
+ const object = unwrap(options);
1872
+ if (object.type !== "ObjectExpression") return fail("dynamic-options", options);
1873
+ const read = readKeys(code, object);
1874
+ if ("ok" in read) return read;
1875
+ return {
1876
+ site: {
1877
+ form,
1878
+ options: {
1879
+ start: start(object),
1880
+ end: end(object)
1881
+ },
1882
+ keys: read.keys,
1883
+ spread: read.spread
1884
+ },
1885
+ object,
1886
+ container,
1887
+ program
1888
+ };
1889
+ }
1890
+ function locateVite(code, program) {
1891
+ const names = importedNames(program, viteModule, (imported) => imported === void 0 || imported === "vitehub");
1892
+ const namespaces = importedNamespaces(program, viteModule);
1893
+ const isViteHubCall = (node) => node.type === "CallExpression" && (node.callee.type === "Identifier" && names.has(node.callee.name) || node.callee.type === "MemberExpression" && node.callee.object.type === "Identifier" && namespaces.has(node.callee.object.name) && keyName(node.callee.property, node.callee.computed) === "vitehub");
1894
+ const root = defaultExport(program);
1895
+ if (!names.size && !namespaces.size || !root) return fail("no-vitehub");
1896
+ const calls = [];
1897
+ let conditional;
1898
+ walk(root, (node, ancestors) => {
1899
+ if (isViteHubCall(node)) {
1900
+ calls.push(node);
1901
+ if (ancestors.some((parent) => parent.type === "ConditionalExpression" || parent.type === "LogicalExpression" || parent.type === "IfStatement" || parent.type === "SwitchCase")) conditional = node;
1902
+ }
1903
+ });
1904
+ if (conditional) return fail("dynamic-options", conditional);
1905
+ const [call, second] = calls;
1906
+ if (!call) {
1907
+ let factored;
1908
+ walk(program, (node) => {
1909
+ if (isViteHubCall(node)) factored = node;
1910
+ });
1911
+ return factored ? fail("dynamic-options", factored) : fail("no-vitehub");
1912
+ }
1913
+ if (second) return fail("multiple-vitehub", second);
1914
+ const argument = call.arguments[0];
1915
+ if (argument && (argument.type === "SpreadElement" || argument.type === "ArgumentPlaceholder")) return fail("dynamic-options", argument);
1916
+ const located = siteFor(code, "vite-call", argument, {
1917
+ kind: "call",
1918
+ node: call
1919
+ }, program);
1920
+ if ("ok" in located) return located;
1921
+ const exported = unwrap(root);
1922
+ const config = exported.type === "CallExpression" && exported.arguments[0] ? unwrap(exported.arguments[0]) : exported;
1923
+ if (config.type !== "ObjectExpression") return {
1924
+ ...located,
1925
+ site: {
1926
+ ...located.site,
1927
+ viteRoot: false
1928
+ }
1929
+ };
1930
+ const keys = readKeys(code, config);
1931
+ const value = "ok" in keys ? void 0 : keys.keys.root;
1932
+ const viteRoot = "ok" in keys || keys.spread || value && (value.kind !== "literal" || typeof value.value !== "string") ? false : value?.value;
1933
+ return {
1934
+ ...located,
1935
+ site: {
1936
+ ...located.site,
1937
+ ...typeof viteRoot === "string" || viteRoot === false ? { viteRoot } : {}
1938
+ }
1939
+ };
1940
+ }
1941
+ function findMember(object, name) {
1942
+ let found;
1943
+ for (const member of object.properties) if (member.type === "ObjectProperty" && keyName(member.key, member.computed) === name) found = member;
1944
+ return found;
1945
+ }
1946
+ function locateNuxt(code, program) {
1947
+ const names = importedNames(program, nuxtModule, () => true);
1948
+ const namespaces = importedNamespaces(program, nuxtModule);
1949
+ let mentioned = names.size > 0 || namespaces.size > 0;
1950
+ walk(program, (node) => {
1951
+ if (node.type === "StringLiteral" && node.value === nuxtModule) mentioned = true;
1952
+ });
1953
+ const exported = defaultExport(program);
1954
+ if (!exported) return fail("no-vitehub");
1955
+ let root = unwrap(exported);
1956
+ if (root.type === "CallExpression" && root.arguments[0]) root = unwrap(root.arguments[0]);
1957
+ if (root.type !== "ObjectExpression") return fail("dynamic-options", root);
1958
+ const nuxt = readKeys(code, root);
1959
+ if ("ok" in nuxt) return nuxt;
1960
+ if (!mentioned) {
1961
+ const extended = nuxt.keys.extends;
1962
+ if (extended && !(extended.kind === "literal" && Array.isArray(extended.value) && extended.value.length === 0)) return fail("dynamic-options", root);
1963
+ return fail("no-vitehub");
1964
+ }
1965
+ const located = locateNuxtOptions(code, program, root, names, namespaces);
1966
+ return "ok" in located ? located : {
1967
+ ...located,
1968
+ site: {
1969
+ ...located.site,
1970
+ nuxt
1971
+ }
1972
+ };
1973
+ }
1974
+ function locateNuxtOptions(code, program, root, names, namespaces) {
1975
+ const modulesProperty = findMember(root, "modules");
1976
+ const keyProperty = findMember(root, "vitehub");
1977
+ const lastSpread = root.properties.findLast((member) => member.type === "SpreadElement");
1978
+ if (lastSpread && [modulesProperty, keyProperty].some((property) => !property || start(property) < start(lastSpread))) return fail("spread", lastSpread);
1979
+ if (!modulesProperty) return fail("no-vitehub");
1980
+ const modules = unwrap(modulesProperty.value);
1981
+ if (modules.type !== "ArrayExpression") return fail("dynamic-options", modules);
1982
+ const dynamicEntry = modules.elements.find((element) => element?.type === "SpreadElement" || element?.type === "ConditionalExpression" || element?.type === "LogicalExpression");
1983
+ if (dynamicEntry) return fail("dynamic-options", dynamicEntry);
1984
+ const isHead = (node) => Boolean(node && (node.type === "StringLiteral" && node.value === nuxtModule || node.type === "Identifier" && names.has(node.name) || node.type === "MemberExpression" && node.object.type === "Identifier" && namespaces.has(node.object.name) && keyName(node.property, node.computed) === "default"));
1985
+ const [entry, second] = modules.elements.filter((element) => {
1986
+ if (!element || element.type === "SpreadElement") return false;
1987
+ return element.type === "ArrayExpression" ? isHead(element.elements[0]) : isHead(element);
1988
+ });
1989
+ if (!entry) return fail("no-vitehub");
1990
+ if (second) return fail("multiple-vitehub", second);
1991
+ const tupleOptions = entry.type === "ArrayExpression" ? entry.elements[1] : void 0;
1992
+ if (tupleOptions && tupleOptions.type === "SpreadElement") return fail("dynamic-options", tupleOptions);
1993
+ if (keyProperty && !tupleOptions) return siteFor(code, "nuxt-config-key", keyProperty.value, { kind: "key" }, program);
1994
+ const container = entry.type === "ArrayExpression" ? {
1995
+ kind: "tuple",
1996
+ node: entry,
1997
+ head: entry.elements[0] ?? entry
1998
+ } : {
1999
+ kind: "bare",
2000
+ node: entry
2001
+ };
2002
+ const located = siteFor(code, "nuxt-module-tuple", tupleOptions ?? void 0, container, program);
2003
+ if ("ok" in located || !keyProperty) return located;
2004
+ const defaults = siteFor(code, "nuxt-config-key", keyProperty.value, { kind: "key" }, program);
2005
+ if ("ok" in defaults) return defaults;
2006
+ const merged = readKeys(code, { properties: [...defaults.object?.properties ?? [], ...located.object?.properties ?? []] });
2007
+ if ("ok" in merged) return merged;
2008
+ return {
2009
+ ...located,
2010
+ defaults,
2011
+ site: {
2012
+ ...located.site,
2013
+ ...merged
2014
+ }
2015
+ };
2016
+ }
2017
+ function parse$3(code) {
2018
+ try {
2019
+ return parseProgram(code);
2020
+ } catch (error) {
2021
+ return fail("parse-error", typeof error === "object" && error !== null && "loc" in error && typeof error.loc === "object" && error.loc !== null && "line" in error.loc && typeof error.loc.line === "number" ? error.loc.line : void 0);
2022
+ }
2023
+ }
2024
+ function locate(file, code) {
2025
+ const program = parse$3(code);
2026
+ if ("ok" in program) return program;
2027
+ let commonjs;
2028
+ walk(program, (node) => {
2029
+ if (node.type !== "AssignmentExpression" || node.left.type !== "MemberExpression") return;
2030
+ const { object, property, computed } = node.left;
2031
+ if (object.type === "Identifier" && object.name === "module" && keyName(property, computed) === "exports") commonjs = node;
2032
+ });
2033
+ if (commonjs) return fail("dynamic-options", commonjs);
2034
+ return isNuxtFile(file) ? locateNuxt(code, program) : locateVite(code, program);
2035
+ }
2036
+ /** Finds the ViteHub options in a `vite.config` or `nuxt.config` file without evaluating it. */
2037
+ function locateViteHubConfig(file, code) {
2038
+ const located = locate(file, code);
2039
+ if ("ok" in located) return located;
2040
+ const options = knownProperty([...located.defaults?.object?.properties ?? [], ...located.object?.properties ?? []], "console");
2041
+ const url = options?.type === "ObjectExpression" ? knownProperty(options.properties, "url") : void 0;
2042
+ const value = url && literalOf(url)?.value;
2043
+ return {
2044
+ ok: true,
2045
+ site: typeof value === "string" ? {
2046
+ ...located.site,
2047
+ consoleUrl: value
2048
+ } : located.site
2049
+ };
2050
+ }
2051
+ function propertyKey(name, style) {
2052
+ if (name === "__proto__") return `[${quoteString(name, style)}]`;
2053
+ return /^[A-Za-z_$][\w$]*$/.test(name) ? name : quoteString(name, style);
2054
+ }
2055
+ function serialize(value, style) {
2056
+ if (value === null) return "null";
2057
+ if (typeof value === "string") return quoteString(value, style);
2058
+ if (typeof value === "number") {
2059
+ invariant(Number.isFinite(value), `ViteHub writes only finite numbers to a config file (${value})`);
2060
+ return Object.is(value, -0) ? "0" : String(value);
2061
+ }
2062
+ if (typeof value === "boolean") return String(value);
2063
+ if (isArray(value)) return `[${value.map((item) => serialize(item, style)).join(", ")}]`;
2064
+ const entries = Object.entries(value);
2065
+ if (!entries.length) return "{}";
2066
+ return `{ ${entries.map(([key, item]) => `${propertyKey(key, style)}: ${serialize(item, style)}`).join(", ")} }`;
2067
+ }
2068
+ function isArray(value) {
2069
+ return Array.isArray(value);
2070
+ }
2071
+ function lineBreakAfter(code, position) {
2072
+ const index = code.indexOf("\n", position);
2073
+ if (index === -1) return code.length;
2074
+ return code[index - 1] === "\r" ? index - 1 : index;
2075
+ }
2076
+ function skipBlanks(code, position) {
2077
+ let cursor = position;
2078
+ while (cursor < code.length && /[ \t]/.test(code[cursor] ?? "")) cursor++;
2079
+ return cursor;
2080
+ }
2081
+ function appendMember(output, code, object, text, style) {
2082
+ appendItem(output, code, object, object.properties.at(-1), text, style, " ");
2083
+ }
2084
+ function appendItem(output, code, list, last, text, style, pad) {
2085
+ const closing = end(list) - 1;
2086
+ if (!last) {
2087
+ const inner = code.slice(start(list) + 1, closing);
2088
+ if (!inner) output.appendLeft(closing, `${pad}${text}${pad}`);
2089
+ else if (/^\s*$/.test(inner)) output.overwrite(start(list) + 1, closing, `${pad}${text}${pad}`);
2090
+ else output.appendLeft(start(list) + 1, `${pad}${text},`);
2091
+ return;
2092
+ }
2093
+ const afterLast = skipBlanks(code, end(last));
2094
+ const trailing = code[afterLast] === ",";
2095
+ const afterComma = trailing ? afterLast + 1 : end(last);
2096
+ const lineBreak = lineBreakAfter(code, afterComma);
2097
+ if (lineBreak >= closing) {
2098
+ output.appendLeft(afterComma, trailing ? ` ${text},` : `, ${text}`);
2099
+ return;
2100
+ }
2101
+ const newline = code.includes("\r\n") ? "\r\n" : "\n";
2102
+ if (!trailing) output.appendLeft(end(last), ",");
2103
+ output.appendLeft(lineBreak, `${newline}${indentAt(code, start(last)) || style.indent}${text}${trailing ? "," : ""}`);
2104
+ }
2105
+ function removeMember(output, code, object, member) {
2106
+ const index = object.properties.indexOf(member);
2107
+ const previous = index > 0 ? object.properties[index - 1] : void 0;
2108
+ const [from, to] = listItemRemoval(code, previous ? {
2109
+ ...member,
2110
+ leadingComments: (member.leadingComments ?? []).filter((comment) => (comment.start ?? 0) > lineBreakAfter(code, end(previous)))
2111
+ } : member);
2112
+ output.remove(from, to);
2113
+ if (index === object.properties.length - 1 && previous && code[from] !== "," && code[skipBlanks(code, end(member))] !== ",") {
2114
+ const comma = skipBlanks(code, end(previous));
2115
+ if (code[comma] === ",") output.remove(comma, comma + 1);
2116
+ }
2117
+ }
2118
+ function sameValue(left, right) {
2119
+ if (!left || !right || left.kind !== right.kind) return false;
2120
+ if (left.kind === "expression" && right.kind === "expression") return left.source === right.source;
2121
+ return left.kind === "literal" && right.kind === "literal" && JSON.stringify(left.value) === JSON.stringify(right.value);
2122
+ }
2123
+ function sameKeys(actual, expected) {
2124
+ const names = Object.keys(expected);
2125
+ if (Object.keys(actual).length !== names.length) return false;
2126
+ return names.every((name) => sameValue(actual[name], expected[name]));
2127
+ }
2128
+ function applyEdit(code, located, edit) {
2129
+ const { site, object, container } = located;
2130
+ const style = detectStyle(code, located.program);
2131
+ const output = new MagicString(code);
2132
+ const members = object?.properties ?? [];
2133
+ const matches = members.filter((member) => member.type !== "SpreadElement" && keyName(member.key, member.computed) === edit.key);
2134
+ if (edit.op === "delete") {
2135
+ if (site.spread) return fail("spread", object);
2136
+ if (!matches.length) return code;
2137
+ if (!object) return code;
2138
+ if (matches.length === members.length) {
2139
+ if (located.program.comments?.some((comment) => {
2140
+ const from = comment.start ?? -1;
2141
+ const to = comment.end ?? -1;
2142
+ return from > start(object) && to < end(object) && !matches.some((member) => from >= start(member) && to <= end(member));
2143
+ })) {
2144
+ for (const member of matches) {
2145
+ let from = start(member);
2146
+ let to = end(member);
2147
+ const comma = skipBlanks(code, to);
2148
+ if (code[comma] === ",") {
2149
+ to = comma + 1;
2150
+ if (code.slice(start(object) + 1, from) === " ") from = start(object) + 1;
2151
+ }
2152
+ output.remove(from, to);
2153
+ }
2154
+ return output.toString();
2155
+ }
2156
+ if (container.kind === "call") {
2157
+ const argument = container.node.arguments[0];
2158
+ const next = container.node.arguments[1];
2159
+ if (argument) output.remove(start(argument), next ? start(next) : end(container.node) - 1);
2160
+ } else if (container.kind === "tuple") output.overwrite(start(container.node), end(container.node), code.slice(start(container.head), end(container.head)));
2161
+ else output.remove(start(object) + 1, end(object) - 1);
2162
+ return output.toString();
2163
+ }
2164
+ for (const match of matches) removeMember(output, code, object, match);
2165
+ return output.toString();
2166
+ }
2167
+ const text = `${propertyKey(edit.key, style)}: ${serialize(edit.value, style)}`;
2168
+ if (!object) {
2169
+ if (container.kind === "call") output.appendLeft(end(container.node) - 1, `{ ${text} }`);
2170
+ else if (container.kind === "tuple") output.appendLeft(end(container.head), `, { ${text} }`);
2171
+ else if (container.kind === "bare") output.overwrite(start(container.node), end(container.node), `[${code.slice(start(container.node), end(container.node))}, { ${text} }]`);
2172
+ return output.toString();
2173
+ }
2174
+ const match = matches.at(-1);
2175
+ const lastSpread = members.findLastIndex((member) => member.type === "SpreadElement");
2176
+ if (match && members.indexOf(match) > lastSpread) {
2177
+ if (match.type === "ObjectProperty" && !match.shorthand) output.overwrite(start(match.value), end(match.value), serialize(edit.value, style));
2178
+ else output.overwrite(start(match), end(match), text);
2179
+ return output.toString();
2180
+ }
2181
+ for (const old of matches) removeMember(output, code, object, old);
2182
+ appendMember(output, code, object, text, style);
2183
+ return output.toString();
2184
+ }
2185
+ /** Sets or deletes top-level ViteHub options. Edits only the options and keeps the rest of the file byte for byte. */
2186
+ function editViteHubConfig(file, code, edits) {
2187
+ let current = code;
2188
+ for (const edit of edits) {
2189
+ let located = locate(file, current);
2190
+ if ("ok" in located) return located;
2191
+ const expected = { ...located.site.keys };
2192
+ if (edit.op === "set") expected[edit.key] = {
2193
+ kind: "literal",
2194
+ value: edit.value
2195
+ };
2196
+ else delete expected[edit.key];
2197
+ if (edit.op === "delete" && located.defaults) {
2198
+ const next = applyEdit(current, located.defaults, edit);
2199
+ if (typeof next !== "string") return next;
2200
+ current = next;
2201
+ located = locate(file, current);
2202
+ if ("ok" in located) return located;
2203
+ }
2204
+ const next = applyEdit(current, located, edit);
2205
+ if (typeof next !== "string") return next;
2206
+ const after = locate(file, next);
2207
+ if ("ok" in after || !sameKeys(after.site.keys, expected)) return fail("parse-error");
2208
+ current = next;
2209
+ }
2210
+ return {
2211
+ ok: true,
2212
+ code: current
2213
+ };
2214
+ }
2215
+ /**
2216
+ * Registers ViteHub with `options` in a config that has no ViteHub yet: `vitehub()` in the Vite `plugins`, or the
2217
+ * `[viteHubNuxt, options]` tuple in the Nuxt `modules`, and the import. Keeps the rest of the file byte for byte.
2218
+ * A config that already registers ViteHub comes back unchanged.
2219
+ */
2220
+ function insertViteHubConfig(file, code, options) {
2221
+ const located = locate(file, code);
2222
+ if (!("ok" in located)) return {
2223
+ ok: true,
2224
+ code
2225
+ };
2226
+ if (located.reason !== "no-vitehub") return located;
2227
+ const program = parse$3(code);
2228
+ if ("ok" in program) return program;
2229
+ const exported = defaultExport(program);
2230
+ if (!exported) return fail("no-vitehub");
2231
+ let root = unwrap(exported);
2232
+ if (root.type === "CallExpression" && root.arguments[0]) root = unwrap(root.arguments[0]);
2233
+ if (root.type !== "ObjectExpression") return fail("dynamic-options", root);
2234
+ const nuxt = isNuxtFile(file);
2235
+ const style = detectStyle(code, program);
2236
+ const source = nuxt ? nuxtModule : viteModule;
2237
+ const imported = importedNames(program, source, (name) => nuxt ? name === void 0 : name === "vitehub");
2238
+ const local = [...imported][0] ?? (nuxt ? "viteHubNuxt" : "vitehub");
2239
+ const item = nuxt ? `[${local}, ${serialize(options, style)}]` : `${local}(${serialize(options, style)})`;
2240
+ const key = nuxt ? "modules" : "plugins";
2241
+ const output = new MagicString(code);
2242
+ const property = findMember(root, key);
2243
+ if (property) {
2244
+ for (const member of root.properties.slice(root.properties.indexOf(property) + 1)) {
2245
+ if (member.type === "SpreadElement") return fail("spread", member);
2246
+ const name = keyName(member.key, member.computed);
2247
+ if (name === void 0) return fail("computed-key", member);
2248
+ if (name === key) return fail("dynamic-options", member);
2249
+ }
2250
+ const list = unwrap(property.value);
2251
+ if (list.type !== "ArrayExpression") return fail("dynamic-options", list);
2252
+ appendItem(output, code, list, list.elements.findLast((element) => element !== null) ?? void 0, item, style, "");
2253
+ } else appendMember(output, code, root, `${key}: [${item}]`, style);
2254
+ if (!imported.size) {
2255
+ const semicolon = style.semicolons ? ";" : "";
2256
+ const statement = nuxt ? `import ${local} from ${quoteString(source, style)}${semicolon}` : `import { ${local} } from ${quoteString(source, style)}${semicolon}`;
2257
+ const lastImport = program.program.body.filter((node) => node.type === "ImportDeclaration").at(-1);
2258
+ if (lastImport) output.appendLeft(end(lastImport), `${code.includes("\r\n") ? "\r\n" : "\n"}${statement}`);
2259
+ else output.prepend(`${statement}\n\n`);
2260
+ }
2261
+ const next = output.toString();
2262
+ const after = locate(file, next);
2263
+ if ("ok" in after || !sameKeys(after.site.keys, Object.fromEntries(Object.entries(options).map(([name, value]) => [name, {
2264
+ kind: "literal",
2265
+ value
2266
+ }])))) return fail("parse-error");
2267
+ return {
2268
+ ok: true,
2269
+ code: next
2270
+ };
2271
+ }
2272
+ // src/setup/project.ts
2273
+ /**
2274
+ * The Nuxt releases that a `nuxt` range allows, as a semver range. A Nuxt 5 nightly counts as its release, so
2275
+ * `npm:nuxt-nightly@5.0.0-2611071848-2d8337c` is `5.0.0`. The `5x` channel tag of `nuxt-nightly` is `5.x`.
2276
+ * `undefined` for another tag or a range without a version.
2277
+ */
2278
+ function nuxtReleases(nuxt) {
2279
+ if (typeof nuxt !== "string") return void 0;
2280
+ const range = validRange(nuxt.replace(/^npm:nuxt-nightly@(\d+)x$/u, "$1.x").replace(/^npm:nuxt(?:-nightly)?@/u, ""));
2281
+ if (!range || !minVersion(range)) return void 0;
2282
+ return new Range(range).set.map((comparators) => comparators.map(({ operator, semver, value }) => typeof semver !== "symbol" && semver.major === 5 && semver.prerelease.length > 0 ? `${operator}5.${semver.minor}.${semver.patch}` : value).join(" ")).join(" || ");
2283
+ }
2284
+ /** True when a `nuxt` range allows only Nuxt 5, so `vitehub init --nuxt-nightly` creates the same app. */
2285
+ function declaresNuxt5(nuxt) {
2286
+ const releases = nuxtReleases(nuxt);
2287
+ return !!releases && subset(releases, ">=5.0.0 <6.0.0");
2288
+ }
2289
+ const nuxtConfigFiles = [
2290
+ "nuxt.config.ts",
2291
+ "nuxt.config.mts",
2292
+ "nuxt.config.js",
2293
+ "nuxt.config.mjs",
2294
+ "nuxt.config.cts",
2295
+ "nuxt.config.cjs"
2296
+ ];
2297
+ const viteConfigFiles = [
2298
+ "vite.config.ts",
2299
+ "vite.config.mts",
2300
+ "vite.config.js",
2301
+ "vite.config.mjs",
2302
+ "vite.config.cts",
2303
+ "vite.config.cjs"
2304
+ ];
2305
+ /** The lockfiles and workspace files that name a package manager, in the order that detection reads them. */
2306
+ const setupLockfiles = [
2307
+ ["pnpm-lock.yaml", "pnpm"],
2308
+ ["pnpm-workspace.yaml", "pnpm"],
2309
+ ["bun.lock", "bun"],
2310
+ ["bun.lockb", "bun"],
2311
+ ["yarn.lock", "yarn"],
2312
+ ["package-lock.json", "npm"],
2313
+ ["npm-shrinkwrap.json", "npm"]
2314
+ ];
2315
+ function parentFolders(root) {
2316
+ const folders = [root];
2317
+ for (let folder = dirname(root); folder !== folders.at(-1); folder = dirname(folder)) folders.push(folder);
2318
+ return folders;
2319
+ }
2320
+ function pnpmWorkspaceFile(root) {
2321
+ return parentFolders(root).map((folder) => join(folder, "pnpm-workspace.yaml")).find(existsSync);
2322
+ }
2323
+ async function resolveNuxtSpecifier(root, specifier) {
2324
+ if (typeof specifier !== "string") return void 0;
2325
+ if (!specifier.startsWith("catalog:")) return specifier;
2326
+ const file = pnpmWorkspaceFile(root);
2327
+ if (!file) return void 0;
2328
+ const workspace = parseDocument(await readFile(file, "utf8"));
2329
+ if (workspace.errors.length) return void 0;
2330
+ const catalog = specifier.slice(8);
2331
+ const entry = workspace.getIn(catalog && catalog !== "default" ? [
2332
+ "catalogs",
2333
+ catalog,
2334
+ "nuxt"
2335
+ ] : ["catalog", "nuxt"]);
2336
+ return typeof entry === "string" ? entry : void 0;
2337
+ }
2338
+ async function readManifest(root) {
2339
+ const file = join(root, "package.json");
2340
+ if (!existsSync(file)) return;
2341
+ const value = JSON.parse(await readFile(file, "utf8"));
2342
+ return value && typeof value === "object" ? value : {};
2343
+ }
2344
+ function packageManagerName(value) {
2345
+ const name = value?.trim().split(/[@/ ]/u)[0];
2346
+ return name === "pnpm" || name === "npm" || name === "yarn" || name === "bun" ? name : void 0;
2347
+ }
2348
+ /** `packageManager` in package.json, then a lockfile in `root` or a parent folder, then the user agent, then npm. */
2349
+ function detectPackageManager(root, manifest, env) {
2350
+ const declared = packageManagerName(manifest?.packageManager);
2351
+ if (declared) return {
2352
+ packageManager: declared,
2353
+ packageManagerSource: "manifest"
2354
+ };
2355
+ for (const folder of parentFolders(root)) {
2356
+ const found = setupLockfiles.find(([file]) => existsSync(join(folder, file)));
2357
+ if (found) return {
2358
+ packageManager: found[1],
2359
+ packageManagerSource: "lockfile"
2360
+ };
2361
+ }
2362
+ const agent = packageManagerName(env.npm_config_user_agent);
2363
+ return agent ? {
2364
+ packageManager: agent,
2365
+ packageManagerSource: "user-agent"
2366
+ } : {
2367
+ packageManager: "npm",
2368
+ packageManagerSource: "default"
2369
+ };
2370
+ }
2371
+ const nuxtLayerKeys = [
2372
+ "extends",
2373
+ "_extends",
2374
+ "theme",
2375
+ "_layers"
2376
+ ];
2377
+ function nuxtDirectoryOverride(value) {
2378
+ return value !== null && typeof value === "object" && [
2379
+ "rootDir",
2380
+ "serverDir",
2381
+ ...nuxtLayerKeys
2382
+ ].some((key) => Object.hasOwn(value, key));
2383
+ }
2384
+ async function nuxtRcAllowsStaticDiscovery(folder) {
2385
+ const file = join(folder, ".nuxtrc");
2386
+ try {
2387
+ if (!(await stat(file)).isFile()) return false;
2388
+ return !nuxtDirectoryOverride(parse$2(await readFile(file, "utf8")));
2389
+ } catch (error) {
2390
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
2391
+ }
2392
+ }
2393
+ async function nuxtServerDirs(root, config, env) {
2394
+ const nuxt = config?.ok ? config.site.nuxt : void 0;
2395
+ if (!nuxt || nuxt.spread) return;
2396
+ for (const key of nuxtLayerKeys) {
2397
+ const layer = nuxt.keys[key];
2398
+ if (layer && !(layer.kind === "literal" && Array.isArray(layer.value) && layer.value.length === 0)) return;
2399
+ }
2400
+ for (const [key, override] of Object.entries(nuxt.keys)) {
2401
+ if (!key.startsWith("$") || key === "$meta") continue;
2402
+ if (override.kind === "expression") return;
2403
+ if (key === "$env") {
2404
+ if (override.value !== null && typeof override.value === "object" && Object.values(override.value).some(nuxtDirectoryOverride)) return;
2405
+ } else if (nuxtDirectoryOverride(override.value)) return;
2406
+ }
2407
+ if (existsSync(join(root, "layers"))) return;
2408
+ const rootDir = nuxt.keys.rootDir;
2409
+ const serverDir = nuxt.keys.serverDir;
2410
+ if (rootDir && (rootDir.kind !== "literal" || typeof rootDir.value !== "string")) return;
2411
+ if (serverDir && (serverDir.kind !== "literal" || typeof serverDir.value !== "string")) return;
2412
+ const appRoot = rootDir?.kind === "literal" && typeof rootDir.value === "string" ? resolve(root, rootDir.value) : root;
2413
+ if (existsSync(join(appRoot, "layers"))) return;
2414
+ const home = homedir();
2415
+ for (const folder of /* @__PURE__ */ new Set([
2416
+ ...parentFolders(root),
2417
+ home,
2418
+ env.XDG_CONFIG_HOME || join(home, ".config")
2419
+ ])) if (!await nuxtRcAllowsStaticDiscovery(folder)) return;
2420
+ return [resolve(appRoot, serverDir?.kind === "literal" && typeof serverDir.value === "string" ? serverDir.value || "server" : "server")];
2421
+ }
2422
+ function globalPackageDirs(name) {
2423
+ return (process$1.env.NODE_PATH ?? "").split(delimiter).filter(Boolean).flatMap((dir) => {
2424
+ try {
2425
+ return [realpathSync(join(dir, name))];
2426
+ } catch {
2427
+ return [];
2428
+ }
2429
+ });
2430
+ }
2431
+ /**
2432
+ * Reads the project in `root` without loading its config: the config file is parsed, never run.
2433
+ * Throws `SETUP_NOT_A_PROJECT` when `root` has no package.json and no Vite or Nuxt config.
2434
+ */
2435
+ async function readSetupProject(root, env) {
2436
+ root = resolve(root);
2437
+ const manifest = await readManifest(root);
2438
+ const dependencies = {
2439
+ ...manifest?.devDependencies,
2440
+ ...manifest?.dependencies
2441
+ };
2442
+ const nuxtConfig = nuxtConfigFiles.find((file) => existsSync(join(root, file)));
2443
+ const viteConfig = viteConfigFiles.find((file) => existsSync(join(root, file)));
2444
+ if (!manifest && !nuxtConfig && !viteConfig) throw cliErrorDiagnostics.SETUP_NOT_A_PROJECT({ root });
2445
+ const framework = nuxtConfig || dependencies.nuxt ? "nuxt" : viteConfig || dependencies.vite ? "vite" : "none";
2446
+ const configFile = framework === "nuxt" ? nuxtConfig : viteConfig;
2447
+ const configSource = configFile ? await readFile(join(root, configFile), "utf8") : void 0;
2448
+ let config = configFile && configSource !== void 0 ? locateViteHubConfig(configFile, configSource) : void 0;
2449
+ if (framework === "nuxt" && (!config || !config.ok && config.reason === "no-vitehub") && existsSync(join(root, "layers"))) config = {
2450
+ ok: false,
2451
+ reason: "dynamic-options"
2452
+ };
2453
+ const folders = parentFolders(root);
2454
+ const require = createRequire(join(root, "package.json"));
2455
+ const nuxt = await resolveNuxtSpecifier(root, dependencies.nuxt);
2456
+ return {
2457
+ config,
2458
+ ...configFile ? {
2459
+ configFile,
2460
+ configSource
2461
+ } : {},
2462
+ framework,
2463
+ declared: (name, dev) => Object.hasOwn(manifest?.dependencies ?? {}, name) || dev && Object.hasOwn(manifest?.devDependencies ?? {}, name),
2464
+ installed: (name) => {
2465
+ if (folders.some((folder) => existsSync(join(folder, "node_modules", name, "package.json")))) return true;
2466
+ const globalCopies = globalPackageDirs(name);
2467
+ for (const specifier of [`${name}/package.json`, name]) try {
2468
+ const file = realpathSync(require.resolve(specifier));
2469
+ if (!globalCopies.some((dir) => file.startsWith(`${dir}${sep}`))) return true;
2470
+ } catch {}
2471
+ return false;
2472
+ },
2473
+ ...detectPackageManager(root, manifest, env),
2474
+ ...nuxt === void 0 ? {} : { nuxt },
2475
+ root,
2476
+ serverDirs: framework === "nuxt" ? await nuxtServerDirs(root, config, env) : [join(root, "server")]
2477
+ };
2478
+ }
2479
+ // src/setup/console-auth.ts
2480
+ var console_auth_exports = /* @__PURE__ */ __exportAll({
2481
+ consoleCredentialsFile: () => consoleCredentialsFile,
2482
+ consoleOrigin: () => consoleOrigin,
2483
+ consoleTokenVariable: () => consoleTokenVariable,
2484
+ consoleUrlVariable: () => consoleUrlVariable,
2485
+ defaultConsoleUrl: () => defaultConsoleUrl,
2486
+ loginCommand: () => loginCommand,
2487
+ logoutCommand: () => logoutCommand,
2488
+ readConsoleCredential: () => readConsoleCredential,
2489
+ selectConsole: () => selectConsole,
2490
+ whoamiCommand: () => whoamiCommand
2491
+ });
2492
+ /** The hosted Console. `--console`, `VITEHUB_CONSOLE_URL`, and `vitehub({ console: { url } })` name a self-hosted one. */
2493
+ const defaultConsoleUrl = "https://console.vitehub.dev";
2494
+ /** An API key for CI. It wins over the saved key for its origin, and `vitehub logout` does not remove it. */
2495
+ const consoleTokenVariable = "VITEHUB_CONSOLE_TOKEN";
2496
+ const consoleUrlVariable = "VITEHUB_CONSOLE_URL";
2497
+ const clientId = "vitehub-cli";
2498
+ /** `$XDG_CONFIG_HOME/vitehub/credentials.json`, else `~/.config/vitehub/credentials.json`. */
2499
+ function consoleCredentialsFile(env) {
2500
+ const base = env.XDG_CONFIG_HOME || join$1(env.HOME || env.USERPROFILE || homedir(), ".config");
2501
+ return join$1(base, "vitehub", "credentials.json");
2502
+ }
2503
+ async function readCredentials(file, signal) {
2504
+ const text = await readFile(file, {
2505
+ encoding: "utf8",
2506
+ signal
2507
+ }).catch((error) => {
2508
+ if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") return void 0;
2509
+ throw error;
2510
+ });
2511
+ if (text === void 0) return {
2512
+ version: 1,
2513
+ consoles: {}
2514
+ };
2515
+ const parsed = JSON.parse(text);
2516
+ const consoles = parsed instanceof Object ? Reflect.get(parsed, "consoles") : void 0;
2517
+ return {
2518
+ version: 1,
2519
+ consoles: consoles instanceof Object ? consoles : {}
2520
+ };
2521
+ }
2522
+ async function writeCredentials(file, value) {
2523
+ await mkdir(dirname$1(file), {
2524
+ mode: 448,
2525
+ recursive: true
2526
+ });
2527
+ const temporary = `${file}.${process.pid}.tmp`;
2528
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 384 });
2529
+ await chmod(temporary, 384);
2530
+ await rename(temporary, file);
2531
+ }
2532
+ /** The origin of a Console URL. Plain `http` is accepted only for a Console on this machine. */
2533
+ function consoleOrigin(value) {
2534
+ let url;
2535
+ try {
2536
+ url = new URL(value);
2537
+ } catch {
2538
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --console must be a URL, such as ${defaultConsoleUrl}. Got ${JSON.stringify(value)}.` });
2539
+ }
2540
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
2541
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --console must be an https:// URL. Plain http:// is only for a Console on localhost. Got ${url.origin}.` });
2542
+ return url.origin;
2543
+ }
2544
+ async function appConsole(context) {
2545
+ const project = await readSetupProject(context.cwd, context.env).catch(() => void 0);
2546
+ return project?.config?.ok ? project.config.site.consoleUrl : void 0;
2547
+ }
2548
+ async function selectConsole(context, flag, signal) {
2549
+ const explicit = flag ?? context.env["VITEHUB_CONSOLE_URL"];
2550
+ return resolveConsole(context.env, explicit, explicit === void 0 ? await appConsole(context) : void 0, signal);
2551
+ }
2552
+ /** Reads the key for an explicit Console or the saved-login fallback, without consulting app config. */
2553
+ async function readConsoleCredential(env, console, signal) {
2554
+ return (await resolveConsole(env, console ?? env["VITEHUB_CONSOLE_URL"], void 0, signal)).credential;
2555
+ }
2556
+ async function resolveConsole(env, explicit, app, signal) {
2557
+ const file = await readCredentials(consoleCredentialsFile(env), signal);
2558
+ const saved = Object.keys(file.consoles);
2559
+ const origin = consoleOrigin(explicit ?? app ?? (saved.length === 1 ? saved[0] : "https://console.vitehub.dev"));
2560
+ const token = env[consoleTokenVariable];
2561
+ if (token && (explicit !== void 0 || origin === "https://console.vitehub.dev")) return {
2562
+ origin,
2563
+ credential: {
2564
+ origin,
2565
+ source: "env",
2566
+ token
2567
+ }
2568
+ };
2569
+ const credential = file.consoles[origin];
2570
+ return credential ? {
2571
+ origin,
2572
+ credential: {
2573
+ origin,
2574
+ saved: credential,
2575
+ source: "file",
2576
+ token: credential.token
2577
+ }
2578
+ } : { origin };
2579
+ }
2580
+ function readArgs(args, usage, extra = {}) {
2581
+ try {
2582
+ return parseArgs({
2583
+ args,
2584
+ options: {
2585
+ ...extra.console ? { console: { type: "string" } } : {},
2586
+ help: {
2587
+ short: "h",
2588
+ type: "boolean",
2589
+ default: false
2590
+ },
2591
+ json: {
2592
+ type: "boolean",
2593
+ default: false
2594
+ }
2595
+ },
2596
+ strict: true
2597
+ }).values;
2598
+ } catch (error) {
2599
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage}` });
2600
+ }
2601
+ }
2602
+ async function postJson(context, url, body) {
2603
+ const response = await (context.fetch ?? fetch)(url, {
2604
+ body: JSON.stringify(body),
2605
+ headers: {
2606
+ accept: "application/json",
2607
+ "content-type": "application/json"
2608
+ },
2609
+ method: "POST"
2610
+ });
2611
+ const data = await response.json().catch(() => ({}));
2612
+ return {
2613
+ data: data instanceof Object ? data : {},
2614
+ headers: response.headers,
2615
+ status: response.status
2616
+ };
2617
+ }
2618
+ function loginFailed(origin, message) {
2619
+ return cliErrorDiagnostics.CLI_CONSOLE_LOGIN_FAILED({
2620
+ console: origin,
2621
+ message
2622
+ });
2623
+ }
2624
+ const wait = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
2625
+ const dateFormat = new Intl.DateTimeFormat("en-GB", {
2626
+ day: "numeric",
2627
+ month: "short",
2628
+ year: "numeric",
2629
+ timeZone: "UTC"
2630
+ });
2631
+ function groupCode(code) {
2632
+ return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
2633
+ }
2634
+ async function deviceLogin(origin, context, prompt) {
2635
+ const started = await postJson(context, `${origin}/api/auth/device/code`, {
2636
+ client_id: clientId,
2637
+ client_name: `vitehub CLI on ${hostname()}`
2638
+ }).catch((error) => {
2639
+ throw loginFailed(origin, `The Console did not answer: ${error instanceof Error ? error.message : String(error)}`);
2640
+ });
2641
+ if (started.status !== 200 || typeof started.data.device_code !== "string") throw loginFailed(origin, `The Console answered ${started.status} to the device code request${typeof started.data.error === "string" ? ` (${started.data.error})` : ""}. Is ${origin} a ViteHub Console?`);
2642
+ const code = started.data;
2643
+ prompt.write(`Open ${code.verification_uri} and enter the code ${groupCode(code.user_code)}\n`);
2644
+ if (code.verification_uri_complete) prompt.write(`Or open ${code.verification_uri_complete}\n`);
2645
+ prompt.write("Waiting for approval...\n");
2646
+ let interval = Number.isFinite(code.interval) ? code.interval : 5;
2647
+ const deadline = Date.now() + code.expires_in * 1e3;
2648
+ while (Date.now() < deadline) {
2649
+ await wait(interval);
2650
+ const answer = await postJson(context, `${origin}/api/auth/cli/token`, {
2651
+ client_id: clientId,
2652
+ device_code: code.device_code
2653
+ });
2654
+ if (answer.status === 200 && typeof answer.data.access_token === "string") return answer.data;
2655
+ if (answer.status === 429) {
2656
+ interval = Math.max(interval, Number(answer.headers.get("retry-after")) || 60);
2657
+ continue;
2658
+ }
2659
+ const error = answer.data.error;
2660
+ if (error === "authorization_pending") continue;
2661
+ if (error === "slow_down") {
2662
+ interval += 5;
2663
+ continue;
2664
+ }
2665
+ if (error === "access_denied") throw loginFailed(origin, "The sign-in was denied in the browser.");
2666
+ if (error === "expired_token") break;
2667
+ throw loginFailed(origin, `The Console answered ${answer.status}${typeof error === "string" ? ` (${error})` : ""}.`);
2668
+ }
2669
+ throw loginFailed(origin, "The code expired before anyone approved it.");
2670
+ }
2671
+ const loginUsage = "vitehub login [--console <url>] [--json]";
2672
+ const loginCommand = {
2673
+ description: `Sign in to a ViteHub Console with the device flow, and save an API key for this machine. The default Console is ${defaultConsoleUrl}; --console, ${consoleUrlVariable}, or console.url in the app config names another.`,
2674
+ name: "login",
2675
+ usage: loginUsage,
2676
+ run: async (args, context) => {
2677
+ const json = args.includes("--json");
2678
+ try {
2679
+ const values = readArgs(args, loginUsage, { console: true });
2680
+ if (values.help) {
2681
+ context.stdout.write(`Usage: ${loginUsage}\n\n${loginCommand.description}\n`);
2682
+ return setupExitCodes.done;
2683
+ }
2684
+ const origin = consoleOrigin(values.console ?? context.env["VITEHUB_CONSOLE_URL"] ?? await appConsole(context) ?? "https://console.vitehub.dev");
2685
+ const answer = await deviceLogin(origin, context, json ? context.stderr : context.stdout);
2686
+ const file = consoleCredentialsFile(context.env);
2687
+ const saved = await readCredentials(file);
2688
+ const credential = {
2689
+ expiresAt: Date.now() + answer.expires_in * 1e3,
2690
+ keyId: answer.key_id,
2691
+ team: answer.team,
2692
+ token: answer.access_token,
2693
+ user: answer.user
2694
+ };
2695
+ await writeCredentials(file, {
2696
+ version: 1,
2697
+ consoles: {
2698
+ ...saved.consoles,
2699
+ [origin]: credential
2700
+ }
2701
+ });
2702
+ const result = {
2703
+ console: origin,
2704
+ expiresAt: new Date(credential.expiresAt).toISOString(),
2705
+ file,
2706
+ team: credential.team,
2707
+ user: credential.user
2708
+ };
2709
+ if (json) writeSetupJson(context, result);
2710
+ else context.stdout.write(`Signed in to ${origin} as ${credential.user.name}${credential.user.email ? ` (${credential.user.email})` : ""} in team ${credential.team.name}.\nThe API key expires on ${dateFormat.format(new Date(credential.expiresAt))}. Saved in ${file}.\n`);
2711
+ if (context.env["VITEHUB_CONSOLE_TOKEN"]) context.stderr.write(`[vitehub] ${consoleTokenVariable} is set, so commands use it instead of this key.\n`);
2712
+ return setupExitCodes.done;
2713
+ } catch (error) {
2714
+ return writeSetupError(context, json, error);
2715
+ }
2716
+ }
2717
+ };
2718
+ const whoamiUsage = "vitehub whoami [--console <url>] [--json]";
2719
+ const whoamiCommand = {
2720
+ description: `Show the person and the team of the Console API key: ${consoleTokenVariable}, else the key of \`vitehub login\`.`,
2721
+ name: "whoami",
2722
+ usage: whoamiUsage,
2723
+ run: async (args, context) => {
2724
+ const json = args.includes("--json");
2725
+ try {
2726
+ const values = readArgs(args, whoamiUsage, { console: true });
2727
+ if (values.help) {
2728
+ context.stdout.write(`Usage: ${whoamiUsage}\n\n${whoamiCommand.description}\n`);
2729
+ return setupExitCodes.done;
2730
+ }
2731
+ const { origin, credential } = await selectConsole(context, values.console);
2732
+ if (!credential) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: origin });
2733
+ const response = await (context.fetch ?? fetch)(`${credential.origin}/api/whoami`, { headers: {
2734
+ accept: "application/json",
2735
+ authorization: `Bearer ${credential.token}`
2736
+ } });
2737
+ if (response.status === 401) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: credential.origin });
2738
+ if (!response.ok) throw cliErrorDiagnostics.CLI_R0001({ message: `[vitehub] ${credential.origin} answered ${response.status} to /api/whoami.` });
2739
+ const me = await response.json();
2740
+ const source = credential.source === "env" ? consoleTokenVariable : consoleCredentialsFile(context.env);
2741
+ if (json) writeSetupJson(context, {
2742
+ console: credential.origin,
2743
+ expiresAt: new Date(me.key.expiresAt).toISOString(),
2744
+ projectIds: me.projectIds,
2745
+ roles: me.roles,
2746
+ source,
2747
+ team: me.team,
2748
+ user: me.user
2749
+ });
2750
+ else {
2751
+ context.stdout.write(`${me.user.name}${me.user.email ? ` (${me.user.email})` : ""} in team ${me.team.name} (${me.roles.join(", ")}) on ${credential.origin}\n`);
2752
+ context.stdout.write(`Key from ${source}, for ${me.projectIds ? `${me.projectIds.length} project${me.projectIds.length === 1 ? "" : "s"}` : "every project of the team"}, expires on ${dateFormat.format(new Date(me.key.expiresAt))}.\n`);
2753
+ }
2754
+ return setupExitCodes.done;
2755
+ } catch (error) {
2756
+ return writeSetupError(context, json, error);
2757
+ }
2758
+ }
2759
+ };
2760
+ const logoutUsage = "vitehub logout [--console <url>] [--json]";
2761
+ const logoutCommand = {
2762
+ description: "Revoke the API key of `vitehub login` on the Console and remove it from this machine.",
2763
+ name: "logout",
2764
+ usage: logoutUsage,
2765
+ run: async (args, context) => {
2766
+ const json = args.includes("--json");
2767
+ try {
2768
+ const values = readArgs(args, logoutUsage, { console: true });
2769
+ if (values.help) {
2770
+ context.stdout.write(`Usage: ${logoutUsage}\n\n${logoutCommand.description}\n`);
2771
+ return setupExitCodes.done;
2772
+ }
2773
+ const file = consoleCredentialsFile(context.env);
2774
+ const saved = await readCredentials(file);
2775
+ const { credential } = await selectConsole({
2776
+ ...context,
2777
+ env: {
2778
+ ...context.env,
2779
+ [consoleTokenVariable]: void 0
2780
+ }
2781
+ }, values.console);
2782
+ if (!credential) {
2783
+ if (json) writeSetupJson(context, { removed: false });
2784
+ else context.stdout.write("Not signed in.\n");
2785
+ return setupExitCodes.done;
2786
+ }
2787
+ const response = await (context.fetch ?? fetch)(`${credential.origin}/api/api-keys/current`, {
2788
+ headers: { authorization: `Bearer ${credential.token}` },
2789
+ method: "DELETE"
2790
+ }).catch(() => void 0);
2791
+ const revoked = response !== void 0 && (response.status === 204 || response.status === 401 || response.status === 404);
2792
+ const { [credential.origin]: _removed, ...consoles } = saved.consoles;
2793
+ await writeCredentials(file, {
2794
+ version: 1,
2795
+ consoles
2796
+ });
2797
+ if (json) writeSetupJson(context, {
2798
+ console: credential.origin,
2799
+ removed: true,
2800
+ revoked
2801
+ });
2802
+ else {
2803
+ context.stdout.write(`Signed out of ${credential.origin}.\n`);
2804
+ if (!revoked) context.stderr.write("[vitehub] The Console did not revoke the key. Revoke it in Account settings, under API keys.\n");
2805
+ }
2806
+ if (context.env["VITEHUB_CONSOLE_TOKEN"]) context.stderr.write(`[vitehub] ${consoleTokenVariable} is still set. Unset it to sign out completely.\n`);
2807
+ return setupExitCodes.done;
2808
+ } catch (error) {
2809
+ return writeSetupError(context, json, error);
2810
+ }
2811
+ }
2812
+ };
2813
+ export { setupLockfiles as _, console_auth_exports as a, locateViteHubConfig as b, logoutCommand as c, whoamiCommand as d, declaresNuxt5 as f, readSetupProject as g, pnpmWorkspaceFile as h, consoleUrlVariable as i, readConsoleCredential as l, nuxtReleases as m, consoleOrigin as n, defaultConsoleUrl as o, detectPackageManager as p, consoleTokenVariable as r, loginCommand as s, consoleCredentialsFile as t, selectConsole as u, editViteHubConfig as v, insertViteHubConfig as y };