@varlock/cloudflare-integration 0.0.0 → 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,1733 @@
1
+ import path from 'path';
2
+ import { initVarlockEnv } from 'varlock/env';
3
+ import { patchGlobalConsole } from 'varlock/patch-console';
4
+ import { patchGlobalServerResponse } from 'varlock/patch-server-response';
5
+ import { patchGlobalResponse } from 'varlock/patch-response';
6
+ import { createDebug } from 'varlock';
7
+ import { execSyncVarlock } from 'varlock/exec-sync-varlock';
8
+ import { cloudflare } from '@cloudflare/vite-plugin';
9
+
10
+ // ../vite/dist/index.js
11
+ var __create = Object.create;
12
+ var __defProp = Object.defineProperty;
13
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
14
+ var __getOwnPropNames = Object.getOwnPropertyNames;
15
+ var __getProtoOf = Object.getPrototypeOf;
16
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
17
+ var __commonJS = (cb, mod) => function __require() {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ __defProp(target, "default", { value: mod, enumerable: true }),
34
+ mod
35
+ ));
36
+ var require_ast_matcher = __commonJS({
37
+ "../../../node_modules/.bun/ast-matcher@1.2.0/node_modules/ast-matcher/index.js"(exports$1, module) {
38
+ var STOP = false;
39
+ var SKIP_BRANCH = 1;
40
+ var IGNORED_KEYS = ["start", "end", "loc", "location", "locations", "line", "column", "range", "ranges", "raw", "extra"];
41
+ var _parser = function() {
42
+ throw new Error("No parser set, you need to set parser before use astMatcher. For instance, astMatcher.setParser(esprima.parse)");
43
+ };
44
+ function setParser(p) {
45
+ if (typeof p !== "function") {
46
+ throw new Error("Input parser must be a function that takes JavaScript contents as input, produce a estree compliant syntax tree object.");
47
+ }
48
+ _parser = function(contents) {
49
+ let node = p(contents);
50
+ if (node.type === "File" && node.program) {
51
+ node = node.program;
52
+ }
53
+ return node;
54
+ };
55
+ }
56
+ function traverse(object, visitor) {
57
+ let child;
58
+ if (!object) return;
59
+ let r = visitor.call(null, object);
60
+ if (r === STOP) return STOP;
61
+ if (r === SKIP_BRANCH) return;
62
+ for (let i = 0, keys = Object.keys(object); i < keys.length; i++) {
63
+ let key = keys[i];
64
+ if (IGNORED_KEYS.indexOf(key) !== -1) continue;
65
+ child = object[key];
66
+ if (typeof child === "object" && child !== null) {
67
+ if (traverse(child, visitor) === STOP) {
68
+ return STOP;
69
+ }
70
+ }
71
+ }
72
+ }
73
+ var ANY = 1;
74
+ var ANL = 2;
75
+ var STR = 3;
76
+ var ARR = 4;
77
+ function matchTerm(pattern) {
78
+ let possible;
79
+ if (pattern.type === "Identifier") {
80
+ possible = pattern.name.toString();
81
+ } else if (pattern.type === "ExpressionStatement" && pattern.expression.type === "Identifier") {
82
+ possible = pattern.expression.name.toString();
83
+ } else if ((pattern.type === "FieldDefinition" || pattern.type === "ClassProperty") && pattern.key.type === "Identifier") {
84
+ possible = pattern.key.name.toString();
85
+ }
86
+ if (!possible || !possible.startsWith("__")) return;
87
+ let type;
88
+ if (possible === "__any" || possible.startsWith("__any_")) {
89
+ type = ANY;
90
+ } else if (possible === "__anl" || possible.startsWith("__anl_")) {
91
+ type = ANL;
92
+ } else if (possible === "__str" || possible.startsWith("__str_")) {
93
+ type = STR;
94
+ } else if (possible === "__arr" || possible.startsWith("__arr_")) {
95
+ type = ARR;
96
+ }
97
+ if (type) return { type, name: possible.slice(6) };
98
+ }
99
+ function extract(pattern, part) {
100
+ if (!pattern) throw new Error("missing pattern");
101
+ if (!part) return STOP;
102
+ let term = matchTerm(pattern);
103
+ if (term) {
104
+ if (term.type === ANY) {
105
+ if (term.name) {
106
+ let r = {};
107
+ r[term.name] = part;
108
+ return r;
109
+ }
110
+ return {};
111
+ } else if (term.type === STR) {
112
+ if (part.type === "Literal" || part.type === "StringLiteral") {
113
+ if (term.name) {
114
+ let r = {};
115
+ r[term.name] = part.value;
116
+ return r;
117
+ }
118
+ return {};
119
+ }
120
+ return STOP;
121
+ }
122
+ }
123
+ if (Array.isArray(pattern)) {
124
+ if (!Array.isArray(part)) return STOP;
125
+ if (pattern.length === 1) {
126
+ let arrTerm = matchTerm(pattern[0]);
127
+ if (arrTerm) {
128
+ if (arrTerm.type === ARR) {
129
+ let arr = part.filter(function(it) {
130
+ return it.type === "Literal" || it.type === "StringLiteral";
131
+ }).map(function(it) {
132
+ return it.value;
133
+ });
134
+ if (arr.length) {
135
+ if (arrTerm.name) {
136
+ let r = {};
137
+ r[arrTerm.name] = arr;
138
+ return r;
139
+ }
140
+ return {};
141
+ }
142
+ return STOP;
143
+ } else if (arrTerm.type === ANL) {
144
+ if (arrTerm.name) {
145
+ let r = {};
146
+ r[arrTerm.name] = part;
147
+ return r;
148
+ }
149
+ return {};
150
+ }
151
+ }
152
+ }
153
+ if (pattern.length !== part.length) {
154
+ return STOP;
155
+ }
156
+ }
157
+ let allResult = {};
158
+ for (let i = 0, keys = Object.keys(pattern); i < keys.length; i++) {
159
+ let key = keys[i];
160
+ if (IGNORED_KEYS.indexOf(key) !== -1) continue;
161
+ let nextPattern = pattern[key];
162
+ let nextPart = part[key];
163
+ if (!nextPattern || typeof nextPattern !== "object") {
164
+ if (nextPattern === nextPart) continue;
165
+ return STOP;
166
+ }
167
+ const result = extract(nextPattern, nextPart);
168
+ if (result === STOP) return STOP;
169
+ if (result) Object.assign(allResult, result);
170
+ }
171
+ return allResult;
172
+ }
173
+ function compilePattern(pattern) {
174
+ let exp = ensureParsed(pattern);
175
+ if (exp.type !== "Program" || !exp.body) {
176
+ throw new Error(`Not a valid expression: "${pattern}".`);
177
+ }
178
+ if (exp.body.length === 0) {
179
+ throw new Error(`There is no statement in pattern "${pattern}".`);
180
+ }
181
+ if (exp.body.length > 1) {
182
+ throw new Error(`Multiple statements is not supported "${pattern}".`);
183
+ }
184
+ exp = exp.body[0];
185
+ if (exp.type === "ExpressionStatement") exp = exp.expression;
186
+ return exp;
187
+ }
188
+ function ensureParsed(codeOrNode) {
189
+ if (codeOrNode && codeOrNode.type) {
190
+ if (codeOrNode.type === "File" && codeOrNode.program) {
191
+ return codeOrNode.program;
192
+ }
193
+ return codeOrNode;
194
+ }
195
+ return _parser(codeOrNode);
196
+ }
197
+ function astMatcher2(pattern) {
198
+ let pat = compilePattern(pattern);
199
+ return function(jsStr) {
200
+ let node = ensureParsed(jsStr);
201
+ let matches = [];
202
+ traverse(node, function(n2) {
203
+ let m = extract(pat, n2);
204
+ if (m) {
205
+ matches.push({
206
+ match: m,
207
+ node: n2
208
+ // this is the full matching node
209
+ });
210
+ }
211
+ });
212
+ return matches.length ? matches : void 0;
213
+ };
214
+ }
215
+ function depFinder() {
216
+ if (arguments.length === 0) {
217
+ throw new Error("No patterns provided.");
218
+ }
219
+ let seed = 0;
220
+ let patterns = Array.prototype.map.call(arguments, function(p) {
221
+ return compilePattern(p.replace(/__dep(s?)/g, function(m, wantArr) {
222
+ return (wantArr ? "__arr_" : "__str_") + ++seed;
223
+ }));
224
+ });
225
+ let len = patterns.length;
226
+ return function(jsStr) {
227
+ let node = ensureParsed(jsStr);
228
+ let deps = [];
229
+ traverse(node, function(n2) {
230
+ for (let i = 0; i < len; i += 1) {
231
+ let result = extract(patterns[i], n2);
232
+ if (result) {
233
+ Object.keys(result).forEach(function(k) {
234
+ let d = result[k];
235
+ if (typeof d === "string") deps.push(d);
236
+ else deps.push.apply(deps, d);
237
+ });
238
+ break;
239
+ }
240
+ }
241
+ });
242
+ return deps;
243
+ };
244
+ }
245
+ module.exports = astMatcher2;
246
+ module.exports.setParser = setParser;
247
+ module.exports.ensureParsed = ensureParsed;
248
+ module.exports.extract = extract;
249
+ module.exports.compilePattern = compilePattern;
250
+ module.exports.depFinder = depFinder;
251
+ module.exports.STOP = STOP;
252
+ module.exports.SKIP_BRANCH = SKIP_BRANCH;
253
+ module.exports.traverse = traverse;
254
+ }
255
+ });
256
+ var comma = ",".charCodeAt(0);
257
+ var semicolon = ";".charCodeAt(0);
258
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
259
+ var intToChar = new Uint8Array(64);
260
+ var charToInt = new Uint8Array(128);
261
+ for (let i = 0; i < chars.length; i++) {
262
+ const c = chars.charCodeAt(i);
263
+ intToChar[i] = c;
264
+ charToInt[c] = i;
265
+ }
266
+ function encodeInteger(builder, num, relative) {
267
+ let delta = num - relative;
268
+ delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
269
+ do {
270
+ let clamped = delta & 31;
271
+ delta >>>= 5;
272
+ if (delta > 0) clamped |= 32;
273
+ builder.write(intToChar[clamped]);
274
+ } while (delta > 0);
275
+ return num;
276
+ }
277
+ var bufLength = 1024 * 16;
278
+ var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
279
+ decode(buf) {
280
+ const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
281
+ return out.toString();
282
+ }
283
+ } : {
284
+ decode(buf) {
285
+ let out = "";
286
+ for (let i = 0; i < buf.length; i++) {
287
+ out += String.fromCharCode(buf[i]);
288
+ }
289
+ return out;
290
+ }
291
+ };
292
+ var StringWriter = class {
293
+ constructor() {
294
+ this.pos = 0;
295
+ this.out = "";
296
+ this.buffer = new Uint8Array(bufLength);
297
+ }
298
+ write(v) {
299
+ const { buffer } = this;
300
+ buffer[this.pos++] = v;
301
+ if (this.pos === bufLength) {
302
+ this.out += td.decode(buffer);
303
+ this.pos = 0;
304
+ }
305
+ }
306
+ flush() {
307
+ const { buffer, out, pos } = this;
308
+ return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
309
+ }
310
+ };
311
+ function encode(decoded) {
312
+ const writer = new StringWriter();
313
+ let sourcesIndex = 0;
314
+ let sourceLine = 0;
315
+ let sourceColumn = 0;
316
+ let namesIndex = 0;
317
+ for (let i = 0; i < decoded.length; i++) {
318
+ const line = decoded[i];
319
+ if (i > 0) writer.write(semicolon);
320
+ if (line.length === 0) continue;
321
+ let genColumn = 0;
322
+ for (let j = 0; j < line.length; j++) {
323
+ const segment = line[j];
324
+ if (j > 0) writer.write(comma);
325
+ genColumn = encodeInteger(writer, segment[0], genColumn);
326
+ if (segment.length === 1) continue;
327
+ sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
328
+ sourceLine = encodeInteger(writer, segment[2], sourceLine);
329
+ sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
330
+ if (segment.length === 4) continue;
331
+ namesIndex = encodeInteger(writer, segment[4], namesIndex);
332
+ }
333
+ }
334
+ return writer.flush();
335
+ }
336
+ var BitSet = class _BitSet {
337
+ constructor(arg) {
338
+ this.bits = arg instanceof _BitSet ? arg.bits.slice() : [];
339
+ }
340
+ add(n2) {
341
+ this.bits[n2 >> 5] |= 1 << (n2 & 31);
342
+ }
343
+ has(n2) {
344
+ return !!(this.bits[n2 >> 5] & 1 << (n2 & 31));
345
+ }
346
+ };
347
+ var Chunk = class _Chunk {
348
+ constructor(start, end, content) {
349
+ this.start = start;
350
+ this.end = end;
351
+ this.original = content;
352
+ this.intro = "";
353
+ this.outro = "";
354
+ this.content = content;
355
+ this.storeName = false;
356
+ this.edited = false;
357
+ {
358
+ this.previous = null;
359
+ this.next = null;
360
+ }
361
+ }
362
+ appendLeft(content) {
363
+ this.outro += content;
364
+ }
365
+ appendRight(content) {
366
+ this.intro = this.intro + content;
367
+ }
368
+ clone() {
369
+ const chunk = new _Chunk(this.start, this.end, this.original);
370
+ chunk.intro = this.intro;
371
+ chunk.outro = this.outro;
372
+ chunk.content = this.content;
373
+ chunk.storeName = this.storeName;
374
+ chunk.edited = this.edited;
375
+ return chunk;
376
+ }
377
+ contains(index) {
378
+ return this.start < index && index < this.end;
379
+ }
380
+ eachNext(fn) {
381
+ let chunk = this;
382
+ while (chunk) {
383
+ fn(chunk);
384
+ chunk = chunk.next;
385
+ }
386
+ }
387
+ eachPrevious(fn) {
388
+ let chunk = this;
389
+ while (chunk) {
390
+ fn(chunk);
391
+ chunk = chunk.previous;
392
+ }
393
+ }
394
+ edit(content, storeName, contentOnly) {
395
+ this.content = content;
396
+ if (!contentOnly) {
397
+ this.intro = "";
398
+ this.outro = "";
399
+ }
400
+ this.storeName = storeName;
401
+ this.edited = true;
402
+ return this;
403
+ }
404
+ prependLeft(content) {
405
+ this.outro = content + this.outro;
406
+ }
407
+ prependRight(content) {
408
+ this.intro = content + this.intro;
409
+ }
410
+ reset() {
411
+ this.intro = "";
412
+ this.outro = "";
413
+ if (this.edited) {
414
+ this.content = this.original;
415
+ this.storeName = false;
416
+ this.edited = false;
417
+ }
418
+ }
419
+ split(index) {
420
+ const sliceIndex = index - this.start;
421
+ const originalBefore = this.original.slice(0, sliceIndex);
422
+ const originalAfter = this.original.slice(sliceIndex);
423
+ this.original = originalBefore;
424
+ const newChunk = new _Chunk(index, this.end, originalAfter);
425
+ newChunk.outro = this.outro;
426
+ this.outro = "";
427
+ this.end = index;
428
+ if (this.edited) {
429
+ newChunk.edit("", false);
430
+ this.content = "";
431
+ } else {
432
+ this.content = originalBefore;
433
+ }
434
+ newChunk.next = this.next;
435
+ if (newChunk.next) newChunk.next.previous = newChunk;
436
+ newChunk.previous = this;
437
+ this.next = newChunk;
438
+ return newChunk;
439
+ }
440
+ toString() {
441
+ return this.intro + this.content + this.outro;
442
+ }
443
+ trimEnd(rx) {
444
+ this.outro = this.outro.replace(rx, "");
445
+ if (this.outro.length) return true;
446
+ const trimmed = this.content.replace(rx, "");
447
+ if (trimmed.length) {
448
+ if (trimmed !== this.content) {
449
+ this.split(this.start + trimmed.length).edit("", void 0, true);
450
+ if (this.edited) {
451
+ this.edit(trimmed, this.storeName, true);
452
+ }
453
+ }
454
+ return true;
455
+ } else {
456
+ this.edit("", void 0, true);
457
+ this.intro = this.intro.replace(rx, "");
458
+ if (this.intro.length) return true;
459
+ }
460
+ }
461
+ trimStart(rx) {
462
+ this.intro = this.intro.replace(rx, "");
463
+ if (this.intro.length) return true;
464
+ const trimmed = this.content.replace(rx, "");
465
+ if (trimmed.length) {
466
+ if (trimmed !== this.content) {
467
+ const newChunk = this.split(this.end - trimmed.length);
468
+ if (this.edited) {
469
+ newChunk.edit(trimmed, this.storeName, true);
470
+ }
471
+ this.edit("", void 0, true);
472
+ }
473
+ return true;
474
+ } else {
475
+ this.edit("", void 0, true);
476
+ this.outro = this.outro.replace(rx, "");
477
+ if (this.outro.length) return true;
478
+ }
479
+ }
480
+ };
481
+ function getBtoa() {
482
+ if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
483
+ return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
484
+ } else if (typeof Buffer === "function") {
485
+ return (str) => Buffer.from(str, "utf-8").toString("base64");
486
+ } else {
487
+ return () => {
488
+ throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
489
+ };
490
+ }
491
+ }
492
+ var btoa = /* @__PURE__ */ getBtoa();
493
+ var SourceMap = class {
494
+ constructor(properties) {
495
+ this.version = 3;
496
+ this.file = properties.file;
497
+ this.sources = properties.sources;
498
+ this.sourcesContent = properties.sourcesContent;
499
+ this.names = properties.names;
500
+ this.mappings = encode(properties.mappings);
501
+ if (typeof properties.x_google_ignoreList !== "undefined") {
502
+ this.x_google_ignoreList = properties.x_google_ignoreList;
503
+ }
504
+ if (typeof properties.debugId !== "undefined") {
505
+ this.debugId = properties.debugId;
506
+ }
507
+ }
508
+ toString() {
509
+ return JSON.stringify(this);
510
+ }
511
+ toUrl() {
512
+ return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
513
+ }
514
+ };
515
+ function guessIndent(code) {
516
+ const lines = code.split("\n");
517
+ const tabbed = lines.filter((line) => /^\t+/.test(line));
518
+ const spaced = lines.filter((line) => /^ {2,}/.test(line));
519
+ if (tabbed.length === 0 && spaced.length === 0) {
520
+ return null;
521
+ }
522
+ if (tabbed.length >= spaced.length) {
523
+ return " ";
524
+ }
525
+ const min = spaced.reduce((previous, current) => {
526
+ const numSpaces = /^ +/.exec(current)[0].length;
527
+ return Math.min(numSpaces, previous);
528
+ }, Infinity);
529
+ return new Array(min + 1).join(" ");
530
+ }
531
+ function getRelativePath(from, to) {
532
+ const fromParts = from.split(/[/\\]/);
533
+ const toParts = to.split(/[/\\]/);
534
+ fromParts.pop();
535
+ while (fromParts[0] === toParts[0]) {
536
+ fromParts.shift();
537
+ toParts.shift();
538
+ }
539
+ if (fromParts.length) {
540
+ let i = fromParts.length;
541
+ while (i--) fromParts[i] = "..";
542
+ }
543
+ return fromParts.concat(toParts).join("/");
544
+ }
545
+ var toString = Object.prototype.toString;
546
+ function isObject(thing) {
547
+ return toString.call(thing) === "[object Object]";
548
+ }
549
+ function getLocator(source) {
550
+ const originalLines = source.split("\n");
551
+ const lineOffsets = [];
552
+ for (let i = 0, pos = 0; i < originalLines.length; i++) {
553
+ lineOffsets.push(pos);
554
+ pos += originalLines[i].length + 1;
555
+ }
556
+ return function locate(index) {
557
+ let i = 0;
558
+ let j = lineOffsets.length;
559
+ while (i < j) {
560
+ const m = i + j >> 1;
561
+ if (index < lineOffsets[m]) {
562
+ j = m;
563
+ } else {
564
+ i = m + 1;
565
+ }
566
+ }
567
+ const line = i - 1;
568
+ const column = index - lineOffsets[line];
569
+ return { line, column };
570
+ };
571
+ }
572
+ var wordRegex = /\w/;
573
+ var Mappings = class {
574
+ constructor(hires) {
575
+ this.hires = hires;
576
+ this.generatedCodeLine = 0;
577
+ this.generatedCodeColumn = 0;
578
+ this.raw = [];
579
+ this.rawSegments = this.raw[this.generatedCodeLine] = [];
580
+ this.pending = null;
581
+ }
582
+ addEdit(sourceIndex, content, loc, nameIndex) {
583
+ if (content.length) {
584
+ const contentLengthMinusOne = content.length - 1;
585
+ let contentLineEnd = content.indexOf("\n", 0);
586
+ let previousContentLineEnd = -1;
587
+ while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
588
+ const segment2 = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
589
+ if (nameIndex >= 0) {
590
+ segment2.push(nameIndex);
591
+ }
592
+ this.rawSegments.push(segment2);
593
+ this.generatedCodeLine += 1;
594
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
595
+ this.generatedCodeColumn = 0;
596
+ previousContentLineEnd = contentLineEnd;
597
+ contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
598
+ }
599
+ const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
600
+ if (nameIndex >= 0) {
601
+ segment.push(nameIndex);
602
+ }
603
+ this.rawSegments.push(segment);
604
+ this.advance(content.slice(previousContentLineEnd + 1));
605
+ } else if (this.pending) {
606
+ this.rawSegments.push(this.pending);
607
+ this.advance(content);
608
+ }
609
+ this.pending = null;
610
+ }
611
+ addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
612
+ let originalCharIndex = chunk.start;
613
+ let first = true;
614
+ let charInHiresBoundary = false;
615
+ while (originalCharIndex < chunk.end) {
616
+ if (original[originalCharIndex] === "\n") {
617
+ loc.line += 1;
618
+ loc.column = 0;
619
+ this.generatedCodeLine += 1;
620
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
621
+ this.generatedCodeColumn = 0;
622
+ first = true;
623
+ charInHiresBoundary = false;
624
+ } else {
625
+ if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
626
+ const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
627
+ if (this.hires === "boundary") {
628
+ if (wordRegex.test(original[originalCharIndex])) {
629
+ if (!charInHiresBoundary) {
630
+ this.rawSegments.push(segment);
631
+ charInHiresBoundary = true;
632
+ }
633
+ } else {
634
+ this.rawSegments.push(segment);
635
+ charInHiresBoundary = false;
636
+ }
637
+ } else {
638
+ this.rawSegments.push(segment);
639
+ }
640
+ }
641
+ loc.column += 1;
642
+ this.generatedCodeColumn += 1;
643
+ first = false;
644
+ }
645
+ originalCharIndex += 1;
646
+ }
647
+ this.pending = null;
648
+ }
649
+ advance(str) {
650
+ if (!str) return;
651
+ const lines = str.split("\n");
652
+ if (lines.length > 1) {
653
+ for (let i = 0; i < lines.length - 1; i++) {
654
+ this.generatedCodeLine++;
655
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
656
+ }
657
+ this.generatedCodeColumn = 0;
658
+ }
659
+ this.generatedCodeColumn += lines[lines.length - 1].length;
660
+ }
661
+ };
662
+ var n = "\n";
663
+ var warned = {
664
+ insertLeft: false,
665
+ insertRight: false,
666
+ storeName: false
667
+ };
668
+ var MagicString = class _MagicString {
669
+ constructor(string, options = {}) {
670
+ const chunk = new Chunk(0, string.length, string);
671
+ Object.defineProperties(this, {
672
+ original: { writable: true, value: string },
673
+ outro: { writable: true, value: "" },
674
+ intro: { writable: true, value: "" },
675
+ firstChunk: { writable: true, value: chunk },
676
+ lastChunk: { writable: true, value: chunk },
677
+ lastSearchedChunk: { writable: true, value: chunk },
678
+ byStart: { writable: true, value: {} },
679
+ byEnd: { writable: true, value: {} },
680
+ filename: { writable: true, value: options.filename },
681
+ indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
682
+ sourcemapLocations: { writable: true, value: new BitSet() },
683
+ storedNames: { writable: true, value: {} },
684
+ indentStr: { writable: true, value: void 0 },
685
+ ignoreList: { writable: true, value: options.ignoreList },
686
+ offset: { writable: true, value: options.offset || 0 }
687
+ });
688
+ this.byStart[0] = chunk;
689
+ this.byEnd[string.length] = chunk;
690
+ }
691
+ addSourcemapLocation(char) {
692
+ this.sourcemapLocations.add(char);
693
+ }
694
+ append(content) {
695
+ if (typeof content !== "string") throw new TypeError("outro content must be a string");
696
+ this.outro += content;
697
+ return this;
698
+ }
699
+ appendLeft(index, content) {
700
+ index = index + this.offset;
701
+ if (typeof content !== "string") throw new TypeError("inserted content must be a string");
702
+ this._split(index);
703
+ const chunk = this.byEnd[index];
704
+ if (chunk) {
705
+ chunk.appendLeft(content);
706
+ } else {
707
+ this.intro += content;
708
+ }
709
+ return this;
710
+ }
711
+ appendRight(index, content) {
712
+ index = index + this.offset;
713
+ if (typeof content !== "string") throw new TypeError("inserted content must be a string");
714
+ this._split(index);
715
+ const chunk = this.byStart[index];
716
+ if (chunk) {
717
+ chunk.appendRight(content);
718
+ } else {
719
+ this.outro += content;
720
+ }
721
+ return this;
722
+ }
723
+ clone() {
724
+ const cloned = new _MagicString(this.original, { filename: this.filename, offset: this.offset });
725
+ let originalChunk = this.firstChunk;
726
+ let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
727
+ while (originalChunk) {
728
+ cloned.byStart[clonedChunk.start] = clonedChunk;
729
+ cloned.byEnd[clonedChunk.end] = clonedChunk;
730
+ const nextOriginalChunk = originalChunk.next;
731
+ const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
732
+ if (nextClonedChunk) {
733
+ clonedChunk.next = nextClonedChunk;
734
+ nextClonedChunk.previous = clonedChunk;
735
+ clonedChunk = nextClonedChunk;
736
+ }
737
+ originalChunk = nextOriginalChunk;
738
+ }
739
+ cloned.lastChunk = clonedChunk;
740
+ if (this.indentExclusionRanges) {
741
+ cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
742
+ }
743
+ cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
744
+ cloned.intro = this.intro;
745
+ cloned.outro = this.outro;
746
+ return cloned;
747
+ }
748
+ generateDecodedMap(options) {
749
+ options = options || {};
750
+ const sourceIndex = 0;
751
+ const names = Object.keys(this.storedNames);
752
+ const mappings = new Mappings(options.hires);
753
+ const locate = getLocator(this.original);
754
+ if (this.intro) {
755
+ mappings.advance(this.intro);
756
+ }
757
+ this.firstChunk.eachNext((chunk) => {
758
+ const loc = locate(chunk.start);
759
+ if (chunk.intro.length) mappings.advance(chunk.intro);
760
+ if (chunk.edited) {
761
+ mappings.addEdit(
762
+ sourceIndex,
763
+ chunk.content,
764
+ loc,
765
+ chunk.storeName ? names.indexOf(chunk.original) : -1
766
+ );
767
+ } else {
768
+ mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
769
+ }
770
+ if (chunk.outro.length) mappings.advance(chunk.outro);
771
+ });
772
+ if (this.outro) {
773
+ mappings.advance(this.outro);
774
+ }
775
+ return {
776
+ file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
777
+ sources: [
778
+ options.source ? getRelativePath(options.file || "", options.source) : options.file || ""
779
+ ],
780
+ sourcesContent: options.includeContent ? [this.original] : void 0,
781
+ names,
782
+ mappings: mappings.raw,
783
+ x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
784
+ };
785
+ }
786
+ generateMap(options) {
787
+ return new SourceMap(this.generateDecodedMap(options));
788
+ }
789
+ _ensureindentStr() {
790
+ if (this.indentStr === void 0) {
791
+ this.indentStr = guessIndent(this.original);
792
+ }
793
+ }
794
+ _getRawIndentString() {
795
+ this._ensureindentStr();
796
+ return this.indentStr;
797
+ }
798
+ getIndentString() {
799
+ this._ensureindentStr();
800
+ return this.indentStr === null ? " " : this.indentStr;
801
+ }
802
+ indent(indentStr, options) {
803
+ const pattern = /^[^\r\n]/gm;
804
+ if (isObject(indentStr)) {
805
+ options = indentStr;
806
+ indentStr = void 0;
807
+ }
808
+ if (indentStr === void 0) {
809
+ this._ensureindentStr();
810
+ indentStr = this.indentStr || " ";
811
+ }
812
+ if (indentStr === "") return this;
813
+ options = options || {};
814
+ const isExcluded = {};
815
+ if (options.exclude) {
816
+ const exclusions = typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude;
817
+ exclusions.forEach((exclusion) => {
818
+ for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
819
+ isExcluded[i] = true;
820
+ }
821
+ });
822
+ }
823
+ let shouldIndentNextCharacter = options.indentStart !== false;
824
+ const replacer = (match) => {
825
+ if (shouldIndentNextCharacter) return `${indentStr}${match}`;
826
+ shouldIndentNextCharacter = true;
827
+ return match;
828
+ };
829
+ this.intro = this.intro.replace(pattern, replacer);
830
+ let charIndex = 0;
831
+ let chunk = this.firstChunk;
832
+ while (chunk) {
833
+ const end = chunk.end;
834
+ if (chunk.edited) {
835
+ if (!isExcluded[charIndex]) {
836
+ chunk.content = chunk.content.replace(pattern, replacer);
837
+ if (chunk.content.length) {
838
+ shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
839
+ }
840
+ }
841
+ } else {
842
+ charIndex = chunk.start;
843
+ while (charIndex < end) {
844
+ if (!isExcluded[charIndex]) {
845
+ const char = this.original[charIndex];
846
+ if (char === "\n") {
847
+ shouldIndentNextCharacter = true;
848
+ } else if (char !== "\r" && shouldIndentNextCharacter) {
849
+ shouldIndentNextCharacter = false;
850
+ if (charIndex === chunk.start) {
851
+ chunk.prependRight(indentStr);
852
+ } else {
853
+ this._splitChunk(chunk, charIndex);
854
+ chunk = chunk.next;
855
+ chunk.prependRight(indentStr);
856
+ }
857
+ }
858
+ }
859
+ charIndex += 1;
860
+ }
861
+ }
862
+ charIndex = chunk.end;
863
+ chunk = chunk.next;
864
+ }
865
+ this.outro = this.outro.replace(pattern, replacer);
866
+ return this;
867
+ }
868
+ insert() {
869
+ throw new Error(
870
+ "magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)"
871
+ );
872
+ }
873
+ insertLeft(index, content) {
874
+ if (!warned.insertLeft) {
875
+ console.warn(
876
+ "magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"
877
+ );
878
+ warned.insertLeft = true;
879
+ }
880
+ return this.appendLeft(index, content);
881
+ }
882
+ insertRight(index, content) {
883
+ if (!warned.insertRight) {
884
+ console.warn(
885
+ "magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"
886
+ );
887
+ warned.insertRight = true;
888
+ }
889
+ return this.prependRight(index, content);
890
+ }
891
+ move(start, end, index) {
892
+ start = start + this.offset;
893
+ end = end + this.offset;
894
+ index = index + this.offset;
895
+ if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
896
+ this._split(start);
897
+ this._split(end);
898
+ this._split(index);
899
+ const first = this.byStart[start];
900
+ const last = this.byEnd[end];
901
+ const oldLeft = first.previous;
902
+ const oldRight = last.next;
903
+ const newRight = this.byStart[index];
904
+ if (!newRight && last === this.lastChunk) return this;
905
+ const newLeft = newRight ? newRight.previous : this.lastChunk;
906
+ if (oldLeft) oldLeft.next = oldRight;
907
+ if (oldRight) oldRight.previous = oldLeft;
908
+ if (newLeft) newLeft.next = first;
909
+ if (newRight) newRight.previous = last;
910
+ if (!first.previous) this.firstChunk = last.next;
911
+ if (!last.next) {
912
+ this.lastChunk = first.previous;
913
+ this.lastChunk.next = null;
914
+ }
915
+ first.previous = newLeft;
916
+ last.next = newRight || null;
917
+ if (!newLeft) this.firstChunk = first;
918
+ if (!newRight) this.lastChunk = last;
919
+ return this;
920
+ }
921
+ overwrite(start, end, content, options) {
922
+ options = options || {};
923
+ return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
924
+ }
925
+ update(start, end, content, options) {
926
+ start = start + this.offset;
927
+ end = end + this.offset;
928
+ if (typeof content !== "string") throw new TypeError("replacement content must be a string");
929
+ if (this.original.length !== 0) {
930
+ while (start < 0) start += this.original.length;
931
+ while (end < 0) end += this.original.length;
932
+ }
933
+ if (end > this.original.length) throw new Error("end is out of bounds");
934
+ if (start === end)
935
+ throw new Error(
936
+ "Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead"
937
+ );
938
+ this._split(start);
939
+ this._split(end);
940
+ if (options === true) {
941
+ if (!warned.storeName) {
942
+ console.warn(
943
+ "The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"
944
+ );
945
+ warned.storeName = true;
946
+ }
947
+ options = { storeName: true };
948
+ }
949
+ const storeName = options !== void 0 ? options.storeName : false;
950
+ const overwrite = options !== void 0 ? options.overwrite : false;
951
+ if (storeName) {
952
+ const original = this.original.slice(start, end);
953
+ Object.defineProperty(this.storedNames, original, {
954
+ writable: true,
955
+ value: true,
956
+ enumerable: true
957
+ });
958
+ }
959
+ const first = this.byStart[start];
960
+ const last = this.byEnd[end];
961
+ if (first) {
962
+ let chunk = first;
963
+ while (chunk !== last) {
964
+ if (chunk.next !== this.byStart[chunk.end]) {
965
+ throw new Error("Cannot overwrite across a split point");
966
+ }
967
+ chunk = chunk.next;
968
+ chunk.edit("", false);
969
+ }
970
+ first.edit(content, storeName, !overwrite);
971
+ } else {
972
+ const newChunk = new Chunk(start, end, "").edit(content, storeName);
973
+ last.next = newChunk;
974
+ newChunk.previous = last;
975
+ }
976
+ return this;
977
+ }
978
+ prepend(content) {
979
+ if (typeof content !== "string") throw new TypeError("outro content must be a string");
980
+ this.intro = content + this.intro;
981
+ return this;
982
+ }
983
+ prependLeft(index, content) {
984
+ index = index + this.offset;
985
+ if (typeof content !== "string") throw new TypeError("inserted content must be a string");
986
+ this._split(index);
987
+ const chunk = this.byEnd[index];
988
+ if (chunk) {
989
+ chunk.prependLeft(content);
990
+ } else {
991
+ this.intro = content + this.intro;
992
+ }
993
+ return this;
994
+ }
995
+ prependRight(index, content) {
996
+ index = index + this.offset;
997
+ if (typeof content !== "string") throw new TypeError("inserted content must be a string");
998
+ this._split(index);
999
+ const chunk = this.byStart[index];
1000
+ if (chunk) {
1001
+ chunk.prependRight(content);
1002
+ } else {
1003
+ this.outro = content + this.outro;
1004
+ }
1005
+ return this;
1006
+ }
1007
+ remove(start, end) {
1008
+ start = start + this.offset;
1009
+ end = end + this.offset;
1010
+ if (this.original.length !== 0) {
1011
+ while (start < 0) start += this.original.length;
1012
+ while (end < 0) end += this.original.length;
1013
+ }
1014
+ if (start === end) return this;
1015
+ if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
1016
+ if (start > end) throw new Error("end must be greater than start");
1017
+ this._split(start);
1018
+ this._split(end);
1019
+ let chunk = this.byStart[start];
1020
+ while (chunk) {
1021
+ chunk.intro = "";
1022
+ chunk.outro = "";
1023
+ chunk.edit("");
1024
+ chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1025
+ }
1026
+ return this;
1027
+ }
1028
+ reset(start, end) {
1029
+ start = start + this.offset;
1030
+ end = end + this.offset;
1031
+ if (this.original.length !== 0) {
1032
+ while (start < 0) start += this.original.length;
1033
+ while (end < 0) end += this.original.length;
1034
+ }
1035
+ if (start === end) return this;
1036
+ if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
1037
+ if (start > end) throw new Error("end must be greater than start");
1038
+ this._split(start);
1039
+ this._split(end);
1040
+ let chunk = this.byStart[start];
1041
+ while (chunk) {
1042
+ chunk.reset();
1043
+ chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1044
+ }
1045
+ return this;
1046
+ }
1047
+ lastChar() {
1048
+ if (this.outro.length) return this.outro[this.outro.length - 1];
1049
+ let chunk = this.lastChunk;
1050
+ do {
1051
+ if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
1052
+ if (chunk.content.length) return chunk.content[chunk.content.length - 1];
1053
+ if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
1054
+ } while (chunk = chunk.previous);
1055
+ if (this.intro.length) return this.intro[this.intro.length - 1];
1056
+ return "";
1057
+ }
1058
+ lastLine() {
1059
+ let lineIndex = this.outro.lastIndexOf(n);
1060
+ if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
1061
+ let lineStr = this.outro;
1062
+ let chunk = this.lastChunk;
1063
+ do {
1064
+ if (chunk.outro.length > 0) {
1065
+ lineIndex = chunk.outro.lastIndexOf(n);
1066
+ if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
1067
+ lineStr = chunk.outro + lineStr;
1068
+ }
1069
+ if (chunk.content.length > 0) {
1070
+ lineIndex = chunk.content.lastIndexOf(n);
1071
+ if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
1072
+ lineStr = chunk.content + lineStr;
1073
+ }
1074
+ if (chunk.intro.length > 0) {
1075
+ lineIndex = chunk.intro.lastIndexOf(n);
1076
+ if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
1077
+ lineStr = chunk.intro + lineStr;
1078
+ }
1079
+ } while (chunk = chunk.previous);
1080
+ lineIndex = this.intro.lastIndexOf(n);
1081
+ if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
1082
+ return this.intro + lineStr;
1083
+ }
1084
+ slice(start = 0, end = this.original.length - this.offset) {
1085
+ start = start + this.offset;
1086
+ end = end + this.offset;
1087
+ if (this.original.length !== 0) {
1088
+ while (start < 0) start += this.original.length;
1089
+ while (end < 0) end += this.original.length;
1090
+ }
1091
+ let result = "";
1092
+ let chunk = this.firstChunk;
1093
+ while (chunk && (chunk.start > start || chunk.end <= start)) {
1094
+ if (chunk.start < end && chunk.end >= end) {
1095
+ return result;
1096
+ }
1097
+ chunk = chunk.next;
1098
+ }
1099
+ if (chunk && chunk.edited && chunk.start !== start)
1100
+ throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
1101
+ const startChunk = chunk;
1102
+ while (chunk) {
1103
+ if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1104
+ result += chunk.intro;
1105
+ }
1106
+ const containsEnd = chunk.start < end && chunk.end >= end;
1107
+ if (containsEnd && chunk.edited && chunk.end !== end)
1108
+ throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
1109
+ const sliceStart = startChunk === chunk ? start - chunk.start : 0;
1110
+ const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1111
+ result += chunk.content.slice(sliceStart, sliceEnd);
1112
+ if (chunk.outro && (!containsEnd || chunk.end === end)) {
1113
+ result += chunk.outro;
1114
+ }
1115
+ if (containsEnd) {
1116
+ break;
1117
+ }
1118
+ chunk = chunk.next;
1119
+ }
1120
+ return result;
1121
+ }
1122
+ // TODO deprecate this? not really very useful
1123
+ snip(start, end) {
1124
+ const clone = this.clone();
1125
+ clone.remove(0, start);
1126
+ clone.remove(end, clone.original.length);
1127
+ return clone;
1128
+ }
1129
+ _split(index) {
1130
+ if (this.byStart[index] || this.byEnd[index]) return;
1131
+ let chunk = this.lastSearchedChunk;
1132
+ let previousChunk = chunk;
1133
+ const searchForward = index > chunk.end;
1134
+ while (chunk) {
1135
+ if (chunk.contains(index)) return this._splitChunk(chunk, index);
1136
+ chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1137
+ if (chunk === previousChunk) return;
1138
+ previousChunk = chunk;
1139
+ }
1140
+ }
1141
+ _splitChunk(chunk, index) {
1142
+ if (chunk.edited && chunk.content.length) {
1143
+ const loc = getLocator(this.original)(index);
1144
+ throw new Error(
1145
+ `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`
1146
+ );
1147
+ }
1148
+ const newChunk = chunk.split(index);
1149
+ this.byEnd[index] = chunk;
1150
+ this.byStart[index] = newChunk;
1151
+ this.byEnd[newChunk.end] = newChunk;
1152
+ if (chunk === this.lastChunk) this.lastChunk = newChunk;
1153
+ this.lastSearchedChunk = chunk;
1154
+ return true;
1155
+ }
1156
+ toString() {
1157
+ let str = this.intro;
1158
+ let chunk = this.firstChunk;
1159
+ while (chunk) {
1160
+ str += chunk.toString();
1161
+ chunk = chunk.next;
1162
+ }
1163
+ return str + this.outro;
1164
+ }
1165
+ isEmpty() {
1166
+ let chunk = this.firstChunk;
1167
+ do {
1168
+ if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim())
1169
+ return false;
1170
+ } while (chunk = chunk.next);
1171
+ return true;
1172
+ }
1173
+ length() {
1174
+ let chunk = this.firstChunk;
1175
+ let length = 0;
1176
+ do {
1177
+ length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1178
+ } while (chunk = chunk.next);
1179
+ return length;
1180
+ }
1181
+ trimLines() {
1182
+ return this.trim("[\\r\\n]");
1183
+ }
1184
+ trim(charType) {
1185
+ return this.trimStart(charType).trimEnd(charType);
1186
+ }
1187
+ trimEndAborted(charType) {
1188
+ const rx = new RegExp((charType || "\\s") + "+$");
1189
+ this.outro = this.outro.replace(rx, "");
1190
+ if (this.outro.length) return true;
1191
+ let chunk = this.lastChunk;
1192
+ do {
1193
+ const end = chunk.end;
1194
+ const aborted = chunk.trimEnd(rx);
1195
+ if (chunk.end !== end) {
1196
+ if (this.lastChunk === chunk) {
1197
+ this.lastChunk = chunk.next;
1198
+ }
1199
+ this.byEnd[chunk.end] = chunk;
1200
+ this.byStart[chunk.next.start] = chunk.next;
1201
+ this.byEnd[chunk.next.end] = chunk.next;
1202
+ }
1203
+ if (aborted) return true;
1204
+ chunk = chunk.previous;
1205
+ } while (chunk);
1206
+ return false;
1207
+ }
1208
+ trimEnd(charType) {
1209
+ this.trimEndAborted(charType);
1210
+ return this;
1211
+ }
1212
+ trimStartAborted(charType) {
1213
+ const rx = new RegExp("^" + (charType || "\\s") + "+");
1214
+ this.intro = this.intro.replace(rx, "");
1215
+ if (this.intro.length) return true;
1216
+ let chunk = this.firstChunk;
1217
+ do {
1218
+ const end = chunk.end;
1219
+ const aborted = chunk.trimStart(rx);
1220
+ if (chunk.end !== end) {
1221
+ if (chunk === this.lastChunk) this.lastChunk = chunk.next;
1222
+ this.byEnd[chunk.end] = chunk;
1223
+ this.byStart[chunk.next.start] = chunk.next;
1224
+ this.byEnd[chunk.next.end] = chunk.next;
1225
+ }
1226
+ if (aborted) return true;
1227
+ chunk = chunk.next;
1228
+ } while (chunk);
1229
+ return false;
1230
+ }
1231
+ trimStart(charType) {
1232
+ this.trimStartAborted(charType);
1233
+ return this;
1234
+ }
1235
+ hasChanged() {
1236
+ return this.original !== this.toString();
1237
+ }
1238
+ _replaceRegexp(searchValue, replacement) {
1239
+ function getReplacement(match, str) {
1240
+ if (typeof replacement === "string") {
1241
+ return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
1242
+ if (i === "$") return "$";
1243
+ if (i === "&") return match[0];
1244
+ const num = +i;
1245
+ if (num < match.length) return match[+i];
1246
+ return `$${i}`;
1247
+ });
1248
+ } else {
1249
+ return replacement(...match, match.index, str, match.groups);
1250
+ }
1251
+ }
1252
+ function matchAll(re, str) {
1253
+ let match;
1254
+ const matches = [];
1255
+ while (match = re.exec(str)) {
1256
+ matches.push(match);
1257
+ }
1258
+ return matches;
1259
+ }
1260
+ if (searchValue.global) {
1261
+ const matches = matchAll(searchValue, this.original);
1262
+ matches.forEach((match) => {
1263
+ if (match.index != null) {
1264
+ const replacement2 = getReplacement(match, this.original);
1265
+ if (replacement2 !== match[0]) {
1266
+ this.overwrite(match.index, match.index + match[0].length, replacement2);
1267
+ }
1268
+ }
1269
+ });
1270
+ } else {
1271
+ const match = this.original.match(searchValue);
1272
+ if (match && match.index != null) {
1273
+ const replacement2 = getReplacement(match, this.original);
1274
+ if (replacement2 !== match[0]) {
1275
+ this.overwrite(match.index, match.index + match[0].length, replacement2);
1276
+ }
1277
+ }
1278
+ }
1279
+ return this;
1280
+ }
1281
+ _replaceString(string, replacement) {
1282
+ const { original } = this;
1283
+ const index = original.indexOf(string);
1284
+ if (index !== -1) {
1285
+ if (typeof replacement === "function") {
1286
+ replacement = replacement(string, index, original);
1287
+ }
1288
+ if (string !== replacement) {
1289
+ this.overwrite(index, index + string.length, replacement);
1290
+ }
1291
+ }
1292
+ return this;
1293
+ }
1294
+ replace(searchValue, replacement) {
1295
+ if (typeof searchValue === "string") {
1296
+ return this._replaceString(searchValue, replacement);
1297
+ }
1298
+ return this._replaceRegexp(searchValue, replacement);
1299
+ }
1300
+ _replaceAllString(string, replacement) {
1301
+ const { original } = this;
1302
+ const stringLength = string.length;
1303
+ for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
1304
+ const previous = original.slice(index, index + stringLength);
1305
+ let _replacement = replacement;
1306
+ if (typeof replacement === "function") {
1307
+ _replacement = replacement(previous, index, original);
1308
+ }
1309
+ if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
1310
+ }
1311
+ return this;
1312
+ }
1313
+ replaceAll(searchValue, replacement) {
1314
+ if (typeof searchValue === "string") {
1315
+ return this._replaceAllString(searchValue, replacement);
1316
+ }
1317
+ if (!searchValue.global) {
1318
+ throw new TypeError(
1319
+ "MagicString.prototype.replaceAll called with a non-global RegExp argument"
1320
+ );
1321
+ }
1322
+ return this._replaceRegexp(searchValue, replacement);
1323
+ }
1324
+ };
1325
+ var import_ast_matcher = __toESM(require_ast_matcher());
1326
+ function escapeStringRegexp(string) {
1327
+ if (typeof string !== "string") throw new TypeError("Expected a string");
1328
+ return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
1329
+ }
1330
+ function markEdited(node, edits) {
1331
+ for (const [start, end] of edits) {
1332
+ if (start <= node.start && node.start < end || start < node.end && node.end <= end) {
1333
+ return false;
1334
+ }
1335
+ }
1336
+ return edits.push([node.start, node.end]);
1337
+ }
1338
+ var SUPPORTED_FILES = ["js", "ts", "mjs", "mts", "cjs", "cts", "jsx", "tsx", "vue", "svelte"];
1339
+ function createReplacerTransformFn(opts) {
1340
+ const keys = Object.keys(opts.replacements);
1341
+ let matchers;
1342
+ const extraMatchersForFileType = {};
1343
+ const findAnyReplacementRegex = new RegExp(`(?:${keys.map(escapeStringRegexp).join("|")})`, "g");
1344
+ return function transform(rollupPluginCtx, code, id) {
1345
+ if (keys.length === 0) return null;
1346
+ const fileExt = id.split("?")[0].split("#")[0].split(".").pop() || "";
1347
+ if (!SUPPORTED_FILES.includes(fileExt)) return null;
1348
+ if (code.search(findAnyReplacementRegex) === -1) return null;
1349
+ const parse = (codeToParse, source = code) => {
1350
+ try {
1351
+ return rollupPluginCtx.parse(codeToParse, void 0);
1352
+ } catch (error) {
1353
+ error.message += ` in ${source}`;
1354
+ throw error;
1355
+ }
1356
+ };
1357
+ const ast = parse(code, id);
1358
+ matchers ||= keys.map((key) => ({
1359
+ matcher: (0, import_ast_matcher.default)(parse(key)),
1360
+ replacement: opts.replacements[key]
1361
+ }));
1362
+ if (fileExt === "vue") {
1363
+ extraMatchersForFileType.vue ||= keys.map((key) => ({
1364
+ matcher: (0, import_ast_matcher.default)(parse(`$setup.${key}`)),
1365
+ replacement: opts.replacements[key]
1366
+ }));
1367
+ }
1368
+ const magicString = new MagicString(code);
1369
+ const edits = [];
1370
+ Object.values([...matchers, ...extraMatchersForFileType[fileExt] || []]).forEach(({ matcher, replacement }) => {
1371
+ for (const { node } of matcher(ast) || []) {
1372
+ if (markEdited(node, edits)) {
1373
+ magicString.overwrite(
1374
+ node.start,
1375
+ node.end,
1376
+ replacement
1377
+ );
1378
+ }
1379
+ }
1380
+ });
1381
+ if (edits.length === 0) return null;
1382
+ return magicString;
1383
+ };
1384
+ }
1385
+ globalThis.__varlockThrowOnMissingKeys = true;
1386
+ var originalProcessEnv = { ...process.env };
1387
+ var debug = createDebug("varlock:vite-integration");
1388
+ var isFirstLoad = !process.__VARLOCK_ENV;
1389
+ debug("varlock vite plugin loaded. first load = ", isFirstLoad);
1390
+ var isDevCommand;
1391
+ var configIsValid = true;
1392
+ var varlockLoadedEnv;
1393
+ var staticReplacements = {};
1394
+ var replacerFn;
1395
+ function resetStaticReplacements() {
1396
+ staticReplacements = {};
1397
+ for (const itemKey in varlockLoadedEnv?.config) {
1398
+ const itemInfo = varlockLoadedEnv.config[itemKey];
1399
+ if (!itemInfo.isSensitive) {
1400
+ const val = itemInfo.value === void 0 ? "undefined" : JSON.stringify(itemInfo.value);
1401
+ staticReplacements[`ENV.${itemKey}`] = val;
1402
+ }
1403
+ }
1404
+ debug("static replacements", staticReplacements);
1405
+ replacerFn = createReplacerTransformFn({
1406
+ replacements: staticReplacements
1407
+ });
1408
+ }
1409
+ var loadCount = 0;
1410
+ function reloadConfig(cwd) {
1411
+ debug("loading config - count =", ++loadCount, cwd ? `(cwd: ${cwd})` : "");
1412
+ try {
1413
+ const execResult = execSyncVarlock("load --format json-full --compact", {
1414
+ env: originalProcessEnv,
1415
+ ...cwd && { cwd }
1416
+ });
1417
+ process.env.__VARLOCK_ENV = execResult;
1418
+ varlockLoadedEnv = JSON.parse(process.env.__VARLOCK_ENV);
1419
+ configIsValid = true;
1420
+ } catch (err) {
1421
+ const errAny = err;
1422
+ const stdout = errAny?.stdout?.toString();
1423
+ if (stdout) {
1424
+ try {
1425
+ varlockLoadedEnv = JSON.parse(stdout);
1426
+ } catch {
1427
+ }
1428
+ }
1429
+ if (errAny?.stderr) console.error(errAny.stderr.toString());
1430
+ configIsValid = false;
1431
+ resetStaticReplacements();
1432
+ return;
1433
+ }
1434
+ initVarlockEnv();
1435
+ patchGlobalConsole();
1436
+ patchGlobalServerResponse();
1437
+ patchGlobalResponse();
1438
+ resetStaticReplacements();
1439
+ }
1440
+ reloadConfig();
1441
+ function varlockVitePlugin(vitePluginOptions) {
1442
+ return {
1443
+ name: "inject-varlock-config",
1444
+ enforce: "post",
1445
+ // hook to modify config before it is resolved
1446
+ async config(config, env) {
1447
+ debug("vite plugin - config fn called");
1448
+ if (config.envDir) {
1449
+ console.warn(`
1450
+ [varlock] \u26A0\uFE0F The \`envDir\` Vite option is not supported by varlock.
1451
+ To load .env files from a custom directory, set \`varlock.loadPath\` in your \`package.json\`:
1452
+
1453
+ {
1454
+ "varlock": {
1455
+ "loadPath": "./your-env-dir/"
1456
+ }
1457
+ }
1458
+
1459
+ See https://varlock.dev/integrations/vite/ for more details.
1460
+ `);
1461
+ }
1462
+ isDevCommand = env.command === "serve";
1463
+ const projectRoot = config.root ? path.resolve(config.root) : void 0;
1464
+ const rootDiffersFromCwd = !!(projectRoot && path.relative(projectRoot, process.cwd()) !== "");
1465
+ if (rootDiffersFromCwd) {
1466
+ reloadConfig(projectRoot);
1467
+ } else if (isFirstLoad) {
1468
+ isFirstLoad = false;
1469
+ } else if (isDevCommand) {
1470
+ reloadConfig();
1471
+ }
1472
+ if (!configIsValid) {
1473
+ if (isDevCommand) {
1474
+ config.clearScreen = false;
1475
+ } else {
1476
+ console.log("\u{1F4A5} Varlock config validation failed \u{1F4A5}");
1477
+ if (varlockLoadedEnv?.errors?.root) {
1478
+ for (const msg of varlockLoadedEnv.errors.root) {
1479
+ console.log(` - ${msg}`);
1480
+ }
1481
+ }
1482
+ if (varlockLoadedEnv?.errors?.configItems) {
1483
+ for (const [key, msg] of Object.entries(varlockLoadedEnv.errors.configItems)) {
1484
+ console.log(` - ${key}: ${msg}`);
1485
+ }
1486
+ }
1487
+ process.exit(1);
1488
+ }
1489
+ }
1490
+ },
1491
+ // hook to observe/modify config after it is resolved
1492
+ configResolved(config) {
1493
+ debug("vite plugin - configResolved fn called");
1494
+ if (!varlockLoadedEnv) return;
1495
+ for (const varlockSource of varlockLoadedEnv.sources) {
1496
+ if (!varlockSource.enabled) continue;
1497
+ if (varlockLoadedEnv.basePath && varlockSource.path) {
1498
+ config.configFileDependencies.push(path.resolve(varlockLoadedEnv.basePath, varlockSource.path));
1499
+ }
1500
+ }
1501
+ },
1502
+ // hook to configure vite dev server
1503
+ async configureServer(server) {
1504
+ debug("vite plugin - configureServer fn called");
1505
+ if (!configIsValid) {
1506
+ server.middlewares.use((req, res, next) => {
1507
+ server.hot.send({
1508
+ type: "error",
1509
+ err: {
1510
+ plugin: "varlock",
1511
+ message: "Your config is currently invalid - check your terminal for more details",
1512
+ stack: ""
1513
+ }
1514
+ });
1515
+ return next();
1516
+ });
1517
+ }
1518
+ },
1519
+ transform(code, id, options) {
1520
+ let magicString = replacerFn(this, code, id);
1521
+ const fileExt = id.split("?")[0].split("#")[0].split(".").pop() || "";
1522
+ let isEntry = false;
1523
+ if (SUPPORTED_FILES.includes(fileExt)) {
1524
+ const moduleIds = Array.from(this.getModuleIds());
1525
+ if (moduleIds[0] === id) isEntry = true;
1526
+ }
1527
+ if (vitePluginOptions?.ssrEntryModuleIds?.includes(id)) isEntry = true;
1528
+ if (isEntry) {
1529
+ debug(`detected entry: ${id}`);
1530
+ let isDevEnv = false;
1531
+ if (this.environment) {
1532
+ isDevEnv = this.environment.mode === "dev";
1533
+ } else {
1534
+ isDevEnv = isDevCommand;
1535
+ }
1536
+ const injectCode = [
1537
+ "// INJECTED BY @varlock/vite-integration ----",
1538
+ "globalThis.__varlockThrowOnMissingKeys = true;"
1539
+ ];
1540
+ if (options?.ssr) {
1541
+ const ssrInjectMode = vitePluginOptions?.ssrInjectMode ?? "init-only";
1542
+ debug("ssrInjectMode =", ssrInjectMode, "isDev =", isDevEnv);
1543
+ if (ssrInjectMode === "auto-load") {
1544
+ injectCode.push(
1545
+ "import 'varlock/auto-load';"
1546
+ );
1547
+ } else {
1548
+ if (ssrInjectMode === "resolved-env") {
1549
+ injectCode.push(`globalThis.__varlockLoadedEnv = ${JSON.stringify(varlockLoadedEnv)};`);
1550
+ }
1551
+ if (vitePluginOptions?.ssrEntryCode?.length) {
1552
+ injectCode.push(...vitePluginOptions.ssrEntryCode);
1553
+ }
1554
+ injectCode.push(
1555
+ "import { initVarlockEnv } from 'varlock/env';",
1556
+ "import { patchGlobalConsole } from 'varlock/patch-console';",
1557
+ "import { patchGlobalResponse } from 'varlock/patch-response';"
1558
+ );
1559
+ injectCode.push(
1560
+ "initVarlockEnv();",
1561
+ "patchGlobalConsole();"
1562
+ );
1563
+ injectCode.push("patchGlobalResponse();");
1564
+ }
1565
+ } else {
1566
+ if (isDevEnv) {
1567
+ injectCode.push(
1568
+ "// NOTE - __varlockValidKeys is only injected during development",
1569
+ `globalThis.__varlockValidKeys = ${JSON.stringify(Object.keys(varlockLoadedEnv?.config || {}))};`
1570
+ );
1571
+ }
1572
+ }
1573
+ injectCode.push("// -------- ");
1574
+ magicString ||= new MagicString(code);
1575
+ magicString.prepend(`${injectCode.join("\n")}
1576
+ `);
1577
+ }
1578
+ if (!magicString) return null;
1579
+ return {
1580
+ code: magicString.toString(),
1581
+ map: magicString.generateMap({ source: code, includeContent: true, hires: true })
1582
+ };
1583
+ },
1584
+ renderChunk(code, chunk) {
1585
+ const magicString = replacerFn(this, code, chunk.fileName);
1586
+ if (!magicString) return null;
1587
+ return {
1588
+ code: magicString.toString(),
1589
+ map: magicString.generateMap({ source: code, includeContent: true, hires: true })
1590
+ };
1591
+ },
1592
+ // this enables replacing %ENV.xxx% constants in html entry-point files
1593
+ // see https://vite.dev/guide/env-and-mode.html#html-constant-replacement
1594
+ transformIndexHtml(html) {
1595
+ if (!configIsValid) {
1596
+ return `
1597
+ <html>
1598
+ <head>
1599
+ <script type="module" src="/@vite/client"></script>
1600
+ <title>Invalid config</title>
1601
+ </head>
1602
+ <body>
1603
+ <h2>Your varlock config is currently invalid!</h2>
1604
+ <p>Check your terminal for more details</p>
1605
+ </body>
1606
+ </html>
1607
+ `;
1608
+ }
1609
+ const replacedHtml = html.replace(
1610
+ // look for "%ENV.xxx%"
1611
+ /%ENV\.([a-zA-Z_][a-zA-Z0-9._]*)%/g,
1612
+ (_fullMatch, itemKey) => {
1613
+ if (!varlockLoadedEnv.config[itemKey]) {
1614
+ throw new Error(`Config item \`${itemKey}\` does not exist`);
1615
+ } else if (varlockLoadedEnv.config[itemKey].isSensitive) {
1616
+ throw new Error(`Config item \`${itemKey}\` is sensitive and cannot be used in html replacements`);
1617
+ } else {
1618
+ return varlockLoadedEnv.config[itemKey].value ?? "";
1619
+ }
1620
+ }
1621
+ );
1622
+ return replacedHtml;
1623
+ }
1624
+ };
1625
+ }
1626
+
1627
+ // src/shared-ssr-entry-code.ts
1628
+ var CLOUDFLARE_SSR_ENTRY_CODE = `
1629
+ if (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') {
1630
+ const { env: __cfEnv } = await import('cloudflare:workers');
1631
+ let __varlockEnvJson;
1632
+ if (__cfEnv?.__VARLOCK_ENV) {
1633
+ __varlockEnvJson = __cfEnv.__VARLOCK_ENV;
1634
+ } else if (__cfEnv?.__VARLOCK_ENV_CHUNKS) {
1635
+ const n = parseInt(__cfEnv.__VARLOCK_ENV_CHUNKS, 10);
1636
+ if (!Number.isFinite(n) || n < 1 || n > 1000) {
1637
+ throw new Error("[varlock] invalid __VARLOCK_ENV_CHUNKS: " + __cfEnv.__VARLOCK_ENV_CHUNKS);
1638
+ }
1639
+ const parts = [];
1640
+ for (let i = 0; i < n; i++) {
1641
+ const chunk = __cfEnv["__VARLOCK_ENV_" + i];
1642
+ if (chunk == null) throw new Error("[varlock] missing chunk __VARLOCK_ENV_" + i);
1643
+ parts.push(chunk);
1644
+ }
1645
+ __varlockEnvJson = parts.join("");
1646
+ }
1647
+ if (__varlockEnvJson) {
1648
+ try {
1649
+ globalThis.__varlockLoadedEnv = JSON.parse(__varlockEnvJson);
1650
+ } catch (e) {
1651
+ throw new Error("[varlock] failed to parse __VARLOCK_ENV: " + e.message);
1652
+ }
1653
+ }
1654
+ }
1655
+ `;
1656
+
1657
+ // src/index.ts
1658
+ var CLOUDFLARE_PLUGIN_NAME = "vite-plugin-cloudflare";
1659
+ function varlockCloudflareVitePlugin(cloudflareOptions) {
1660
+ const conflictGuard = {
1661
+ name: "varlock-cloudflare-conflict-guard",
1662
+ configResolved(config) {
1663
+ const cfPluginCount = config.plugins.filter(
1664
+ (p) => typeof p?.name === "string" && p.name === CLOUDFLARE_PLUGIN_NAME
1665
+ ).length;
1666
+ if (cfPluginCount > 1) {
1667
+ throw new Error(
1668
+ "[varlock] `@cloudflare/vite-plugin` is already present in your Vite plugins. Remove it \u2014 `varlockCloudflareVitePlugin` injects (and configures) it for you."
1669
+ );
1670
+ }
1671
+ }
1672
+ };
1673
+ let isDevMode = false;
1674
+ const modeDetector = {
1675
+ name: "varlock-cloudflare-mode",
1676
+ enforce: "pre",
1677
+ config(_config, env) {
1678
+ isDevMode = env.command === "serve";
1679
+ }
1680
+ };
1681
+ const userConfig = cloudflareOptions?.config;
1682
+ const mergedConfig = (cfg) => {
1683
+ let userResult;
1684
+ if (typeof userConfig === "function") {
1685
+ userResult = userConfig(cfg) || void 0;
1686
+ } else if (userConfig) {
1687
+ userResult = userConfig;
1688
+ }
1689
+ if (!isDevMode) return userResult;
1690
+ const serializedGraph = execSyncVarlock("load --format json-full --compact");
1691
+ let graph;
1692
+ try {
1693
+ graph = JSON.parse(serializedGraph);
1694
+ } catch (err) {
1695
+ throw new Error(`[varlock] failed to parse config graph: ${err.message}`);
1696
+ }
1697
+ const vars = {};
1698
+ for (const key in graph.config) {
1699
+ const { value } = graph.config[key];
1700
+ if (value === void 0) continue;
1701
+ vars[key] = typeof value === "string" ? value : JSON.stringify(value);
1702
+ }
1703
+ return {
1704
+ ...userResult,
1705
+ vars: {
1706
+ ...cfg.vars,
1707
+ ...userResult?.vars,
1708
+ ...vars,
1709
+ __VARLOCK_ENV: serializedGraph
1710
+ }
1711
+ };
1712
+ };
1713
+ const varlockPlugin = varlockVitePlugin({
1714
+ ssrEntryModuleIds: ["\0virtual:cloudflare/worker-entry"],
1715
+ ssrEntryCode: [CLOUDFLARE_SSR_ENTRY_CODE]
1716
+ });
1717
+ const cloudflarePlugin = cloudflare({
1718
+ ...cloudflareOptions,
1719
+ config: mergedConfig
1720
+ });
1721
+ return [
1722
+ conflictGuard,
1723
+ modeDetector,
1724
+ varlockPlugin,
1725
+ // cloudflare() may return a single plugin or an array
1726
+ ...Array.isArray(cloudflarePlugin) ? cloudflarePlugin : [cloudflarePlugin]
1727
+ ];
1728
+ }
1729
+ //! Note on vite's built-in html constant replacement
1730
+
1731
+ export { varlockCloudflareVitePlugin };
1732
+ //# sourceMappingURL=index.js.map
1733
+ //# sourceMappingURL=index.js.map