magic-string.umd.js 39 KB

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