@vite-hub/cli 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,22 +1,23 @@
1
- import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
- import { $ as isRecord, B as formatInstallArgument, H as installSpecifier, I as featureIds, L as featurePackages, Q as internalErrorDiagnostics, R as featureSupport, V as impliedFeatures, W as invariant, b as loadAllEnv, c as createNetlifyApiClient, f as resolveHostCredentials, l as createVercelProvisionClient, m as cliErrorDiagnostics, o as createCloudflareApiClient, p as runHostCli, s as createCloudflareProvisionClient, u as isProvisionRequestError, x as withViteStageEnvironment, z as features } from "./provision-DgT_lpyn.js";
3
- import { i as setupFailure, o as writeSetupError, r as setupExitCodes, s as writeSetupJson, t as isSetupFailure } from "./envelope-C7e408hm.js";
1
+ import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.js";
2
+ import { A as resolveDeploymentPlan, B as readConsoleCredential, D as shellQuote, E as setupStatus, G as setupFailure, H as isSetupFailure, J as writeSetupJson, Mt as isRecord, W as setupExitCodes, Y as cliErrorDiagnostics, _ as consoleAppUrl, b as listConsoleApps, c as createNetlifyApiClient, f as resolveHostCredentials, g as checkProblem, h as checkConsoleApp, k as hostFromNitroPreset, l as createVercelProvisionClient, nt as withViteStageEnvironment, o as createCloudflareApiClient, p as runHostCli, q as writeSetupError, s as createCloudflareProvisionClient, tt as loadAllEnv, u as isProvisionRequestError, wt as invariant, x as openConsole, y as linkConsoleApp } from "./provision-akHsvf-B.js";
4
3
  import { createRequire } from "node:module";
5
4
  import { spawn } from "node:child_process";
6
- import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
7
- import process$1 from "node:process";
5
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
6
+ import process from "node:process";
8
7
  import { basename, dirname, join, relative, resolve } from "pathe";
9
8
  import { mkdir, mkdtemp, open, readFile, readdir, realpath, rm, stat, unlink, writeFile } from "node:fs/promises";
10
9
  import { basename as basename$1, delimiter, sep } from "node:path";
11
10
  import { createInterface } from "node:readline/promises";
12
11
  import { constants, homedir, tmpdir } from "node:os";
12
+ import { parseArgs, parseEnv } from "node:util";
13
13
  import { parse as parse$1 } from "@babel/parser";
14
14
  import { parse as parse$2 } from "rc9";
15
- import { parseArgs, parseEnv } from "node:util";
15
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
16
+ import { normalizeConsoleProjectUrl } from "@vite-hub/runtime/internal/console";
16
17
  import { createPublicKey, diffieHellman, generateKeyPairSync, randomBytes } from "node:crypto";
17
18
  import { hsalsa, xsalsa20poly1305 } from "@noble/ciphers/salsa.js";
18
19
  import { blake2b } from "@noble/hashes/blake2.js";
19
- //#region ../internal/dist/ast.js
20
+ // ../internal/dist/ast.js
20
21
  /** Parses JavaScript or TypeScript. `jsx` adds JSX syntax. */
