@vite-hub/cli 0.5.0 → 0.5.1

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,6 +1,6 @@
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 { $ as internalErrorDiagnostics, B as formatInstallArgument, H as installSpecifier, I as featureIds, L as featurePackages, Q as isRecord, 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-DlknnTAt.js";
3
+ import { i as setupFailure, o as writeSetupError, r as setupExitCodes, s as writeSetupJson, t as isSetupFailure } from "./envelope-DbplCDko.js";
4
4
  import { createRequire } from "node:module";
5
5
  import { spawn } from "node:child_process";
6
6
  import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
@@ -16,7 +16,7 @@ import { parseArgs, parseEnv } from "node:util";
16
16
  import { createPublicKey, diffieHellman, generateKeyPairSync, randomBytes } from "node:crypto";
17
17
  import { hsalsa, xsalsa20poly1305 } from "@noble/ciphers/salsa.js";
18
18
  import { blake2b } from "@noble/hashes/blake2.js";
19
- //#region ../internal/dist/ast.js
19
+ // ../internal/dist/ast.js
20
20
  /** Parses JavaScript or TypeScript. `jsx` adds JSX syntax. */
21
21
  function parseProgram(code, options = {}) {
22
22
  const plugins = [];
@@ -118,16 +118,15 @@ function quoteString(value, style) {
118
118
  if (style.quote === "\"") return json;
119
119
  return `'${json.slice(1, -1).replaceAll("\\\"", "\"").replaceAll("'", "\\'")}'`;
120
120
  }
121
- //#endregion
122
- //#region ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.6.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
121
+ // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.6.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
123
122
  var comma = ",".charCodeAt(0);
124
123
  var semicolon = ";".charCodeAt(0);
125
124
  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
126
- var intToChar = /* @__PURE__ */ new Uint8Array(64);
125
+ var intToChar$1 = /* @__PURE__ */ new Uint8Array(64);
127
126
  var charToInt = /* @__PURE__ */ new Uint8Array(128);
128
127
  for (let i = 0; i < chars.length; i++) {
129
128
  const c = chars.charCodeAt(i);
130
- intToChar[i] = c;
129
+ intToChar$1[i] = c;
131
130
  charToInt[c] = i;
132
131
  }
133
132
  function encodeInteger(builder, num) {
@@ -135,7 +134,7 @@ function encodeInteger(builder, num) {
135
134
  let clamped = num & 31;
136
135
  num >>>= 5;
137
136
  if (num > 0) clamped |= 32;
138
- builder.write(intToChar[clamped]);
137
+ builder.write(intToChar$1[clamped]);
139
138
  } while (num > 0);
140
139
  }
141
140
  function encodeSign(num) {
@@ -168,6 +167,21 @@ var StringWriter = class {
168
167
  return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
169
168
  }
170
169
  };
170
+ function encodeRangeMappings(decoded) {
171
+ if (decoded.length === 0) return "";
172
+ const writer = new StringWriter();
173
+ for (let i = 0; i < decoded.length; i++) {
174
+ const indices = decoded[i];
175
+ if (i > 0) writer.write(semicolon);
176
+ let index = 0;
177
+ for (let j = 0; j < indices.length; j++) {
178
+ const offset = indices[j];
179
+ encodeInteger(writer, offset - index);
180
+ index = offset;
181
+ }
182
+ }
183
+ return writer.flush();
184
+ }
171
185
  function encode(decoded) {
172
186
  const writer = new StringWriter();
173
187
  let sourcesIndex = 0;
@@ -198,8 +212,7 @@ function encode(decoded) {
198
212
  }
199
213
  return writer.flush();
200
214
  }
201
- //#endregion
202
- //#region ../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs
215
+ // ../../node_modules/.pnpm/magic-string@1.4.5/node_modules/magic-string/dist/index.mjs
203
216
  var BitSet = class BitSet {
204
217
  constructor(arg) {
205
218
  this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
@@ -210,6 +223,17 @@ var BitSet = class BitSet {
210
223
  has(n) {
211
224
  return !!(this.bits[n >> 5] & 1 << (n & 31));
212
225
  }
226
+ forEach(fn) {
227
+ const bits = this.bits;
228
+ for (let w = 0; w < bits.length; w++) {
229
+ let word = bits[w];
230
+ while (word) {
231
+ const lowest = word & -word;
232
+ fn((w << 5) + 31 - Math.clz32(lowest));
233
+ word ^= lowest;
234
+ }
235
+ }
236
+ }
213
237
  };
214
238
  var Chunk = class Chunk {
215
239
  constructor(start, end, content) {
@@ -221,6 +245,8 @@ var Chunk = class Chunk {
221
245
  this.content = content;
222
246
  this.storeName = false;
223
247
  this.edited = false;
248
+ this.replacesUntil = -1;
249
+ this.replacedFrom = -1;
224
250
  this.previous = null;
225
251
  this.next = null;
226
252
  }
@@ -237,20 +263,24 @@ var Chunk = class Chunk {
237
263
  chunk.content = this.content;
238
264
  chunk.storeName = this.storeName;
239
265
  chunk.edited = this.edited;
266
+ chunk.replacesUntil = this.replacesUntil;
267
+ chunk.replacedFrom = this.replacedFrom;
240
268
  return chunk;
241
269
  }
242
270
  contains(index) {
243
271
  return this.start < index && index < this.end;
244
272
  }
245
273
  eachNext(fn) {
246
- let chunk = this;
274
+ fn(this);
275
+ let chunk = this.next;
247
276
  while (chunk) {
248
277
  fn(chunk);
249
278
  chunk = chunk.next;
250
279
  }
251
280
  }
252
281
  eachPrevious(fn) {
253
- let chunk = this;
282
+ fn(this);
283
+ let chunk = this.previous;
254
284
  while (chunk) {
255
285
  fn(chunk);
256
286
  chunk = chunk.previous;
@@ -275,6 +305,8 @@ var Chunk = class Chunk {
275
305
  reset() {
276
306
  this.intro = "";
277
307
  this.outro = "";
308
+ this.replacesUntil = -1;
309
+ this.replacedFrom = -1;
278
310
  if (this.edited) {
279
311
  this.content = this.original;
280
312
  this.storeName = false;
@@ -291,8 +323,8 @@ var Chunk = class Chunk {
291
323
  this.outro = "";
292
324
  this.end = index;
293
325
  if (this.edited) {
294
- newChunk.edit("", false);
295
- this.content = "";
326
+ newChunk.edit("", false, true);
327
+ newChunk.replacedFrom = this.replacedFrom;
296
328
  } else this.content = originalBefore;
297
329
  newChunk.next = this.next;
298
330
  if (newChunk.next) newChunk.next.previous = newChunk;
@@ -309,8 +341,8 @@ var Chunk = class Chunk {
309
341
  const trimmed = this.content.replace(rx, "");
310
342
  if (trimmed.length) {
311
343
  if (trimmed !== this.content) {
312
- this.split(this.start + trimmed.length).edit("", void 0, true);
313
344
  if (this.edited) this.edit(trimmed, this.storeName, true);
345
+ else this.split(this.start + trimmed.length).edit("", void 0, true);
314
346
  }
315
347
  return true;
316
348
  } else {
@@ -325,9 +357,11 @@ var Chunk = class Chunk {
325
357
  const trimmed = this.content.replace(rx, "");
326
358
  if (trimmed.length) {
327
359
  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);
360
+ if (this.edited) this.edit(trimmed, this.storeName, true);
361
+ else {
362
+ this.split(this.end - trimmed.length);
363
+ this.edit("", void 0, true);
364
+ }
331
365
  }
332
366
  return true;
333
367
  } else {
@@ -337,14 +371,29 @@ var Chunk = class Chunk {
337
371
  }
338
372
  }
339
373
  };
374
+ /**
375
+ * The single error type thrown by MagicString.
376
+ *
377
+ * Every message is prefixed with `[MagicString]` so its source is obvious at a
378
+ * glance, and is kept short and consistent in tone.
379
+ */
380
+ var MagicStringError = class extends Error {
381
+ name = "MagicStringError";
382
+ constructor(message, options) {
383
+ super(`[MagicString] ${message}`, options);
384
+ }
385
+ };
340
386
  function getBtoa() {
387
+ /* v8 ignore next -- environment fallback, unreachable when `btoa` is present */
341
388
  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.");
389
+ const buffer = globalThis["Buffer"];
390
+ if (buffer) return (str) => buffer.from(str, "utf-8").toString("base64");
391
+ return () => {
392
+ throw new MagicStringError("unsupported environment: `btoa` or `Buffer` is required");
345
393
  };
394
+ /* v8 ignore stop */
346
395
  }
347
- const btoa = /*#__PURE__*/ getBtoa();
396
+ const btoa = /* #__PURE__ */ getBtoa();
348
397
  var SourceMap = class {
349
398
  constructor(properties) {
350
399
  this.version = 3;
@@ -352,28 +401,49 @@ var SourceMap = class {
352
401
  this.sources = properties.sources;
353
402
  this.sourcesContent = properties.sourcesContent;
354
403
  this.names = properties.names;
355
- this.mappings = encode(properties.mappings);
404
+ this.mappings = typeof properties.mappings === "string" ? properties.mappings : encode(properties.mappings);
356
405
  if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList;
357
406
  if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId;
407
+ if (typeof properties.rangeMappings !== "undefined") {
408
+ let shouldOutputRangeMapping = false;
409
+ for (const line of properties.rangeMappings) if (line.length !== 0) {
410
+ shouldOutputRangeMapping = true;
411
+ break;
412
+ }
413
+ if (shouldOutputRangeMapping) this.rangeMappings = encodeRangeMappings(properties.rangeMappings);
414
+ }
358
415
  }
416
+ /**
417
+ * Returns the equivalent of `JSON.stringify(map)`
418
+ */
359
419
  toString() {
360
420
  return JSON.stringify(this);
361
421
  }
422
+ /**
423
+ * Returns a DataURI containing the sourcemap. Useful for doing this sort of thing:
424
+ * `generateMap(options?: SourceMapOptions): SourceMap;`
425
+ */
362
426
  toUrl() {
363
- return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
427
+ return `data:application/json;charset=utf-8;base64,${btoa(this.toString())}`;
364
428
  }
365
429
  };
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(" ");
430
+ function getLocator(source) {
431
+ const lineOffsets = [0];
432
+ for (let i = source.indexOf("\n"); i !== -1; i = source.indexOf("\n", i + 1)) lineOffsets.push(i + 1);
433
+ return function locate(index) {
434
+ let i = 0;
435
+ let j = lineOffsets.length;
436
+ while (i < j) {
437
+ const m = i + j >> 1;
438
+ if (index < lineOffsets[m]) j = m;
439
+ else i = m + 1;
440
+ }
441
+ const line = i - 1;
442
+ return {
443
+ line,
444
+ column: index - lineOffsets[line]
445
+ };
446
+ };
377
447
  }
378
448
  function getRelativePath(from, to) {
379
449
  const fromParts = from.split(/[/\\]/);
@@ -389,41 +459,157 @@ function getRelativePath(from, to) {
389
459
  }
390
460
  return fromParts.concat(toParts).join("/");
391
461
  }
462
+ function guessIndent(code) {
463
+ const lines = code.split("\n");
464
+ const tabbed = lines.filter((line) => /^\t+/.test(line));
465
+ const spaced = lines.filter((line) => /^ {2,}/.test(line));
466
+ if (tabbed.length === 0 && spaced.length === 0) return null;
467
+ if (tabbed.length >= spaced.length) return " ";
468
+ const min = spaced.reduce((previous, current) => {
469
+ const numSpaces = /^ +/.exec(current)[0].length;
470
+ return Math.min(numSpaces, previous);
471
+ }, Infinity);
472
+ return " ".repeat(min);
473
+ }
392
474
  const toString = Object.prototype.toString;
393
475
  function isObject(thing) {
394
476
  return toString.call(thing) === "[object Object]";
395
477
  }
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;
478
+ const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
479
+ const intToChar = /* #__PURE__ */ (() => {
480
+ const chars = /* @__PURE__ */ new Uint8Array(64);
481
+ for (let i = 0; i < 64; i++) chars[i] = BASE64_CHARS.charCodeAt(i);
482
+ return chars;
483
+ })();
484
+ const COMMA = 44;
485
+ const SEMICOLON = 59;
486
+ const BUFFER_SIZE = 16384;
487
+ const FLUSH_THRESHOLD = 16348;
488
+ const scratch = /* #__PURE__ */ new Uint8Array(BUFFER_SIZE);
489
+ function writeVlq(pos, num) {
490
+ num = num < 0 ? -num << 1 | 1 : num << 1;
491
+ do {
492
+ let clamped = num & 31;
493
+ num >>>= 5;
494
+ if (num > 0) clamped |= 32;
495
+ scratch[pos++] = intToChar[clamped];
496
+ } while (num > 0);
497
+ return pos;
498
+ }
499
+ const decoder = /* #__PURE__ */ new TextDecoder();
500
+ var MappingsEncoder = class {
501
+ constructor() {
502
+ this.out = "";
503
+ this.pos = 0;
504
+ this.lines = [];
505
+ this.buffered = 0;
506
+ this.needsComma = false;
507
+ this.prevGenColumn = 0;
508
+ this.prevSourceIndex = 0;
509
+ this.prevSourceLine = 0;
510
+ this.prevSourceColumn = 0;
511
+ this.prevNameIndex = 0;
512
+ }
513
+ endLine(segments) {
514
+ this.lines.push(segments);
515
+ this.buffered += segments.length + 1;
516
+ if (this.buffered >= 4096) this.drain(null);
517
+ }
518
+ segments(segments) {
519
+ this.drain(segments);
520
+ }
521
+ finish(segments) {
522
+ this.drain(segments);
523
+ this.flush();
524
+ return this.out;
525
+ }
526
+ drain(trailing) {
527
+ const lines = this.lines;
528
+ const lineCount = lines.length;
529
+ for (let l = 0; l <= lineCount; l++) {
530
+ const line = l < lineCount ? lines[l] : trailing;
531
+ if (line === null) break;
532
+ for (let i = 0; i < line.length; i++) {
533
+ if (this.pos > FLUSH_THRESHOLD) this.flush();
534
+ const segment = line[i];
535
+ if (this.needsComma) scratch[this.pos++] = COMMA;
536
+ this.needsComma = true;
537
+ this.pos = writeVlq(this.pos, segment[0] - this.prevGenColumn);
538
+ this.prevGenColumn = segment[0];
539
+ this.pos = writeVlq(this.pos, segment[1] - this.prevSourceIndex);
540
+ this.prevSourceIndex = segment[1];
541
+ this.pos = writeVlq(this.pos, segment[2] - this.prevSourceLine);
542
+ this.prevSourceLine = segment[2];
543
+ this.pos = writeVlq(this.pos, segment[3] - this.prevSourceColumn);
544
+ this.prevSourceColumn = segment[3];
545
+ if (segment.length === 5) {
546
+ this.pos = writeVlq(this.pos, segment[4] - this.prevNameIndex);
547
+ this.prevNameIndex = segment[4];
548
+ }
549
+ }
550
+ if (l < lineCount) {
551
+ if (this.pos > FLUSH_THRESHOLD) this.flush();
552
+ scratch[this.pos++] = SEMICOLON;
553
+ this.needsComma = false;
554
+ this.prevGenColumn = 0;
555
+ }
410
556
  }
411
- const line = i - 1;
412
- return {
413
- line,
414
- column: index - lineOffsets[line]
415
- };
416
- };
557
+ lines.length = 0;
558
+ this.buffered = 0;
559
+ this.flush();
560
+ }
561
+ flush() {
562
+ this.out += decoder.decode(scratch.subarray(0, this.pos));
563
+ this.pos = 0;
564
+ }
565
+ };
566
+ const NEWLINE_CHAR$1 = 10;
567
+ function isWordCode(code) {
568
+ return code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 95;
417
569
  }
418
- const wordRegex = /\w/;
419
570
  var Mappings = class {
420
- constructor(hires) {
571
+ constructor(hires, encoder = null) {
421
572
  this.hires = hires;
422
573
  this.generatedCodeLine = 0;
423
574
  this.generatedCodeColumn = 0;
424
575
  this.raw = [];
425
576
  this.rawSegments = this.raw[this.generatedCodeLine] = [];
426
- this.pending = null;
577
+ this.rawRangeMappingsIndices = [];
578
+ this.rawRangeMappings = hires === "experimental-range" ? [this.rawRangeMappingsIndices] : void 0;
579
+ this.encoder = encoder;
580
+ }
581
+ nextLine() {
582
+ if (this.encoder === null) {
583
+ this.generatedCodeLine += 1;
584
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
585
+ } else {
586
+ this.encoder.endLine(this.rawSegments);
587
+ this.rawSegments = [];
588
+ this.generatedCodeLine += 1;
589
+ }
590
+ this.generatedCodeColumn = 0;
591
+ if (this.rawRangeMappings) this.rawRangeMappings[this.generatedCodeLine] = this.rawRangeMappingsIndices = [];
592
+ }
593
+ /**
594
+ * Emits the mappings for one MagicString: its intro, every chunk (with the
595
+ * chunk's own intro/outro) and its outro. `sourceIndex === -1` means the
596
+ * string has no source of its own, so its content only advances the
597
+ * generated position without mapping anything.
598
+ */
599
+ addMagicString(magicString, sourceIndex, nameIndex) {
600
+ const { original } = magicString;
601
+ const locate = getLocator(original);
602
+ if (magicString.intro) this.advance(magicString.intro);
603
+ magicString.firstChunk.eachNext((chunk) => {
604
+ if (chunk.intro.length) this.advance(chunk.intro);
605
+ if (sourceIndex === -1) this.advance(chunk.content);
606
+ else if (chunk.edited) {
607
+ const name = chunk.storeName ? nameIndex.get(original.slice(chunk.start, chunk.replacesUntil)) : void 0;
608
+ this.addEdit(sourceIndex, chunk.content, locate(chunk.start), name ?? -1);
609
+ } else this.addUneditedChunk(sourceIndex, chunk, original, locate(chunk.start), magicString.sourcemapLocations);
610
+ if (chunk.outro.length) this.advance(chunk.outro);
611
+ });
612
+ if (magicString.outro) this.advance(magicString.outro);
427
613
  }
428
614
  addEdit(sourceIndex, content, loc, nameIndex) {
429
615
  if (content.length) {
@@ -439,9 +625,7 @@ var Mappings = class {
439
625
  ];
440
626
  if (nameIndex >= 0) segment.push(nameIndex);
441
627
  this.rawSegments.push(segment);
442
- this.generatedCodeLine += 1;
443
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
444
- this.generatedCodeColumn = 0;
628
+ this.nextLine();
445
629
  previousContentLineEnd = contentLineEnd;
446
630
  contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
447
631
  }
@@ -454,73 +638,193 @@ var Mappings = class {
454
638
  if (nameIndex >= 0) segment.push(nameIndex);
455
639
  this.rawSegments.push(segment);
456
640
  this.advance(content.slice(previousContentLineEnd + 1));
457
- } else if (this.pending) {
458
- this.rawSegments.push(this.pending);
459
- this.advance(content);
460
641
  }
461
- this.pending = null;
462
642
  }
463
643
  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])) {
644
+ const end = chunk.end;
645
+ let i = chunk.start;
646
+ if (this.hires) {
647
+ const boundary = this.hires === "boundary";
648
+ const experimentalRange = this.hires === "experimental-range";
649
+ const encoder = experimentalRange ? null : this.encoder;
650
+ let charInHiresBoundary = false;
651
+ while (i < end) {
652
+ if (encoder !== null && this.rawSegments.length >= 4096) {
653
+ encoder.segments(this.rawSegments);
654
+ this.rawSegments.length = 0;
655
+ }
656
+ if (experimentalRange && i + 1 >= end) this.rawSegments.push([
657
+ this.generatedCodeColumn,
658
+ sourceIndex,
659
+ loc.line,
660
+ loc.column
661
+ ]);
662
+ const code = original.charCodeAt(i);
663
+ if (code === NEWLINE_CHAR$1) {
664
+ loc.line += 1;
665
+ loc.column = 0;
666
+ this.nextLine();
667
+ charInHiresBoundary = false;
668
+ } else {
669
+ if (boundary) {
670
+ if (isWordCode(code)) {
486
671
  if (!charInHiresBoundary) {
487
- this.rawSegments.push(segment);
672
+ this.rawSegments.push([
673
+ this.generatedCodeColumn,
674
+ sourceIndex,
675
+ loc.line,
676
+ loc.column
677
+ ]);
488
678
  charInHiresBoundary = true;
489
679
  }
490
680
  } else {
491
- this.rawSegments.push(segment);
681
+ this.rawSegments.push([
682
+ this.generatedCodeColumn,
683
+ sourceIndex,
684
+ loc.line,
685
+ loc.column
686
+ ]);
492
687
  charInHiresBoundary = false;
493
688
  }
494
- } else this.rawSegments.push(segment);
689
+ } else if (experimentalRange) {
690
+ if (i === chunk.start) {
691
+ this.rawRangeMappingsIndices.push(this.rawSegments.length);
692
+ this.rawSegments.push([
693
+ this.generatedCodeColumn,
694
+ sourceIndex,
695
+ loc.line,
696
+ loc.column
697
+ ]);
698
+ }
699
+ } else this.rawSegments.push([
700
+ this.generatedCodeColumn,
701
+ sourceIndex,
702
+ loc.line,
703
+ loc.column
704
+ ]);
705
+ loc.column += 1;
706
+ this.generatedCodeColumn += 1;
495
707
  }
496
- loc.column += 1;
497
- this.generatedCodeColumn += 1;
498
- first = false;
708
+ i += 1;
709
+ }
710
+ } else {
711
+ const bits = sourcemapLocations.bits;
712
+ while (i < end) {
713
+ let newline = original.indexOf("\n", i);
714
+ if (newline === -1 || newline > end) newline = end;
715
+ if (newline > i) {
716
+ this.rawSegments.push([
717
+ this.generatedCodeColumn,
718
+ sourceIndex,
719
+ loc.line,
720
+ loc.column
721
+ ]);
722
+ for (let w = i + 1 >> 5, last = newline - 1 >> 5; w <= last; w++) {
723
+ let word = bits[w];
724
+ if (!word) continue;
725
+ const base = w << 5;
726
+ while (word) {
727
+ const lowest = word & -word;
728
+ const index = base + 31 - Math.clz32(lowest);
729
+ if (index > i && index < newline) {
730
+ const offset = index - i;
731
+ this.rawSegments.push([
732
+ this.generatedCodeColumn + offset,
733
+ sourceIndex,
734
+ loc.line,
735
+ loc.column + offset
736
+ ]);
737
+ }
738
+ word ^= lowest;
739
+ }
740
+ }
741
+ loc.column += newline - i;
742
+ this.generatedCodeColumn += newline - i;
743
+ }
744
+ if (newline === end) break;
745
+ loc.line += 1;
746
+ loc.column = 0;
747
+ this.nextLine();
748
+ i = newline + 1;
499
749
  }
500
- originalCharIndex += 1;
501
750
  }
502
- this.pending = null;
503
751
  }
504
752
  advance(str) {
505
753
  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;
754
+ const lastNewline = str.lastIndexOf("\n");
755
+ for (let i = str.indexOf("\n"); i !== -1; i = str.indexOf("\n", i + 1)) this.nextLine();
756
+ this.generatedCodeColumn += str.length - lastNewline - 1;
515
757
  }
516
758
  };
517
759
  const n = "\n";
760
+ const NEWLINE_CHAR = "\n".charCodeAt(0);
761
+ const CR_CHAR = "\r".charCodeAt(0);
518
762
  const warned = {
519
763
  insertLeft: false,
520
764
  insertRight: false,
521
765
  storeName: false
522
766
  };
767
+ /**
768
+ * Expands the `$` substitution patterns that `String.prototype.replace` accepts
769
+ * in a string replacement.
770
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
771
+ *
772
+ * `captures` holds the capture groups in order, so `captures[0]` is `$1`.
773
+ * `namedCaptures` is `undefined` when the pattern has no named groups, and
774
+ * `$<name>` is then literal text - which is also the case for a string search
775
+ * value, where there are no groups of either kind.
776
+ */
777
+ function expandReplacement(replacement, matched, position, str, captures, namedCaptures) {
778
+ if (!replacement.includes("$")) return replacement;
779
+ let result = "";
780
+ let index = 0;
781
+ while (index < replacement.length) {
782
+ const dollar = replacement.indexOf("$", index);
783
+ if (dollar === -1) {
784
+ result += replacement.slice(index);
785
+ break;
786
+ }
787
+ result += replacement.slice(index, dollar);
788
+ const char = replacement[dollar + 1];
789
+ let expansion = "$";
790
+ let consumed = 1;
791
+ if (char === "$") consumed = 2;
792
+ else if (char === "&") {
793
+ expansion = matched;
794
+ consumed = 2;
795
+ } else if (char === "`") {
796
+ expansion = str.slice(0, position);
797
+ consumed = 2;
798
+ } else if (char === "'") {
799
+ expansion = str.slice(position + matched.length);
800
+ consumed = 2;
801
+ } else if (char === "<" && namedCaptures !== void 0) {
802
+ const close = replacement.indexOf(">", dollar + 2);
803
+ if (close !== -1) {
804
+ expansion = namedCaptures[replacement.slice(dollar + 2, close)] ?? "";
805
+ consumed = close + 1 - dollar;
806
+ }
807
+ } else if (char >= "0" && char <= "9") {
808
+ const second = replacement[dollar + 2];
809
+ const double = second >= "0" && second <= "9" ? Number(char + second) : NaN;
810
+ const single = Number(char);
811
+ if (double >= 1 && double <= captures.length) {
812
+ expansion = captures[double - 1] ?? "";
813
+ consumed = 3;
814
+ } else if (single >= 1 && single <= captures.length) {
815
+ expansion = captures[single - 1] ?? "";
816
+ consumed = 2;
817
+ }
818
+ }
819
+ result += expansion;
820
+ index = dollar + consumed;
821
+ }
822
+ return result;
823
+ }
523
824
  var MagicString = class MagicString {
825
+ /**
826
+ * Wraps `string` for editing; every index passed to the editing methods refers to this original string.
827
+ */
524
828
  constructor(string, options = {}) {
525
829
  const chunk = new Chunk(0, string.length, string);
526
830
  Object.defineProperties(this, {
@@ -550,11 +854,11 @@ var MagicString = class MagicString {
550
854
  },
551
855
  byStart: {
552
856
  writable: true,
553
- value: {}
857
+ value: /* @__PURE__ */ new Map([[0, chunk]])
554
858
  },
555
859
  byEnd: {
556
860
  writable: true,
557
- value: {}
861
+ value: /* @__PURE__ */ new Map([[string.length, chunk]])
558
862
  },
559
863
  filename: {
560
864
  writable: true,
@@ -570,7 +874,7 @@ var MagicString = class MagicString {
570
874
  },
571
875
  storedNames: {
572
876
  writable: true,
573
- value: {}
877
+ value: /* @__PURE__ */ new Set()
574
878
  },
575
879
  indentStr: {
576
880
  writable: true,
@@ -583,47 +887,74 @@ var MagicString = class MagicString {
583
887
  offset: {
584
888
  writable: true,
585
889
  value: options.offset || 0
890
+ },
891
+ hasMovedChunks: {
892
+ writable: true,
893
+ value: false
586
894
  }
587
895
  });
588
- this.byStart[0] = chunk;
589
- this.byEnd[string.length] = chunk;
590
896
  }
897
+ /**
898
+ * Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is false.
899
+ */
591
900
  addSourcemapLocation(char) {
592
901
  this.sourcemapLocations.add(char);
593
902
  }
903
+ /**
904
+ * Appends the specified content to the end of the string.
905
+ */
594
906
  append(content) {
595
- if (typeof content !== "string") throw new TypeError("outro content must be a string");
907
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
596
908
  this.outro += content;
597
909
  return this;
598
910
  }
911
+ /**
912
+ * Appends the specified content at the index in the original string.
913
+ * If a range *ending* with index is subsequently moved, the insert will be moved with it.
914
+ * See also `s.prependLeft(...)`.
915
+ */
599
916
  appendLeft(index, content) {
600
- index = index + this.offset;
601
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
917
+ index = this._resolveIndex(index);
918
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
919
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
602
920
  this._split(index);
603
- const chunk = this.byEnd[index];
921
+ const chunk = this.byEnd.get(index);
604
922
  if (chunk) chunk.appendLeft(content);
605
923
  else this.intro += content;
606
924
  return this;
607
925
  }
926
+ /**
927
+ * Appends the specified content at the index in the original string.
928
+ * If a range *starting* with index is subsequently moved, the insert will be moved with it.
929
+ * See also `s.prependRight(...)`.
930
+ */
608
931
  appendRight(index, content) {
609
- index = index + this.offset;
610
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
932
+ index = this._resolveIndex(index);
933
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
934
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
611
935
  this._split(index);
612
- const chunk = this.byStart[index];
936
+ const chunk = this.byStart.get(index);
613
937
  if (chunk) chunk.appendRight(content);
614
938
  else this.outro += content;
615
939
  return this;
616
940
  }
941
+ /**
942
+ * Returns an independent copy: the chunk list, string-level intro/outro,
943
+ * sourcemap locations, stored names, indent exclusion ranges, `offset`,
944
+ * `filename` and `ignoreList` are all copied; later edits to either string
945
+ * do not affect the other.
946
+ */
617
947
  clone() {
618
948
  const cloned = new MagicString(this.original, {
619
949
  filename: this.filename,
950
+ ignoreList: this.ignoreList,
620
951
  offset: this.offset
621
952
  });
622
953
  let originalChunk = this.firstChunk;
623
954
  let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
624
955
  while (originalChunk) {
625
- cloned.byStart[clonedChunk.start] = clonedChunk;
626
- cloned.byEnd[clonedChunk.end] = clonedChunk;
956
+ cloned.byStart.set(clonedChunk.start, clonedChunk);
957
+ cloned.byEnd.set(clonedChunk.end, clonedChunk);
627
958
  const nextOriginalChunk = originalChunk.next;
628
959
  const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
629
960
  if (nextClonedChunk) {
@@ -636,47 +967,72 @@ var MagicString = class MagicString {
636
967
  cloned.lastChunk = clonedChunk;
637
968
  if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
638
969
  cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
970
+ cloned.storedNames = new Set(this.storedNames);
639
971
  cloned.intro = this.intro;
640
972
  cloned.outro = this.outro;
973
+ cloned.hasMovedChunks = this.hasMovedChunks;
641
974
  return cloned;
642
975
  }
976
+ /**
977
+ * Generates a sourcemap object with raw mappings in array form, rather than encoded as a string.
978
+ * Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead.
979
+ */
643
980
  generateDecodedMap(options) {
644
981
  options = options || {};
645
- const sourceIndex = 0;
646
- const names = Object.keys(this.storedNames);
647
982
  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);
983
+ const names = this._generateMappings(mappings);
984
+ return {
985
+ ...this._mapProperties(options, names),
986
+ mappings: mappings.raw,
987
+ rangeMappings: mappings.rawRangeMappings
988
+ };
989
+ }
990
+ /**
991
+ * Generates a version 3 sourcemap.
992
+ */
993
+ generateMap(options) {
994
+ options = options || {};
995
+ const encoder = new MappingsEncoder();
996
+ const mappings = new Mappings(options.hires, encoder);
997
+ const names = this._generateMappings(mappings);
998
+ return new SourceMap({
999
+ ...this._mapProperties(options, names),
1000
+ mappings: encoder.finish(mappings.rawSegments),
1001
+ rangeMappings: mappings.rawRangeMappings
656
1002
  });
657
- if (this.outro) mappings.advance(this.outro);
1003
+ }
1004
+ /** @internal */
1005
+ _generateMappings(mappings) {
1006
+ const names = [...this.storedNames];
1007
+ mappings.addMagicString(this, 0, new Map(names.map((name, i) => [name, i])));
1008
+ return names;
1009
+ }
1010
+ /** @internal */
1011
+ _mapProperties(options, names) {
658
1012
  return {
659
1013
  file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
660
1014
  sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
661
1015
  sourcesContent: options.includeContent ? [this.original] : void 0,
662
1016
  names,
663
- mappings: mappings.raw,
664
- x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
1017
+ x_google_ignoreList: this.ignoreList ? [0] : void 0
665
1018
  };
666
1019
  }
667
- generateMap(options) {
668
- return new SourceMap(this.generateDecodedMap(options));
669
- }
1020
+ /** @internal */
670
1021
  _ensureindentStr() {
671
1022
  if (this.indentStr === void 0) this.indentStr = guessIndent(this.original);
672
1023
  }
1024
+ /** @internal */
673
1025
  _getRawIndentString() {
674
1026
  this._ensureindentStr();
675
1027
  return this.indentStr;
676
1028
  }
1029
+ /**
1030
+ * Returns the indentation string guessed from the original content, falling back to a single tab character.
1031
+ * This is the value `s.indent()` uses when no prefix is supplied.
1032
+ */
677
1033
  getIndentString() {
678
1034
  this._ensureindentStr();
679
- return this.indentStr === null ? " " : this.indentStr;
1035
+ return this.indentStr ?? " ";
680
1036
  }
681
1037
  indent(indentStr, options) {
682
1038
  const pattern = /^[^\r\n]/gm;
@@ -689,55 +1045,78 @@ var MagicString = class MagicString {
689
1045
  indentStr = this.indentStr || " ";
690
1046
  }
691
1047
  if (indentStr === "") return this;
1048
+ const resolvedIndentStr = indentStr;
692
1049
  options = options || {};
693
- const isExcluded = {};
1050
+ const isExcluded = new BitSet();
694
1051
  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;
1052
+ for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded.add(i);
696
1053
  });
697
1054
  let shouldIndentNextCharacter = options.indentStart !== false;
698
- const replacer = (match) => {
699
- if (shouldIndentNextCharacter) return `${indentStr}${match}`;
700
- shouldIndentNextCharacter = true;
701
- return match;
1055
+ const indentPiece = (str) => {
1056
+ if (str === "") return str;
1057
+ const indented = str.replace(pattern, (match, offset) => offset > 0 || shouldIndentNextCharacter ? `${resolvedIndentStr}${match}` : match);
1058
+ shouldIndentNextCharacter = str[str.length - 1] === "\n";
1059
+ return indented;
702
1060
  };
703
- this.intro = this.intro.replace(pattern, replacer);
1061
+ this.intro = indentPiece(this.intro);
704
1062
  let charIndex = 0;
705
1063
  let chunk = this.firstChunk;
1064
+ const indentAt = (index) => {
1065
+ shouldIndentNextCharacter = false;
1066
+ if (index === chunk.start) chunk.appendRight(resolvedIndentStr);
1067
+ else {
1068
+ this._splitChunk(chunk, index);
1069
+ chunk = chunk.next;
1070
+ chunk.prependRight(resolvedIndentStr);
1071
+ }
1072
+ };
706
1073
  while (chunk) {
707
1074
  const end = chunk.end;
1075
+ if (!isExcluded.has(chunk.start)) chunk.intro = indentPiece(chunk.intro);
708
1076
  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";
1077
+ if (!isExcluded.has(chunk.start)) chunk.content = indentPiece(chunk.content);
1078
+ else if (chunk.content) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
1079
+ } else if (options.exclude) {
1080
+ charIndex = chunk.start;
1081
+ while (charIndex < end) {
1082
+ if (!isExcluded.has(charIndex)) {
1083
+ const char = this.original.charCodeAt(charIndex);
1084
+ if (char === NEWLINE_CHAR) shouldIndentNextCharacter = true;
1085
+ else if (char !== CR_CHAR && shouldIndentNextCharacter) indentAt(charIndex);
1086
+ }
1087
+ charIndex += 1;
712
1088
  }
713
1089
  } else {
714
1090
  charIndex = chunk.start;
715
1091
  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
- }
1092
+ if (!shouldIndentNextCharacter) {
1093
+ const nextLine = this.original.indexOf(n, charIndex);
1094
+ if (nextLine === -1 || nextLine >= end) break;
1095
+ shouldIndentNextCharacter = true;
1096
+ charIndex = nextLine + 1;
1097
+ continue;
728
1098
  }
1099
+ const char = this.original.charCodeAt(charIndex);
1100
+ if (char === NEWLINE_CHAR || char === CR_CHAR) {
1101
+ charIndex += 1;
1102
+ continue;
1103
+ }
1104
+ indentAt(charIndex);
729
1105
  charIndex += 1;
730
1106
  }
731
1107
  }
1108
+ if (!isExcluded.has(chunk.end - 1)) chunk.outro = indentPiece(chunk.outro);
732
1109
  charIndex = chunk.end;
733
1110
  chunk = chunk.next;
734
1111
  }
735
- this.outro = this.outro.replace(pattern, replacer);
1112
+ this.outro = indentPiece(this.outro);
736
1113
  return this;
737
1114
  }
1115
+ /** @internal */
738
1116
  insert() {
739
- throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
1117
+ throw new MagicStringError("insert() is deprecated, use appendLeft() or prependRight()");
740
1118
  }
1119
+ /** @internal */
741
1120
  insertLeft(index, content) {
742
1121
  if (!warned.insertLeft) {
743
1122
  console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
@@ -745,6 +1124,7 @@ var MagicString = class MagicString {
745
1124
  }
746
1125
  return this.appendLeft(index, content);
747
1126
  }
1127
+ /** @internal */
748
1128
  insertRight(index, content) {
749
1129
  if (!warned.insertRight) {
750
1130
  console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
@@ -752,53 +1132,117 @@ var MagicString = class MagicString {
752
1132
  }
753
1133
  return this.prependRight(index, content);
754
1134
  }
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");
1135
+ /**
1136
+ * Moves the characters from `start` and `end` to `index`.
1137
+ *
1138
+ * `affinity` controls where the range is anchored at `index`. With the
1139
+ * default `'right'`, it is inserted before the content that starts at `index`;
1140
+ * with `'left'`, it is inserted after the content that ends at `index`. The
1141
+ * two differ only when other content has already been moved to that boundary,
1142
+ * mirroring the `appendLeft`/`appendRight` distinction.
1143
+ */
1144
+ move(start, end, index, affinity = "right") {
1145
+ start = this._resolveIndex(start);
1146
+ end = this._resolveIndex(end);
1147
+ index = this._resolveIndex(index);
1148
+ if (start === end) return this;
1149
+ if (start < 0 || end > this.original.length || index < 0 || index > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1150
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
1151
+ if (index >= start && index <= end) throw new MagicStringError("cannot move a selection inside itself");
760
1152
  this._split(start);
761
1153
  this._split(end);
762
1154
  this._split(index);
763
- const first = this.byStart[start];
764
- const last = this.byEnd[end];
1155
+ const first = this.byStart.get(start);
1156
+ const last = this.byEnd.get(end);
1157
+ if (!first || !last) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1158
+ if (this.hasMovedChunks) {
1159
+ let cursor = first;
1160
+ while (cursor !== last) {
1161
+ cursor = cursor.next;
1162
+ if (!cursor || cursor.start < start || cursor.end > end) throw new MagicStringError(`cannot move ${start} to ${end} because an earlier move split that range`);
1163
+ }
1164
+ }
765
1165
  const oldLeft = first.previous;
766
1166
  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;
1167
+ let newLeft;
1168
+ let newRight;
1169
+ if (affinity === "left") {
1170
+ newLeft = this.byEnd.get(index) ?? null;
1171
+ if (!newLeft) {
1172
+ if (first === this.firstChunk) return this;
1173
+ newRight = this.firstChunk;
1174
+ } else {
1175
+ if (newLeft.next === first) return this;
1176
+ newRight = newLeft.next;
1177
+ }
1178
+ } else {
1179
+ newRight = this.byStart.get(index) ?? null;
1180
+ if (!newRight) {
1181
+ if (last === this.lastChunk) return this;
1182
+ newLeft = this.lastChunk;
1183
+ } else {
1184
+ if (newRight.previous === last) return this;
1185
+ newLeft = newRight.previous;
1186
+ }
1187
+ }
770
1188
  if (oldLeft) oldLeft.next = oldRight;
771
1189
  if (oldRight) oldRight.previous = oldLeft;
772
1190
  if (newLeft) newLeft.next = first;
773
1191
  if (newRight) newRight.previous = last;
774
- if (!first.previous) this.firstChunk = last.next;
775
- if (!last.next) {
776
- this.lastChunk = first.previous;
1192
+ if (!oldLeft) this.firstChunk = oldRight;
1193
+ if (!oldRight) {
1194
+ this.lastChunk = oldLeft;
777
1195
  this.lastChunk.next = null;
778
1196
  }
779
1197
  first.previous = newLeft;
780
1198
  last.next = newRight || null;
781
1199
  if (!newLeft) this.firstChunk = first;
782
1200
  if (!newRight) this.lastChunk = last;
1201
+ this.hasMovedChunks = true;
783
1202
  return this;
784
1203
  }
1204
+ /**
1205
+ * Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in
1206
+ * that range. The same restrictions as `s.remove()` apply.
1207
+ *
1208
+ * The fourth argument is optional. It can have a storeName property - if true, the original name will be stored
1209
+ * for later inclusion in a sourcemap's names array - and a contentOnly property which determines whether only
1210
+ * the content is overwritten, or anything that was appended/prepended to the range as well.
1211
+ *
1212
+ * It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content.
1213
+ */
785
1214
  overwrite(start, end, content, options) {
786
- options = options || {};
1215
+ if (options === true) {
1216
+ if (!warned.storeName) {
1217
+ console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
1218
+ warned.storeName = true;
1219
+ }
1220
+ return this.update(start, end, content, {
1221
+ storeName: true,
1222
+ overwrite: true
1223
+ });
1224
+ }
1225
+ const optionObject = typeof options === "object" && options ? options : {};
787
1226
  return this.update(start, end, content, {
788
- ...options,
789
- overwrite: !options.contentOnly
1227
+ ...optionObject,
1228
+ overwrite: !optionObject.contentOnly
790
1229
  });
791
1230
  }
1231
+ /**
1232
+ * Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply.
1233
+ *
1234
+ * The fourth argument is optional. It can have a storeName property - if true, the original name will be stored
1235
+ * for later inclusion in a sourcemap's names array - and an overwrite property which determines whether only
1236
+ * the content is overwritten, or anything that was appended/prepended to the range as well.
1237
+ */
792
1238
  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");
1239
+ start = this._resolveIndex(start);
1240
+ end = this._resolveIndex(end);
1241
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
1242
+ if (start < 0) throw new MagicStringError(`start ${start} is out of bounds`);
1243
+ if (end > this.original.length) throw new MagicStringError(`end ${end} is out of bounds`);
1244
+ if (start === end) throw new MagicStringError(`cannot overwrite a zero-length range at ${start}, use appendLeft() or prependRight()`);
1245
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
802
1246
  this._split(start);
803
1247
  this._split(end);
804
1248
  if (options === true) {
@@ -808,152 +1252,178 @@ var MagicString = class MagicString {
808
1252
  }
809
1253
  options = { storeName: true };
810
1254
  }
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
- });
1255
+ const optionObject = typeof options === "object" && options ? options : {};
1256
+ const storeName = optionObject.storeName || false;
1257
+ const overwrite = optionObject.overwrite || false;
1258
+ if (storeName) this.storedNames.add(this.original.slice(start, end));
1259
+ const first = this.byStart.get(start);
1260
+ for (let chunk = first; chunk.end < end;) {
1261
+ const next = chunk.next;
1262
+ if (next === null || next !== this.byStart.get(chunk.end)) throw new MagicStringError("cannot overwrite across a split point");
1263
+ chunk = next;
820
1264
  }
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;
1265
+ for (let chunk = first.next; chunk !== null && chunk.start < end; chunk = chunk.next) {
1266
+ chunk.edit("", false, !overwrite);
1267
+ chunk.replacesUntil = -1;
1268
+ chunk.replacedFrom = start;
835
1269
  }
1270
+ first.edit(content, storeName, !overwrite);
1271
+ first.replacesUntil = end;
1272
+ first.replacedFrom = -1;
836
1273
  return this;
837
1274
  }
1275
+ /**
1276
+ * Prepends the string with the specified content.
1277
+ */
838
1278
  prepend(content) {
839
- if (typeof content !== "string") throw new TypeError("outro content must be a string");
1279
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
840
1280
  this.intro = content + this.intro;
841
1281
  return this;
842
1282
  }
1283
+ /**
1284
+ * Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at index
1285
+ */
843
1286
  prependLeft(index, content) {
844
- index = index + this.offset;
845
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
1287
+ index = this._resolveIndex(index);
1288
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
1289
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
846
1290
  this._split(index);
847
- const chunk = this.byEnd[index];
1291
+ const chunk = this.byEnd.get(index);
848
1292
  if (chunk) chunk.prependLeft(content);
849
1293
  else this.intro = content + this.intro;
850
1294
  return this;
851
1295
  }
1296
+ /**
1297
+ * Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
1298
+ */
852
1299
  prependRight(index, content) {
853
- index = index + this.offset;
854
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
1300
+ index = this._resolveIndex(index);
1301
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
1302
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
855
1303
  this._split(index);
856
- const chunk = this.byStart[index];
1304
+ const chunk = this.byStart.get(index);
857
1305
  if (chunk) chunk.prependRight(content);
858
1306
  else this.outro = content + this.outro;
859
1307
  return this;
860
1308
  }
1309
+ /**
1310
+ * Removes the characters from `start` to `end` (of the original string, **not** the generated string).
1311
+ * Content appended or prepended at positions strictly inside the range is removed with it, while
1312
+ * content attached at `start` or `end` is preserved — use `s.overwrite(start, end, '')` to remove
1313
+ * the range including its edge inserts.
1314
+ * Repeated removals and removals with partially overlapping ranges are allowed.
1315
+ */
861
1316
  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
- }
1317
+ start = this._resolveIndex(start);
1318
+ end = this._resolveIndex(end);
868
1319
  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");
1320
+ if (start < 0 || end > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1321
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
871
1322
  this._split(start);
872
1323
  this._split(end);
873
- let chunk = this.byStart[start];
1324
+ let chunk = this.byStart.get(start);
874
1325
  while (chunk) {
875
- chunk.intro = "";
876
- chunk.outro = "";
877
- chunk.edit("");
878
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1326
+ if (chunk.start > start) chunk.intro = "";
1327
+ if (chunk.end < end) chunk.outro = "";
1328
+ chunk.edit("", false, true);
1329
+ chunk.replacesUntil = -1;
1330
+ chunk.replacedFrom = -1;
1331
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : void 0;
879
1332
  }
880
1333
  return this;
881
1334
  }
1335
+ /**
1336
+ * Reset the modified characters from `start` to `end` (of the original string, **not** the generated string).
1337
+ */
882
1338
  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
- }
1339
+ start = this._resolveIndex(start);
1340
+ end = this._resolveIndex(end);
889
1341
  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");
1342
+ if (start < 0 || end > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1343
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
892
1344
  this._split(start);
893
1345
  this._split(end);
894
- let chunk = this.byStart[start];
1346
+ let chunk = this.byStart.get(start);
895
1347
  while (chunk) {
896
1348
  chunk.reset();
897
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1349
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : void 0;
898
1350
  }
899
1351
  return this;
900
1352
  }
1353
+ /**
1354
+ * Returns the last character of the generated string, or `''` if it is empty.
1355
+ */
901
1356
  lastChar() {
902
1357
  if (this.outro.length) return this.outro[this.outro.length - 1];
903
1358
  let chunk = this.lastChunk;
904
- do {
1359
+ while (chunk) {
905
1360
  if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
906
1361
  if (chunk.content.length) return chunk.content[chunk.content.length - 1];
907
1362
  if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
908
- } while (chunk = chunk.previous);
1363
+ chunk = chunk.previous;
1364
+ }
909
1365
  if (this.intro.length) return this.intro[this.intro.length - 1];
910
1366
  return "";
911
1367
  }
1368
+ /**
1369
+ * Returns everything after the last newline in the generated string, or the whole string if there is no newline.
1370
+ */
912
1371
  lastLine() {
913
1372
  let lineIndex = this.outro.lastIndexOf(n);
914
- if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
1373
+ if (lineIndex !== -1) return this.outro.slice(lineIndex + 1);
915
1374
  let lineStr = this.outro;
916
1375
  let chunk = this.lastChunk;
917
- do {
1376
+ while (chunk) {
918
1377
  if (chunk.outro.length > 0) {
919
1378
  lineIndex = chunk.outro.lastIndexOf(n);
920
- if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
1379
+ if (lineIndex !== -1) return chunk.outro.slice(lineIndex + 1) + lineStr;
921
1380
  lineStr = chunk.outro + lineStr;
922
1381
  }
923
1382
  if (chunk.content.length > 0) {
924
1383
  lineIndex = chunk.content.lastIndexOf(n);
925
- if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
1384
+ if (lineIndex !== -1) return chunk.content.slice(lineIndex + 1) + lineStr;
926
1385
  lineStr = chunk.content + lineStr;
927
1386
  }
928
1387
  if (chunk.intro.length > 0) {
929
1388
  lineIndex = chunk.intro.lastIndexOf(n);
930
- if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
1389
+ if (lineIndex !== -1) return chunk.intro.slice(lineIndex + 1) + lineStr;
931
1390
  lineStr = chunk.intro + lineStr;
932
1391
  }
933
- } while (chunk = chunk.previous);
1392
+ chunk = chunk.previous;
1393
+ }
934
1394
  lineIndex = this.intro.lastIndexOf(n);
935
- if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
1395
+ if (lineIndex !== -1) return this.intro.slice(lineIndex + 1) + lineStr;
936
1396
  return this.intro + lineStr;
937
1397
  }
1398
+ /**
1399
+ * Returns the content of the generated string that corresponds to the slice
1400
+ * between `start` and `end` of the original string, walking the generated
1401
+ * string from the chunk holding `start` to the chunk holding `end`. Throws
1402
+ * if either index falls inside replaced content. After `move()`, a range
1403
+ * whose end now comes before its start in the output yields `''`.
1404
+ */
938
1405
  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
- }
1406
+ start = this._resolveIndex(start);
1407
+ end = this._resolveIndex(end);
945
1408
  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;
1409
+ let chunk;
1410
+ if (this.hasMovedChunks) {
1411
+ chunk = this.firstChunk;
1412
+ while (chunk && (chunk.start > start || chunk.end <= start)) {
1413
+ if (chunk.start < end && chunk.end >= end || end === 0 && chunk.start === 0) return result;
1414
+ chunk = chunk.next;
1415
+ }
1416
+ } else {
1417
+ if (start >= end) return result;
1418
+ chunk = this._chunkAt(start);
950
1419
  }
951
- if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
1420
+ if (chunk && chunk.edited && chunk.start !== start) throw new MagicStringError(`cannot use edited character ${start} as slice start anchor`);
952
1421
  const startChunk = chunk;
953
1422
  while (chunk) {
1423
+ if (end === 0 && chunk.start === 0) break;
954
1424
  if (chunk.intro && (startChunk !== chunk || chunk.start === start)) result += chunk.intro;
955
1425
  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.`);
1426
+ if (containsEnd && chunk.edited && chunk.end !== end) throw new MagicStringError(`cannot use edited character ${end} as slice end anchor`);
957
1427
  const sliceStart = startChunk === chunk ? start - chunk.start : 0;
958
1428
  const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
959
1429
  result += chunk.content.slice(sliceStart, sliceEnd);
@@ -963,37 +1433,74 @@ var MagicString = class MagicString {
963
1433
  }
964
1434
  return result;
965
1435
  }
1436
+ /**
1437
+ * Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed.
1438
+ */
966
1439
  snip(start, end) {
967
1440
  const clone = this.clone();
968
- clone.remove(0, start);
969
- clone.remove(end, clone.original.length);
1441
+ clone.remove(-clone.offset, start);
1442
+ clone.remove(end, clone.original.length - clone.offset);
970
1443
  return clone;
971
1444
  }
1445
+ /**
1446
+ * Applies `offset`, resolves a negative index from the end of `original` as
1447
+ * `update`/`remove` always have, and rejects anything that is not an integer.
1448
+ * Bounds are checked by the caller, because the methods report them differently.
1449
+ *
1450
+ * @internal
1451
+ */
1452
+ _resolveIndex(index) {
1453
+ const resolved = index + this.offset;
1454
+ if (!Number.isInteger(resolved)) throw new MagicStringError(`index must be an integer, got ${index}`);
1455
+ if (resolved < 0 && this.original.length !== 0) return Math.max(0, resolved + this.original.length);
1456
+ return resolved;
1457
+ }
1458
+ /**
1459
+ * The chunk whose original range holds `index` (`chunk.start <= index < chunk.end`),
1460
+ * or `undefined` when `index` is at or past the end. Searches from the last
1461
+ * visited chunk so that scans over nearby indices stay cheap.
1462
+ *
1463
+ * @internal
1464
+ */
1465
+ _chunkAt(index) {
1466
+ let chunk = this.byStart.get(index);
1467
+ if (chunk) return chunk;
1468
+ chunk = this.lastSearchedChunk;
1469
+ const searchForward = index >= chunk.end;
1470
+ while (chunk && !chunk.contains(index)) chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
1471
+ if (chunk) this.lastSearchedChunk = chunk;
1472
+ return chunk;
1473
+ }
1474
+ /** @internal */
972
1475
  _split(index) {
973
- if (this.byStart[index] || this.byEnd[index]) return;
1476
+ if (this.byStart.get(index) || this.byEnd.get(index)) return;
974
1477
  let chunk = this.lastSearchedChunk;
975
1478
  let previousChunk = chunk;
976
1479
  const searchForward = index > chunk.end;
977
1480
  while (chunk) {
978
1481
  if (chunk.contains(index)) return this._splitChunk(chunk, index);
979
- chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1482
+ chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
980
1483
  if (chunk === previousChunk) return;
981
1484
  previousChunk = chunk;
982
1485
  }
983
1486
  }
1487
+ /** @internal */
984
1488
  _splitChunk(chunk, index) {
985
1489
  if (chunk.edited && chunk.content.length) {
986
1490
  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}")`);
1491
+ throw new MagicStringError(`cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`);
988
1492
  }
989
1493
  const newChunk = chunk.split(index);
990
- this.byEnd[index] = chunk;
991
- this.byStart[index] = newChunk;
992
- this.byEnd[newChunk.end] = newChunk;
1494
+ this.byEnd.set(index, chunk);
1495
+ this.byStart.set(index, newChunk);
1496
+ this.byEnd.set(newChunk.end, newChunk);
993
1497
  if (chunk === this.lastChunk) this.lastChunk = newChunk;
994
1498
  this.lastSearchedChunk = chunk;
995
1499
  return true;
996
1500
  }
1501
+ /**
1502
+ * Returns the generated string.
1503
+ */
997
1504
  toString() {
998
1505
  let str = this.intro;
999
1506
  let chunk = this.firstChunk;
@@ -1003,29 +1510,48 @@ var MagicString = class MagicString {
1003
1510
  }
1004
1511
  return str + this.outro;
1005
1512
  }
1513
+ /**
1514
+ * Returns true if the resulting source is empty (disregarding white space).
1515
+ */
1006
1516
  isEmpty() {
1517
+ if (this.intro.length && this.intro.trim()) return false;
1007
1518
  let chunk = this.firstChunk;
1008
- do
1519
+ while (chunk) {
1009
1520
  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);
1521
+ chunk = chunk.next;
1522
+ }
1523
+ if (this.outro.length && this.outro.trim()) return false;
1011
1524
  return true;
1012
1525
  }
1526
+ /**
1527
+ * Returns the length of the generated string, counting only content attached to the original characters.
1528
+ * Content outside the string body (`s.prepend()`/`s.append()`, and inserts before the first or after the last
1529
+ * character) is not counted, so this can differ from `s.toString().length`.
1530
+ */
1013
1531
  length() {
1014
1532
  let chunk = this.firstChunk;
1015
1533
  let length = 0;
1016
- do
1534
+ while (chunk) {
1017
1535
  length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1018
- while (chunk = chunk.next);
1536
+ chunk = chunk.next;
1537
+ }
1019
1538
  return length;
1020
1539
  }
1540
+ /**
1541
+ * Removes empty lines from the start and end.
1542
+ */
1021
1543
  trimLines() {
1022
1544
  return this.trim("[\\r\\n]");
1023
1545
  }
1546
+ /**
1547
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end.
1548
+ */
1024
1549
  trim(charType) {
1025
1550
  return this.trimStart(charType).trimEnd(charType);
1026
1551
  }
1552
+ /** @internal */
1027
1553
  trimEndAborted(charType) {
1028
- const rx = new RegExp((charType || "\\s") + "+$");
1554
+ const rx = new RegExp(`${charType || "\\s"}+$`);
1029
1555
  this.outro = this.outro.replace(rx, "");
1030
1556
  if (this.outro.length) return true;
1031
1557
  let chunk = this.lastChunk;
@@ -1033,22 +1559,28 @@ var MagicString = class MagicString {
1033
1559
  const end = chunk.end;
1034
1560
  const aborted = chunk.trimEnd(rx);
1035
1561
  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;
1562
+ const next = chunk.next;
1563
+ if (this.lastChunk === chunk) this.lastChunk = next;
1564
+ this.byEnd.set(chunk.end, chunk);
1565
+ this.byStart.set(next.start, next);
1566
+ this.byEnd.set(next.end, next);
1040
1567
  }
1041
1568
  if (aborted) return true;
1042
1569
  chunk = chunk.previous;
1043
1570
  } while (chunk);
1044
- return false;
1571
+ this.intro = this.intro.replace(rx, "");
1572
+ return this.intro.length > 0;
1045
1573
  }
1574
+ /**
1575
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end.
1576
+ */
1046
1577
  trimEnd(charType) {
1047
1578
  this.trimEndAborted(charType);
1048
1579
  return this;
1049
1580
  }
1581
+ /** @internal */
1050
1582
  trimStartAborted(charType) {
1051
- const rx = new RegExp("^" + (charType || "\\s") + "+");
1583
+ const rx = new RegExp(`^${charType || "\\s"}+`);
1052
1584
  this.intro = this.intro.replace(rx, "");
1053
1585
  if (this.intro.length) return true;
1054
1586
  let chunk = this.firstChunk;
@@ -1056,86 +1588,148 @@ var MagicString = class MagicString {
1056
1588
  const end = chunk.end;
1057
1589
  const aborted = chunk.trimStart(rx);
1058
1590
  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;
1591
+ const next = chunk.next;
1592
+ if (chunk === this.lastChunk) this.lastChunk = next;
1593
+ this.byEnd.set(chunk.end, chunk);
1594
+ this.byStart.set(next.start, next);
1595
+ this.byEnd.set(next.end, next);
1063
1596
  }
1064
1597
  if (aborted) return true;
1065
1598
  chunk = chunk.next;
1066
1599
  } while (chunk);
1067
- return false;
1600
+ this.outro = this.outro.replace(rx, "");
1601
+ return this.outro.length > 0;
1068
1602
  }
1603
+ /**
1604
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start.
1605
+ */
1069
1606
  trimStart(charType) {
1070
1607
  this.trimStartAborted(charType);
1071
1608
  return this;
1072
1609
  }
1610
+ /**
1611
+ * Indicates if the string has been changed.
1612
+ */
1073
1613
  hasChanged() {
1074
- return this.original !== this.toString();
1614
+ if (this.intro || this.outro) return true;
1615
+ let outputIndex = 0;
1616
+ let chunk = this.firstChunk;
1617
+ while (chunk) {
1618
+ if (chunk.intro || chunk.outro) return true;
1619
+ if (!chunk.edited && chunk.start === outputIndex) outputIndex = chunk.end;
1620
+ else {
1621
+ if (!this.original.startsWith(chunk.content, outputIndex)) return true;
1622
+ outputIndex += chunk.content.length;
1623
+ }
1624
+ chunk = chunk.next;
1625
+ }
1626
+ return outputIndex !== this.original.length;
1627
+ }
1628
+ /**
1629
+ * Whether the original range [start, end) has had any of its characters
1630
+ * removed. `replace`/`replaceAll` search `original`, so a match can land on
1631
+ * text that is no longer in the output - overwriting it would resurrect the
1632
+ * removed characters, so such matches are skipped instead.
1633
+ *
1634
+ * @internal
1635
+ */
1636
+ _hasRemovedContent(start, end) {
1637
+ const atBoundary = this.byStart.get(start);
1638
+ if (atBoundary && start === end) {
1639
+ const previous = this.byEnd.get(start);
1640
+ return !!previous && previous.content === "" && atBoundary.content === "";
1641
+ }
1642
+ let chunk = this._chunkAt(start);
1643
+ while (chunk && chunk.start < end) {
1644
+ if (chunk.content === "" && (chunk.replacedFrom < start || this.byStart.get(chunk.replacedFrom).replacesUntil < chunk.end)) return true;
1645
+ chunk = this.byStart.get(chunk.end);
1646
+ }
1647
+ return false;
1075
1648
  }
1649
+ /** @internal */
1076
1650
  _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);
1651
+ function getReplacement(match, index, str) {
1652
+ if (typeof replacement === "string") return expandReplacement(replacement, match[0], index, str, match.slice(1), match.groups);
1653
+ else return match.groups === void 0 ? replacement(match[0], ...match.slice(1), index, str) : replacement(match[0], ...match.slice(1), index, str, match.groups);
1085
1654
  }
1086
- function matchAll(re, str) {
1087
- let match;
1088
- const matches = [];
1089
- while (match = re.exec(str)) matches.push(match);
1090
- return matches;
1091
- }
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 {
1655
+ const replaceMatch = (match) => {
1656
+ /* v8 ignore next 2 -- `match.index` is always defined for matches from `matchAll` */
1657
+ if (match.index == null) return false;
1658
+ if (this._hasRemovedContent(match.index, match.index + match[0].length)) return false;
1659
+ const replacement = getReplacement(match, match.index, this.original);
1660
+ if (replacement === match[0]) return true;
1661
+ if (match[0].length === 0) this.appendRight(match.index - this.offset, replacement);
1662
+ else this.overwrite(match.index - this.offset, match.index + match[0].length - this.offset, replacement);
1663
+ return true;
1664
+ };
1665
+ if (searchValue.global) {
1666
+ searchValue.lastIndex = 0;
1667
+ for (const match of this.original.matchAll(searchValue)) replaceMatch(match);
1668
+ } else {
1099
1669
  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);
1670
+ if (match && !replaceMatch(match)) {
1671
+ const global = new RegExp(searchValue.source, `${searchValue.flags}g`);
1672
+ for (const next of this.original.matchAll(global)) if (replaceMatch(next)) break;
1103
1673
  }
1104
1674
  }
1105
1675
  return this;
1106
1676
  }
1677
+ /** @internal */
1107
1678
  _replaceString(string, replacement) {
1108
1679
  const { original } = this;
1109
- const index = original.indexOf(string);
1110
- if (index !== -1) {
1680
+ let index = original.indexOf(string);
1681
+ while (index !== -1) {
1682
+ if (this._hasRemovedContent(index, index + string.length)) {
1683
+ index = original.indexOf(string, index + string.length);
1684
+ continue;
1685
+ }
1111
1686
  if (typeof replacement === "function") replacement = replacement(string, index, original);
1112
- if (string !== replacement) this.overwrite(index, index + string.length, replacement);
1687
+ else replacement = expandReplacement(replacement, string, index, original, [], void 0);
1688
+ if (string !== replacement) {
1689
+ if (string.length === 0) this.appendRight(index - this.offset, replacement);
1690
+ else this.overwrite(index - this.offset, index + string.length - this.offset, replacement);
1691
+ }
1692
+ break;
1113
1693
  }
1114
1694
  return this;
1115
1695
  }
1696
+ /**
1697
+ * String replacement with RegExp or string.
1698
+ */
1116
1699
  replace(searchValue, replacement) {
1117
1700
  if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
1118
1701
  return this._replaceRegexp(searchValue, replacement);
1119
1702
  }
1703
+ /** @internal */
1120
1704
  _replaceAllString(string, replacement) {
1121
1705
  const { original } = this;
1122
1706
  const stringLength = string.length;
1707
+ if (stringLength === 0) {
1708
+ for (let index = 0; index <= original.length; index += 1) {
1709
+ if (this._hasRemovedContent(index, index)) continue;
1710
+ const _replacement = typeof replacement === "function" ? replacement("", index, original) : expandReplacement(replacement, "", index, original, [], void 0);
1711
+ if (_replacement !== "") this.appendRight(index - this.offset, _replacement);
1712
+ }
1713
+ return this;
1714
+ }
1123
1715
  for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
1716
+ if (this._hasRemovedContent(index, index + stringLength)) continue;
1124
1717
  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);
1718
+ const _replacement = typeof replacement === "function" ? replacement(previous, index, original) : expandReplacement(replacement, previous, index, original, [], void 0);
1719
+ if (previous !== _replacement) this.overwrite(index - this.offset, index + stringLength - this.offset, _replacement);
1128
1720
  }
1129
1721
  return this;
1130
1722
  }
1723
+ /**
1724
+ * Same as `s.replace`, but replace all matched strings instead of just one.
1725
+ */
1131
1726
  replaceAll(searchValue, replacement) {
1132
1727
  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");
1728
+ if (!searchValue.global) throw new MagicStringError("replaceAll() requires a global RegExp");
1134
1729
  return this._replaceRegexp(searchValue, replacement);
1135
1730
  }
1136
1731
  };
