magic-string.umd.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.MagicString = factory());
  5. })(this, (function () { 'use strict';
  6. class BitSet {
  7. constructor(arg) {
  8. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  9. }
  10. add(n) {
  11. this.bits[n >> 5] |= 1 << (n & 31);
  12. }
  13. has(n) {
  14. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  15. }
  16. }
  17. class Chunk {
  18. constructor(start, end, content) {
  19. this.start = start;
  20. this.end = end;
  21. this.original = content;
  22. this.intro = '';
  23. this.outro = '';
  24. this.content = content;
  25. this.storeName = false;
  26. this.edited = false;
  27. {
  28. this.previous = null;
  29. this.next = null;
  30. }
  31. }
  32. appendLeft(content) {
  33. this.outro += content;
  34. }
  35. appendRight(content) {
  36. this.intro = this.intro + content;
  37. }
  38. clone() {
  39. const chunk = new Chunk(this.start, this.end, this.original);
  40. chunk.intro = this.intro;
  41. chunk.outro = this.outro;
  42. chunk.content = this.content;
  43. chunk.storeName = this.storeName;
  44. chunk.edited = this.edited;
  45. return chunk;
  46. }
  47. contains(index) {
  48. return this.start < index && index < this.end;
  49. }
  50. eachNext(fn) {
  51. let chunk = this;
  52. while (chunk) {
  53. fn(chunk);
  54. chunk = chunk.next;
  55. }
  56. }
  57. eachPrevious(fn) {
  58. let chunk = this;
  59. while (chunk) {
  60. fn(chunk);
  61. chunk = chunk.previous;
  62. }
  63. }
  64. edit(content, storeName, contentOnly) {
  65. this.content = content;
  66. if (!contentOnly) {
  67. this.intro = '';
  68. this.outro = '';
  69. }
  70. this.storeName = storeName;
  71. this.edited = true;
  72. return this;
  73. }
  74. prependLeft(content) {
  75. this.outro = content + this.outro;
  76. }
  77. prependRight(content) {
  78. this.intro = content + this.intro;
  79. }
  80. reset() {
  81. this.intro = '';
  82. this.outro = '';
  83. if (this.edited) {
  84. this.content = this.original;
  85. this.storeName = false;
  86. this.edited = false;
  87. }
  88. }
  89. split(index) {
  90. const sliceIndex = index - this.start;
  91. const originalBefore = this.original.slice(0, sliceIndex);
  92. const originalAfter = this.original.slice(sliceIndex);
  93. this.original = originalBefore;
  94. const newChunk = new Chunk(index, this.end, originalAfter);
  95. newChunk.outro = this.outro;
  96. this.outro = '';
  97. this.end = index;
  98. if (this.edited) {
  99. // after split we should save the edit content record into the correct chunk
  100. // to make sure sourcemap correct
  101. // For example:
  102. // ' test'.trim()
  103. // split -> ' ' + 'test'
  104. // ✔️ edit -> '' + 'test'
  105. // ✖️ edit -> 'test' + ''
  106. // TODO is this block necessary?...
  107. newChunk.edit('', false);
  108. this.content = '';
  109. } else {
  110. this.content = originalBefore;
  111. }
  112. newChunk.next = this.next;
  113. if (newChunk.next) newChunk.next.previous = newChunk;
  114. newChunk.previous = this;
  115. this.next = newChunk;
  116. return newChunk;
  117. }
  118. toString() {
  119. return this.intro + this.content + this.outro;
  120. }
  121. trimEnd(rx) {
  122. this.outro = this.outro.replace(rx, '');
  123. if (this.outro.length) return true;
  124. const trimmed = this.content.replace(rx, '');
  125. if (trimmed.length) {
  126. if (trimmed !== this.content) {
  127. this.split(this.start + trimmed.length).edit('', undefined, true);
  128. if (this.edited) {
  129. // save the change, if it has been edited
  130. this.edit(trimmed, this.storeName, true);
  131. }
  132. }
  133. return true;
  134. } else {
  135. this.edit('', undefined, true);
  136. this.intro = this.intro.replace(rx, '');
  137. if (this.intro.length) return true;
  138. }
  139. }
  140. trimStart(rx) {
  141. this.intro = this.intro.replace(rx, '');
  142. if (this.intro.length) return true;
  143. const trimmed = this.content.replace(rx, '');
  144. if (trimmed.length) {
  145. if (trimmed !== this.content) {
  146. const newChunk = this.split(this.end - trimmed.length);
  147. if (this.edited) {
  148. // save the change, if it has been edited
  149. newChunk.edit(trimmed, this.storeName, true);
  150. }
  151. this.edit('', undefined, true);
  152. }
  153. return true;
  154. } else {
  155. this.edit('', undefined, true);
  156. this.outro = this.outro.replace(rx, '');
  157. if (this.outro.length) return true;
  158. }
  159. }
  160. }
  161. const comma = ','.charCodeAt(0);
  162. const semicolon = ';'.charCodeAt(0);
  163. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  164. const intToChar = new Uint8Array(64); // 64 possible chars.
  165. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  166. for (let i = 0; i < chars.length; i++) {
  167. const c = chars.charCodeAt(i);
  168. intToChar[i] = c;
  169. charToInt[c] = i;
  170. }
  171. // Provide a fallback for older environments.
  172. const td = typeof TextDecoder !== 'undefined'
  173. ? /* #__PURE__ */ new TextDecoder()
  174. : typeof Buffer !== 'undefined'
  175. ? {
  176. decode(buf) {
  177. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  178. return out.toString();
  179. },
  180. }
  181. : {
  182. decode(buf) {
  183. let out = '';
  184. for (let i = 0; i < buf.length; i++) {
  185. out += String.fromCharCode(buf[i]);
  186. }
  187. return out;
  188. },
  189. };
  190. function encode(decoded) {
  191. const state = new Int32Array(5);
  192. const bufLength = 1024 * 16;
  193. const subLength = bufLength - 36;
  194. const buf = new Uint8Array(bufLength);
  195. const sub = buf.subarray(0, subLength);
  196. let pos = 0;
  197. let out = '';
  198. for (let i = 0; i < decoded.length; i++) {
  199. const line = decoded[i];
  200. if (i > 0) {
  201. if (pos === bufLength) {
  202. out += td.decode(buf);
  203. pos = 0;
  204. }
  205. buf[pos++] = semicolon;
  206. }
  207. if (line.length === 0)
  208. continue;
  209. state[0] = 0;
  210. for (let j = 0; j < line.length; j++) {
  211. const segment = line[j];
  212. // We can push up to 5 ints, each int can take at most 7 chars, and we
  213. // may push a comma.
  214. if (pos > subLength) {
  215. out += td.decode(sub);
  216. buf.copyWithin(0, subLength, pos);
  217. pos -= subLength;
  218. }
  219. if (j > 0)
  220. buf[pos++] = comma;
  221. pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
  222. if (segment.length === 1)
  223. continue;
  224. pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
  225. pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
  226. pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
  227. if (segment.length === 4)
  228. continue;
  229. pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
  230. }
  231. }
  232. return out + td.decode(buf.subarray(0, pos));
  233. }
  234. function encodeInteger(buf, pos, state, segment, j) {
  235. const next = segment[j];
  236. let num = next - state[j];
  237. state[j] = next;
  238. num = num < 0 ? (-num << 1) | 1 : num << 1;
  239. do {
  240. let clamped = num & 0b011111;
  241. num >>>= 5;
  242. if (num > 0)
  243. clamped |= 0b100000;
  244. buf[pos++] = intToChar[clamped];
  245. } while (num > 0);
  246. return pos;
  247. }
  248. function getBtoa() {
  249. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  250. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  251. } else if (typeof Buffer === 'function') {
  252. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  253. } else {
  254. return () => {
  255. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  256. };
  257. }
  258. }
  259. const btoa = /*#__PURE__*/ getBtoa();
  260. class SourceMap {
  261. constructor(properties) {
  262. this.version = 3;
  263. this.file = properties.file;
  264. this.sources = properties.sources;
  265. this.sourcesContent = properties.sourcesContent;
  266. this.names = properties.names;
  267. this.mappings = encode(properties.mappings);
  268. if (typeof properties.x_google_ignoreList !== 'undefined') {
  269. this.x_google_ignoreList = properties.x_google_ignoreList;
  270. }
  271. }
  272. toString() {
  273. return JSON.stringify(this);
  274. }
  275. toUrl() {
  276. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  277. }
  278. }
  279. function guessIndent(code) {
  280. const lines = code.split('\n');
  281. const tabbed = lines.filter((line) => /^\t+/.test(line));
  282. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  283. if (tabbed.length === 0 && spaced.length === 0) {
  284. return null;
  285. }
  286. // More lines tabbed than spaced? Assume tabs, and
  287. // default to tabs in the case of a tie (or nothing
  288. // to go on)
  289. if (tabbed.length >= spaced.length) {
  290. return '\t';
  291. }
  292. // Otherwise, we need to guess the multiple
  293. const min = spaced.reduce((previous, current) => {
  294. const numSpaces = /^ +/.exec(current)[0].length;
  295. return Math.min(numSpaces, previous);
  296. }, Infinity);
  297. return new Array(min + 1).join(' ');
  298. }
  299. function getRelativePath(from, to) {
  300. const fromParts = from.split(/[/\\]/);
  301. const toParts = to.split(/[/\\]/);
  302. fromParts.pop(); // get dirname
  303. while (fromParts[0] === toParts[0]) {
  304. fromParts.shift();
  305. toParts.shift();
  306. }
  307. if (fromParts.length) {
  308. let i = fromParts.length;
  309. while (i--) fromParts[i] = '..';
  310. }
  311. return fromParts.concat(toParts).join('/');
  312. }
  313. const toString = Object.prototype.toString;
  314. function isObject(thing) {
  315. return toString.call(thing) === '[object Object]';
  316. }
  317. function getLocator(source) {
  318. const originalLines = source.split('\n');
  319. const lineOffsets = [];
  320. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  321. lineOffsets.push(pos);
  322. pos += originalLines[i].length + 1;
  323. }
  324. return function locate(index) {
  325. let i = 0;
  326. let j = lineOffsets.length;
  327. while (i < j) {
  328. const m = (i + j) >> 1;
  329. if (index < lineOffsets[m]) {
  330. j = m;
  331. } else {
  332. i = m + 1;
  333. }
  334. }
  335. const line = i - 1;
  336. const column = index - lineOffsets[line];
  337. return { line, column };
  338. };
  339. }
  340. const wordRegex = /\w/;
  341. class Mappings {
  342. constructor(hires) {
  343. this.hires = hires;
  344. this.generatedCodeLine = 0;
  345. this.generatedCodeColumn = 0;
  346. this.raw = [];
  347. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  348. this.pending = null;
  349. }
  350. addEdit(sourceIndex, content, loc, nameIndex) {
  351. if (content.length) {
  352. const contentLengthMinusOne = content.length - 1;
  353. let contentLineEnd = content.indexOf('\n', 0);
  354. let previousContentLineEnd = -1;
  355. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  356. // else code afterwards would fill one line too many
  357. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  358. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  359. if (nameIndex >= 0) {
  360. segment.push(nameIndex);
  361. }
  362. this.rawSegments.push(segment);
  363. this.generatedCodeLine += 1;
  364. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  365. this.generatedCodeColumn = 0;
  366. previousContentLineEnd = contentLineEnd;
  367. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  368. }
  369. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  370. if (nameIndex >= 0) {
  371. segment.push(nameIndex);
  372. }
  373. this.rawSegments.push(segment);
  374. this.advance(content.slice(previousContentLineEnd + 1));
  375. } else if (this.pending) {
  376. this.rawSegments.push(this.pending);
  377. this.advance(content);
  378. }
  379. this.pending = null;
  380. }
  381. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  382. let originalCharIndex = chunk.start;
  383. let first = true;
  384. // when iterating each char, check if it's in a word boundary
  385. let charInHiresBoundary = false;
  386. while (originalCharIndex < chunk.end) {
  387. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  388. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  389. if (this.hires === 'boundary') {
  390. // in hires "boundary", group segments per word boundary than per char
  391. if (wordRegex.test(original[originalCharIndex])) {
  392. // for first char in the boundary found, start the boundary by pushing a segment
  393. if (!charInHiresBoundary) {
  394. this.rawSegments.push(segment);
  395. charInHiresBoundary = true;
  396. }
  397. } else {
  398. // for non-word char, end the boundary by pushing a segment
  399. this.rawSegments.push(segment);
  400. charInHiresBoundary = false;
  401. }
  402. } else {
  403. this.rawSegments.push(segment);
  404. }
  405. }
  406. if (original[originalCharIndex] === '\n') {
  407. loc.line += 1;
  408. loc.column = 0;
  409. this.generatedCodeLine += 1;
  410. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  411. this.generatedCodeColumn = 0;
  412. first = true;
  413. } else {
  414. loc.column += 1;
  415. this.generatedCodeColumn += 1;
  416. first = false;
  417. }
  418. originalCharIndex += 1;
  419. }
  420. this.pending = null;
  421. }
  422. advance(str) {
  423. if (!str) return;
  424. const lines = str.split('\n');
  425. if (lines.length > 1) {
  426. for (let i = 0; i < lines.length - 1; i++) {
  427. this.generatedCodeLine++;
  428. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  429. }
  430. this.generatedCodeColumn = 0;
  431. }
  432. this.generatedCodeColumn += lines[lines.length - 1].length;
  433. }
  434. }
  435. const n = '\n';
  436. const warned = {
  437. insertLeft: false,
  438. insertRight: false,
  439. storeName: false,
  440. };
  441. class MagicString {
  442. constructor(string, options = {}) {
  443. const chunk = new Chunk(0, string.length, string);
  444. Object.defineProperties(this, {
  445. original: { writable: true, value: string },
  446. outro: { writable: true, value: '' },
  447. intro: { writable: true, value: '' },
  448. firstChunk: { writable: true, value: chunk },
  449. lastChunk: { writable: true, value: chunk },
  450. lastSearchedChunk: { writable: true, value: chunk },
  451. byStart: { writable: true, value: {} },
  452. byEnd: { writable: true, value: {} },
  453. filename: { writable: true, value: options.filename },
  454. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  455. sourcemapLocations: { writable: true, value: new BitSet() },
  456. storedNames: { writable: true, value: {} },
  457. indentStr: { writable: true, value: undefined },
  458. ignoreList: { writable: true, value: options.ignoreList },
  459. });
  460. this.byStart[0] = chunk;
  461. this.byEnd[string.length] = chunk;
  462. }
  463. addSourcemapLocation(char) {
  464. this.sourcemapLocations.add(char);
  465. }
  466. append(content) {
  467. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  468. this.outro += content;
  469. return this;
  470. }
  471. appendLeft(index, content) {
  472. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  473. this._split(index);
  474. const chunk = this.byEnd[index];
  475. if (chunk) {
  476. chunk.appendLeft(content);
  477. } else {
  478. this.intro += content;
  479. }
  480. return this;
  481. }
  482. appendRight(index, content) {
  483. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  484. this._split(index);
  485. const chunk = this.byStart[index];
  486. if (chunk) {
  487. chunk.appendRight(content);
  488. } else {
  489. this.outro += content;
  490. }
  491. return this;
  492. }
  493. clone() {
  494. const cloned = new MagicString(this.original, { filename: this.filename });
  495. let originalChunk = this.firstChunk;
  496. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  497. while (originalChunk) {
  498. cloned.byStart[clonedChunk.start] = clonedChunk;
  499. cloned.byEnd[clonedChunk.end] = clonedChunk;
  500. const nextOriginalChunk = originalChunk.next;
  501. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  502. if (nextClonedChunk) {
  503. clonedChunk.next = nextClonedChunk;
  504. nextClonedChunk.previous = clonedChunk;
  505. clonedChunk = nextClonedChunk;
  506. }
  507. originalChunk = nextOriginalChunk;
  508. }
  509. cloned.lastChunk = clonedChunk;
  510. if (this.indentExclusionRanges) {
  511. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  512. }
  513. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  514. cloned.intro = this.intro;
  515. cloned.outro = this.outro;
  516. return cloned;
  517. }
  518. generateDecodedMap(options) {
  519. options = options || {};
  520. const sourceIndex = 0;
  521. const names = Object.keys(this.storedNames);
  522. const mappings = new Mappings(options.hires);
  523. const locate = getLocator(this.original);
  524. if (this.intro) {
  525. mappings.advance(this.intro);
  526. }
  527. this.firstChunk.eachNext((chunk) => {
  528. const loc = locate(chunk.start);
  529. if (chunk.intro.length) mappings.advance(chunk.intro);
  530. if (chunk.edited) {
  531. mappings.addEdit(
  532. sourceIndex,
  533. chunk.content,
  534. loc,
  535. chunk.storeName ? names.indexOf(chunk.original) : -1,
  536. );
  537. } else {
  538. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  539. }
  540. if (chunk.outro.length) mappings.advance(chunk.outro);
  541. });
  542. return {
  543. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  544. sources: [
  545. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  546. ],
  547. sourcesContent: options.includeContent ? [this.original] : undefined,
  548. names,
  549. mappings: mappings.raw,
  550. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  551. };
  552. }
  553. generateMap(options) {
  554. return new SourceMap(this.generateDecodedMap(options));
  555. }
  556. _ensureindentStr() {
  557. if (this.indentStr === undefined) {
  558. this.indentStr = guessIndent(this.original);
  559. }
  560. }
  561. _getRawIndentString() {
  562. this._ensureindentStr();
  563. return this.indentStr;
  564. }
  565. getIndentString() {
  566. this._ensureindentStr();
  567. return this.indentStr === null ? '\t' : this.indentStr;
  568. }
  569. indent(indentStr, options) {
  570. const pattern = /^[^\r\n]/gm;
  571. if (isObject(indentStr)) {
  572. options = indentStr;
  573. indentStr = undefined;
  574. }
  575. if (indentStr === undefined) {
  576. this._ensureindentStr();
  577. indentStr = this.indentStr || '\t';
  578. }
  579. if (indentStr === '') return this; // noop
  580. options = options || {};
  581. // Process exclusion ranges
  582. const isExcluded = {};
  583. if (options.exclude) {
  584. const exclusions =
  585. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  586. exclusions.forEach((exclusion) => {
  587. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  588. isExcluded[i] = true;
  589. }
  590. });
  591. }
  592. let shouldIndentNextCharacter = options.indentStart !== false;
  593. const replacer = (match) => {
  594. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  595. shouldIndentNextCharacter = true;
  596. return match;
  597. };
  598. this.intro = this.intro.replace(pattern, replacer);
  599. let charIndex = 0;
  600. let chunk = this.firstChunk;
  601. while (chunk) {
  602. const end = chunk.end;
  603. if (chunk.edited) {
  604. if (!isExcluded[charIndex]) {
  605. chunk.content = chunk.content.replace(pattern, replacer);
  606. if (chunk.content.length) {
  607. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  608. }
  609. }
  610. } else {
  611. charIndex = chunk.start;
  612. while (charIndex < end) {
  613. if (!isExcluded[charIndex]) {
  614. const char = this.original[charIndex];
  615. if (char === '\n') {
  616. shouldIndentNextCharacter = true;
  617. } else if (char !== '\r' && shouldIndentNextCharacter) {
  618. shouldIndentNextCharacter = false;
  619. if (charIndex === chunk.start) {
  620. chunk.prependRight(indentStr);
  621. } else {
  622. this._splitChunk(chunk, charIndex);
  623. chunk = chunk.next;
  624. chunk.prependRight(indentStr);
  625. }
  626. }
  627. }
  628. charIndex += 1;
  629. }
  630. }
  631. charIndex = chunk.end;
  632. chunk = chunk.next;
  633. }
  634. this.outro = this.outro.replace(pattern, replacer);
  635. return this;
  636. }
  637. insert() {
  638. throw new Error(
  639. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  640. );
  641. }
  642. insertLeft(index, content) {
  643. if (!warned.insertLeft) {
  644. console.warn(
  645. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  646. ); // eslint-disable-line no-console
  647. warned.insertLeft = true;
  648. }
  649. return this.appendLeft(index, content);
  650. }
  651. insertRight(index, content) {
  652. if (!warned.insertRight) {
  653. console.warn(
  654. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  655. ); // eslint-disable-line no-console
  656. warned.insertRight = true;
  657. }
  658. return this.prependRight(index, content);
  659. }
  660. move(start, end, index) {
  661. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  662. this._split(start);
  663. this._split(end);
  664. this._split(index);
  665. const first = this.byStart[start];
  666. const last = this.byEnd[end];
  667. const oldLeft = first.previous;
  668. const oldRight = last.next;
  669. const newRight = this.byStart[index];
  670. if (!newRight && last === this.lastChunk) return this;
  671. const newLeft = newRight ? newRight.previous : this.lastChunk;
  672. if (oldLeft) oldLeft.next = oldRight;
  673. if (oldRight) oldRight.previous = oldLeft;
  674. if (newLeft) newLeft.next = first;
  675. if (newRight) newRight.previous = last;
  676. if (!first.previous) this.firstChunk = last.next;
  677. if (!last.next) {
  678. this.lastChunk = first.previous;
  679. this.lastChunk.next = null;
  680. }
  681. first.previous = newLeft;
  682. last.next = newRight || null;
  683. if (!newLeft) this.firstChunk = first;
  684. if (!newRight) this.lastChunk = last;
  685. return this;
  686. }
  687. overwrite(start, end, content, options) {
  688. options = options || {};
  689. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  690. }
  691. update(start, end, content, options) {
  692. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  693. while (start < 0) start += this.original.length;
  694. while (end < 0) end += this.original.length;
  695. if (end > this.original.length) throw new Error('end is out of bounds');
  696. if (start === end)
  697. throw new Error(
  698. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  699. );
  700. this._split(start);
  701. this._split(end);
  702. if (options === true) {
  703. if (!warned.storeName) {
  704. console.warn(
  705. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  706. ); // eslint-disable-line no-console
  707. warned.storeName = true;
  708. }
  709. options = { storeName: true };
  710. }
  711. const storeName = options !== undefined ? options.storeName : false;
  712. const overwrite = options !== undefined ? options.overwrite : false;
  713. if (storeName) {
  714. const original = this.original.slice(start, end);
  715. Object.defineProperty(this.storedNames, original, {
  716. writable: true,
  717. value: true,
  718. enumerable: true,
  719. });
  720. }
  721. const first = this.byStart[start];
  722. const last = this.byEnd[end];
  723. if (first) {
  724. let chunk = first;
  725. while (chunk !== last) {
  726. if (chunk.next !== this.byStart[chunk.end]) {
  727. throw new Error('Cannot overwrite across a split point');
  728. }
  729. chunk = chunk.next;
  730. chunk.edit('', false);
  731. }
  732. first.edit(content, storeName, !overwrite);
  733. } else {
  734. // must be inserting at the end
  735. const newChunk = new Chunk(start, end, '').edit(content, storeName);
  736. // TODO last chunk in the array may not be the last chunk, if it's moved...
  737. last.next = newChunk;
  738. newChunk.previous = last;
  739. }
  740. return this;
  741. }
  742. prepend(content) {
  743. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  744. this.intro = content + this.intro;
  745. return this;
  746. }
  747. prependLeft(index, content) {
  748. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  749. this._split(index);
  750. const chunk = this.byEnd[index];
  751. if (chunk) {
  752. chunk.prependLeft(content);
  753. } else {
  754. this.intro = content + this.intro;
  755. }
  756. return this;
  757. }
  758. prependRight(index, content) {
  759. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  760. this._split(index);
  761. const chunk = this.byStart[index];
  762. if (chunk) {
  763. chunk.prependRight(content);
  764. } else {
  765. this.outro = content + this.outro;
  766. }
  767. return this;
  768. }
  769. remove(start, end) {
  770. while (start < 0) start += this.original.length;
  771. while (end < 0) end += this.original.length;
  772. if (start === end) return this;
  773. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  774. if (start > end) throw new Error('end must be greater than start');
  775. this._split(start);
  776. this._split(end);
  777. let chunk = this.byStart[start];
  778. while (chunk) {
  779. chunk.intro = '';
  780. chunk.outro = '';
  781. chunk.edit('');
  782. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  783. }
  784. return this;
  785. }
  786. reset(start, end) {
  787. while (start < 0) start += this.original.length;
  788. while (end < 0) end += this.original.length;
  789. if (start === end) return this;
  790. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  791. if (start > end) throw new Error('end must be greater than start');
  792. this._split(start);
  793. this._split(end);
  794. let chunk = this.byStart[start];
  795. while (chunk) {
  796. chunk.reset();
  797. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  798. }
  799. return this;
  800. }
  801. lastChar() {
  802. if (this.outro.length) return this.outro[this.outro.length - 1];
  803. let chunk = this.lastChunk;
  804. do {
  805. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  806. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  807. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  808. } while ((chunk = chunk.previous));
  809. if (this.intro.length) return this.intro[this.intro.length - 1];
  810. return '';
  811. }
  812. lastLine() {
  813. let lineIndex = this.outro.lastIndexOf(n);
  814. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  815. let lineStr = this.outro;
  816. let chunk = this.lastChunk;
  817. do {
  818. if (chunk.outro.length > 0) {
  819. lineIndex = chunk.outro.lastIndexOf(n);
  820. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  821. lineStr = chunk.outro + lineStr;
  822. }
  823. if (chunk.content.length > 0) {
  824. lineIndex = chunk.content.lastIndexOf(n);
  825. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  826. lineStr = chunk.content + lineStr;
  827. }
  828. if (chunk.intro.length > 0) {
  829. lineIndex = chunk.intro.lastIndexOf(n);
  830. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  831. lineStr = chunk.intro + lineStr;
  832. }
  833. } while ((chunk = chunk.previous));
  834. lineIndex = this.intro.lastIndexOf(n);
  835. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  836. return this.intro + lineStr;
  837. }
  838. slice(start = 0, end = this.original.length) {
  839. while (start < 0) start += this.original.length;
  840. while (end < 0) end += this.original.length;
  841. let result = '';
  842. // find start chunk
  843. let chunk = this.firstChunk;
  844. while (chunk && (chunk.start > start || chunk.end <= start)) {
  845. // found end chunk before start
  846. if (chunk.start < end && chunk.end >= end) {
  847. return result;
  848. }
  849. chunk = chunk.next;
  850. }
  851. if (chunk && chunk.edited && chunk.start !== start)
  852. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  853. const startChunk = chunk;
  854. while (chunk) {
  855. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  856. result += chunk.intro;
  857. }
  858. const containsEnd = chunk.start < end && chunk.end >= end;
  859. if (containsEnd && chunk.edited && chunk.end !== end)
  860. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  861. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  862. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  863. result += chunk.content.slice(sliceStart, sliceEnd);
  864. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  865. result += chunk.outro;
  866. }
  867. if (containsEnd) {
  868. break;
  869. }
  870. chunk = chunk.next;
  871. }
  872. return result;
  873. }
  874. // TODO deprecate this? not really very useful
  875. snip(start, end) {
  876. const clone = this.clone();
  877. clone.remove(0, start);
  878. clone.remove(end, clone.original.length);
  879. return clone;
  880. }
  881. _split(index) {
  882. if (this.byStart[index] || this.byEnd[index]) return;
  883. let chunk = this.lastSearchedChunk;
  884. const searchForward = index > chunk.end;
  885. while (chunk) {
  886. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  887. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  888. }
  889. }
  890. _splitChunk(chunk, index) {
  891. if (chunk.edited && chunk.content.length) {
  892. // zero-length edited chunks are a special case (overlapping replacements)
  893. const loc = getLocator(this.original)(index);
  894. throw new Error(
  895. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  896. );
  897. }
  898. const newChunk = chunk.split(index);
  899. this.byEnd[index] = chunk;
  900. this.byStart[index] = newChunk;
  901. this.byEnd[newChunk.end] = newChunk;
  902. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  903. this.lastSearchedChunk = chunk;
  904. return true;
  905. }
  906. toString() {
  907. let str = this.intro;
  908. let chunk = this.firstChunk;
  909. while (chunk) {
  910. str += chunk.toString();
  911. chunk = chunk.next;
  912. }
  913. return str + this.outro;
  914. }
  915. isEmpty() {
  916. let chunk = this.firstChunk;
  917. do {
  918. if (
  919. (chunk.intro.length && chunk.intro.trim()) ||
  920. (chunk.content.length && chunk.content.trim()) ||
  921. (chunk.outro.length && chunk.outro.trim())
  922. )
  923. return false;
  924. } while ((chunk = chunk.next));
  925. return true;
  926. }
  927. length() {
  928. let chunk = this.firstChunk;
  929. let length = 0;
  930. do {
  931. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  932. } while ((chunk = chunk.next));
  933. return length;
  934. }
  935. trimLines() {
  936. return this.trim('[\\r\\n]');
  937. }
  938. trim(charType) {
  939. return this.trimStart(charType).trimEnd(charType);
  940. }
  941. trimEndAborted(charType) {
  942. const rx = new RegExp((charType || '\\s') + '+$');
  943. this.outro = this.outro.replace(rx, '');
  944. if (this.outro.length) return true;
  945. let chunk = this.lastChunk;
  946. do {
  947. const end = chunk.end;
  948. const aborted = chunk.trimEnd(rx);
  949. // if chunk was trimmed, we have a new lastChunk
  950. if (chunk.end !== end) {
  951. if (this.lastChunk === chunk) {
  952. this.lastChunk = chunk.next;
  953. }
  954. this.byEnd[chunk.end] = chunk;
  955. this.byStart[chunk.next.start] = chunk.next;
  956. this.byEnd[chunk.next.end] = chunk.next;
  957. }
  958. if (aborted) return true;
  959. chunk = chunk.previous;
  960. } while (chunk);
  961. return false;
  962. }
  963. trimEnd(charType) {
  964. this.trimEndAborted(charType);
  965. return this;
  966. }
  967. trimStartAborted(charType) {
  968. const rx = new RegExp('^' + (charType || '\\s') + '+');
  969. this.intro = this.intro.replace(rx, '');
  970. if (this.intro.length) return true;
  971. let chunk = this.firstChunk;
  972. do {
  973. const end = chunk.end;
  974. const aborted = chunk.trimStart(rx);
  975. if (chunk.end !== end) {
  976. // special case...
  977. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  978. this.byEnd[chunk.end] = chunk;
  979. this.byStart[chunk.next.start] = chunk.next;
  980. this.byEnd[chunk.next.end] = chunk.next;
  981. }
  982. if (aborted) return true;
  983. chunk = chunk.next;
  984. } while (chunk);
  985. return false;
  986. }
  987. trimStart(charType) {
  988. this.trimStartAborted(charType);
  989. return this;
  990. }
  991. hasChanged() {
  992. return this.original !== this.toString();
  993. }
  994. _replaceRegexp(searchValue, replacement) {
  995. function getReplacement(match, str) {
  996. if (typeof replacement === 'string') {
  997. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  998. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  999. if (i === '$') return '$';
  1000. if (i === '&') return match[0];
  1001. const num = +i;
  1002. if (num < match.length) return match[+i];
  1003. return `$${i}`;
  1004. });
  1005. } else {
  1006. return replacement(...match, match.index, str, match.groups);
  1007. }
  1008. }
  1009. function matchAll(re, str) {
  1010. let match;
  1011. const matches = [];
  1012. while ((match = re.exec(str))) {
  1013. matches.push(match);
  1014. }
  1015. return matches;
  1016. }
  1017. if (searchValue.global) {
  1018. const matches = matchAll(searchValue, this.original);
  1019. matches.forEach((match) => {
  1020. if (match.index != null)
  1021. this.overwrite(
  1022. match.index,
  1023. match.index + match[0].length,
  1024. getReplacement(match, this.original),
  1025. );
  1026. });
  1027. } else {
  1028. const match = this.original.match(searchValue);
  1029. if (match && match.index != null)
  1030. this.overwrite(
  1031. match.index,
  1032. match.index + match[0].length,
  1033. getReplacement(match, this.original),
  1034. );
  1035. }
  1036. return this;
  1037. }
  1038. _replaceString(string, replacement) {
  1039. const { original } = this;
  1040. const index = original.indexOf(string);
  1041. if (index !== -1) {
  1042. this.overwrite(index, index + string.length, replacement);
  1043. }
  1044. return this;
  1045. }
  1046. replace(searchValue, replacement) {
  1047. if (typeof searchValue === 'string') {
  1048. return this._replaceString(searchValue, replacement);
  1049. }
  1050. return this._replaceRegexp(searchValue, replacement);
  1051. }
  1052. _replaceAllString(string, replacement) {
  1053. const { original } = this;
  1054. const stringLength = string.length;
  1055. for (
  1056. let index = original.indexOf(string);
  1057. index !== -1;
  1058. index = original.indexOf(string, index + stringLength)
  1059. ) {
  1060. this.overwrite(index, index + stringLength, replacement);
  1061. }
  1062. return this;
  1063. }
  1064. replaceAll(searchValue, replacement) {
  1065. if (typeof searchValue === 'string') {
  1066. return this._replaceAllString(searchValue, replacement);
  1067. }
  1068. if (!searchValue.global) {
  1069. throw new TypeError(
  1070. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  1071. );
  1072. }
  1073. return this._replaceRegexp(searchValue, replacement);
  1074. }
  1075. }
  1076. const hasOwnProp = Object.prototype.hasOwnProperty;
  1077. class Bundle {
  1078. constructor(options = {}) {
  1079. this.intro = options.intro || '';
  1080. this.separator = options.separator !== undefined ? options.separator : '\n';
  1081. this.sources = [];
  1082. this.uniqueSources = [];
  1083. this.uniqueSourceIndexByFilename = {};
  1084. }
  1085. addSource(source) {
  1086. if (source instanceof MagicString) {
  1087. return this.addSource({
  1088. content: source,
  1089. filename: source.filename,
  1090. separator: this.separator,
  1091. });
  1092. }
  1093. if (!isObject(source) || !source.content) {
  1094. throw new Error(
  1095. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  1096. );
  1097. }
  1098. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1099. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1100. });
  1101. if (source.separator === undefined) {
  1102. // TODO there's a bunch of this sort of thing, needs cleaning up
  1103. source.separator = this.separator;
  1104. }
  1105. if (source.filename) {
  1106. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1107. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1108. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1109. } else {
  1110. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1111. if (source.content.original !== uniqueSource.content) {
  1112. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1113. }
  1114. }
  1115. }
  1116. this.sources.push(source);
  1117. return this;
  1118. }
  1119. append(str, options) {
  1120. this.addSource({
  1121. content: new MagicString(str),
  1122. separator: (options && options.separator) || '',
  1123. });
  1124. return this;
  1125. }
  1126. clone() {
  1127. const bundle = new Bundle({
  1128. intro: this.intro,
  1129. separator: this.separator,
  1130. });
  1131. this.sources.forEach((source) => {
  1132. bundle.addSource({
  1133. filename: source.filename,
  1134. content: source.content.clone(),
  1135. separator: source.separator,
  1136. });
  1137. });
  1138. return bundle;
  1139. }
  1140. generateDecodedMap(options = {}) {
  1141. const names = [];
  1142. let x_google_ignoreList = undefined;
  1143. this.sources.forEach((source) => {
  1144. Object.keys(source.content.storedNames).forEach((name) => {
  1145. if (!~names.indexOf(name)) names.push(name);
  1146. });
  1147. });
  1148. const mappings = new Mappings(options.hires);
  1149. if (this.intro) {
  1150. mappings.advance(this.intro);
  1151. }
  1152. this.sources.forEach((source, i) => {
  1153. if (i > 0) {
  1154. mappings.advance(this.separator);
  1155. }
  1156. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1157. const magicString = source.content;
  1158. const locate = getLocator(magicString.original);
  1159. if (magicString.intro) {
  1160. mappings.advance(magicString.intro);
  1161. }
  1162. magicString.firstChunk.eachNext((chunk) => {
  1163. const loc = locate(chunk.start);
  1164. if (chunk.intro.length) mappings.advance(chunk.intro);
  1165. if (source.filename) {
  1166. if (chunk.edited) {
  1167. mappings.addEdit(
  1168. sourceIndex,
  1169. chunk.content,
  1170. loc,
  1171. chunk.storeName ? names.indexOf(chunk.original) : -1,
  1172. );
  1173. } else {
  1174. mappings.addUneditedChunk(
  1175. sourceIndex,
  1176. chunk,
  1177. magicString.original,
  1178. loc,
  1179. magicString.sourcemapLocations,
  1180. );
  1181. }
  1182. } else {
  1183. mappings.advance(chunk.content);
  1184. }
  1185. if (chunk.outro.length) mappings.advance(chunk.outro);
  1186. });
  1187. if (magicString.outro) {
  1188. mappings.advance(magicString.outro);
  1189. }
  1190. if (source.ignoreList && sourceIndex !== -1) {
  1191. if (x_google_ignoreList === undefined) {
  1192. x_google_ignoreList = [];
  1193. }
  1194. x_google_ignoreList.push(sourceIndex);
  1195. }
  1196. });
  1197. return {
  1198. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  1199. sources: this.uniqueSources.map((source) => {
  1200. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1201. }),
  1202. sourcesContent: this.uniqueSources.map((source) => {
  1203. return options.includeContent ? source.content : null;
  1204. }),
  1205. names,
  1206. mappings: mappings.raw,
  1207. x_google_ignoreList,
  1208. };
  1209. }
  1210. generateMap(options) {
  1211. return new SourceMap(this.generateDecodedMap(options));
  1212. }
  1213. getIndentString() {
  1214. const indentStringCounts = {};
  1215. this.sources.forEach((source) => {
  1216. const indentStr = source.content._getRawIndentString();
  1217. if (indentStr === null) return;
  1218. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1219. indentStringCounts[indentStr] += 1;
  1220. });
  1221. return (
  1222. Object.keys(indentStringCounts).sort((a, b) => {
  1223. return indentStringCounts[a] - indentStringCounts[b];
  1224. })[0] || '\t'
  1225. );
  1226. }
  1227. indent(indentStr) {
  1228. if (!arguments.length) {
  1229. indentStr = this.getIndentString();
  1230. }
  1231. if (indentStr === '') return this; // noop
  1232. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1233. this.sources.forEach((source, i) => {
  1234. const separator = source.separator !== undefined ? source.separator : this.separator;
  1235. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1236. source.content.indent(indentStr, {
  1237. exclude: source.indentExclusionRanges,
  1238. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1239. });
  1240. trailingNewline = source.content.lastChar() === '\n';
  1241. });
  1242. if (this.intro) {
  1243. this.intro =
  1244. indentStr +
  1245. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1246. return index > 0 ? indentStr + match : match;
  1247. });
  1248. }
  1249. return this;
  1250. }
  1251. prepend(str) {
  1252. this.intro = str + this.intro;
  1253. return this;
  1254. }
  1255. toString() {
  1256. const body = this.sources
  1257. .map((source, i) => {
  1258. const separator = source.separator !== undefined ? source.separator : this.separator;
  1259. const str = (i > 0 ? separator : '') + source.content.toString();
  1260. return str;
  1261. })
  1262. .join('');
  1263. return this.intro + body;
  1264. }
  1265. isEmpty() {
  1266. if (this.intro.length && this.intro.trim()) return false;
  1267. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1268. return true;
  1269. }
  1270. length() {
  1271. return this.sources.reduce(
  1272. (length, source) => length + source.content.length(),
  1273. this.intro.length,
  1274. );
  1275. }
  1276. trimLines() {
  1277. return this.trim('[\\r\\n]');
  1278. }
  1279. trim(charType) {
  1280. return this.trimStart(charType).trimEnd(charType);
  1281. }
  1282. trimStart(charType) {
  1283. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1284. this.intro = this.intro.replace(rx, '');
  1285. if (!this.intro) {
  1286. let source;
  1287. let i = 0;
  1288. do {
  1289. source = this.sources[i++];
  1290. if (!source) {
  1291. break;
  1292. }
  1293. } while (!source.content.trimStartAborted(charType));
  1294. }
  1295. return this;
  1296. }
  1297. trimEnd(charType) {
  1298. const rx = new RegExp((charType || '\\s') + '+$');
  1299. let source;
  1300. let i = this.sources.length - 1;
  1301. do {
  1302. source = this.sources[i--];
  1303. if (!source) {
  1304. this.intro = this.intro.replace(rx, '');
  1305. break;
  1306. }
  1307. } while (!source.content.trimEndAborted(charType));
  1308. return this;
  1309. }
  1310. }
  1311. MagicString.Bundle = Bundle;
  1312. MagicString.SourceMap = SourceMap;
  1313. MagicString.default = MagicString; // work around TypeScript bug https://github.com/Rich-Harris/magic-string/pull/121
  1314. return MagicString;
  1315. }));
  1316. //# sourceMappingURL=magic-string.umd.js.map