21
22
  function parseProgram(code, options = {}) {
22
23
  const plugins = [];
@@ -118,16 +119,15 @@ function quoteString(value, style) {
118
119
  if (style.quote === "\"") return json;
119
120
  return `'${json.slice(1, -1).replaceAll("\\\"", "\"").replaceAll("'", "\\'")}'`;
120
121
  }
121
- //#endregion
122
- //#region ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.6.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
122
+ // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.6.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
123
123
  var comma = ",".charCodeAt(0);
124
124
  var semicolon = ";".charCodeAt(0);
125
125
  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
126
- var intToChar = /* @__PURE__ */ new Uint8Array(64);
126
+ var intToChar$1 = /* @__PURE__ */ new Uint8Array(64);
127
127
  var charToInt = /* @__PURE__ */ new Uint8Array(128);
128
128
  for (let i = 0; i < chars.length; i++) {
129
129
  const c = chars.charCodeAt(i);
130
- intToChar[i] = c;
130
+ intToChar$1[i] = c;
131
131
  charToInt[c] = i;
132
132
  }
133
133
  function encodeInteger(builder, num) {
@@ -135,7 +135,7 @@ function encodeInteger(builder, num) {
135
135
  let clamped = num & 31;
136
136
  num >>>= 5;
137
137
  if (num > 0) clamped |= 32;
138
- builder.write(intToChar[clamped]);
138
+ builder.write(intToChar$1[clamped]);
139
139
  } while (num > 0);
140
140
  }
141
141
  function encodeSign(num) {
@@ -168,6 +168,21 @@ var StringWriter = class {
168
168
  return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
169
169
  }
170
170
  };
171
+ function encodeRangeMappings(decoded) {
172
+ if (decoded.length === 0) return "";
173
+ const writer = new StringWriter();
174
+ for (let i = 0; i < decoded.length; i++) {
175
+ const indices = decoded[i];
176
+ if (i > 0) writer.write(semicolon);
177
+ let index = 0;
178
+ for (let j = 0; j < indices.length; j++) {
179
+ const offset = indices[j];
180
+ encodeInteger(writer, offset - index);
181
+ index = offset;
182
+ }
183
+ }
184
+ return writer.flush();
185
+ }
171
186
  function encode(decoded) {
172
187
  const writer = new StringWriter();
173
188
  let sourcesIndex = 0;
@@ -198,8 +213,7 @@ function encode(decoded) {
198
213
  }
199
214
  return writer.flush();
200
215
  }
201
- //#endregion
202
- //#region ../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs
216
+ // ../../node_modules/.pnpm/magic-string@1.4.5/node_modules/magic-string/dist/index.mjs
203
217
  var BitSet = class BitSet {
204
218
  constructor(arg) {
205
219
  this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
@@ -210,6 +224,17 @@ var BitSet = class BitSet {
210
224
  has(n) {
211
225
  return !!(this.bits[n >> 5] & 1 << (n & 31));
212
226
  }
227
+ forEach(fn) {
228
+ const bits = this.bits;
229
+ for (let w = 0; w < bits.length; w++) {
230
+ let word = bits[w];
231
+ while (word) {
232
+ const lowest = word & -word;
233
+ fn((w << 5) + 31 - Math.clz32(lowest));
234
+ word ^= lowest;
235
+ }
236
+ }
237
+ }
213
238
  };
214
239
  var Chunk = class Chunk {
215
240
  constructor(start, end, content) {
@@ -221,6 +246,8 @@ var Chunk = class Chunk {
221
246
  this.content = content;
222
247
  this.storeName = false;
223
248
  this.edited = false;
249
+ this.replacesUntil = -1;
250
+ this.replacedFrom = -1;
224
251
  this.previous = null;
225
252
  this.next = null;
226
253
  }
@@ -237,20 +264,24 @@ var Chunk = class Chunk {
237
264
  chunk.content = this.content;
238
265
  chunk.storeName = this.storeName;
239
266
  chunk.edited = this.edited;
267
+ chunk.replacesUntil = this.replacesUntil;
268
+ chunk.replacedFrom = this.replacedFrom;
240
269
  return chunk;
241
270
  }
242
271
  contains(index) {
243
272
  return this.start < index && index < this.end;
244
273
  }
245
274
  eachNext(fn) {
246
- let chunk = this;
275
+ fn(this);
276
+ let chunk = this.next;
247
277
  while (chunk) {
248
278
  fn(chunk);
249
279
  chunk = chunk.next;
250
280
  }
251
281
  }
252
282
  eachPrevious(fn) {
253
- let chunk = this;
283
+ fn(this);
284
+ let chunk = this.previous;
254
285
  while (chunk) {
255
286
  fn(chunk);
256
287
  chunk = chunk.previous;
@@ -275,6 +306,8 @@ var Chunk = class Chunk {
275
306
  reset() {
276
307
  this.intro = "";
277
308
  this.outro = "";
309
+ this.replacesUntil = -1;
310
+ this.replacedFrom = -1;
278
311
  if (this.edited) {
279
312
  this.content = this.original;
280
313
  this.storeName = false;
@@ -291,8 +324,8 @@ var Chunk = class Chunk {
291
324
  this.outro = "";
292
325
  this.end = index;
293
326
  if (this.edited) {
294
- newChunk.edit("", false);
295
- this.content = "";
327
+ newChunk.edit("", false, true);
328
+ newChunk.replacedFrom = this.replacedFrom;
296
329
  } else this.content = originalBefore;
297
330
  newChunk.next = this.next;
298
331
  if (newChunk.next) newChunk.next.previous = newChunk;
@@ -309,8 +342,8 @@ var Chunk = class Chunk {
309
342
  const trimmed = this.content.replace(rx, "");
310
343
  if (trimmed.length) {
311
344
  if (trimmed !== this.content) {
312
- this.split(this.start + trimmed.length).edit("", void 0, true);
313
345
  if (this.edited) this.edit(trimmed, this.storeName, true);
346
+ else this.split(this.start + trimmed.length).edit("", void 0, true);
314
347
  }
315
348
  return true;
316
349
  } else {
@@ -325,9 +358,11 @@ var Chunk = class Chunk {
325
358
  const trimmed = this.content.replace(rx, "");
326
359
  if (trimmed.length) {
327
360
  if (trimmed !== this.content) {
328
- const newChunk = this.split(this.end - trimmed.length);
329
- if (this.edited) newChunk.edit(trimmed, this.storeName, true);
330
- this.edit("", void 0, true);
361
+ if (this.edited) this.edit(trimmed, this.storeName, true);
362
+ else {
363
+ this.split(this.end - trimmed.length);
364
+ this.edit("", void 0, true);
365
+ }
331
366
  }
332
367
  return true;
333
368
  } else {
@@ -337,14 +372,29 @@ var Chunk = class Chunk {
337
372
  }
338
373
  }
339
374
  };
375
+ /**
376
+ * The single error type thrown by MagicString.
377
+ *
378
+ * Every message is prefixed with `[MagicString]` so its source is obvious at a
379
+ * glance, and is kept short and consistent in tone.
380
+ */
381
+ var MagicStringError = class extends Error {
382
+ name = "MagicStringError";
383
+ constructor(message, options) {
384
+ super(`[MagicString] ${message}`, options);
385
+ }
386
+ };
340
387
  function getBtoa() {
388
+ /* v8 ignore next -- environment fallback, unreachable when `btoa` is present */
341
389
  if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
342
- else if (typeof Buffer === "function") return (str) => Buffer.from(str, "utf-8").toString("base64");
343
- else return () => {
344
- throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
390
+ const buffer = globalThis["Buffer"];
391
+ if (buffer) return (str) => buffer.from(str, "utf-8").toString("base64");
392
+ return () => {
393
+ throw new MagicStringError("unsupported environment: `btoa` or `Buffer` is required");
345
394
  };
395
+ /* v8 ignore stop */
346
396
  }
347
- const btoa = /*#__PURE__*/ getBtoa();
397
+ const btoa = /* #__PURE__ */ getBtoa();
348
398
  var SourceMap = class {
349
399
  constructor(properties) {
350
400
  this.version = 3;
@@ -352,28 +402,49 @@ var SourceMap = class {
352
402
  this.sources = properties.sources;
353
403
  this.sourcesContent = properties.sourcesContent;
354
404
  this.names = properties.names;
355
- this.mappings = encode(properties.mappings);
405
+ this.mappings = typeof properties.mappings === "string" ? properties.mappings : encode(properties.mappings);
356
406
  if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList;
357
407
  if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId;
408
+ if (typeof properties.rangeMappings !== "undefined") {
409
+ let shouldOutputRangeMapping = false;
410
+ for (const line of properties.rangeMappings) if (line.length !== 0) {
411
+ shouldOutputRangeMapping = true;
412
+ break;
413
+ }
414
+ if (shouldOutputRangeMapping) this.rangeMappings = encodeRangeMappings(properties.rangeMappings);
415
+ }
358
416
  }
417
+ /**
418
+ * Returns the equivalent of `JSON.stringify(map)`
419
+ */
359
420
  toString() {
360
421
  return JSON.stringify(this);
361
422
  }
423
+ /**
424
+ * Returns a DataURI containing the sourcemap. Useful for doing this sort of thing:
425
+ * `generateMap(options?: SourceMapOptions): SourceMap;`
426
+ */
362
427
  toUrl() {
363
- return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
428
+ return `data:application/json;charset=utf-8;base64,${btoa(this.toString())}`;
364
429
  }
365
430
  };
366
- function guessIndent(code) {
367
- const lines = code.split("\n");
368
- const tabbed = lines.filter((line) => /^\t+/.test(line));
369
- const spaced = lines.filter((line) => /^ {2,}/.test(line));
370
- if (tabbed.length === 0 && spaced.length === 0) return null;
371
- if (tabbed.length >= spaced.length) return " ";
372
- const min = spaced.reduce((previous, current) => {
373
- const numSpaces = /^ +/.exec(current)[0].length;
374
- return Math.min(numSpaces, previous);
375
- }, Infinity);
376
- return new Array(min + 1).join(" ");
431
+ function getLocator(source) {
432
+ const lineOffsets = [0];
433
+ for (let i = source.indexOf("\n"); i !== -1; i = source.indexOf("\n", i + 1)) lineOffsets.push(i + 1);
434
+ return function locate(index) {
435
+ let i = 0;
436
+ let j = lineOffsets.length;
437
+ while (i < j) {
438
+ const m = i + j >> 1;
439
+ if (index < lineOffsets[m]) j = m;
440
+ else i = m + 1;
441
+ }
442
+ const line = i - 1;
443
+ return {
444
+ line,
445
+ column: index - lineOffsets[line]
446
+ };
447
+ };
377
448
  }
378
449
  function getRelativePath(from, to) {
379
450
  const fromParts = from.split(/[/\\]/);
@@ -389,41 +460,157 @@ function getRelativePath(from, to) {
389
460
  }
390
461
  return fromParts.concat(toParts).join("/");
391
462
  }
463
+ function guessIndent(code) {
464
+ const lines = code.split("\n");
465
+ const tabbed = lines.filter((line) => /^\t+/.test(line));
466
+ const spaced = lines.filter((line) => /^ {2,}/.test(line));
467
+ if (tabbed.length === 0 && spaced.length === 0) return null;
468
+ if (tabbed.length >= spaced.length) return " ";
469
+ const min = spaced.reduce((previous, current) => {
470
+ const numSpaces = /^ +/.exec(current)[0].length;
471
+ return Math.min(numSpaces, previous);
472
+ }, Infinity);
473
+ return " ".repeat(min);
474
+ }
392
475
  const toString = Object.prototype.toString;
393
476
  function isObject(thing) {
394
477
  return toString.call(thing) === "[object Object]";
395
478
  }
396
- function getLocator(source) {
397
- const originalLines = source.split("\n");
398
- const lineOffsets = [];
399
- for (let i = 0, pos = 0; i < originalLines.length; i++) {
400
- lineOffsets.push(pos);
401
- pos += originalLines[i].length + 1;
402
- }
403
- return function locate(index) {
404
- let i = 0;
405
- let j = lineOffsets.length;
406
- while (i < j) {
407
- const m = i + j >> 1;
408
- if (index < lineOffsets[m]) j = m;
409
- else i = m + 1;
479
+ const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
480
+ const intToChar = /* #__PURE__ */ (() => {
481
+ const chars = /* @__PURE__ */ new Uint8Array(64);
482
+ for (let i = 0; i < 64; i++) chars[i] = BASE64_CHARS.charCodeAt(i);
483
+ return chars;
484
+ })();
485
+ const COMMA = 44;
486
+ const SEMICOLON = 59;
487
+ const BUFFER_SIZE = 16384;
488
+ const FLUSH_THRESHOLD = 16348;
489
+ const scratch = /* #__PURE__ */ new Uint8Array(BUFFER_SIZE);
490
+ function writeVlq(pos, num) {
491
+ num = num < 0 ? -num << 1 | 1 : num << 1;
492
+ do {
493
+ let clamped = num & 31;
494
+ num >>>= 5;
495
+ if (num > 0) clamped |= 32;
496
+ scratch[pos++] = intToChar[clamped];
497
+ } while (num > 0);
498
+ return pos;
499
+ }
500
+ const decoder = /* #__PURE__ */ new TextDecoder();
501
+ var MappingsEncoder = class {
502
+ constructor() {
503
+ this.out = "";
504
+ this.pos = 0;
505
+ this.lines = [];
506
+ this.buffered = 0;
507
+ this.needsComma = false;
508
+ this.prevGenColumn = 0;
509
+ this.prevSourceIndex = 0;
510
+ this.prevSourceLine = 0;
511
+ this.prevSourceColumn = 0;
512
+ this.prevNameIndex = 0;
513
+ }
514
+ endLine(segments) {
515
+ this.lines.push(segments);
516
+ this.buffered += segments.length + 1;
517
+ if (this.buffered >= 4096) this.drain(null);
518
+ }
519
+ segments(segments) {
520
+ this.drain(segments);
521
+ }
522
+ finish(segments) {
523
+ this.drain(segments);
524
+ this.flush();
525
+ return this.out;
526
+ }
527
+ drain(trailing) {
528
+ const lines = this.lines;
529
+ const lineCount = lines.length;
530
+ for (let l = 0; l <= lineCount; l++) {
531
+ const line = l < lineCount ? lines[l] : trailing;
532
+ if (line === null) break;
533
+ for (let i = 0; i < line.length; i++) {
534
+ if (this.pos > FLUSH_THRESHOLD) this.flush();
535
+ const segment = line[i];
536
+ if (this.needsComma) scratch[this.pos++] = COMMA;
537
+ this.needsComma = true;
538
+ this.pos = writeVlq(this.pos, segment[0] - this.prevGenColumn);
539
+ this.prevGenColumn = segment[0];
540
+ this.pos = writeVlq(this.pos, segment[1] - this.prevSourceIndex);
541
+ this.prevSourceIndex = segment[1];
542
+ this.pos = writeVlq(this.pos, segment[2] - this.prevSourceLine);
543
+ this.prevSourceLine = segment[2];
544
+ this.pos = writeVlq(this.pos, segment[3] - this.prevSourceColumn);
545
+ this.prevSourceColumn = segment[3];
546
+ if (segment.length === 5) {
547
+ this.pos = writeVlq(this.pos, segment[4] - this.prevNameIndex);
548
+ this.prevNameIndex = segment[4];
549
+ }
550
+ }
551
+ if (l < lineCount) {
552
+ if (this.pos > FLUSH_THRESHOLD) this.flush();
553
+ scratch[this.pos++] = SEMICOLON;
554
+ this.needsComma = false;
555
+ this.prevGenColumn = 0;
556
+ }
410
557
  }
411
- const line = i - 1;
412
- return {
413
- line,
414
- column: index - lineOffsets[line]
415
- };
416
- };
558
+ lines.length = 0;
559
+ this.buffered = 0;
560
+ this.flush();
561
+ }
562
+ flush() {
563
+ this.out += decoder.decode(scratch.subarray(0, this.pos));
564
+ this.pos = 0;
565
+ }
566
+ };
567
+ const NEWLINE_CHAR$1 = 10;
568
+ function isWordCode(code) {
569
+ return code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 95;
417
570
  }
418
- const wordRegex = /\w/;
419
571
  var Mappings = class {
420
- constructor(hires) {
572
+ constructor(hires, encoder = null) {
421
573
  this.hires = hires;
422
574
  this.generatedCodeLine = 0;
423
575
  this.generatedCodeColumn = 0;
424
576
  this.raw = [];
425
577
  this.rawSegments = this.raw[this.generatedCodeLine] = [];
426
- this.pending = null;
578
+ this.rawRangeMappingsIndices = [];
579
+ this.rawRangeMappings = hires === "experimental-range" ? [this.rawRangeMappingsIndices] : void 0;
580
+ this.encoder = encoder;
581
+ }
582
+ nextLine() {
583
+ if (this.encoder === null) {
584
+ this.generatedCodeLine += 1;
585
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
586
+ } else {
587
+ this.encoder.endLine(this.rawSegments);
588
+ this.rawSegments = [];
589
+ this.generatedCodeLine += 1;
590
+ }
591
+ this.generatedCodeColumn = 0;
592
+ if (this.rawRangeMappings) this.rawRangeMappings[this.generatedCodeLine] = this.rawRangeMappingsIndices = [];
593
+ }
594
+ /**
595
+ * Emits the mappings for one MagicString: its intro, every chunk (with the
596
+ * chunk's own intro/outro) and its outro. `sourceIndex === -1` means the
597
+ * string has no source of its own, so its content only advances the
598
+ * generated position without mapping anything.
599
+ */
600
+ addMagicString(magicString, sourceIndex, nameIndex) {
601
+ const { original } = magicString;
602
+ const locate = getLocator(original);
603
+ if (magicString.intro) this.advance(magicString.intro);
604
+ magicString.firstChunk.eachNext((chunk) => {
605
+ if (chunk.intro.length) this.advance(chunk.intro);
606
+ if (sourceIndex === -1) this.advance(chunk.content);
607
+ else if (chunk.edited) {
608
+ const name = chunk.storeName ? nameIndex.get(original.slice(chunk.start, chunk.replacesUntil)) : void 0;
609
+ this.addEdit(sourceIndex, chunk.content, locate(chunk.start), name ?? -1);
610
+ } else this.addUneditedChunk(sourceIndex, chunk, original, locate(chunk.start), magicString.sourcemapLocations);
611
+ if (chunk.outro.length) this.advance(chunk.outro);
612
+ });
613
+ if (magicString.outro) this.advance(magicString.outro);
427
614
  }
428
615
  addEdit(sourceIndex, content, loc, nameIndex) {
429
616
  if (content.length) {
@@ -439,9 +626,7 @@ var Mappings = class {
439
626
  ];
440
627
  if (nameIndex >= 0) segment.push(nameIndex);
441
628
  this.rawSegments.push(segment);
442
- this.generatedCodeLine += 1;
443
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
444
- this.generatedCodeColumn = 0;
629
+ this.nextLine();
445
630
  previousContentLineEnd = contentLineEnd;
446
631
  contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
447
632
  }
@@ -454,73 +639,193 @@ var Mappings = class {
454
639
  if (nameIndex >= 0) segment.push(nameIndex);
455
640
  this.rawSegments.push(segment);
456
641
  this.advance(content.slice(previousContentLineEnd + 1));
457
- } else if (this.pending) {
458
- this.rawSegments.push(this.pending);
459
- this.advance(content);
460
642
  }
461
- this.pending = null;
462
643
  }
463
644
  addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
464
- let originalCharIndex = chunk.start;
465
- let first = true;
466
- let charInHiresBoundary = false;
467
- while (originalCharIndex < chunk.end) {
468
- if (original[originalCharIndex] === "\n") {
469
- loc.line += 1;
470
- loc.column = 0;
471
- this.generatedCodeLine += 1;
472
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
473
- this.generatedCodeColumn = 0;
474
- first = true;
475
- charInHiresBoundary = false;
476
- } else {
477
- if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
478
- const segment = [
479
- this.generatedCodeColumn,
480
- sourceIndex,
481
- loc.line,
482
- loc.column
483
- ];
484
- if (this.hires === "boundary") {
485
- if (wordRegex.test(original[originalCharIndex])) {
645
+ const end = chunk.end;
646
+ let i = chunk.start;
647
+ if (this.hires) {
648
+ const boundary = this.hires === "boundary";
649
+ const experimentalRange = this.hires === "experimental-range";
650
+ const encoder = experimentalRange ? null : this.encoder;
651
+ let charInHiresBoundary = false;
652
+ while (i < end) {
653
+ if (encoder !== null && this.rawSegments.length >= 4096) {
654
+ encoder.segments(this.rawSegments);
655
+ this.rawSegments.length = 0;
656
+ }
657
+ if (experimentalRange && i + 1 >= end) this.rawSegments.push([
658
+ this.generatedCodeColumn,
659
+ sourceIndex,
660
+ loc.line,
661
+ loc.column
662
+ ]);
663
+ const code = original.charCodeAt(i);
664
+ if (code === NEWLINE_CHAR$1) {
665
+ loc.line += 1;
666
+ loc.column = 0;
667
+ this.nextLine();
668
+ charInHiresBoundary = false;
669
+ } else {
670
+ if (boundary) {
671
+ if (isWordCode(code)) {
486
672
  if (!charInHiresBoundary) {
487
- this.rawSegments.push(segment);
673
+ this.rawSegments.push([
674
+ this.generatedCodeColumn,
675
+ sourceIndex,
676
+ loc.line,
677
+ loc.column
678
+ ]);
488
679
  charInHiresBoundary = true;
489
680
  }
490
681
  } else {
491
- this.rawSegments.push(segment);
682
+ this.rawSegments.push([
683
+ this.generatedCodeColumn,
684
+ sourceIndex,
685
+ loc.line,
686
+ loc.column
687
+ ]);
492
688
  charInHiresBoundary = false;
493
689
  }
494
- } else this.rawSegments.push(segment);
690
+ } else if (experimentalRange) {
691
+ if (i === chunk.start) {
692
+ this.rawRangeMappingsIndices.push(this.rawSegments.length);
693
+ this.rawSegments.push([
694
+ this.generatedCodeColumn,
695
+ sourceIndex,
696
+ loc.line,
697
+ loc.column
698
+ ]);
699
+ }
700
+ } else this.rawSegments.push([
701
+ this.generatedCodeColumn,
702
+ sourceIndex,
703
+ loc.line,
704
+ loc.column
705
+ ]);
706
+ loc.column += 1;
707
+ this.generatedCodeColumn += 1;
495
708
  }
496
- loc.column += 1;
497
- this.generatedCodeColumn += 1;
498
- first = false;
709
+ i += 1;
710
+ }
711
+ } else {
712
+ const bits = sourcemapLocations.bits;
713
+ while (i < end) {
714
+ let newline = original.indexOf("\n", i);
715
+ if (newline === -1 || newline > end) newline = end;
716
+ if (newline > i) {
717
+ this.rawSegments.push([
718
+ this.generatedCodeColumn,
719
+ sourceIndex,
720
+ loc.line,
721
+ loc.column
722
+ ]);
723
+ for (let w = i + 1 >> 5, last = newline - 1 >> 5; w <= last; w++) {
724
+ let word = bits[w];
725
+ if (!word) continue;
726
+ const base = w << 5;
727
+ while (word) {
728
+ const lowest = word & -word;
729
+ const index = base + 31 - Math.clz32(lowest);
730
+ if (index > i && index < newline) {
731
+ const offset = index - i;
732
+ this.rawSegments.push([
733
+ this.generatedCodeColumn + offset,
734
+ sourceIndex,
735
+ loc.line,
736
+ loc.column + offset
737
+ ]);
738
+ }
739
+ word ^= lowest;
740
+ }
741
+ }
742
+ loc.column += newline - i;
743
+ this.generatedCodeColumn += newline - i;
744
+ }
745
+ if (newline === end) break;
746
+ loc.line += 1;
747
+ loc.column = 0;
748
+ this.nextLine();
749
+ i = newline + 1;
499
750
  }
500
- originalCharIndex += 1;
501
751
  }
502
- this.pending = null;
503
752
  }
504
753
  advance(str) {
505
754
  if (!str) return;
506
- const lines = str.split("\n");
507
- if (lines.length > 1) {
508
- for (let i = 0; i < lines.length - 1; i++) {
509
- this.generatedCodeLine++;
510
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
511
- }
512
- this.generatedCodeColumn = 0;
513
- }
514
- this.generatedCodeColumn += lines[lines.length - 1].length;
755
+ const lastNewline = str.lastIndexOf("\n");
756
+ for (let i = str.indexOf("\n"); i !== -1; i = str.indexOf("\n", i + 1)) this.nextLine();
757
+ this.generatedCodeColumn += str.length - lastNewline - 1;
515
758
  }
516
759
  };
517
760
  const n = "\n";
761
+ const NEWLINE_CHAR = "\n".charCodeAt(0);
762
+ const CR_CHAR = "\r".charCodeAt(0);
518
763
  const warned = {
519
764
  insertLeft: false,
520
765
  insertRight: false,
521
766
  storeName: false
522
767
  };
768
+ /**
769
+ * Expands the `$` substitution patterns that `String.prototype.replace` accepts
770
+ * in a string replacement.
771
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
772
+ *
773
+ * `captures` holds the capture groups in order, so `captures[0]` is `$1`.
774
+ * `namedCaptures` is `undefined` when the pattern has no named groups, and
775
+ * `$<name>` is then literal text - which is also the case for a string search
776
+ * value, where there are no groups of either kind.
777
+ */
778
+ function expandReplacement(replacement, matched, position, str, captures, namedCaptures) {
779
+ if (!replacement.includes("$")) return replacement;
780
+ let result = "";
781
+ let index = 0;
782
+ while (index < replacement.length) {
783
+ const dollar = replacement.indexOf("$", index);
784
+ if (dollar === -1) {
785
+ result += replacement.slice(index);
786
+ break;
787
+ }
788
+ result += replacement.slice(index, dollar);
789
+ const char = replacement[dollar + 1];
790
+ let expansion = "$";
791
+ let consumed = 1;
792
+ if (char === "$") consumed = 2;
793
+ else if (char === "&") {
794
+ expansion = matched;
795
+ consumed = 2;
796
+ } else if (char === "`") {
797
+ expansion = str.slice(0, position);
798
+ consumed = 2;
799
+ } else if (char === "'") {
800
+ expansion = str.slice(position + matched.length);
801
+ consumed = 2;
802
+ } else if (char === "<" && namedCaptures !== void 0) {
803
+ const close = replacement.indexOf(">", dollar + 2);
804
+ if (close !== -1) {
805
+ expansion = namedCaptures[replacement.slice(dollar + 2, close)] ?? "";
806
+ consumed = close + 1 - dollar;
807
+ }
808
+ } else if (char >= "0" && char <= "9") {
809
+ const second = replacement[dollar + 2];
810
+ const double = second >= "0" && second <= "9" ? Number(char + second) : NaN;
811
+ const single = Number(char);
812
+ if (double >= 1 && double <= captures.length) {
813
+ expansion = captures[double - 1] ?? "";
814
+ consumed = 3;
815
+ } else if (single >= 1 && single <= captures.length) {
816
+ expansion = captures[single - 1] ?? "";
817
+ consumed = 2;
818
+ }
819
+ }
820
+ result += expansion;
821
+ index = dollar + consumed;
822
+ }
823
+ return result;
824
+ }
523
825
  var MagicString = class MagicString {
826
+ /**
827
+ * Wraps `string` for editing; every index passed to the editing methods refers to this original string.
828
+ */
524
829
  constructor(string, options = {}) {
525
830
  const chunk = new Chunk(0, string.length, string);
526
831
  Object.defineProperties(this, {
@@ -550,11 +855,11 @@ var MagicString = class MagicString {
550
855
  },
551
856
  byStart: {
552
857
  writable: true,
553
- value: {}
858
+ value: /* @__PURE__ */ new Map([[0, chunk]])
554
859
  },
555
860
  byEnd: {
556
861
  writable: true,
557
- value: {}
862
+ value: /* @__PURE__ */ new Map([[string.length, chunk]])
558
863
  },
559
864
  filename: {
560
865
  writable: true,
@@ -570,7 +875,7 @@ var MagicString = class MagicString {
570
875
  },
571
876
  storedNames: {
572
877
  writable: true,
573
- value: {}
878
+ value: /* @__PURE__ */ new Set()
574
879
  },
575
880
  indentStr: {
576
881
  writable: true,
@@ -583,47 +888,74 @@ var MagicString = class MagicString {
583
888
  offset: {
584
889
  writable: true,
585
890
  value: options.offset || 0
891
+ },
892
+ hasMovedChunks: {
893
+ writable: true,
894
+ value: false
586
895
  }
587
896
  });
588
- this.byStart[0] = chunk;
589
- this.byEnd[string.length] = chunk;
590
897
  }
898
+ /**
899
+ * Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is false.
900
+ */
591
901
  addSourcemapLocation(char) {
592
902
  this.sourcemapLocations.add(char);
593
903
  }
904
+ /**
905
+ * Appends the specified content to the end of the string.
906
+ */
594
907
  append(content) {
595
- if (typeof content !== "string") throw new TypeError("outro content must be a string");
908
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
596
909
  this.outro += content;
597
910
  return this;
598
911
  }
912
+ /**
913
+ * Appends the specified content at the index in the original string.
914
+ * If a range *ending* with index is subsequently moved, the insert will be moved with it.
915
+ * See also `s.prependLeft(...)`.
916
+ */
599
917
  appendLeft(index, content) {
600
- index = index + this.offset;
601
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
918
+ index = this._resolveIndex(index);
919
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
920
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
602
921
  this._split(index);
603
- const chunk = this.byEnd[index];
922
+ const chunk = this.byEnd.get(index);
604
923
  if (chunk) chunk.appendLeft(content);
605
924
  else this.intro += content;
606
925
  return this;
607
926
  }
927
+ /**
928
+ * Appends the specified content at the index in the original string.
929
+ * If a range *starting* with index is subsequently moved, the insert will be moved with it.
930
+ * See also `s.prependRight(...)`.
931
+ */
608
932
  appendRight(index, content) {
609
- index = index + this.offset;
610
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
933
+ index = this._resolveIndex(index);
934
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
935
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
611
936
  this._split(index);
612
- const chunk = this.byStart[index];
937
+ const chunk = this.byStart.get(index);
613
938
  if (chunk) chunk.appendRight(content);
614
939
  else this.outro += content;
615
940
  return this;
616
941
  }
942
+ /**
943
+ * Returns an independent copy: the chunk list, string-level intro/outro,
944
+ * sourcemap locations, stored names, indent exclusion ranges, `offset`,
945
+ * `filename` and `ignoreList` are all copied; later edits to either string
946
+ * do not affect the other.
947
+ */
617
948
  clone() {
618
949
  const cloned = new MagicString(this.original, {
619
950
  filename: this.filename,
951
+ ignoreList: this.ignoreList,
620
952
  offset: this.offset
621
953
  });
622
954
  let originalChunk = this.firstChunk;
623
955
  let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
624
956
  while (originalChunk) {
625
- cloned.byStart[clonedChunk.start] = clonedChunk;
626
- cloned.byEnd[clonedChunk.end] = clonedChunk;
957
+ cloned.byStart.set(clonedChunk.start, clonedChunk);
958
+ cloned.byEnd.set(clonedChunk.end, clonedChunk);
627
959
  const nextOriginalChunk = originalChunk.next;
628
960
  const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
629
961
  if (nextClonedChunk) {
@@ -636,47 +968,72 @@ var MagicString = class MagicString {
636
968
  cloned.lastChunk = clonedChunk;
637
969
  if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
638
970
  cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
971
+ cloned.storedNames = new Set(this.storedNames);
639
972
  cloned.intro = this.intro;
640
973
  cloned.outro = this.outro;
974
+ cloned.hasMovedChunks = this.hasMovedChunks;
641
975
  return cloned;
642
976
  }
977
+ /**
978
+ * Generates a sourcemap object with raw mappings in array form, rather than encoded as a string.
979
+ * Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead.
980
+ */
643
981
  generateDecodedMap(options) {
644
982
  options = options || {};
645
- const sourceIndex = 0;
646
- const names = Object.keys(this.storedNames);
647
983
  const mappings = new Mappings(options.hires);
648
- const locate = getLocator(this.original);
649
- if (this.intro) mappings.advance(this.intro);
650
- this.firstChunk.eachNext((chunk) => {
651
- const loc = locate(chunk.start);
652
- if (chunk.intro.length) mappings.advance(chunk.intro);
653
- if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
654
- else mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
655
- if (chunk.outro.length) mappings.advance(chunk.outro);
984
+ const names = this._generateMappings(mappings);
985
+ return {
986
+ ...this._mapProperties(options, names),
987
+ mappings: mappings.raw,
988
+ rangeMappings: mappings.rawRangeMappings
989
+ };
990
+ }
991
+ /**
992
+ * Generates a version 3 sourcemap.
993
+ */
994
+ generateMap(options) {
995
+ options = options || {};
996
+ const encoder = new MappingsEncoder();
997
+ const mappings = new Mappings(options.hires, encoder);
998
+ const names = this._generateMappings(mappings);
999
+ return new SourceMap({
1000
+ ...this._mapProperties(options, names),
1001
+ mappings: encoder.finish(mappings.rawSegments),
1002
+ rangeMappings: mappings.rawRangeMappings
656
1003
  });
657
- if (this.outro) mappings.advance(this.outro);
1004
+ }
1005
+ /** @internal */
1006
+ _generateMappings(mappings) {
1007
+ const names = [...this.storedNames];
1008
+ mappings.addMagicString(this, 0, new Map(names.map((name, i) => [name, i])));
1009
+ return names;
1010
+ }
1011
+ /** @internal */
1012
+ _mapProperties(options, names) {
658
1013
  return {
659
1014
  file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
660
1015
  sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
661
1016
  sourcesContent: options.includeContent ? [this.original] : void 0,
662
1017
  names,
663
- mappings: mappings.raw,
664
- x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
1018
+ x_google_ignoreList: this.ignoreList ? [0] : void 0
665
1019
  };
666
1020
  }
667
- generateMap(options) {
668
- return new SourceMap(this.generateDecodedMap(options));
669
- }
1021
+ /** @internal */
670
1022
  _ensureindentStr() {
671
1023
  if (this.indentStr === void 0) this.indentStr = guessIndent(this.original);
672
1024
  }
1025
+ /** @internal */
673
1026
  _getRawIndentString() {
674
1027
  this._ensureindentStr();
675
1028
  return this.indentStr;
676
1029
  }
1030
+ /**
1031
+ * Returns the indentation string guessed from the original content, falling back to a single tab character.
1032
+ * This is the value `s.indent()` uses when no prefix is supplied.
1033
+ */
677
1034
  getIndentString() {
678
1035
  this._ensureindentStr();
679
- return this.indentStr === null ? " " : this.indentStr;
1036
+ return this.indentStr ?? " ";
680
1037
  }
681
1038
  indent(indentStr, options) {
682
1039
  const pattern = /^[^\r\n]/gm;
@@ -689,55 +1046,78 @@ var MagicString = class MagicString {
689
1046
  indentStr = this.indentStr || " ";
690
1047
  }
691
1048
  if (indentStr === "") return this;
1049
+ const resolvedIndentStr = indentStr;
692
1050
  options = options || {};
693
- const isExcluded = {};
1051
+ const isExcluded = new BitSet();
694
1052
  if (options.exclude) (typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude).forEach((exclusion) => {
695
- for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded[i] = true;
1053
+ for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded.add(i);
696
1054
  });
697
1055
  let shouldIndentNextCharacter = options.indentStart !== false;
698
- const replacer = (match) => {
699
- if (shouldIndentNextCharacter) return `${indentStr}${match}`;
700
- shouldIndentNextCharacter = true;
701
- return match;
1056
+ const indentPiece = (str) => {
1057
+ if (str === "") return str;
1058
+ const indented = str.replace(pattern, (match, offset) => offset > 0 || shouldIndentNextCharacter ? `${resolvedIndentStr}${match}` : match);
1059
+ shouldIndentNextCharacter = str[str.length - 1] === "\n";
1060
+ return indented;
702
1061
  };
703
- this.intro = this.intro.replace(pattern, replacer);
1062
+ this.intro = indentPiece(this.intro);
704
1063
  let charIndex = 0;
705
1064
  let chunk = this.firstChunk;
1065
+ const indentAt = (index) => {
1066
+ shouldIndentNextCharacter = false;
1067
+ if (index === chunk.start) chunk.appendRight(resolvedIndentStr);
1068
+ else {
1069
+ this._splitChunk(chunk, index);
1070
+ chunk = chunk.next;
1071
+ chunk.prependRight(resolvedIndentStr);
1072
+ }
1073
+ };
706
1074
  while (chunk) {
707
1075
  const end = chunk.end;
1076
+ if (!isExcluded.has(chunk.start)) chunk.intro = indentPiece(chunk.intro);
708
1077
  if (chunk.edited) {
709
- if (!isExcluded[charIndex]) {
710
- chunk.content = chunk.content.replace(pattern, replacer);
711
- if (chunk.content.length) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
1078
+ if (!isExcluded.has(chunk.start)) chunk.content = indentPiece(chunk.content);
1079
+ else if (chunk.content) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
1080
+ } else if (options.exclude) {
1081
+ charIndex = chunk.start;
1082
+ while (charIndex < end) {
1083
+ if (!isExcluded.has(charIndex)) {
1084
+ const char = this.original.charCodeAt(charIndex);
1085
+ if (char === NEWLINE_CHAR) shouldIndentNextCharacter = true;
1086
+ else if (char !== CR_CHAR && shouldIndentNextCharacter) indentAt(charIndex);
1087
+ }
1088
+ charIndex += 1;
712
1089
  }
713
1090
  } else {
714
1091
  charIndex = chunk.start;
715
1092
  while (charIndex < end) {
716
- if (!isExcluded[charIndex]) {
717
- const char = this.original[charIndex];
718
- if (char === "\n") shouldIndentNextCharacter = true;
719
- else if (char !== "\r" && shouldIndentNextCharacter) {
720
- shouldIndentNextCharacter = false;
721
- if (charIndex === chunk.start) chunk.prependRight(indentStr);
722
- else {
723
- this._splitChunk(chunk, charIndex);
724
- chunk = chunk.next;
725
- chunk.prependRight(indentStr);
726
- }
727
- }
1093
+ if (!shouldIndentNextCharacter) {
1094
+ const nextLine = this.original.indexOf(n, charIndex);
1095
+ if (nextLine === -1 || nextLine >= end) break;
1096
+ shouldIndentNextCharacter = true;
1097
+ charIndex = nextLine + 1;
1098
+ continue;
1099
+ }
1100
+ const char = this.original.charCodeAt(charIndex);
1101
+ if (char === NEWLINE_CHAR || char === CR_CHAR) {
1102
+ charIndex += 1;
1103
+ continue;
728
1104
  }
1105
+ indentAt(charIndex);
729
1106
  charIndex += 1;
730
1107
  }
731
1108
  }
1109
+ if (!isExcluded.has(chunk.end - 1)) chunk.outro = indentPiece(chunk.outro);
732
1110
  charIndex = chunk.end;
733
1111
  chunk = chunk.next;
734
1112
  }
735
- this.outro = this.outro.replace(pattern, replacer);
1113
+ this.outro = indentPiece(this.outro);
736
1114
  return this;
737
1115
  }
1116
+ /** @internal */
738
1117
  insert() {
739
- throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
1118
+ throw new MagicStringError("insert() is deprecated, use appendLeft() or prependRight()");
740
1119
  }
1120
+ /** @internal */
741
1121
  insertLeft(index, content) {
742
1122
  if (!warned.insertLeft) {
743
1123
  console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
@@ -745,6 +1125,7 @@ var MagicString = class MagicString {
745
1125
  }
746
1126
  return this.appendLeft(index, content);
747
1127
  }
1128
+ /** @internal */
748
1129
  insertRight(index, content) {
749
1130
  if (!warned.insertRight) {
750
1131
  console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
@@ -752,53 +1133,117 @@ var MagicString = class MagicString {
752
1133
  }
753
1134
  return this.prependRight(index, content);
754
1135
  }
755
- move(start, end, index) {
756
- start = start + this.offset;
757
- end = end + this.offset;
758
- index = index + this.offset;
759
- if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
1136
+ /**
1137
+ * Moves the characters from `start` and `end` to `index`.
1138
+ *
1139
+ * `affinity` controls where the range is anchored at `index`. With the
1140
+ * default `'right'`, it is inserted before the content that starts at `index`;
1141
+ * with `'left'`, it is inserted after the content that ends at `index`. The
1142
+ * two differ only when other content has already been moved to that boundary,
1143
+ * mirroring the `appendLeft`/`appendRight` distinction.
1144
+ */
1145
+ move(start, end, index, affinity = "right") {
1146
+ start = this._resolveIndex(start);
1147
+ end = this._resolveIndex(end);
1148
+ index = this._resolveIndex(index);
1149
+ if (start === end) return this;
1150
+ if (start < 0 || end > this.original.length || index < 0 || index > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1151
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
1152
+ if (index >= start && index <= end) throw new MagicStringError("cannot move a selection inside itself");
760
1153
  this._split(start);
761
1154
  this._split(end);
762
1155
  this._split(index);
763
- const first = this.byStart[start];
764
- const last = this.byEnd[end];
1156
+ const first = this.byStart.get(start);
1157
+ const last = this.byEnd.get(end);
1158
+ if (!first || !last) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1159
+ if (this.hasMovedChunks) {
1160
+ let cursor = first;
1161
+ while (cursor !== last) {
1162
+ cursor = cursor.next;
1163
+ if (!cursor || cursor.start < start || cursor.end > end) throw new MagicStringError(`cannot move ${start} to ${end} because an earlier move split that range`);
1164
+ }
1165
+ }
765
1166
  const oldLeft = first.previous;
766
1167
  const oldRight = last.next;
767
- const newRight = this.byStart[index];
768
- if (!newRight && last === this.lastChunk) return this;
769
- const newLeft = newRight ? newRight.previous : this.lastChunk;
1168
+ let newLeft;
1169
+ let newRight;
1170
+ if (affinity === "left") {
1171
+ newLeft = this.byEnd.get(index) ?? null;
1172
+ if (!newLeft) {
1173
+ if (first === this.firstChunk) return this;
1174
+ newRight = this.firstChunk;
1175
+ } else {
1176
+ if (newLeft.next === first) return this;
1177
+ newRight = newLeft.next;
1178
+ }
1179
+ } else {
1180
+ newRight = this.byStart.get(index) ?? null;
1181
+ if (!newRight) {
1182
+ if (last === this.lastChunk) return this;
1183
+ newLeft = this.lastChunk;
1184
+ } else {
1185
+ if (newRight.previous === last) return this;
1186
+ newLeft = newRight.previous;
1187
+ }
1188
+ }
770
1189
  if (oldLeft) oldLeft.next = oldRight;
771
1190
  if (oldRight) oldRight.previous = oldLeft;
772
1191
  if (newLeft) newLeft.next = first;
773
1192
  if (newRight) newRight.previous = last;
774
- if (!first.previous) this.firstChunk = last.next;
775
- if (!last.next) {
776
- this.lastChunk = first.previous;
1193
+ if (!oldLeft) this.firstChunk = oldRight;
1194
+ if (!oldRight) {
1195
+ this.lastChunk = oldLeft;
777
1196
  this.lastChunk.next = null;
778
1197
  }
779
1198
  first.previous = newLeft;
780
1199
  last.next = newRight || null;
781
1200
  if (!newLeft) this.firstChunk = first;
782
1201
  if (!newRight) this.lastChunk = last;
1202
+ this.hasMovedChunks = true;
783
1203
  return this;
784
1204
  }
1205
+ /**
1206
+ * Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in
1207
+ * that range. The same restrictions as `s.remove()` apply.
1208
+ *
1209
+ * The fourth argument is optional. It can have a storeName property - if true, the original name will be stored
1210
+ * for later inclusion in a sourcemap's names array - and a contentOnly property which determines whether only
1211
+ * the content is overwritten, or anything that was appended/prepended to the range as well.
1212
+ *
1213
+ * It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content.
1214
+ */
785
1215
  overwrite(start, end, content, options) {
786
- options = options || {};
1216
+ if (options === true) {
1217
+ if (!warned.storeName) {
1218
+ console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
1219
+ warned.storeName = true;
1220
+ }
1221
+ return this.update(start, end, content, {
1222
+ storeName: true,
1223
+ overwrite: true
1224
+ });
1225
+ }
1226
+ const optionObject = typeof options === "object" && options ? options : {};
787
1227
  return this.update(start, end, content, {
788
- ...options,
789
- overwrite: !options.contentOnly
1228
+ ...optionObject,
1229
+ overwrite: !optionObject.contentOnly
790
1230
  });
791
1231
  }
1232
+ /**
1233
+ * Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply.
1234
+ *
1235
+ * The fourth argument is optional. It can have a storeName property - if true, the original name will be stored
1236
+ * for later inclusion in a sourcemap's names array - and an overwrite property which determines whether only
1237
+ * the content is overwritten, or anything that was appended/prepended to the range as well.
1238
+ */
792
1239
  update(start, end, content, options) {
793
- start = start + this.offset;
794
- end = end + this.offset;
795
- if (typeof content !== "string") throw new TypeError("replacement content must be a string");
796
- if (this.original.length !== 0) {
797
- while (start < 0) start += this.original.length;
798
- while (end < 0) end += this.original.length;
799
- }
800
- if (end > this.original.length) throw new Error("end is out of bounds");
801
- if (start === end) throw new Error("Cannot overwrite a zero-length range – use appendLeft or prependRight instead");
1240
+ start = this._resolveIndex(start);
1241
+ end = this._resolveIndex(end);
1242
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
1243
+ if (start < 0) throw new MagicStringError(`start ${start} is out of bounds`);
1244
+ if (end > this.original.length) throw new MagicStringError(`end ${end} is out of bounds`);
1245
+ if (start === end) throw new MagicStringError(`cannot overwrite a zero-length range at ${start}, use appendLeft() or prependRight()`);
1246
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
802
1247
  this._split(start);
803
1248
  this._split(end);
804
1249
  if (options === true) {
@@ -808,152 +1253,178 @@ var MagicString = class MagicString {
808
1253
  }
809
1254
  options = { storeName: true };
810
1255
  }
811
- const storeName = options !== void 0 ? options.storeName : false;
812
- const overwrite = options !== void 0 ? options.overwrite : false;
813
- if (storeName) {
814
- const original = this.original.slice(start, end);
815
- Object.defineProperty(this.storedNames, original, {
816
- writable: true,
817
- value: true,
818
- enumerable: true
819
- });
1256
+ const optionObject = typeof options === "object" && options ? options : {};
1257
+ const storeName = optionObject.storeName || false;
1258
+ const overwrite = optionObject.overwrite || false;
1259
+ if (storeName) this.storedNames.add(this.original.slice(start, end));
1260
+ const first = this.byStart.get(start);
1261
+ for (let chunk = first; chunk.end < end;) {
1262
+ const next = chunk.next;
1263
+ if (next === null || next !== this.byStart.get(chunk.end)) throw new MagicStringError("cannot overwrite across a split point");
1264
+ chunk = next;
820
1265
  }
821
- const first = this.byStart[start];
822
- const last = this.byEnd[end];
823
- if (first) {
824
- let chunk = first;
825
- while (chunk !== last) {
826
- if (chunk.next !== this.byStart[chunk.end]) throw new Error("Cannot overwrite across a split point");
827
- chunk = chunk.next;
828
- chunk.edit("", false);
829
- }
830
- first.edit(content, storeName, !overwrite);
831
- } else {
832
- const newChunk = new Chunk(start, end, "").edit(content, storeName);
833
- last.next = newChunk;
834
- newChunk.previous = last;
1266
+ for (let chunk = first.next; chunk !== null && chunk.start < end; chunk = chunk.next) {
1267
+ chunk.edit("", false, !overwrite);
1268
+ chunk.replacesUntil = -1;
1269
+ chunk.replacedFrom = start;
835
1270
  }
1271
+ first.edit(content, storeName, !overwrite);
1272
+ first.replacesUntil = end;
1273
+ first.replacedFrom = -1;
836
1274
  return this;
837
1275
  }
1276
+ /**
1277
+ * Prepends the string with the specified content.
1278
+ */
838
1279
  prepend(content) {
839
- if (typeof content !== "string") throw new TypeError("outro content must be a string");
1280
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
840
1281
  this.intro = content + this.intro;
841
1282
  return this;
842
1283
  }
1284
+ /**
1285
+ * Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at index
1286
+ */
843
1287
  prependLeft(index, content) {
844
- index = index + this.offset;
845
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
1288
+ index = this._resolveIndex(index);
1289
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
1290
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
846
1291
  this._split(index);
847
- const chunk = this.byEnd[index];
1292
+ const chunk = this.byEnd.get(index);
848
1293
  if (chunk) chunk.prependLeft(content);
849
1294
  else this.intro = content + this.intro;
850
1295
  return this;
851
1296
  }
1297
+ /**
1298
+ * Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
1299
+ */
852
1300
  prependRight(index, content) {
853
- index = index + this.offset;
854
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
1301
+ index = this._resolveIndex(index);
1302
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
1303
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
855
1304
  this._split(index);
856
- const chunk = this.byStart[index];
1305
+ const chunk = this.byStart.get(index);
857
1306
  if (chunk) chunk.prependRight(content);
858
1307
  else this.outro = content + this.outro;
859
1308
  return this;
860
1309
  }
1310
+ /**
1311
+ * Removes the characters from `start` to `end` (of the original string, **not** the generated string).
1312
+ * Content appended or prepended at positions strictly inside the range is removed with it, while
1313
+ * content attached at `start` or `end` is preserved — use `s.overwrite(start, end, '')` to remove
1314
+ * the range including its edge inserts.
1315
+ * Repeated removals and removals with partially overlapping ranges are allowed.
1316
+ */
861
1317
  remove(start, end) {
862
- start = start + this.offset;
863
- end = end + this.offset;
864
- if (this.original.length !== 0) {
865
- while (start < 0) start += this.original.length;
866
- while (end < 0) end += this.original.length;
867
- }
1318
+ start = this._resolveIndex(start);
1319
+ end = this._resolveIndex(end);
868
1320
  if (start === end) return this;
869
- if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
870
- if (start > end) throw new Error("end must be greater than start");
1321
+ if (start < 0 || end > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1322
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
871
1323
  this._split(start);
872
1324
  this._split(end);
873
- let chunk = this.byStart[start];
1325
+ let chunk = this.byStart.get(start);
874
1326
  while (chunk) {
875
- chunk.intro = "";
876
- chunk.outro = "";
877
- chunk.edit("");
878
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1327
+ if (chunk.start > start) chunk.intro = "";
1328
+ if (chunk.end < end) chunk.outro = "";
1329
+ chunk.edit("", false, true);
1330
+ chunk.replacesUntil = -1;
1331
+ chunk.replacedFrom = -1;
1332
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : void 0;
879
1333
  }
880
1334
  return this;
881
1335
  }
1336
+ /**
1337
+ * Reset the modified characters from `start` to `end` (of the original string, **not** the generated string).
1338
+ */
882
1339
  reset(start, end) {
883
- start = start + this.offset;
884
- end = end + this.offset;
885
- if (this.original.length !== 0) {
886
- while (start < 0) start += this.original.length;
887
- while (end < 0) end += this.original.length;
888
- }
1340
+ start = this._resolveIndex(start);
1341
+ end = this._resolveIndex(end);
889
1342
  if (start === end) return this;
890
- if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
891
- if (start > end) throw new Error("end must be greater than start");
1343
+ if (start < 0 || end > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1344
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
892
1345
  this._split(start);
893
1346
  this._split(end);
894
- let chunk = this.byStart[start];
1347
+ let chunk = this.byStart.get(start);
895
1348
  while (chunk) {
896
1349
  chunk.reset();
897
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1350
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : void 0;
898
1351
  }
899
1352
  return this;
900
1353
  }
1354
+ /**
1355
+ * Returns the last character of the generated string, or `''` if it is empty.
1356
+ */
901
1357
  lastChar() {
902
1358
  if (this.outro.length) return this.outro[this.outro.length - 1];
903
1359
  let chunk = this.lastChunk;
904
- do {
1360
+ while (chunk) {
905
1361
  if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
906
1362
  if (chunk.content.length) return chunk.content[chunk.content.length - 1];
907
1363
  if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
908
- } while (chunk = chunk.previous);
1364
+ chunk = chunk.previous;
1365
+ }
909
1366
  if (this.intro.length) return this.intro[this.intro.length - 1];
910
1367
  return "";
911
1368
  }
1369
+ /**
1370
+ * Returns everything after the last newline in the generated string, or the whole string if there is no newline.
1371
+ */
912
1372
  lastLine() {
913
1373
  let lineIndex = this.outro.lastIndexOf(n);
914
- if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
1374
+ if (lineIndex !== -1) return this.outro.slice(lineIndex + 1);
915
1375
  let lineStr = this.outro;
916
1376
  let chunk = this.lastChunk;
917
- do {
1377
+ while (chunk) {
918
1378
  if (chunk.outro.length > 0) {
919
1379
  lineIndex = chunk.outro.lastIndexOf(n);
920
- if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
1380
+ if (lineIndex !== -1) return chunk.outro.slice(lineIndex + 1) + lineStr;
921
1381
  lineStr = chunk.outro + lineStr;
922
1382
  }
923
1383
  if (chunk.content.length > 0) {
924
1384
  lineIndex = chunk.content.lastIndexOf(n);
925
- if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
1385
+ if (lineIndex !== -1) return chunk.content.slice(lineIndex + 1) + lineStr;
926
1386
  lineStr = chunk.content + lineStr;
927
1387
  }
928
1388
  if (chunk.intro.length > 0) {
929
1389
  lineIndex = chunk.intro.lastIndexOf(n);
930
- if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
1390
+ if (lineIndex !== -1) return chunk.intro.slice(lineIndex + 1) + lineStr;
931
1391
  lineStr = chunk.intro + lineStr;
932
1392
  }
933
- } while (chunk = chunk.previous);
1393
+ chunk = chunk.previous;
1394
+ }
934
1395
  lineIndex = this.intro.lastIndexOf(n);
935
- if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
1396
+ if (lineIndex !== -1) return this.intro.slice(lineIndex + 1) + lineStr;
936
1397
  return this.intro + lineStr;
937
1398
  }
1399
+ /**
1400
+ * Returns the content of the generated string that corresponds to the slice
1401
+ * between `start` and `end` of the original string, walking the generated
1402
+ * string from the chunk holding `start` to the chunk holding `end`. Throws
1403
+ * if either index falls inside replaced content. After `move()`, a range
1404
+ * whose end now comes before its start in the output yields `''`.
1405
+ */
938
1406
  slice(start = 0, end = this.original.length - this.offset) {
939
- start = start + this.offset;
940
- end = end + this.offset;
941
- if (this.original.length !== 0) {
942
- while (start < 0) start += this.original.length;
943
- while (end < 0) end += this.original.length;
944
- }
1407
+ start = this._resolveIndex(start);
1408
+ end = this._resolveIndex(end);
945
1409
  let result = "";
946
- let chunk = this.firstChunk;
947
- while (chunk && (chunk.start > start || chunk.end <= start)) {
948
- if (chunk.start < end && chunk.end >= end) return result;
949
- chunk = chunk.next;
1410
+ let chunk;
1411
+ if (this.hasMovedChunks) {
1412
+ chunk = this.firstChunk;
1413
+ while (chunk && (chunk.start > start || chunk.end <= start)) {
1414
+ if (chunk.start < end && chunk.end >= end || end === 0 && chunk.start === 0) return result;
1415
+ chunk = chunk.next;
1416
+ }
1417
+ } else {
1418
+ if (start >= end) return result;
1419
+ chunk = this._chunkAt(start);
950
1420
  }
951
- if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
1421
+ if (chunk && chunk.edited && chunk.start !== start) throw new MagicStringError(`cannot use edited character ${start} as slice start anchor`);
952
1422
  const startChunk = chunk;
953
1423
  while (chunk) {
1424
+ if (end === 0 && chunk.start === 0) break;
954
1425
  if (chunk.intro && (startChunk !== chunk || chunk.start === start)) result += chunk.intro;
955
1426
  const containsEnd = chunk.start < end && chunk.end >= end;
956
- if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
1427
+ if (containsEnd && chunk.edited && chunk.end !== end) throw new MagicStringError(`cannot use edited character ${end} as slice end anchor`);
957
1428
  const sliceStart = startChunk === chunk ? start - chunk.start : 0;
958
1429
  const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
959
1430
  result += chunk.content.slice(sliceStart, sliceEnd);
@@ -963,37 +1434,74 @@ var MagicString = class MagicString {
963
1434
  }
964
1435
  return result;
965
1436
  }
1437
+ /**
1438
+ * Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed.
1439
+ */
966
1440
  snip(start, end) {
967
1441
  const clone = this.clone();
968
- clone.remove(0, start);
969
- clone.remove(end, clone.original.length);
1442
+ clone.remove(-clone.offset, start);
1443
+ clone.remove(end, clone.original.length - clone.offset);
970
1444
  return clone;
971
1445
  }
1446
+ /**
1447
+ * Applies `offset`, resolves a negative index from the end of `original` as
1448
+ * `update`/`remove` always have, and rejects anything that is not an integer.
1449
+ * Bounds are checked by the caller, because the methods report them differently.
1450
+ *
1451
+ * @internal
1452
+ */
1453
+ _resolveIndex(index) {
1454
+ const resolved = index + this.offset;
1455
+ if (!Number.isInteger(resolved)) throw new MagicStringError(`index must be an integer, got ${index}`);
1456
+ if (resolved < 0 && this.original.length !== 0) return Math.max(0, resolved + this.original.length);
1457
+ return resolved;
1458
+ }
1459
+ /**
1460
+ * The chunk whose original range holds `index` (`chunk.start <= index < chunk.end`),
1461
+ * or `undefined` when `index` is at or past the end. Searches from the last
1462
+ * visited chunk so that scans over nearby indices stay cheap.
1463
+ *
1464
+ * @internal
1465
+ */
1466
+ _chunkAt(index) {
1467
+ let chunk = this.byStart.get(index);
1468
+ if (chunk) return chunk;
1469
+ chunk = this.lastSearchedChunk;
1470
+ const searchForward = index >= chunk.end;
1471
+ while (chunk && !chunk.contains(index)) chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
1472
+ if (chunk) this.lastSearchedChunk = chunk;
1473
+ return chunk;
1474
+ }
1475
+ /** @internal */
972
1476
  _split(index) {
973
- if (this.byStart[index] || this.byEnd[index]) return;
1477
+ if (this.byStart.get(index) || this.byEnd.get(index)) return;
974
1478
  let chunk = this.lastSearchedChunk;
975
1479
  let previousChunk = chunk;
976
1480
  const searchForward = index > chunk.end;
977
1481
  while (chunk) {
978
1482
  if (chunk.contains(index)) return this._splitChunk(chunk, index);
979
- chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1483
+ chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
980
1484
  if (chunk === previousChunk) return;
981
1485
  previousChunk = chunk;
982
1486
  }
983
1487
  }
1488
+ /** @internal */
984
1489
  _splitChunk(chunk, index) {
985
1490
  if (chunk.edited && chunk.content.length) {
986
1491
  const loc = getLocator(this.original)(index);
987
- throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`);
1492
+ throw new MagicStringError(`cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`);
988
1493
  }
989
1494
  const newChunk = chunk.split(index);
990
- this.byEnd[index] = chunk;
991
- this.byStart[index] = newChunk;
992
- this.byEnd[newChunk.end] = newChunk;
1495
+ this.byEnd.set(index, chunk);
1496
+ this.byStart.set(index, newChunk);
1497
+ this.byEnd.set(newChunk.end, newChunk);
993
1498
  if (chunk === this.lastChunk) this.lastChunk = newChunk;
994
1499
  this.lastSearchedChunk = chunk;
995
1500
  return true;
996
1501
  }
1502
+ /**
1503
+ * Returns the generated string.
1504
+ */
997
1505
  toString() {
998
1506
  let str = this.intro;
999
1507
  let chunk = this.firstChunk;
@@ -1003,29 +1511,48 @@ var MagicString = class MagicString {
1003
1511
  }
1004
1512
  return str + this.outro;
1005
1513
  }
1514
+ /**
1515
+ * Returns true if the resulting source is empty (disregarding white space).
1516
+ */
1006
1517
  isEmpty() {
1518
+ if (this.intro.length && this.intro.trim()) return false;
1007
1519
  let chunk = this.firstChunk;
1008
- do
1520
+ while (chunk) {
1009
1521
  if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return false;
1010
- while (chunk = chunk.next);
1522
+ chunk = chunk.next;
1523
+ }
1524
+ if (this.outro.length && this.outro.trim()) return false;
1011
1525
  return true;
1012
1526
  }
1527
+ /**
1528
+ * Returns the length of the generated string, counting only content attached to the original characters.
1529
+ * Content outside the string body (`s.prepend()`/`s.append()`, and inserts before the first or after the last
1530
+ * character) is not counted, so this can differ from `s.toString().length`.
1531
+ */
1013
1532
  length() {
1014
1533
  let chunk = this.firstChunk;
1015
1534
  let length = 0;
1016
- do
1535
+ while (chunk) {
1017
1536
  length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1018
- while (chunk = chunk.next);
1537
+ chunk = chunk.next;
1538
+ }
1019
1539
  return length;
1020
1540
  }
1541
+ /**
1542
+ * Removes empty lines from the start and end.
1543
+ */
1021
1544
  trimLines() {
1022
1545
  return this.trim("[\\r\\n]");
1023
1546
  }
1547
+ /**
1548
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end.
1549
+ */
1024
1550
  trim(charType) {
1025
1551
  return this.trimStart(charType).trimEnd(charType);
1026
1552
  }
1553
+ /** @internal */
1027
1554
  trimEndAborted(charType) {
1028
- const rx = new RegExp((charType || "\\s") + "+$");
1555
+ const rx = new RegExp(`${charType || "\\s"}+$`);
1029
1556
  this.outro = this.outro.replace(rx, "");
1030
1557
  if (this.outro.length) return true;
1031
1558
  let chunk = this.lastChunk;
@@ -1033,22 +1560,28 @@ var MagicString = class MagicString {
1033
1560
  const end = chunk.end;
1034
1561
  const aborted = chunk.trimEnd(rx);
1035
1562
  if (chunk.end !== end) {
1036
- if (this.lastChunk === chunk) this.lastChunk = chunk.next;
1037
- this.byEnd[chunk.end] = chunk;
1038
- this.byStart[chunk.next.start] = chunk.next;
1039
- this.byEnd[chunk.next.end] = chunk.next;
1563
+ const next = chunk.next;
1564
+ if (this.lastChunk === chunk) this.lastChunk = next;
1565
+ this.byEnd.set(chunk.end, chunk);
1566
+ this.byStart.set(next.start, next);
1567
+ this.byEnd.set(next.end, next);
1040
1568
  }
1041
1569
  if (aborted) return true;
1042
1570
  chunk = chunk.previous;
1043
1571
  } while (chunk);
1044
- return false;
1572
+ this.intro = this.intro.replace(rx, "");
1573
+ return this.intro.length > 0;
1045
1574
  }
1575
+ /**
1576
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end.
1577
+ */
1046
1578
  trimEnd(charType) {
1047
1579
  this.trimEndAborted(charType);
1048
1580
  return this;
1049
1581
  }
1582
+ /** @internal */
1050
1583
  trimStartAborted(charType) {
1051
- const rx = new RegExp("^" + (charType || "\\s") + "+");
1584
+ const rx = new RegExp(`^${charType || "\\s"}+`);
1052
1585
  this.intro = this.intro.replace(rx, "");
1053
1586
  if (this.intro.length) return true;
1054
1587
  let chunk = this.firstChunk;
@@ -1056,86 +1589,148 @@ var MagicString = class MagicString {
1056
1589
  const end = chunk.end;
1057
1590
  const aborted = chunk.trimStart(rx);
1058
1591
  if (chunk.end !== end) {
1059
- if (chunk === this.lastChunk) this.lastChunk = chunk.next;
1060
- this.byEnd[chunk.end] = chunk;
1061
- this.byStart[chunk.next.start] = chunk.next;
1062
- this.byEnd[chunk.next.end] = chunk.next;
1592
+ const next = chunk.next;
1593
+ if (chunk === this.lastChunk) this.lastChunk = next;
1594
+ this.byEnd.set(chunk.end, chunk);
1595
+ this.byStart.set(next.start, next);
1596
+ this.byEnd.set(next.end, next);
1063
1597
  }
1064
1598
  if (aborted) return true;
1065
1599
  chunk = chunk.next;
1066
1600
  } while (chunk);
1067
- return false;
1601
+ this.outro = this.outro.replace(rx, "");
1602
+ return this.outro.length > 0;
1068
1603
  }
1604
+ /**
1605
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start.
1606
+ */
1069
1607
  trimStart(charType) {
1070
1608
  this.trimStartAborted(charType);
1071
1609
  return this;
1072
1610
  }
1611
+ /**
1612
+ * Indicates if the string has been changed.
1613
+ */
1073
1614
  hasChanged() {
1074
- return this.original !== this.toString();
1615
+ if (this.intro || this.outro) return true;
1616
+ let outputIndex = 0;
1617
+ let chunk = this.firstChunk;
1618
+ while (chunk) {
1619
+ if (chunk.intro || chunk.outro) return true;
1620
+ if (!chunk.edited && chunk.start === outputIndex) outputIndex = chunk.end;
1621
+ else {
1622
+ if (!this.original.startsWith(chunk.content, outputIndex)) return true;
1623
+ outputIndex += chunk.content.length;
1624
+ }
1625
+ chunk = chunk.next;
1626
+ }
1627
+ return outputIndex !== this.original.length;
1628
+ }
1629
+ /**
1630
+ * Whether the original range [start, end) has had any of its characters
1631
+ * removed. `replace`/`replaceAll` search `original`, so a match can land on
1632
+ * text that is no longer in the output - overwriting it would resurrect the
1633
+ * removed characters, so such matches are skipped instead.
1634
+ *
1635
+ * @internal
1636
+ */
1637
+ _hasRemovedContent(start, end) {
1638
+ const atBoundary = this.byStart.get(start);
1639
+ if (atBoundary && start === end) {
1640
+ const previous = this.byEnd.get(start);
1641
+ return !!previous && previous.content === "" && atBoundary.content === "";
1642
+ }
1643
+ let chunk = this._chunkAt(start);
1644
+ while (chunk && chunk.start < end) {
1645
+ if (chunk.content === "" && (chunk.replacedFrom < start || this.byStart.get(chunk.replacedFrom).replacesUntil < chunk.end)) return true;
1646
+ chunk = this.byStart.get(chunk.end);
1647
+ }
1648
+ return false;
1075
1649
  }
1650
+ /** @internal */
1076
1651
  _replaceRegexp(searchValue, replacement) {
1077
- function getReplacement(match, str) {
1078
- if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
1079
- if (i === "$") return "$";
1080
- if (i === "&") return match[0];
1081
- if (+i < match.length) return match[+i];
1082
- return `$${i}`;
1083
- });
1084
- else return replacement(...match, match.index, str, match.groups);
1085
- }
1086
- function matchAll(re, str) {
1087
- let match;
1088
- const matches = [];
1089
- while (match = re.exec(str)) matches.push(match);
1090
- return matches;
1652
+ function getReplacement(match, index, str) {
1653
+ if (typeof replacement === "string") return expandReplacement(replacement, match[0], index, str, match.slice(1), match.groups);
1654
+ else return match.groups === void 0 ? replacement(match[0], ...match.slice(1), index, str) : replacement(match[0], ...match.slice(1), index, str, match.groups);
1091
1655
  }
1092
- if (searchValue.global) matchAll(searchValue, this.original).forEach((match) => {
1093
- if (match.index != null) {
1094
- const replacement = getReplacement(match, this.original);
1095
- if (replacement !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement);
1096
- }
1097
- });
1098
- else {
1656
+ const replaceMatch = (match) => {
1657
+ /* v8 ignore next 2 -- `match.index` is always defined for matches from `matchAll` */
1658
+ if (match.index == null) return false;
1659
+ if (this._hasRemovedContent(match.index, match.index + match[0].length)) return false;
1660
+ const replacement = getReplacement(match, match.index, this.original);
1661
+ if (replacement === match[0]) return true;
1662
+ if (match[0].length === 0) this.appendRight(match.index - this.offset, replacement);
1663
+ else this.overwrite(match.index - this.offset, match.index + match[0].length - this.offset, replacement);
1664
+ return true;
1665
+ };
1666
+ if (searchValue.global) {
1667
+ searchValue.lastIndex = 0;
1668
+ for (const match of this.original.matchAll(searchValue)) replaceMatch(match);
1669
+ } else {
1099
1670
  const match = this.original.match(searchValue);
1100
- if (match && match.index != null) {
1101
- const replacement = getReplacement(match, this.original);
1102
- if (replacement !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement);
1671
+ if (match && !replaceMatch(match)) {
1672
+ const global = new RegExp(searchValue.source, `${searchValue.flags}g`);
1673
+ for (const next of this.original.matchAll(global)) if (replaceMatch(next)) break;
1103
1674
  }
1104
1675
  }
1105
1676
  return this;
1106
1677
  }
1678
+ /** @internal */
1107
1679
  _replaceString(string, replacement) {
1108
1680
  const { original } = this;
1109
- const index = original.indexOf(string);
1110
- if (index !== -1) {
1681
+ let index = original.indexOf(string);
1682
+ while (index !== -1) {
1683
+ if (this._hasRemovedContent(index, index + string.length)) {
1684
+ index = original.indexOf(string, index + string.length);
1685
+ continue;
1686
+ }
1111
1687
  if (typeof replacement === "function") replacement = replacement(string, index, original);
1112
- if (string !== replacement) this.overwrite(index, index + string.length, replacement);
1688
+ else replacement = expandReplacement(replacement, string, index, original, [], void 0);
1689
+ if (string !== replacement) {
1690
+ if (string.length === 0) this.appendRight(index - this.offset, replacement);
1691
+ else this.overwrite(index - this.offset, index + string.length - this.offset, replacement);
1692
+ }
1693
+ break;
1113
1694
  }
1114
1695
  return this;
1115
1696
  }
1697
+ /**
1698
+ * String replacement with RegExp or string.
1699
+ */
1116
1700
  replace(searchValue, replacement) {
1117
1701
  if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
1118
1702
  return this._replaceRegexp(searchValue, replacement);
1119
1703
  }
1704
+ /** @internal */
1120
1705
  _replaceAllString(string, replacement) {
1121
1706
  const { original } = this;
1122
1707
  const stringLength = string.length;
1708
+ if (stringLength === 0) {
1709
+ for (let index = 0; index <= original.length; index += 1) {
1710
+ if (this._hasRemovedContent(index, index)) continue;
1711
+ const _replacement = typeof replacement === "function" ? replacement("", index, original) : expandReplacement(replacement, "", index, original, [], void 0);
1712
+ if (_replacement !== "") this.appendRight(index - this.offset, _replacement);
1713
+ }
1714
+ return this;
1715
+ }
1123
1716
  for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
1717
+ if (this._hasRemovedContent(index, index + stringLength)) continue;
1124
1718
  const previous = original.slice(index, index + stringLength);
1125
- let _replacement = replacement;
1126
- if (typeof replacement === "function") _replacement = replacement(previous, index, original);
1127
- if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
1719
+ const _replacement = typeof replacement === "function" ? replacement(previous, index, original) : expandReplacement(replacement, previous, index, original, [], void 0);
1720
+ if (previous !== _replacement) this.overwrite(index - this.offset, index + stringLength - this.offset, _replacement);
1128
1721
  }
1129
1722
  return this;
1130
1723
  }
1724
+ /**
1725
+ * Same as `s.replace`, but replace all matched strings instead of just one.
1726
+ */
1131
1727
  replaceAll(searchValue, replacement) {
1132
1728
  if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement);
1133
- if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
1729
+ if (!searchValue.global) throw new MagicStringError("replaceAll() requires a global RegExp");
1134
1730
  return this._replaceRegexp(searchValue, replacement);
1135
1731
  }
1136
1732
  };
1137
- //#endregion
1138
- //#region ../internal/dist/config-edit.js
1733
+ // ../internal/dist/config-edit.js
1139
1734
  const viteModule = "vite-hub";
1140
1735
  const nuxtModule = "vite-hub/nuxt";
1141
1736
  function fail(reason, at) {
@@ -1647,8 +2242,7 @@ function insertViteHubConfig(file, code, options) {
1647
2242
  code: next
1648
2243
  };
1649
2244
  }
1650
- //#endregion
1651
- //#region src/setup/project.ts
2245
+ // src/setup/project.ts
1652
2246
  const nuxtConfigFiles = [
1653
2247
  "nuxt.config.ts",
1654
2248
  "nuxt.config.mts",
@@ -1765,7 +2359,7 @@ async function nuxtServerDirs(root, config, env) {
1765
2359
  return [resolve(appRoot, serverDir?.kind === "literal" && typeof serverDir.value === "string" ? serverDir.value || "server" : "server")];
1766
2360
  }
1767
2361
  function globalPackageDirs(name) {
1768
- return (process$1.env.NODE_PATH ?? "").split(delimiter).filter(Boolean).flatMap((dir) => {
2362
+ return (process.env.NODE_PATH ?? "").split(delimiter).filter(Boolean).flatMap((dir) => {
1769
2363
  try {
1770
2364
  return [realpathSync(join(dir, name))];
1771
2365
  } catch {
@@ -1819,463 +2413,7 @@ async function readSetupProject(root, env) {
1819
2413
  serverDirs: framework === "nuxt" ? await nuxtServerDirs(root, config, env) : [join(root, "server")]
1820
2414
  };
1821
2415
  }
1822
- //#endregion
1823
- //#region ../internal/dist/definition-catalog.js
1824
- const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
1825
- const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
1826
- const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
1827
- const ignoredDirs = /* @__PURE__ */ new Set([
1828
- "node_modules",
1829
- "dist",
1830
- ".output",
1831
- ".nuxt",
1832
- ".vercel",
1833
- ".git",
1834
- ".vitehub"
1835
- ]);
1836
- function readDirEntries(root) {
1837
- try {
1838
- return readdirSync(root, { withFileTypes: true });
1839
- } catch (error) {
1840
- if (error.code === "ENOENT") return [];
1841
- throw error;
1842
- }
1843
- }
1844
- function isGitRepositoryDirectory(directory) {
1845
- return existsSync(resolve(directory, ".git"));
1846
- }
1847
- function listMatchingFiles(root, predicate, options = {}) {
1848
- const files = [];
1849
- for (const entry of readDirEntries(root)) {
1850
- const absolute = resolve(root, entry.name);
1851
- if (entry.isDirectory() && !entry.isSymbolicLink()) {
1852
- if (isGitRepositoryDirectory(absolute)) continue;
1853
- if (entry.name.startsWith(".")) continue;
1854
- if (ignoredDirs.has(entry.name)) continue;
1855
- files.push(...listMatchingFiles(absolute, predicate, options));
1856
- continue;
1857
- }
1858
- if (entry.name.startsWith(".") && !options.includeHidden) continue;
1859
- if (entry.isFile() && predicate(entry.name)) files.push(absolute);
1860
- }
1861
- return files.sort();
1862
- }
1863
- /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
1864
- function isDefinitionSourceFile(name) {
1865
- return sourceFilePattern.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
1866
- }
1867
- function listSourceFiles(root, options = {}) {
1868
- return listMatchingFiles(root, isDefinitionSourceFile, options);
1869
- }
1870
- /**
1871
- * Whether `path` is a file, or a folder that holds a Definition source file. A Definition file in a server directory,
1872
- * such as `server/auth.ts` or a file in `server/queues/`, turns its feature on without a key. An empty folder, which
1873
- * Git does not keep, turns nothing on.
1874
- */
1875
- function hasDefinitionFiles(path) {
1876
- if (!existsSync(path)) return false;
1877
- return statSync(path).isFile() || listSourceFiles(path).length > 0;
1878
- }
1879
- //#endregion
1880
- //#region ../internal/dist/deployment.js
1881
- const unsupported = (reason) => ({
1882
- reason,
1883
- supported: false
1884
- });
1885
- const plans = {
1886
- cloudflare: {
1887
- host: "cloudflare",
1888
- nitroPreset: "cloudflare-module",
1889
- output: {
1890
- directory: ".output",
1891
- entry: "server/index.mjs",
1892
- packaging: "none"
1893
- },
1894
- runtime: "workerd",
1895
- services: {
1896
- blob: {
1897
- driver: "cloudflare",
1898
- guarantee: "native",
1899
- supported: true
1900
- },
1901
- browser: {
1902
- driver: "cloudflare",
1903
- guarantee: "native",
1904
- supported: true
1905
- },
1906
- queue: {
1907
- driver: "cloudflare",
1908
- guarantee: "native",
1909
- supported: true
1910
- },
1911
- rateLimit: {
1912
- driver: "cloudflare",
1913
- guarantee: "native",
1914
- supported: true
1915
- },
1916
- realtime: {
1917
- driver: "cloudflare",
1918
- guarantee: "native",
1919
- supported: true
1920
- },
1921
- sandbox: {
1922
- driver: "cloudflare",
1923
- guarantee: "native",
1924
- supported: true
1925
- }
1926
- }
1927
- },
1928
- deno: {
1929
- host: "deno",
1930
- nitroPreset: "deno-deploy",
1931
- output: {
1932
- directory: ".output",
1933
- entry: "server/index.mjs",
1934
- packaging: "deno-node-modules"
1935
- },
1936
- runtime: "deno",
1937
- services: {
1938
- blob: unsupported("Deno Deploy has no built-in durable Blob Store with ViteHub's object-storage contract."),
1939
- browser: unsupported("Deno Deploy has no built-in Browser Provider."),
1940
- queue: unsupported("Deno Deploy has no built-in Queue Provider with ViteHub's delivery contract."),
1941
- rateLimit: unsupported("Deno Deploy has no built-in distributed Rate Limit driver."),
1942
- realtime: unsupported("Deno Deploy has no shared room authority for Realtime."),
1943
- sandbox: unsupported("Deno Deploy has no built-in isolated Sandbox Provider.")
1944
- }
1945
- },
1946
- netlify: {
1947
- host: "netlify",
1948
- nitroPreset: "netlify",
1949
- output: {
1950
- directory: ".netlify",
1951
- entry: "v1/functions/server/server.mjs",
1952
- packaging: "none"
1953
- },
1954
- runtime: "node",
1955
- services: {
1956
- blob: {
1957
- driver: "netlify-blobs",
1958
- guarantee: "native",
1959
- supported: true
1960
- },
1961
- browser: unsupported("Netlify has no built-in Browser Provider."),
1962
- queue: unsupported("Netlify has no built-in Queue Provider with ViteHub's delivery contract."),
1963
- rateLimit: unsupported("Netlify has no built-in distributed Rate Limit driver."),
1964
- realtime: unsupported("Netlify has no shared room authority for Realtime."),
1965
- sandbox: unsupported("Netlify has no built-in isolated Sandbox Provider.")
1966
- }
1967
- },
1968
- node: {
1969
- host: "node",
1970
- nitroPreset: "node-server",
1971
- output: {
1972
- directory: ".output",
1973
- entry: "server/index.mjs",
1974
- packaging: "none"
1975
- },
1976
- runtime: "node",
1977
- services: {
1978
- blob: {
1979
- driver: "fs",
1980
- guarantee: "single-host",
1981
- supported: true
1982
- },
1983
- browser: unsupported("The Node host has no built-in Browser Provider."),
1984
- queue: {
1985
- driver: "local",
1986
- guarantee: "single-host",
1987
- supported: true
1988
- },
1989
- rateLimit: {
1990
- driver: "memory",
1991
- guarantee: "process-local",
1992
- supported: true
1993
- },
1994
- realtime: {
1995
- driver: "node",
1996
- guarantee: "native",
1997
- supported: true
1998
- },
1999
- sandbox: unsupported("The Node host has no built-in isolated Sandbox Provider.")
2000
- }
2001
- },
2002
- vercel: {
2003
- host: "vercel",
2004
- nitroPreset: "vercel",
2005
- output: {
2006
- directory: ".vercel/output",
2007
- entry: "functions/__server.func/index.mjs",
2008
- packaging: "none"
2009
- },
2010
- runtime: "node",
2011
- services: {
2012
- blob: {
2013
- driver: "vercel",
2014
- guarantee: "native",
2015
- supported: true
2016
- },
2017
- browser: unsupported("Vercel has no built-in Browser Provider."),
2018
- queue: {
2019
- driver: "vercel",
2020
- guarantee: "native",
2021
- supported: true
2022
- },
2023
- rateLimit: unsupported("Vercel has no built-in distributed Rate Limit driver."),
2024
- realtime: unsupported("Vercel has no shared room authority for Realtime."),
2025
- sandbox: {
2026
- driver: "vercel",
2027
- guarantee: "native",
2028
- supported: true
2029
- }
2030
- }
2031
- }
2032
- };
2033
- function resolveDeploymentPlan(host) {
2034
- const plan = plans[host];
2035
- if (!plan) throw internalErrorDiagnostics.INTERNAL_R0001({ message: `Unknown ViteHub host: ${JSON.stringify(host)}.` });
2036
- return plan;
2037
- }
2038
- /** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
2039
- function hostFromNitroPreset(value) {
2040
- const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
2041
- if (!normalized) return;
2042
- if (normalized.startsWith("cloudflare")) return "cloudflare";
2043
- if (normalized.startsWith("deno")) return "deno";
2044
- if (normalized.startsWith("netlify")) return "netlify";
2045
- if (normalized === "node" || normalized.startsWith("node-")) return "node";
2046
- if (normalized.startsWith("vercel")) return "vercel";
2047
- }
2048
- const providerHosts = [
2049
- ["WORKERS_CI", "cloudflare"],
2050
- ["NETLIFY", "netlify"],
2051
- ["NOW_BUILDER", "vercel"],
2052
- ["VERCEL", "vercel"],
2053
- ["VERCEL_ENV", "vercel"],
2054
- ["DENO_DEPLOY", "deno"],
2055
- ["DENO_DEPLOYMENT_ID", "deno"]
2056
- ];
2057
- /**
2058
- * Returns the ViteHub host that this process builds or runs on, or `undefined` when no variable names a host.
2059
- * The order is `VITEHUB_HOST`, `NITRO_PRESET`, `SERVER_PRESET`, then the provider variables:
2060
- * `WORKERS_CI` (Cloudflare Workers Builds), `NETLIFY`, `NOW_BUILDER`, `VERCEL` or `VERCEL_ENV`, then `DENO_DEPLOY` or `DENO_DEPLOYMENT_ID`.
2061
- * `vitehub()` uses this result when `host` is omitted, and `"node"` when it is `undefined`.
2062
- */
2063
- function detectHost(env = process.env) {
2064
- for (const name of [
2065
- "VITEHUB_HOST",
2066
- "NITRO_PRESET",
2067
- "SERVER_PRESET"
2068
- ]) {
2069
- const host = hostFromNitroPreset(env[name]);
2070
- if (host) return host;
2071
- }
2072
- return providerHosts.find(([name]) => env[name]?.trim())?.[1];
2073
- }
2074
- //#endregion
2075
- //#region src/setup/status.ts
2076
- const addArgs = {
2077
- bun: {
2078
- dev: ["add", "-d"],
2079
- prod: ["add"]
2080
- },
2081
- npm: {
2082
- dev: ["install", "-D"],
2083
- prod: ["install"]
2084
- },
2085
- pnpm: {
2086
- dev: ["add", "-D"],
2087
- prod: ["add"]
2088
- },
2089
- yarn: {
2090
- dev: ["add", "-D"],
2091
- prod: ["add"]
2092
- }
2093
- };
2094
- /** Quotes `value` for a POSIX shell when it needs quotes. */
2095
- function shellQuote(value) {
2096
- return /^[\w@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
2097
- }
2098
- /** The arguments of the `packageManager` command that installs `packages`, such as `["add", "-D", "drizzle-kit"]`. */
2099
- function installArgs(packageManager, packages, dev) {
2100
- return [...addArgs[packageManager][dev ? "dev" : "prod"], ...packages];
2101
- }
2102
- const removeArgs = {
2103
- bun: ["remove"],
2104
- npm: ["uninstall"],
2105
- pnpm: ["remove"],
2106
- yarn: ["remove"]
2107
- };
2108
- /** The arguments of the `packageManager` command that uninstalls `packages`, such as `["remove", "@vite-hub/queue"]`. */
2109
- function uninstallArgs(packageManager, packages) {
2110
- return [...removeArgs[packageManager], ...packages];
2111
- }
2112
- function formatInstallCommand(command, args) {
2113
- return [command, ...args].map(formatInstallArgument).join(" ");
2114
- }
2115
- function installCommand(packageManager, prod, dev) {
2116
- const commands = [...prod.length ? [formatInstallCommand(packageManager, installArgs(packageManager, prod, false))] : [], ...dev.length ? [formatInstallCommand(packageManager, installArgs(packageManager, dev, true))] : []];
2117
- return commands.length ? commands.join(" && ") : void 0;
2118
- }
2119
- function readHost(project, env) {
2120
- const config = project.config;
2121
- if (config && !config.ok && config.reason !== "no-vitehub") return {
2122
- name: "unknown",
2123
- source: "config"
2124
- };
2125
- const site = config?.ok ? config.site : void 0;
2126
- const host = site?.keys.host;
2127
- const fromConfig = host?.kind === "literal" && typeof host.value === "string" ? hostFromNitroPreset(host.value) : void 0;
2128
- if (fromConfig) return {
2129
- name: fromConfig,
2130
- source: "config"
2131
- };
2132
- if (host || site?.spread) return {
2133
- name: "unknown",
2134
- source: "config"
2135
- };
2136
- const fromEnv = detectHost(env);
2137
- return fromEnv ? {
2138
- name: fromEnv,
2139
- source: "env"
2140
- } : {
2141
- name: "node",
2142
- source: "default"
2143
- };
2144
- }
2145
- function readEnabled(project, id, withoutDefinitions) {
2146
- const config = project.config;
2147
- if (!config || !config.ok && config.reason === "no-vitehub") return {
2148
- enabled: "off",
2149
- reason: "default"
2150
- };
2151
- if (!config.ok) return {
2152
- enabled: "unknown",
2153
- reason: "config"
2154
- };
2155
- const value = config.site.keys[id];
2156
- if (value?.kind === "expression") return {
2157
- enabled: "unknown",
2158
- reason: "config"
2159
- };
2160
- if (value) return {
2161
- enabled: value.value === false ? "off" : "on",
2162
- reason: "config"
2163
- };
2164
- if (config.site.spread) return {
2165
- enabled: "unknown",
2166
- reason: "config"
2167
- };
2168
- if (features[id].enabledByDefault) return {
2169
- enabled: "on",
2170
- reason: "default"
2171
- };
2172
- if (withoutDefinitions?.has(id)) return {
2173
- enabled: "off",
2174
- reason: "default"
2175
- };
2176
- const discovery = features[id].enabledByDiscovery;
2177
- const directories = project.serverDirs ?? (project.framework === "nuxt" ? void 0 : [join(project.root, "server")]);
2178
- if (discovery && !directories) return {
2179
- enabled: "unknown",
2180
- reason: "default"
2181
- };
2182
- return {
2183
- enabled: discovery?.some((file) => directories?.some((directory) => hasDefinitionFiles(join(directory, file)))) ? "on" : "off",
2184
- reason: "default"
2185
- };
2186
- }
2187
- const kvDefaultStoreOption = "kv.stores.default.driver";
2188
- function kvStores(value) {
2189
- return isRecord(value) && isRecord(value.stores) ? value.stores : void 0;
2190
- }
2191
- function missingProviderOption(project, option, value) {
2192
- const [id, key] = option.split(".");
2193
- const configured = project.config?.ok ? project.config.site.keys[id] : void 0;
2194
- if (configured?.kind === "expression") return;
2195
- const options = value ?? configured?.value;
2196
- const stores = option === "kv.driver" ? kvStores(options) : void 0;
2197
- if (stores) {
2198
- const store = stores.default;
2199
- const driver = isRecord(store) ? store.driver : void 0;
2200
- if (driver !== "upstash" && driver !== "redis" && driver !== "database") return kvDefaultStoreOption;
2201
- return;
2202
- }
2203
- if (!isRecord(options) || !(key in options)) return option;
2204
- }
2205
- function featureFix(project, id, support, host, missing, providerChosen) {
2206
- const install = installCommand(project.packageManager, missing.prod.map(installSpecifier), missing.dev.map(installSpecifier));
2207
- if (install) return install;
2208
- if (support.level === "unsupported") return `Set \`${id}: false\`, or build for another host than ${host}.`;
2209
- if (support.level === "explicit" && !providerChosen) {
2210
- const option = missingProviderOption(project, support.option);
2211
- if (option) return `Set \`${option}\` in vitehub() to choose a provider on ${host}.`;
2212
- }
2213
- }
2214
- /** What the project enables, on which host, and what each enabled feature still needs. Reads the config without running it. */
2215
- function setupStatus(project, env, withoutDefinitions) {
2216
- const host = readHost(project, env);
2217
- const enabled = new Map(featureIds.map((id) => [id, readEnabled(project, id, withoutDefinitions)]));
2218
- const on = featureIds.filter((id) => enabled.get(id).enabled === "on");
2219
- const keep = featureIds.filter((id) => enabled.get(id).enabled !== "on" && enabled.get(id).reason === "config");
2220
- const maybeOn = featureIds.filter((id) => enabled.get(id).enabled !== "off");
2221
- const disabled = keep.filter((id) => enabled.get(id).enabled === "off");
2222
- const definite = impliedFeatures(on, keep);
2223
- for (const id of impliedFeatures(maybeOn, disabled)) {
2224
- const state = enabled.get(id);
2225
- if (state.enabled === "off" && state.reason === "default") enabled.set(id, {
2226
- enabled: definite.includes(id) ? "on" : "unknown",
2227
- reason: "implied"
2228
- });
2229
- }
2230
- return {
2231
- config: !project.config ? { manual: "no-vitehub" } : project.config.ok ? {
2232
- file: project.configFile,
2233
- form: project.config.site.form
2234
- } : {
2235
- file: project.configFile,
2236
- manual: project.config.reason,
2237
- ...project.config.line === void 0 ? {} : { line: project.config.line }
2238
- },
2239
- features: featureIds.map((id) => {
2240
- const state = enabled.get(id);
2241
- const support = host.name === "unknown" ? {
2242
- level: "unknown",
2243
- detail: "The config does not statically identify the deployment host."
2244
- } : featureSupport(id, host.name);
2245
- const definition = features[id];
2246
- const value = project.config?.ok ? project.config.site.keys[id] : void 0;
2247
- const literal = value?.kind === "literal" ? value.value : void 0;
2248
- const packages = featurePackages(id, literal, host.name, featureIds.filter((feature) => enabled.get(feature)?.enabled === "on"));
2249
- const missing = state.enabled === "on" ? {
2250
- dev: definition.devPackages.filter((name) => !project.installed(name)),
2251
- prod: packages.filter((name) => !project.installed(name))
2252
- } : {
2253
- dev: [],
2254
- prod: []
2255
- };
2256
- const providerChosen = id === "workflow" && host.name !== "netlify" && packages.includes("openworkflow");
2257
- const fix = state.enabled === "on" ? featureFix(project, id, support, host.name, missing, providerChosen) : void 0;
2258
- const resolvedSupport = support.level === "explicit" && support.option === "kv.driver" && kvStores(literal) ? {
2259
- ...support,
2260
- option: kvDefaultStoreOption
2261
- } : support;
2262
- return {
2263
- id,
2264
- ...state,
2265
- missingPackages: [...missing.prod, ...missing.dev],
2266
- support: resolvedSupport,
2267
- ...fix ? { fix } : {}
2268
- };
2269
- }),
2270
- framework: project.framework,
2271
- host,
2272
- packageManager: project.packageManager,
2273
- root: project.root,
2274
- schemaVersion: 1
2275
- };
2276
- }
2277
- //#endregion
2278
- //#region src/setup/deploy/host.ts
2416
+ // src/setup/deploy/host.ts
2279
2417
  /** A failed host CLI that may print values on stdout, such as `vercel env ls --json`: only stderr goes into the reason. */
2280
2418
  function hostListFailed(step, result, secrets) {
2281
2419
  return hostCliFailed(step, {
@@ -2299,14 +2437,14 @@ async function untilInterrupted(work) {
2299
2437
  received ??= signal;
2300
2438
  controller.abort();
2301
2439
  };
2302
- process$1.on("SIGINT", stop);
2303
- process$1.on("SIGTERM", stop);
2440
+ process.on("SIGINT", stop);
2441
+ process.on("SIGTERM", stop);
2304
2442
  try {
2305
2443
  return await work(controller.signal);
2306
2444
  } finally {
2307
- process$1.off("SIGINT", stop);
2308
- process$1.off("SIGTERM", stop);
2309
- if (received) process$1.exit(128 + constants.signals[received]);
2445
+ process.off("SIGINT", stop);
2446
+ process.off("SIGTERM", stop);
2447
+ if (received) process.exit(128 + constants.signals[received]);
2310
2448
  }
2311
2449
  }
2312
2450
  /**
@@ -2352,7 +2490,7 @@ function createDeployRun(stderr, secrets) {
2352
2490
  "pipe",
2353
2491
  "pipe"
2354
2492
  ],
2355
- detached: process$1.platform !== "win32"
2493
+ detached: process.platform !== "win32"
2356
2494
  });
2357
2495
  const output = {
2358
2496
  stderr: "",
@@ -2416,7 +2554,7 @@ function createDeployRun(stderr, secrets) {
2416
2554
  };
2417
2555
  const killTree = (signal) => {
2418
2556
  if (!child.pid) return;
2419
- if (process$1.platform === "win32") spawn("taskkill", [
2557
+ if (process.platform === "win32") spawn("taskkill", [
2420
2558
  "/pid",
2421
2559
  String(child.pid),
2422
2560
  "/T",
@@ -2428,7 +2566,7 @@ function createDeployRun(stderr, secrets) {
2428
2566
  child.kill(signal);
2429
2567
  });
2430
2568
  else try {
2431
- process$1.kill(-child.pid, signal);
2569
+ process.kill(-child.pid, signal);
2432
2570
  } catch (error) {
2433
2571
  if (error.code !== "ESRCH") child.kill(signal);
2434
2572
  }
@@ -2475,7 +2613,7 @@ function windowsNodeEntry(file) {
2475
2613
  if (/\.(?:exe|cmd|bat)$/iu.test(file)) return;
2476
2614
  if (!existsSync(file)) return;
2477
2615
  const source = readFileSync(file, "utf8");
2478
- if (/\.[cm]?js$/iu.test(file) || /^#![^\r\n]*\bnode(?:\.exe)?(?:\s|$)/u.test(source)) return [process$1.execPath, file];
2616
+ if (/\.[cm]?js$/iu.test(file) || /^#![^\r\n]*\bnode(?:\.exe)?(?:\s|$)/u.test(source)) return [process.execPath, file];
2479
2617
  }
2480
2618
  function executableIn(folder, name, platform) {
2481
2619
  const file = join(folder, name);
@@ -2492,7 +2630,7 @@ function executableIn(folder, name, platform) {
2492
2630
  * The host CLI as a command and its first arguments: the project's `node_modules/.bin` (walking up), then `PATH`,
2493
2631
  * then `npx --yes <package>`, which the build output also names.
2494
2632
  */
2495
- function hostCli(name, npmPackage, root, env, platform = process$1.platform) {
2633
+ function hostCli(name, npmPackage, root, env, platform = process.platform) {
2496
2634
  for (let folder = root;; folder = dirname(folder)) {
2497
2635
  const found = executableIn(join(folder, "node_modules", ".bin"), name, platform);
2498
2636
  if (found) return found;
@@ -2504,7 +2642,7 @@ function hostCli(name, npmPackage, root, env, platform = process$1.platform) {
2504
2642
  if (found) return found;
2505
2643
  }
2506
2644
  if (platform === "win32") {
2507
- for (const folder of [...path, dirname(process$1.execPath)]) {
2645
+ for (const folder of [...path, dirname(process.execPath)]) {
2508
2646
  const npx = executableIn(folder, "npx", platform);
2509
2647
  if (npx) return [
2510
2648
  ...npx,
@@ -2629,8 +2767,7 @@ async function readDeployCommit(run, root, env) {
2629
2767
  return;
2630
2768
  }
2631
2769
  }
2632
- //#endregion
2633
- //#region src/setup/build-output.ts
2770
+ // src/setup/build-output.ts
2634
2771
  /** Runs the build script for `host`. VITEHUB_HOST_SOURCE=cli makes `host` win over a `host` literal in vitehub(). */
2635
2772
  async function build(project, host, context) {
2636
2773
  const command = `${project.packageManager} run build`;
@@ -2712,8 +2849,85 @@ async function readBuildOutput(root, host) {
2712
2849
  ...identityName ? { identityName } : {}
2713
2850
  };
2714
2851
  }
2715
- //#endregion
2716
- //#region src/setup/deploy/cloudflare.ts
2852
+ // src/setup/deploy/console.ts
2853
+ const consoleKeyPrefix = "VITEHUB_CONSOLE_KEY_";
2854
+ const checkDelays = [
2855
+ 1e3,
2856
+ 2e3,
2857
+ 4e3
2858
+ ];
2859
+ /** True when the build reads `VITEHUB_CONSOLE_KEY_<NAME>`, which `console: true` adds. */
2860
+ function readsConsoleKey(entries) {
2861
+ return entries.some((entry) => entry.prefix === consoleKeyPrefix);
2862
+ }
2863
+ async function openDeployConsole(context) {
2864
+ if (!await readConsoleCredential(context.env)) return;
2865
+ try {
2866
+ const client = await openConsole(context);
2867
+ const apps = await listConsoleApps(client);
2868
+ return {
2869
+ apps,
2870
+ client,
2871
+ keys: Object.fromEntries(apps.flatMap((app) => app.keyVariable && app.publicKey ? [[app.keyVariable, app.publicKey]] : []))
2872
+ };
2873
+ } catch (error) {
2874
+ context.stderr.write(`Warning: deploy does not link the app in the Console, because the Console failed: ${errorMessage(error)}\n`);
2875
+ return "unavailable";
2876
+ }
2877
+ }
2878
+ async function linkDeployedApp(options) {
2879
+ const { client } = options.console;
2880
+ try {
2881
+ const target = normalizeConsoleProjectUrl(options.url);
2882
+ const installed = options.console.apps.filter((app) => app.keyVariable && options.onHost.has(app.keyVariable));
2883
+ const known = installed.find((app) => app.url === target);
2884
+ if (!known && installed.length) {
2885
+ options.context.stderr.write(`Warning: the installed Console key links to ${installed.map((app) => app.url).join(", ")}, not ${options.url}. Link the current production URL and set its key with \`vitehub apps link ${options.url}\`.\n`);
2886
+ return;
2887
+ }
2888
+ const { app, created } = known ? {
2889
+ app: known,
2890
+ created: false
2891
+ } : await linkConsoleApp(client, {
2892
+ label: options.label,
2893
+ url: options.url
2894
+ });
2895
+ const keySet = app.keyVariable && app.publicKey && !options.onHost.has(app.keyVariable) ? app.keyVariable : void 0;
2896
+ const liveUrl = keySet && app.publicKey ? await options.setKey(keySet, app.publicKey) : options.url;
2897
+ if (!liveUrl || normalizeConsoleProjectUrl(liveUrl) !== app.url) {
2898
+ options.context.stderr.write(`Warning: the Console record for ${app.url} does not match the final production URL (${liveUrl ?? "not reported"}). Check the production URL before linking the app.\n`);
2899
+ return;
2900
+ }
2901
+ let check = await checkConsoleApp(client, app.id);
2902
+ for (const delay of checkDelays) {
2903
+ if (check.linked) break;
2904
+ await setTimeout$1(delay);
2905
+ check = await checkConsoleApp(client, app.id);
2906
+ }
2907
+ return {
2908
+ app: app.id,
2909
+ console: client.origin,
2910
+ created,
2911
+ ...keySet ? { keySet } : {},
2912
+ linked: check.linked,
2913
+ ...check.linked ? {} : { problem: checkProblem(check) },
2914
+ url: consoleAppUrl(client.origin, app)
2915
+ };
2916
+ } catch (error) {
2917
+ options.context.stderr.write(`Warning: the app is deployed, but deploy could not link it in the Console: ${errorMessage(error)} Run \`vitehub apps link ${options.url}\`.\n`);
2918
+ }
2919
+ }
2920
+ function formatDeployConsole(output) {
2921
+ return `${[
2922
+ ...output.created ? [`Linked the app in ${output.console} as ${output.app}.`] : [],
2923
+ ...output.keySet ? [`Set ${output.keySet} on the host.`] : [],
2924
+ output.linked ? `Console: ${output.url}` : `The app does not accept the Console yet: ${output.problem ?? "no answer"}. Run \`vitehub apps check ${output.app}\`.`
2925
+ ].join("\n")}\n`;
2926
+ }
2927
+ function errorMessage(error) {
2928
+ return error instanceof Error ? error.message : String(error);
2929
+ }
2930
+ // src/setup/deploy/cloudflare.ts
2717
2931
  const valueFlags = /* @__PURE__ */ new Set(["--config"]);
2718
2932
  const plainFlags = /* @__PURE__ */ new Set(["--containers-rollout=gradual"]);
2719
2933
  async function readWranglerCommand(outputDir) {
@@ -2813,6 +3027,28 @@ async function readWranglerOutput(file) {
2813
3027
  }
2814
3028
  });
2815
3029
  }
3030
+ /**
3031
+ * Wrangler 4.157 writes the `workers.dev` target as an `https://` URL, a custom domain as a bare host, such as
3032
+ * `example.com (custom domain)`, and a route as its pattern. A route with one host and the path `/*` serves every path
3033
+ * of that host. A wildcard host, a narrower path, triggers, and a custom domain with `production: disabled` have no
3034
+ * URL to request.
3035
+ */
3036
+ function wranglerTargetUrl(targets) {
3037
+ const texts = Array.isArray(targets) ? targets.filter((target) => typeof target === "string") : [];
3038
+ return [...texts.map(directTargetUrl), ...texts.map(routeTargetUrl)].find((url) => url !== void 0 && URL.canParse(url));
3039
+ }
3040
+ const workersDevTarget = /^https:\/\/[^\s*/]+\.workers\.dev\/?$/u;
3041
+ const customDomainTarget = /^([^\s*/:]+) \(custom domain[ )]/u;
3042
+ const catchAllRouteTarget = /^(?:https:\/\/)?([^\s*/:]+)\/\*(?: \(zone (?:id|name): [^)]+\))?$/u;
3043
+ function directTargetUrl(target) {
3044
+ if (workersDevTarget.test(target)) return target;
3045
+ const domain = customDomainTarget.exec(target)?.[1];
3046
+ return domain && !target.includes("production: disabled") ? `https://${domain}` : void 0;
3047
+ }
3048
+ function routeTargetUrl(target) {
3049
+ const host = catchAllRouteTarget.exec(target)?.[1];
3050
+ return host ? `https://${host}` : void 0;
3051
+ }
2816
3052
  const durationUnits = {
2817
3053
  second: 1e3,
2818
3054
  minute: 6e4,
@@ -2921,18 +3157,19 @@ async function cloudflareAdapter(context) {
2921
3157
  show: true,
2922
3158
  signal
2923
3159
  });
2924
- if (result.exitCode !== 0) throw hostCliFailed(context.preview ? "wrangler versions upload" : "wrangler deploy", result, context.secrets);
3160
+ const step = context.preview ? "wrangler versions upload" : "wrangler deploy";
3161
+ if (result.exitCode !== 0) throw hostCliFailed(step, result, context.secrets);
2925
3162
  const entry = (await readWranglerOutput(outputFile)).findLast((item) => item.type === (context.preview ? "version-upload" : "deploy"));
2926
3163
  const text = `${result.stdout}\n${result.stderr}`;
2927
- const targets = Array.isArray(entry?.targets) ? entry.targets.filter((target) => typeof target === "string") : [];
2928
- const url = (context.preview ? optionalString$1(entry?.preview_url) : targets[0]) ?? findUrl(text, /\.workers\.dev$/u);
2929
- if (!url) throw hostCliFailed("wrangler deploy printed no URL", result, context.secrets);
3164
+ const fromTargets = entry && !context.preview;
3165
+ const url = fromTargets ? wranglerTargetUrl(entry.targets) : optionalString$1(entry?.preview_url) ?? findUrl(text, /\.workers\.dev$/u);
3166
+ if (!url && !fromTargets) throw hostCliFailed(`${step} printed no URL`, result, context.secrets);
2930
3167
  const version = optionalString$1(entry?.version_id);
2931
3168
  const claimUrl = /Claim URL:\s*(https:\/\/\S+)/u.exec(text)?.[1];
2932
3169
  const expiresAt = claimExpiry(text);
2933
3170
  const name = optionalString$1(entry?.worker_name);
2934
3171
  return {
2935
- url,
3172
+ ...url ? { url } : {},
2936
3173
  ...version ? { version } : {},
2937
3174
  ...claimUrl ? { claim: {
2938
3175
  url: claimUrl,
@@ -3137,8 +3374,7 @@ const listCloudflareDeployments = async (context, { limit, includeLive }) => {
3137
3374
  if (includeLive && live && !recent.includes(live)) recent.push(live);
3138
3375
  return recent;
3139
3376
  };
3140
- //#endregion
3141
- //#region src/setup/deploy/deno.ts
3377
+ // src/setup/deploy/deno.ts
3142
3378
  const runnerFirstLine = "import { spawn } from \"node:child_process\"";
3143
3379
  async function denoAdapter(context, organization) {
3144
3380
  const runner = join(context.outputDir, "deploy.mjs");
@@ -3151,7 +3387,7 @@ async function denoAdapter(context, organization) {
3151
3387
  DENO_DEPLOY_ORG: organization
3152
3388
  };
3153
3389
  return { async deploy() {
3154
- const result = await context.run(process$1.execPath, [runner], {
3390
+ const result = await context.run(process.execPath, [runner], {
3155
3391
  cwd: context.root,
3156
3392
  env,
3157
3393
  show: true
@@ -3227,7 +3463,7 @@ function denoEnv(context) {
3227
3463
  return Array.isArray(value) ? value.flatMap((item) => isRecord(item) && typeof item.key === "string" ? [item.key] : []) : [];
3228
3464
  },
3229
3465
  async setSecret(name, value, { secret }) {
3230
- if (process$1.platform === "win32") throw setupFailure(cliErrorDiagnostics.SETUP_ENV_VALUE_UNSUPPORTED({
3466
+ if (process.platform === "win32") throw setupFailure(cliErrorDiagnostics.SETUP_ENV_VALUE_UNSUPPORTED({
3231
3467
  host: "deno",
3232
3468
  name,
3233
3469
  reason: "Windows has no /dev/stdin for `deno deploy env load`."
@@ -3318,8 +3554,7 @@ const listDenoDeployments = async (context, { limit, includeLive }) => {
3318
3554
  });
3319
3555
  return recent;
3320
3556
  };
3321
- //#endregion
3322
- //#region ../internal/dist/abort.js
3557
+ // ../internal/dist/abort.js
3323
3558
  /**
3324
3559
  * Runs `task` and rejects as soon as `signal` aborts, without waiting for the task.
3325
3560
  *
@@ -3349,8 +3584,7 @@ function abortReason(signal, message) {
3349
3584
  if (signal?.reason !== void 0) return signal.reason;
3350
3585
  return new DOMException(message, "AbortError");
3351
3586
  }
3352
- //#endregion
3353
- //#region src/setup/deploy/netlify.ts
3587
+ // src/setup/deploy/netlify.ts
3354
3588
  const publishDir = "dist";
3355
3589
  function netlifyAdapter(context) {
3356
3590
  const netlify = hostCli("netlify", "netlify-cli", context.root, context.env);
@@ -3616,8 +3850,7 @@ const listNetlifyDeployments = async (context, { limit, includeLive }) => {
3616
3850
  }
3617
3851
  return recent;
3618
3852
  };
3619
- //#endregion
3620
- //#region src/setup/deploy/vercel.ts
3853
+ // src/setup/deploy/vercel.ts
3621
3854
  /** Check the CLI's saved session without reading its auth files or exposing a token. */
3622
3855
  async function hasVercelLogin(root, context) {
3623
3856
  try {
@@ -3674,12 +3907,14 @@ function vercelAdapter(context) {
3674
3907
  if (result.exitCode !== 0) throw hostCliFailed("vercel deploy", result, context.secrets);
3675
3908
  const json = lastJsonObject(result.stdout);
3676
3909
  const deployment = isRecord(json?.deployment) ? json.deployment : json;
3677
- const url = context.preview ? optionalString$1(deployment?.url) : optionalString$1(deployment?.productionUrl) ?? optionalString$1(deployment?.url);
3910
+ const productionUrl = context.preview ? void 0 : optionalString$1(deployment?.productionUrl);
3911
+ const url = productionUrl ?? optionalString$1(deployment?.url);
3678
3912
  if (!url) throw hostCliFailed("vercel deploy printed no URL", result, context.secrets);
3679
3913
  const id = optionalString$1(deployment?.id);
3680
3914
  const claim = context.temporary ? await readClaim(context.root) : void 0;
3681
3915
  return {
3682
3916
  url,
3917
+ ...productionUrl ? { productionUrl } : {},
3683
3918
  ...id ? { deploymentId: id } : {},
3684
3919
  ...claim ? { claim } : {},
3685
3920
  ...context.temporary ? {} : { project: {
@@ -3824,8 +4059,7 @@ const listVercelDeployments = async (context, { limit, includeLive }) => {
3824
4059
  }
3825
4060
  return recent;
3826
4061
  };
3827
- //#endregion
3828
- //#region src/setup/link.ts
4062
+ // src/setup/link.ts
3829
4063
  /** The link file, relative to the project root. It is gitignored and never holds a secret. */
3830
4064
  const SETUP_LINK_FILE = ".vitehub/link.json";
3831
4065
  const linkHosts = [
@@ -4399,8 +4633,7 @@ function describeCredentials(credentials) {
4399
4633
  async function readSetupLinkStatus(project, host, context) {
4400
4634
  return (await readSetupLinkState(project, host, context)).status;
4401
4635
  }
4402
- //#endregion
4403
- //#region src/setup/env-encrypted.ts
4636
+ // src/setup/env-encrypted.ts
4404
4637
  const prefix = "encrypted:";
4405
4638
  /** The file where dotenvx writes private keys. It must never be in git. */
4406
4639
  const envKeysFile = ".env.keys";
@@ -4466,8 +4699,7 @@ async function decryptEnvValues(root, items, env) {
4466
4699
  values
4467
4700
  };
4468
4701
  }
4469
- //#endregion
4470
- //#region src/setup/deploy/github.ts
4702
+ // src/setup/deploy/github.ts
4471
4703
  const apiBase = "https://api.github.com";
4472
4704
  const repositoryPattern = /^[\w.-]+\/[\w.-]+$/u;
4473
4705
  /** GitHub accepts letters, digits, and `_`, not a digit first, and reserves the `GITHUB_` prefix. */
@@ -4643,14 +4875,8 @@ function githubEnv(context) {
4643
4875
  }
4644
4876
  };
4645
4877
  }
4646
- //#endregion
4647
- //#region src/setup/env.ts
4648
- var env_exports = /* @__PURE__ */ __exportAll({
4649
- checkDeployEnv: () => checkDeployEnv,
4650
- diffEnvNames: () => diffEnvNames,
4651
- readLocalEnvValues: () => readLocalEnvValues,
4652
- runEnvCommand: () => runEnvCommand
4653
- });
4878
+ // src/setup/env.ts
4879
+ var env_exports = /* @__PURE__ */ __exportAll({ runEnvCommand: () => runEnvCommand });
4654
4880
  const defaultStage = "production";
4655
4881
  const tokenNames = [
4656
4882
  "CLOUDFLARE_API_TOKEN",
@@ -5162,8 +5388,8 @@ async function decryptPlanned(planned, root, env, secrets) {
5162
5388
  }
5163
5389
  async function confirmPush(planned, label) {
5164
5390
  const terminal = createInterface({
5165
- input: process$1.stdin,
5166
- output: process$1.stderr
5391
+ input: process.stdin,
5392
+ output: process.stderr
5167
5393
  });
5168
5394
  try {
5169
5395
  return /^y(?:es)?$/iu.test((await terminal.question(`Push ${planned.map((item) => item.name).join(", ")} to ${label}? [y/N] `)).trim());
@@ -5191,7 +5417,7 @@ function addRedactions(planned, secrets) {
5191
5417
  for (const item of planned) if (item.secret || item.value.length >= 4) secrets.push(item.value);
5192
5418
  }
5193
5419
  function sourceLabel(source) {
5194
- return source === "process" ? "the shell" : source === "generated" ? "a generated value" : source;
5420
+ return source === "process" ? "the shell" : source === "generated" ? "a generated value" : source === "console" ? "the Console" : source;
5195
5421
  }
5196
5422
  function writePush(output, context) {
5197
5423
  const lines = output.pushed.length ? [`Pushed to ${targetLabel(output)}:`, ...output.pushed.map((item) => ` ${item.name} from ${sourceLabel(item.source)}${item.encrypted ? ", decrypted" : ""}${item.replaced ? ", replaced" : ""}`)] : [`Nothing to push to ${targetLabel(output)}.`];
@@ -5216,7 +5442,7 @@ async function runPush(args, context) {
5216
5442
  await assertUntracked(stored, target.project.root, target.run, context.env, context.stderr);
5217
5443
  const planned = await decryptPlanned(stored, target.project.root, context.env, target.secrets);
5218
5444
  if (!args.yes) {
5219
- if (!(!args.json && !!process$1.stdin.isTTY && !!process$1.stderr.isTTY)) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: `[vitehub] \`vitehub env push\` changes ${target.github ? "GitHub Actions secrets" : "host variables"} and was not confirmed. Without a terminal, pass --yes.` }), setupExitCodes.inputNeeded, { rerun: pushRerun(args) });
5445
+ if (!(!args.json && !!process.stdin.isTTY && !!process.stderr.isTTY)) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: `[vitehub] \`vitehub env push\` changes ${target.github ? "GitHub Actions secrets" : "host variables"} and was not confirmed. Without a terminal, pass --yes.` }), setupExitCodes.inputNeeded, { rerun: pushRerun(args) });
5220
5446
  if (!await confirmPush(planned, targetLabel(output))) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The push was not confirmed. Nothing was pushed." }), setupExitCodes.error);
5221
5447
  }
5222
5448
  const remoteName = (name) => target.github ? name.toUpperCase() : name;
@@ -5238,8 +5464,8 @@ async function runPush(args, context) {
5238
5464
  const appSecretName = "VITEHUB_SECRET";
5239
5465
  async function confirmGenerate(label) {
5240
5466
  const terminal = createInterface({
5241
- input: process$1.stdin,
5242
- output: process$1.stderr
5467
+ input: process.stdin,
5468
+ output: process.stderr
5243
5469
  });
5244
5470
  try {
5245
5471
  return /^y(?:es)?$/iu.test((await terminal.question(`${appSecretName} is not set on ${label} and has no local value. Generate one and set it? [y/N] `)).trim());
@@ -5268,6 +5494,7 @@ async function checkDeployEnv(options) {
5268
5494
  };
5269
5495
  if (!entries.length) return {
5270
5496
  apply: async () => {},
5497
+ onHost: /* @__PURE__ */ new Set(),
5271
5498
  output,
5272
5499
  upload: {}
5273
5500
  };
@@ -5283,6 +5510,12 @@ async function checkDeployEnv(options) {
5283
5510
  }) : void 0;
5284
5511
  const onHost = new Set(hostEnv ? await hostEnv.listSecretNames() : []);
5285
5512
  const values = await readLocalEnvValues(options.root, options.envDir, stage, context.env);
5513
+ for (const [name, value] of Object.entries(host === "cloudflare" ? options.consoleKeys ?? {} : {})) if (onHost.has(name) && !values.has(name)) values.set(name, {
5514
+ encrypted: false,
5515
+ files: [],
5516
+ source: "console",
5517
+ value
5518
+ });
5286
5519
  const configVars = await configVarNames(host, options.outputDir);
5287
5520
  const stored = planPush(entries, values, [], options.pushEnv || host === "cloudflare" ? configVars : onHost).planned;
5288
5521
  if (host === "cloudflare") {
@@ -5296,6 +5529,7 @@ async function checkDeployEnv(options) {
5296
5529
  }
5297
5530
  const unavailable = [...onHost].filter((name) => !values.has(name));
5298
5531
  if (unavailable.length) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_ENV_STAGE_UNSAFE({
5532
+ console: unavailable.some((name) => name.startsWith(consoleKeyPrefix)),
5299
5533
  names: unavailable.join(", "),
5300
5534
  stage
5301
5535
  }), setupExitCodes.inputNeeded);
@@ -5319,11 +5553,12 @@ async function checkDeployEnv(options) {
5319
5553
  output.generated = [appSecretName];
5320
5554
  }
5321
5555
  addRedactions(stored, options.secrets);
5322
- const missing = unset();
5556
+ const missing = unset().filter((entry) => !options.deferConsoleKey || entry.prefix !== "VITEHUB_CONSOLE_KEY_");
5323
5557
  const required = missing.filter(isRequired);
5324
5558
  if (required.length) {
5325
5559
  const names = required.map((entry) => entryLabel(diffEntry(entry))).join(", ");
5326
5560
  throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_ENV_MISSING({
5561
+ console: required.some((entry) => entry.prefix === consoleKeyPrefix),
5327
5562
  firstDeploy: !link,
5328
5563
  host,
5329
5564
  names,
@@ -5346,8 +5581,14 @@ async function checkDeployEnv(options) {
5346
5581
  output.pushed = planned.map((item) => item.name);
5347
5582
  if (output.missing.length) context.stderr.write(`Warning: optional env not set on ${host}: ${output.missing.map(entryLabel).join(", ")}.\n`);
5348
5583
  for (const item of planned) context.stderr.write(item.source === "generated" ? `Generated ${item.name} and set it on ${host}.\n` : `Setting ${item.name} on ${host}${host === "cloudflare" ? " with the new version" : ""} from ${sourceLabel(item.source)}${item.encrypted ? ", decrypted" : ""}${onHost.has(item.name) ? ", replaced" : ""}.\n`);
5584
+ const deployedNames = /* @__PURE__ */ new Set([
5585
+ ...onHost,
5586
+ ...configVars,
5587
+ ...output.pushed
5588
+ ]);
5349
5589
  if (host === "cloudflare" || !hostEnv) return {
5350
5590
  apply: async () => {},
5591
+ onHost: deployedNames,
5351
5592
  output,
5352
5593
  upload: host === "cloudflare" ? Object.fromEntries(planned.map((item) => [item.name, item.value])) : {}
5353
5594
  };
@@ -5355,6 +5596,7 @@ async function checkDeployEnv(options) {
5355
5596
  apply: async () => {
5356
5597
  for (const item of planned) await hostEnv.setSecret(item.name, item.value, { secret: item.secret });
5357
5598
  },
5599
+ onHost: deployedNames,
5358
5600
  output,
5359
5601
  upload: {}
5360
5602
  };
@@ -5374,5 +5616,4 @@ async function runEnvCommand(feature, args, context) {
5374
5616
  return writeSetupError(context, json, error);
5375
5617
  }
5376
5618
  }
5377
- //#endregion
5378
- export { readDeployCommit as A, listMatchingFiles as B, denoOrganization as C, build as D, listCloudflareDeployments as E, setupStatus as F, insertViteHubConfig as G, readSetupProject as H, shellQuote as I, locateViteHubConfig as K, uninstallArgs as L, installArgs as M, installCommand as N, readBuildOutput as O, missingProviderOption as P, hostFromNitroPreset as R, denoAdapter as S, cloudflareAdapter as T, setupLockfiles as U, detectPackageManager as V, editViteHubConfig as W, listVercelDeployments as _, ensureViteHubGitignore as a, netlifyAdapter as b, linkSetupProject as c, readSetupLinkStatus as d, readSetupLinks as f, hasVercelLogin as g, writeSeparateResourcesNote as h, addSetupLink as i, formatInstallCommand as j, createDeployRun as k, readLinkHostOption as l, unlinkSetupProject as m, env_exports as n, gitignoreWithViteHub as o, selectSetupLink as p, SETUP_LINK_FILE as r, hostRequired as s, checkDeployEnv as t, readSetupLinkState as u, vercelAdapter as v, listDenoDeployments as w, abortable as x, listNetlifyDeployments as y, hasDefinitionFiles as z };
5619
+ export { openDeployConsole as A, insertViteHubConfig as B, denoAdapter as C, listCloudflareDeployments as D, cloudflareAdapter as E, readDeployCommit as F, detectPackageManager as I, readSetupProject as L, build as M, readBuildOutput as N, formatDeployConsole as O, createDeployRun as P, setupLockfiles as R, abortable as S, listDenoDeployments as T, locateViteHubConfig as V, hasVercelLogin as _, addSetupLink as a, listNetlifyDeployments as b, hostRequired as c, readSetupLinkState as d, readSetupLinkStatus as f, writeSeparateResourcesNote as g, unlinkSetupProject as h, SETUP_LINK_FILE as i, readsConsoleKey as j, linkDeployedApp as k, linkSetupProject as l, selectSetupLink as m, env_exports as n, ensureViteHubGitignore as o, readSetupLinks as p, hostEnvs as r, gitignoreWithViteHub as s, checkDeployEnv as t, readLinkHostOption as u, listVercelDeployments as v, denoOrganization as w, netlifyAdapter as x, vercelAdapter as y, editViteHubConfig as z };