1137
- //#endregion
1138
- //#region ../internal/dist/config-edit.js
1732
+ // ../internal/dist/config-edit.js
1139
1733
  const viteModule = "vite-hub";
1140
1734
  const nuxtModule = "vite-hub/nuxt";
1141
1735
  function fail(reason, at) {
@@ -1647,8 +2241,7 @@ function insertViteHubConfig(file, code, options) {
1647
2241
  code: next
1648
2242
  };
1649
2243
  }
1650
- //#endregion
1651
- //#region src/setup/project.ts
2244
+ // src/setup/project.ts
1652
2245
  const nuxtConfigFiles = [
1653
2246
  "nuxt.config.ts",
1654
2247
  "nuxt.config.mts",
@@ -1819,8 +2412,7 @@ async function readSetupProject(root, env) {
1819
2412
  serverDirs: framework === "nuxt" ? await nuxtServerDirs(root, config, env) : [join(root, "server")]
1820
2413
  };
1821
2414
  }
1822
- //#endregion
1823
- //#region ../internal/dist/definition-catalog.js
2415
+ // ../internal/dist/definition-catalog.js
1824
2416
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
1825
2417
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
1826
2418
  const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
@@ -1876,8 +2468,7 @@ function hasDefinitionFiles(path) {
1876
2468
  if (!existsSync(path)) return false;
1877
2469
  return statSync(path).isFile() || listSourceFiles(path).length > 0;
1878
2470
  }
