magic-string.umd.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  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. let contentLineEnd = content.indexOf('\n', 0);
  344. let previousContentLineEnd = -1;
  345. while (contentLineEnd >= 0) {
  346. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  347. if (nameIndex >= 0) {
  348. segment.push(nameIndex);
  349. }
  350. this.rawSegments.push(segment);
  351. this.generatedCodeLine += 1;
  352. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  353. this.generatedCodeColumn = 0;
  354. previousContentLineEnd = contentLineEnd;
  355. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  356. }
  357. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  358. if (nameIndex >= 0) {
  359. segment.push(nameIndex);
  360. }
  361. this.rawSegments.push(segment);
  362. this.advance(content.slice(previousContentLineEnd + 1));
  363. } else if (this.pending) {
  364. this.rawSegments.push(this.pending);
  365. this.advance(content);
  366. }
  367. this.pending = null;
  368. }
  369. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  370. let originalCharIndex = chunk.start;
  371. let first = true;
  372. // when iterating each char, check if it's in a word boundary
  373. let charInHiresBoundary = false;
  374. while (originalCharIndex < chunk.end) {
  375. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  376. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  377. if (this.hires === 'boundary') {
  378. // in hires "boundary", group segments per word boundary than per char
  379. if (wordRegex.test(original[originalCharIndex])) {
  380. // for first char in the boundary found, start the boundary by pushing a segment
  381. if (!charInHiresBoundary) {
  382. this.rawSegments.push(segment);
  383. charInHiresBoundary = true;
  384. }
  385. } else {
  386. // for non-word char, end the boundary by pushing a segment
  387. this.rawSegments.push(segment);
  388. charInHiresBoundary = false;
  389. }
  390. } else {
  391. this.rawSegments.push(segment);
  392. }
  393. }
  394. if (original[originalCharIndex] === '\n') {
  395. loc.line += 1;
  396. loc.column = 0;
  397. this.generatedCodeLine += 1;
  398. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  399. this.generatedCodeColumn = 0;
  400. first = true;
  401. } else {
  402. loc.column += 1;
  403. this.generatedCodeColumn += 1;
  404. first = false;
  405. }
  406. originalCharIndex += 1;
  407. }
  408. this.pending = null;
  409. }
  410. advance(str) {
  411. if (!str) return;
  412. const lines = str.split('\n');
  413. if (lines.length > 1) {
  414. for (let i = 0; i < lines.length - 1; i++) {
  415. this.generatedCodeLine++;
  416. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  417. }
  418. this.generatedCodeColumn = 0;
  419. }
  420. this.generatedCodeColumn += lines[lines.length - 1].length;
  421. }
  422. }
  423. const n = '\n';
  424. const warned = {
  425. insertLeft: false,
  426. insertRight: false,
  427. storeName: false,
  428. };
  429. class MagicString {
  430. constructor(string, options = {}) {
  431. const chunk = new Chunk(0, string.length, string);
  432. Object.defineProperties(this, {
  433. original: { writable: true, value: string },
  434. outro: { writable: true, value: '' },
  435. intro: { writable: true, value: '' },
  436. firstChunk: { writable: true, value: chunk },
  437. lastChunk: { writable: true, value: chunk },
  438. lastSearchedChunk: { writable: true, value: chunk },
  439. byStart: { writable: true, value: {} },
  440. byEnd: { writable: true, value: {} },
  441. filename: { writable: true, value: options.filename },
  442. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  443. sourcemapLocations: { writable: true, value: new BitSet() },
  444. storedNames: { writable: true, value: {} },
  445. indentStr: { writable: true, value: undefined },
  446. ignoreList: { writable: true, value: options.ignoreList },
  447. });
  448. this.byStart[0] = chunk;
  449. this.byEnd[string.length] = chunk;
  450. }
  451. addSourcemapLocation(char) {
  452. this.sourcemapLocations.add(char);
  453. }
  454. append(content) {
  455. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  456. this.outro += content;
  457. return this;
  458. }
  459. appendLeft(index, content) {
  460. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  461. this._split(index);
  462. const chunk = this.byEnd[index];
  463. if (chunk) {
  464. chunk.appendLeft(content);
  465. } else {
  466. this.intro += content;
  467. }
  468. return this;
  469. }
  470. appendRight(index, content) {
  471. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  472. this._split(index);
  473. const chunk = this.byStart[index];
  474. if (chunk) {
  475. chunk.appendRight(content);
  476. } else {
  477. this.outro += content;
  478. }
  479. return this;
  480. }
  481. clone() {
  482. const cloned = new MagicString(this.original, { filename: this.filename });
  483. let originalChunk = this.firstChunk;
  484. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  485. while (originalChunk) {
  486. cloned.byStart[clonedChunk.start] = clonedChunk;
  487. cloned.byEnd[clonedChunk.end] = clonedChunk;
  488. const nextOriginalChunk = originalChunk.next;
  489. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  490. if (nextClonedChunk) {
  491. clonedChunk.next = nextClonedChunk;
  492. nextClonedChunk.previous = clonedChunk;
  493. clonedChunk = nextClonedChunk;
  494. }
  495. originalChunk = nextOriginalChunk;
  496. }
  497. cloned.lastChunk = clonedChunk;
  498. if (this.indentExclusionRanges) {
  499. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  500. }
  501. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  502. cloned.intro = this.intro;
  503. cloned.outro = this.outro;
  504. return cloned;
  505. }
  506. generateDecodedMap(options) {
  507. options = options || {};
  508. const sourceIndex = 0;
  509. const names = Object.keys(this.storedNames);
  510. const mappings = new Mappings(options.hires);
  511. const locate = getLocator(this.original);
  512. if (this.intro) {
  513. mappings.advance(this.intro);
  514. }
  515. this.firstChunk.eachNext((chunk) => {
  516. const loc = locate(chunk.start);
  517. if (chunk.intro.length) mappings.advance(chunk.intro);
  518. if (chunk.edited) {
  519. mappings.addEdit(
  520. sourceIndex,
  521. chunk.content,
  522. loc,
  523. chunk.storeName ? names.indexOf(chunk.original) : -1,
  524. );
  525. } else {
  526. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  527. }
  528. if (chunk.outro.length) mappings.advance(chunk.outro);
  529. });
  530. return {
  531. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  532. sources: [
  533. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  534. ],
  535. sourcesContent: options.includeContent ? [this.original] : undefined,
  536. names,
  537. mappings: mappings.raw,
  538. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  539. };
  540. }
  541. generateMap(options) {
  542. return new SourceMap(this.generateDecodedMap(options));
  543. }
  544. _ensureindentStr() {
  545. if (this.indentStr === undefined) {
  546. this.indentStr = guessIndent(this.original);
  547. }
  548. }
  549. _getRawIndentString() {
  550. this._ensureindentStr();
  551. return this.indentStr;
  552. }
  553. getIndentString() {
  554. this._ensureindentStr();
  555. return this.indentStr === null ? '\t' : this.indentStr;
  556. }
  557. indent(indentStr, options) {
  558. const pattern = /^[^\r\n]/gm;
  559. if (isObject(indentStr)) {
  560. options = indentStr;
  561. indentStr = undefined;
  562. }
  563. if (indentStr === undefined) {
  564. this._ensureindentStr();
  565. indentStr = this.indentStr || '\t';
  566. }
  567. if (indentStr === '') return this; // noop
  568. options = options || {};
  569. // Process exclusion ranges
  570. const isExcluded = {};
  571. if (options.exclude) {
  572. const exclusions =
  573. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  574. exclusions.forEach((exclusion) => {
  575. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  576. isExcluded[i] = true;
  577. }
  578. });
  579. }
  580. let shouldIndentNextCharacter = options.indentStart !== false;
  581. const replacer = (match) => {
  582. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  583. shouldIndentNextCharacter = true;
  584. return match;
  585. };
  586. this.intro = this.intro.replace(pattern, replacer);
  587. let charIndex = 0;
  588. let chunk = this.firstChunk;
  589. while (chunk) {
  590. const end = chunk.end;
  591. if (chunk.edited) {
  592. if (!isExcluded[charIndex]) {
  593. chunk.content = chunk.content.replace(pattern, replacer);
  594. if (chunk.content.length) {
  595. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  596. }
  597. }
  598. } else {
  599. charIndex = chunk.start;
  600. while (charIndex < end) {
  601. if (!isExcluded[charIndex]) {
  602. const char = this.original[charIndex];
  603. if (char === '\n') {
  604. shouldIndentNextCharacter = true;
  605. } else if (char !== '\r' && shouldIndentNextCharacter) {
  606. shouldIndentNextCharacter = false;
  607. if (charIndex === chunk.start) {
  608. chunk.prependRight(indentStr);
  609. } else {
  610. this._splitChunk(chunk, charIndex);
  611. chunk = chunk.next;
  612. chunk.prependRight(indentStr);
  613. }
  614. }
  615. }
  616. charIndex += 1;
  617. }
  618. }
  619. charIndex = chunk.end;
  620. chunk = chunk.next;
  621. }
  622. this.outro = this.outro.replace(pattern, replacer);
  623. return this;
  624. }
  625. insert() {
  626. throw new Error(
  627. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  628. );
  629. }
  630. insertLeft(index, content) {
  631. if (!warned.insertLeft) {
  632. console.warn(
  633. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  634. ); // eslint-disable-line no-console
  635. warned.insertLeft = true;
  636. }
  637. return this.appendLeft(index, content);
  638. }
  639. insertRight(index, content) {
  640. if (!warned.insertRight) {
  641. console.warn(
  642. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  643. ); // eslint-disable-line no-console
  644. warned.insertRight = true;
  645. }
  646. return this.prependRight(index, content);
  647. }
  648. move(start, end, index) {
  649. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  650. this._split(start);
  651. this._split(end);
  652. this._split(index);
  653. const first = this.byStart[start];
  654. const last = this.byEnd[end];
  655. const oldLeft = first.previous;
  656. const oldRight = last.next;
  657. const newRight = this.byStart[index];
  658. if (!newRight && last === this.lastChunk) return this;
  659. const newLeft = newRight ? newRight.previous : this.lastChunk;
  660. if (oldLeft) oldLeft.next = oldRight;
  661. if (oldRight) oldRight.previous = oldLeft;
  662. if (newLeft) newLeft.next = first;
  663. if (newRight) newRight.previous = last;
  664. if (!first.previous) this.firstChunk = last.next;
  665. if (!last.next) {
  666. this.lastChunk = first.previous;
  667. this.lastChunk.next = null;
  668. }
  669. first.previous = newLeft;
  670. last.next = newRight || null;
  671. if (!newLeft) this.firstChunk = first;
  672. if (!newRight) this.lastChunk = last;
  673. return this;
  674. }
  675. overwrite(start, end, content, options) {
  676. options = options || {};
  677. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  678. }
  679. update(start, end, content, options) {
  680. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  681. while (start < 0) start += this.original.length;
  682. while (end < 0) end += this.original.length;
  683. if (end > this.original.length) throw new Error('end is out of bounds');
  684. if (start === end)
  685. throw new Error(
  686. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  687. );
  688. this._split(start);
  689. this._split(end);
  690. if (options === true) {
  691. if (!warned.storeName) {
  692. console.warn(
  693. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  694. ); // eslint-disable-line no-console
  695. warned.storeName = true;
  696. }
  697. options = { storeName: true };
  698. }
  699. const storeName = options !== undefined ? options.storeName : false;
  700. const overwrite = options !== undefined ? options.overwrite : false;
  701. if (storeName) {
  702. const original = this.original.slice(start, end);
  703. Object.defineProperty(this.storedNames, original, {
  704. writable: true,
  705. value: true,
  706. enumerable: true,
  707. });
  708. }
  709. const first = this.byStart[start];
  710. const last = this.byEnd[end];
  711. if (first) {
  712. let chunk = first;
  713. while (chunk !== last) {
  714. if (chunk.next !== this.byStart[chunk.end]) {
  715. throw new Error('Cannot overwrite across a split point');
  716. }
  717. chunk = chunk.next;
  718. chunk.edit('', false);
  719. }
  720. first.edit(content, storeName, !overwrite);
  721. } else {
  722. // must be inserting at the end
  723. const newChunk = new Chunk(start, end, '').edit(content, storeName);
  724. // TODO last chunk in the array may not be the last chunk, if it's moved...
  725. last.next = newChunk;
  726. newChunk.previous = last;
  727. }
  728. return this;
  729. }
  730. prepend(content) {
  731. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  732. this.intro = content + this.intro;
  733. return this;
  734. }
  735. prependLeft(index, content) {
  736. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  737. this._split(index);
  738. const chunk = this.byEnd[index];
  739. if (chunk) {
  740. chunk.prependLeft(content);
  741. } else {
  742. this.intro = content + this.intro;
  743. }
  744. return this;
  745. }
  746. prependRight(index, content) {
  747. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  748. this._split(index);
  749. const chunk = this.byStart[index];
  750. if (chunk) {
  751. chunk.prependRight(content);
  752. } else {
  753. this.outro = content + this.outro;
  754. }
  755. return this;
  756. }
  757. remove(start, end) {
  758. while (start < 0) start += this.original.length;
  759. while (end < 0) end += this.original.length;
  760. if (start === end) return this;
  761. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  762. if (start > end) throw new Error('end must be greater than start');
  763. this._split(start);
  764. this._split(end);
  765. let chunk = this.byStart[start];
  766. while (chunk) {
  767. chunk.intro = '';
  768. chunk.outro = '';
  769. chunk.edit('');
  770. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  771. }
  772. return this;
  773. }
  774. lastChar() {
  775. if (this.outro.length) return this.outro[this.outro.length - 1];
  776. let chunk = this.lastChunk;
  777. do {
  778. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  779. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  780. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  781. } while ((chunk = chunk.previous));
  782. if (this.intro.length) return this.intro[this.intro.length - 1];
  783. return '';
  784. }
  785. lastLine() {
  786. let lineIndex = this.outro.lastIndexOf(n);
  787. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  788. let lineStr = this.outro;
  789. let chunk = this.lastChunk;
  790. do {
  791. if (chunk.outro.length > 0) {
  792. lineIndex = chunk.outro.lastIndexOf(n);
  793. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  794. lineStr = chunk.outro + lineStr;
  795. }
  796. if (chunk.content.length > 0) {
  797. lineIndex = chunk.content.lastIndexOf(n);
  798. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  799. lineStr = chunk.content + lineStr;
  800. }
  801. if (chunk.intro.length > 0) {
  802. lineIndex = chunk.intro.lastIndexOf(n);
  803. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  804. lineStr = chunk.intro + lineStr;
  805. }
  806. } while ((chunk = chunk.previous));
  807. lineIndex = this.intro.lastIndexOf(n);
  808. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  809. return this.intro + lineStr;
  810. }
  811. slice(start = 0, end = this.original.length) {
  812. while (start < 0) start += this.original.length;
  813. while (end < 0) end += this.original.length;
  814. let result = '';
  815. // find start chunk
  816. let chunk = this.firstChunk;
  817. while (chunk && (chunk.start > start || chunk.end <= start)) {
  818. // found end chunk before start
  819. if (chunk.start < end && chunk.end >= end) {
  820. return result;
  821. }
  822. chunk = chunk.next;
  823. }
  824. if (chunk && chunk.edited && chunk.start !== start)
  825. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  826. const startChunk = chunk;
  827. while (chunk) {
  828. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  829. result += chunk.intro;
  830. }
  831. const containsEnd = chunk.start < end && chunk.end >= end;
  832. if (containsEnd && chunk.edited && chunk.end !== end)
  833. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  834. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  835. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  836. result += chunk.content.slice(sliceStart, sliceEnd);
  837. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  838. result += chunk.outro;
  839. }
  840. if (containsEnd) {
  841. break;
  842. }
  843. chunk = chunk.next;
  844. }
  845. return result;
  846. }
  847. // TODO deprecate this? not really very useful
  848. snip(start, end) {
  849. const clone = this.clone();
  850. clone.remove(0, start);
  851. clone.remove(end, clone.original.length);
  852. return clone;
  853. }
  854. _split(index) {
  855. if (this.byStart[index] || this.byEnd[index]) return;
  856. let chunk = this.lastSearchedChunk;
  857. const searchForward = index > chunk.end;
  858. while (chunk) {
  859. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  860. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  861. }
  862. }
  863. _splitChunk(chunk, index) {
  864. if (chunk.edited && chunk.content.length) {
  865. // zero-length edited chunks are a special case (overlapping replacements)
  866. const loc = getLocator(this.original)(index);
  867. throw new Error(
  868. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  869. );
  870. }
  871. const newChunk = chunk.split(index);
  872. this.byEnd[index] = chunk;
  873. this.byStart[index] = newChunk;
  874. this.byEnd[newChunk.end] = newChunk;
  875. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  876. this.lastSearchedChunk = chunk;
  877. return true;
  878. }
  879. toString() {
  880. let str = this.intro;
  881. let chunk = this.firstChunk;
  882. while (chunk) {
  883. str += chunk.toString();
  884. chunk = chunk.next;
  885. }
  886. return str + this.outro;
  887. }
  888. isEmpty() {
  889. let chunk = this.firstChunk;
  890. do {
  891. if (
  892. (chunk.intro.length && chunk.intro.trim()) ||
  893. (chunk.content.length && chunk.content.trim()) ||
  894. (chunk.outro.length && chunk.outro.trim())
  895. )
  896. return false;
  897. } while ((chunk = chunk.next));
  898. return true;
  899. }
  900. length() {
  901. let chunk = this.firstChunk;
  902. let length = 0;
  903. do {
  904. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  905. } while ((chunk = chunk.next));
  906. return length;
  907. }
  908. trimLines() {
  909. return this.trim('[\\r\\n]');
  910. }
  911. trim(charType) {
  912. return this.trimStart(charType).trimEnd(charType);
  913. }
  914. trimEndAborted(charType) {
  915. const rx = new RegExp((charType || '\\s') + '+$');
  916. this.outro = this.outro.replace(rx, '');
  917. if (this.outro.length) return true;
  918. let chunk = this.lastChunk;
  919. do {
  920. const end = chunk.end;
  921. const aborted = chunk.trimEnd(rx);
  922. // if chunk was trimmed, we have a new lastChunk
  923. if (chunk.end !== end) {
  924. if (this.lastChunk === chunk) {
  925. this.lastChunk = chunk.next;
  926. }
  927. this.byEnd[chunk.end] = chunk;
  928. this.byStart[chunk.next.start] = chunk.next;
  929. this.byEnd[chunk.next.end] = chunk.next;
  930. }
  931. if (aborted) return true;
  932. chunk = chunk.previous;
  933. } while (chunk);
  934. return false;
  935. }
  936. trimEnd(charType) {
  937. this.trimEndAborted(charType);
  938. return this;
  939. }
  940. trimStartAborted(charType) {
  941. const rx = new RegExp('^' + (charType || '\\s') + '+');
  942. this.intro = this.intro.replace(rx, '');
  943. if (this.intro.length) return true;
  944. let chunk = this.firstChunk;
  945. do {
  946. const end = chunk.end;
  947. const aborted = chunk.trimStart(rx);
  948. if (chunk.end !== end) {
  949. // special case...
  950. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  951. this.byEnd[chunk.end] = chunk;
  952. this.byStart[chunk.next.start] = chunk.next;
  953. this.byEnd[chunk.next.end] = chunk.next;
  954. }
  955. if (aborted) return true;
  956. chunk = chunk.next;
  957. } while (chunk);
  958. return false;
  959. }
  960. trimStart(charType) {
  961. this.trimStartAborted(charType);
  962. return this;
  963. }
  964. hasChanged() {
  965. return this.original !== this.toString();
  966. }
  967. _replaceRegexp(searchValue, replacement) {
  968. function getReplacement(match, str) {
  969. if (typeof replacement === 'string') {
  970. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  971. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  972. if (i === '$') return '$';
  973. if (i === '&') return match[0];
  974. const num = +i;
  975. if (num < match.length) return match[+i];
  976. return `$${i}`;
  977. });
  978. } else {
  979. return replacement(...match, match.index, str, match.groups);
  980. }
  981. }
  982. function matchAll(re, str) {
  983. let match;
  984. const matches = [];
  985. while ((match = re.exec(str))) {
  986. matches.push(match);
  987. }
  988. return matches;
  989. }
  990. if (searchValue.global) {
  991. const matches = matchAll(searchValue, this.original);
  992. matches.forEach((match) => {
  993. if (match.index != null)
  994. this.overwrite(
  995. match.index,
  996. match.index + match[0].length,
  997. getReplacement(match, this.original),
  998. );
  999. });
  1000. } else {
  1001. const match = this.original.match(searchValue);
  1002. if (match && match.index != null)
  1003. this.overwrite(
  1004. match.index,
  1005. match.index + match[0].length,
  1006. getReplacement(match, this.original),
  1007. );
  1008. }
  1009. return this;
  1010. }
  1011. _replaceString(string, replacement) {
  1012. const { original } = this;
  1013. const index = original.indexOf(string);
  1014. if (index !== -1) {
  1015. this.overwrite(index, index + string.length, replacement);
  1016. }
  1017. return this;
  1018. }
  1019. replace(searchValue, replacement) {
  1020. if (typeof searchValue === 'string') {
  1021. return this._replaceString(searchValue, replacement);
  1022. }
  1023. return this._replaceRegexp(searchValue, replacement);
  1024. }
  1025. _replaceAllString(string, replacement) {
  1026. const { original } = this;
  1027. const stringLength = string.length;
  1028. for (
  1029. let index = original.indexOf(string);
  1030. index !== -1;
  1031. index = original.indexOf(string, index + stringLength)
  1032. ) {
  1033. this.overwrite(index, index + stringLength, replacement);
  1034. }
  1035. return this;
  1036. }
  1037. replaceAll(searchValue, replacement) {
  1038. if (typeof searchValue === 'string') {
  1039. return this._replaceAllString(searchValue, replacement);
  1040. }
  1041. if (!searchValue.global) {
  1042. throw new TypeError(
  1043. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  1044. );
  1045. }
  1046. return this._replaceRegexp(searchValue, replacement);
  1047. }
  1048. }
  1049. const hasOwnProp = Object.prototype.hasOwnProperty;
  1050. class Bundle {
  1051. constructor(options = {}) {
  1052. this.intro = options.intro || '';
  1053. this.separator = options.separator !== undefined ? options.separator : '\n';
  1054. this.sources = [];
  1055. this.uniqueSources = [];
  1056. this.uniqueSourceIndexByFilename = {};
  1057. }
  1058. addSource(source) {
  1059. if (source instanceof MagicString) {
  1060. return this.addSource({
  1061. content: source,
  1062. filename: source.filename,
  1063. separator: this.separator,
  1064. });
  1065. }
  1066. if (!isObject(source) || !source.content) {
  1067. throw new Error(
  1068. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  1069. );
  1070. }
  1071. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1072. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1073. });
  1074. if (source.separator === undefined) {
  1075. // TODO there's a bunch of this sort of thing, needs cleaning up
  1076. source.separator = this.separator;
  1077. }
  1078. if (source.filename) {
  1079. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1080. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1081. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1082. } else {
  1083. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1084. if (source.content.original !== uniqueSource.content) {
  1085. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1086. }
  1087. }
  1088. }
  1089. this.sources.push(source);
  1090. return this;
  1091. }
  1092. append(str, options) {
  1093. this.addSource({
  1094. content: new MagicString(str),
  1095. separator: (options && options.separator) || '',
  1096. });
  1097. return this;
  1098. }
  1099. clone() {
  1100. const bundle = new Bundle({
  1101. intro: this.intro,
  1102. separator: this.separator,
  1103. });
  1104. this.sources.forEach((source) => {
  1105. bundle.addSource({
  1106. filename: source.filename,
  1107. content: source.content.clone(),
  1108. separator: source.separator,
  1109. });
  1110. });
  1111. return bundle;
  1112. }
  1113. generateDecodedMap(options = {}) {
  1114. const names = [];
  1115. let x_google_ignoreList = undefined;
  1116. this.sources.forEach((source) => {
  1117. Object.keys(source.content.storedNames).forEach((name) => {
  1118. if (!~names.indexOf(name)) names.push(name);
  1119. });
  1120. });
  1121. const mappings = new Mappings(options.hires);
  1122. if (this.intro) {
  1123. mappings.advance(this.intro);
  1124. }
  1125. this.sources.forEach((source, i) => {
  1126. if (i > 0) {
  1127. mappings.advance(this.separator);
  1128. }
  1129. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1130. const magicString = source.content;
  1131. const locate = getLocator(magicString.original);
  1132. if (magicString.intro) {
  1133. mappings.advance(magicString.intro);
  1134. }
  1135. magicString.firstChunk.eachNext((chunk) => {
  1136. const loc = locate(chunk.start);
  1137. if (chunk.intro.length) mappings.advance(chunk.intro);
  1138. if (source.filename) {
  1139. if (chunk.edited) {
  1140. mappings.addEdit(
  1141. sourceIndex,
  1142. chunk.content,
  1143. loc,
  1144. chunk.storeName ? names.indexOf(chunk.original) : -1,
  1145. );
  1146. } else {
  1147. mappings.addUneditedChunk(
  1148. sourceIndex,
  1149. chunk,
  1150. magicString.original,
  1151. loc,
  1152. magicString.sourcemapLocations,
  1153. );
  1154. }
  1155. } else {
  1156. mappings.advance(chunk.content);
  1157. }
  1158. if (chunk.outro.length) mappings.advance(chunk.outro);
  1159. });
  1160. if (magicString.outro) {
  1161. mappings.advance(magicString.outro);
  1162. }
  1163. if (source.ignoreList && sourceIndex !== -1) {
  1164. if (x_google_ignoreList === undefined) {
  1165. x_google_ignoreList = [];
  1166. }
  1167. x_google_ignoreList.push(sourceIndex);
  1168. }
  1169. });
  1170. return {
  1171. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  1172. sources: this.uniqueSources.map((source) => {
  1173. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1174. }),
  1175. sourcesContent: this.uniqueSources.map((source) => {
  1176. return options.includeContent ? source.content : null;
  1177. }),
  1178. names,
  1179. mappings: mappings.raw,
  1180. x_google_ignoreList,
  1181. };
  1182. }
  1183. generateMap(options) {
  1184. return new SourceMap(this.generateDecodedMap(options));
  1185. }
  1186. getIndentString() {
  1187. const indentStringCounts = {};
  1188. this.sources.forEach((source) => {
  1189. const indentStr = source.content._getRawIndentString();
  1190. if (indentStr === null) return;
  1191. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1192. indentStringCounts[indentStr] += 1;
  1193. });
  1194. return (
  1195. Object.keys(indentStringCounts).sort((a, b) => {
  1196. return indentStringCounts[a] - indentStringCounts[b];
  1197. })[0] || '\t'
  1198. );
  1199. }
  1200. indent(indentStr) {
  1201. if (!arguments.length) {
  1202. indentStr = this.getIndentString();
  1203. }
  1204. if (indentStr === '') return this; // noop
  1205. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1206. this.sources.forEach((source, i) => {
  1207. const separator = source.separator !== undefined ? source.separator : this.separator;
  1208. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1209. source.content.indent(indentStr, {
  1210. exclude: source.indentExclusionRanges,
  1211. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1212. });
  1213. trailingNewline = source.content.lastChar() === '\n';
  1214. });
  1215. if (this.intro) {
  1216. this.intro =
  1217. indentStr +
  1218. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1219. return index > 0 ? indentStr + match : match;
  1220. });
  1221. }
  1222. return this;
  1223. }
  1224. prepend(str) {
  1225. this.intro = str + this.intro;
  1226. return this;
  1227. }
  1228. toString() {
  1229. const body = this.sources
  1230. .map((source, i) => {
  1231. const separator = source.separator !== undefined ? source.separator : this.separator;
  1232. const str = (i > 0 ? separator : '') + source.content.toString();
  1233. return str;
  1234. })
  1235. .join('');
  1236. return this.intro + body;
  1237. }
  1238. isEmpty() {
  1239. if (this.intro.length && this.intro.trim()) return false;
  1240. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1241. return true;
  1242. }
  1243. length() {
  1244. return this.sources.reduce(
  1245. (length, source) => length + source.content.length(),
  1246. this.intro.length,
  1247. );
  1248. }
  1249. trimLines() {
  1250. return this.trim('[\\r\\n]');
  1251. }
  1252. trim(charType) {
  1253. return this.trimStart(charType).trimEnd(charType);
  1254. }
  1255. trimStart(charType) {
  1256. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1257. this.intro = this.intro.replace(rx, '');
  1258. if (!this.intro) {
  1259. let source;
  1260. let i = 0;
  1261. do {
  1262. source = this.sources[i++];
  1263. if (!source) {
  1264. break;
  1265. }
  1266. } while (!source.content.trimStartAborted(charType));
  1267. }
  1268. return this;
  1269. }
  1270. trimEnd(charType) {
  1271. const rx = new RegExp((charType || '\\s') + '+$');
  1272. let source;
  1273. let i = this.sources.length - 1;
  1274. do {
  1275. source = this.sources[i--];
  1276. if (!source) {
  1277. this.intro = this.intro.replace(rx, '');
  1278. break;
  1279. }
  1280. } while (!source.content.trimEndAborted(charType));
  1281. return this;
  1282. }
  1283. }
  1284. MagicString.Bundle = Bundle;
  1285. MagicString.SourceMap = SourceMap;
  1286. MagicString.default = MagicString; // work around TypeScript bug https://github.com/Rich-Harris/magic-string/pull/121
  1287. return MagicString;
  1288. }));
  1289. //# sourceMappingURL=magic-string.umd.js.map