1879
- //#endregion
1880
- //#region ../internal/dist/deployment.js
2471
+ // ../internal/dist/deployment.js
1881
2472
  const unsupported = (reason) => ({
1882
2473
  reason,
1883
2474
  supported: false
@@ -2071,8 +2662,7 @@ function detectHost(env = process.env) {
2071
2662
  }
2072
2663
  return providerHosts.find(([name]) => env[name]?.trim())?.[1];
2073
2664
  }
2074
- //#endregion
2075
- //#region src/setup/status.ts
2665
+ // src/setup/status.ts
2076
2666
  const addArgs = {
2077
2667
  bun: {
2078
2668
  dev: ["add", "-d"],
@@ -2274,8 +2864,7 @@ function setupStatus(project, env, withoutDefinitions) {
2274
2864
  schemaVersion: 1
2275
2865
  };
2276
2866
  }
2277
- //#endregion
2278
- //#region src/setup/deploy/host.ts
2867
+ // src/setup/deploy/host.ts
2279
2868
  /** A failed host CLI that may print values on stdout, such as `vercel env ls --json`: only stderr goes into the reason. */
2280
2869
  function hostListFailed(step, result, secrets) {
2281
2870
  return hostCliFailed(step, {
@@ -2629,8 +3218,7 @@ async function readDeployCommit(run, root, env) {
2629
3218
  return;
2630
3219
  }
2631
3220
  }
2632
- //#endregion
2633
- //#region src/setup/build-output.ts
3221
+ // src/setup/build-output.ts
2634
3222
  /** Runs the build script for `host`. VITEHUB_HOST_SOURCE=cli makes `host` win over a `host` literal in vitehub(). */
2635
3223
  async function build(project, host, context) {
2636
3224
  const command = `${project.packageManager} run build`;
@@ -2712,8 +3300,7 @@ async function readBuildOutput(root, host) {
2712
3300
  ...identityName ? { identityName } : {}
2713
3301
  };
2714
3302
  }
2715
- //#endregion
2716
- //#region src/setup/deploy/cloudflare.ts
3303
+ // src/setup/deploy/cloudflare.ts
2717
3304
  const valueFlags = /* @__PURE__ */ new Set(["--config"]);
2718
3305
  const plainFlags = /* @__PURE__ */ new Set(["--containers-rollout=gradual"]);
2719
3306
  async function readWranglerCommand(outputDir) {
@@ -3137,8 +3724,7 @@ const listCloudflareDeployments = async (context, { limit, includeLive }) => {
3137
3724
  if (includeLive && live && !recent.includes(live)) recent.push(live);
3138
3725
  return recent;
3139
3726
  };
3140
- //#endregion
3141
- //#region src/setup/deploy/deno.ts
3727
+ // src/setup/deploy/deno.ts
3142
3728
  const runnerFirstLine = "import { spawn } from \"node:child_process\"";
3143
3729
  async function denoAdapter(context, organization) {
3144
3730
  const runner = join(context.outputDir, "deploy.mjs");
@@ -3318,8 +3904,7 @@ const listDenoDeployments = async (context, { limit, includeLive }) => {
3318
3904
  });
3319
3905
  return recent;
3320
3906
  };
3321
- //#endregion
3322
- //#region ../internal/dist/abort.js
3907
+ // ../internal/dist/abort.js
3323
3908
  /**
3324
3909
  * Runs `task` and rejects as soon as `signal` aborts, without waiting for the task.
3325
3910
  *
@@ -3349,8 +3934,7 @@ function abortReason(signal, message) {
3349
3934
  if (signal?.reason !== void 0) return signal.reason;
3350
3935
  return new DOMException(message, "AbortError");
3351
3936
  }
3352
- //#endregion
3353
- //#region src/setup/deploy/netlify.ts
3937
+ // src/setup/deploy/netlify.ts
3354
3938
  const publishDir = "dist";
3355
3939
  function netlifyAdapter(context) {
3356
3940
  const netlify = hostCli("netlify", "netlify-cli", context.root, context.env);
@@ -3616,8 +4200,7 @@ const listNetlifyDeployments = async (context, { limit, includeLive }) => {
3616
4200
  }
3617
4201
  return recent;
3618
4202
  };
3619
- //#endregion
3620
- //#region src/setup/deploy/vercel.ts
4203
+ // src/setup/deploy/vercel.ts
3621
4204
  /** Check the CLI's saved session without reading its auth files or exposing a token. */
3622
4205
  async function hasVercelLogin(root, context) {
3623
4206
  try {
@@ -3824,8 +4407,7 @@ const listVercelDeployments = async (context, { limit, includeLive }) => {
3824
4407
  }
3825
4408
  return recent;
3826
4409
  };
3827
- //#endregion
3828
- //#region src/setup/link.ts
4410
+ // src/setup/link.ts
3829
4411
  /** The link file, relative to the project root. It is gitignored and never holds a secret. */
3830
4412
  const SETUP_LINK_FILE = ".vitehub/link.json";
3831
4413
  const linkHosts = [
@@ -4399,8 +4981,7 @@ function describeCredentials(credentials) {
4399
4981
  async function readSetupLinkStatus(project, host, context) {
4400
4982
  return (await readSetupLinkState(project, host, context)).status;
4401
4983
  }
4402
- //#endregion
4403
- //#region src/setup/env-encrypted.ts
4984
+ // src/setup/env-encrypted.ts
4404
4985
  const prefix = "encrypted:";
4405
4986
  /** The file where dotenvx writes private keys. It must never be in git. */
4406
4987
  const envKeysFile = ".env.keys";
@@ -4466,8 +5047,7 @@ async function decryptEnvValues(root, items, env) {
4466
5047
  values
4467
5048
  };
4468
5049
  }
4469
- //#endregion
4470
- //#region src/setup/deploy/github.ts
5050
+ // src/setup/deploy/github.ts
4471
5051
  const apiBase = "https://api.github.com";
4472
5052
  const repositoryPattern = /^[\w.-]+\/[\w.-]+$/u;
4473
5053
  /** GitHub accepts letters, digits, and `_`, not a digit first, and reserves the `GITHUB_` prefix. */
@@ -4643,14 +5223,8 @@ function githubEnv(context) {
4643
5223
  }
4644
5224
  };
4645
5225
  }
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
- });
5226
+ // src/setup/env.ts
5227
+ var env_exports = /* @__PURE__ */ __exportAll({ runEnvCommand: () => runEnvCommand });
4654
5228
  const defaultStage = "production";
4655
5229
  const tokenNames = [
4656
5230
  "CLOUDFLARE_API_TOKEN",
@@ -5374,5 +5948,4 @@ async function runEnvCommand(feature, args, context) {
5374
5948
  return writeSetupError(context, json, error);
5375
5949
  }
5376
5950
  }
5377
- //#endregion
5378
5951
  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 };