magic-string.es.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  1. import { encode } from 'sourcemap-codec';
  2. var BitSet = function BitSet(arg) {
  3. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  4. };
  5. BitSet.prototype.add = function add (n) {
  6. this.bits[n >> 5] |= 1 << (n & 31);
  7. };
  8. BitSet.prototype.has = function has (n) {
  9. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  10. };
  11. var Chunk = function Chunk(start, end, content) {
  12. this.start = start;
  13. this.end = end;
  14. this.original = content;
  15. this.intro = '';
  16. this.outro = '';
  17. this.content = content;
  18. this.storeName = false;
  19. this.edited = false;
  20. // we make these non-enumerable, for sanity while debugging
  21. Object.defineProperties(this, {
  22. previous: { writable: true, value: null },
  23. next: { writable: true, value: null },
  24. });
  25. };
  26. Chunk.prototype.appendLeft = function appendLeft (content) {
  27. this.outro += content;
  28. };
  29. Chunk.prototype.appendRight = function appendRight (content) {
  30. this.intro = this.intro + content;
  31. };
  32. Chunk.prototype.clone = function clone () {
  33. var chunk = new Chunk(this.start, this.end, this.original);
  34. chunk.intro = this.intro;
  35. chunk.outro = this.outro;
  36. chunk.content = this.content;
  37. chunk.storeName = this.storeName;
  38. chunk.edited = this.edited;
  39. return chunk;
  40. };
  41. Chunk.prototype.contains = function contains (index) {
  42. return this.start < index && index < this.end;
  43. };
  44. Chunk.prototype.eachNext = function eachNext (fn) {
  45. var chunk = this;
  46. while (chunk) {
  47. fn(chunk);
  48. chunk = chunk.next;
  49. }
  50. };
  51. Chunk.prototype.eachPrevious = function eachPrevious (fn) {
  52. var chunk = this;
  53. while (chunk) {
  54. fn(chunk);
  55. chunk = chunk.previous;
  56. }
  57. };
  58. Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
  59. this.content = content;
  60. if (!contentOnly) {
  61. this.intro = '';
  62. this.outro = '';
  63. }
  64. this.storeName = storeName;
  65. this.edited = true;
  66. return this;
  67. };
  68. Chunk.prototype.prependLeft = function prependLeft (content) {
  69. this.outro = content + this.outro;
  70. };
  71. Chunk.prototype.prependRight = function prependRight (content) {
  72. this.intro = content + this.intro;
  73. };
  74. Chunk.prototype.split = function split (index) {
  75. var sliceIndex = index - this.start;
  76. var originalBefore = this.original.slice(0, sliceIndex);
  77. var originalAfter = this.original.slice(sliceIndex);
  78. this.original = originalBefore;
  79. var newChunk = new Chunk(index, this.end, originalAfter);
  80. newChunk.outro = this.outro;
  81. this.outro = '';
  82. this.end = index;
  83. if (this.edited) {
  84. // TODO is this block necessary?...
  85. newChunk.edit('', false);
  86. this.content = '';
  87. } else {
  88. this.content = originalBefore;
  89. }
  90. newChunk.next = this.next;
  91. if (newChunk.next) { newChunk.next.previous = newChunk; }
  92. newChunk.previous = this;
  93. this.next = newChunk;
  94. return newChunk;
  95. };
  96. Chunk.prototype.toString = function toString () {
  97. return this.intro + this.content + this.outro;
  98. };
  99. Chunk.prototype.trimEnd = function trimEnd (rx) {
  100. this.outro = this.outro.replace(rx, '');
  101. if (this.outro.length) { return true; }
  102. var trimmed = this.content.replace(rx, '');
  103. if (trimmed.length) {
  104. if (trimmed !== this.content) {
  105. this.split(this.start + trimmed.length).edit('', undefined, true);
  106. }
  107. return true;
  108. } else {
  109. this.edit('', undefined, true);
  110. this.intro = this.intro.replace(rx, '');
  111. if (this.intro.length) { return true; }
  112. }
  113. };
  114. Chunk.prototype.trimStart = function trimStart (rx) {
  115. this.intro = this.intro.replace(rx, '');
  116. if (this.intro.length) { return true; }
  117. var trimmed = this.content.replace(rx, '');
  118. if (trimmed.length) {
  119. if (trimmed !== this.content) {
  120. this.split(this.end - trimmed.length);
  121. this.edit('', undefined, true);
  122. }
  123. return true;
  124. } else {
  125. this.edit('', undefined, true);
  126. this.outro = this.outro.replace(rx, '');
  127. if (this.outro.length) { return true; }
  128. }
  129. };
  130. var btoa = function () {
  131. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  132. };
  133. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  134. btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  135. } else if (typeof Buffer === 'function') {
  136. btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  137. }
  138. var SourceMap = function SourceMap(properties) {
  139. this.version = 3;
  140. this.file = properties.file;
  141. this.sources = properties.sources;
  142. this.sourcesContent = properties.sourcesContent;
  143. this.names = properties.names;
  144. this.mappings = encode(properties.mappings);
  145. };
  146. SourceMap.prototype.toString = function toString () {
  147. return JSON.stringify(this);
  148. };
  149. SourceMap.prototype.toUrl = function toUrl () {
  150. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  151. };
  152. function guessIndent(code) {
  153. var lines = code.split('\n');
  154. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  155. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  156. if (tabbed.length === 0 && spaced.length === 0) {
  157. return null;
  158. }
  159. // More lines tabbed than spaced? Assume tabs, and
  160. // default to tabs in the case of a tie (or nothing
  161. // to go on)
  162. if (tabbed.length >= spaced.length) {
  163. return '\t';
  164. }
  165. // Otherwise, we need to guess the multiple
  166. var min = spaced.reduce(function (previous, current) {
  167. var numSpaces = /^ +/.exec(current)[0].length;
  168. return Math.min(numSpaces, previous);
  169. }, Infinity);
  170. return new Array(min + 1).join(' ');
  171. }
  172. function getRelativePath(from, to) {
  173. var fromParts = from.split(/[/\\]/);
  174. var toParts = to.split(/[/\\]/);
  175. fromParts.pop(); // get dirname
  176. while (fromParts[0] === toParts[0]) {
  177. fromParts.shift();
  178. toParts.shift();
  179. }
  180. if (fromParts.length) {
  181. var i = fromParts.length;
  182. while (i--) { fromParts[i] = '..'; }
  183. }
  184. return fromParts.concat(toParts).join('/');
  185. }
  186. var toString = Object.prototype.toString;
  187. function isObject(thing) {
  188. return toString.call(thing) === '[object Object]';
  189. }
  190. function getLocator(source) {
  191. var originalLines = source.split('\n');
  192. var lineOffsets = [];
  193. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  194. lineOffsets.push(pos);
  195. pos += originalLines[i].length + 1;
  196. }
  197. return function locate(index) {
  198. var i = 0;
  199. var j = lineOffsets.length;
  200. while (i < j) {
  201. var m = (i + j) >> 1;
  202. if (index < lineOffsets[m]) {
  203. j = m;
  204. } else {
  205. i = m + 1;
  206. }
  207. }
  208. var line = i - 1;
  209. var column = index - lineOffsets[line];
  210. return { line: line, column: column };
  211. };
  212. }
  213. var Mappings = function Mappings(hires) {
  214. this.hires = hires;
  215. this.generatedCodeLine = 0;
  216. this.generatedCodeColumn = 0;
  217. this.raw = [];
  218. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  219. this.pending = null;
  220. };
  221. Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
  222. if (content.length) {
  223. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  224. if (nameIndex >= 0) {
  225. segment.push(nameIndex);
  226. }
  227. this.rawSegments.push(segment);
  228. } else if (this.pending) {
  229. this.rawSegments.push(this.pending);
  230. }
  231. this.advance(content);
  232. this.pending = null;
  233. };
  234. Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
  235. var originalCharIndex = chunk.start;
  236. var first = true;
  237. while (originalCharIndex < chunk.end) {
  238. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  239. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  240. }
  241. if (original[originalCharIndex] === '\n') {
  242. loc.line += 1;
  243. loc.column = 0;
  244. this.generatedCodeLine += 1;
  245. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  246. this.generatedCodeColumn = 0;
  247. first = true;
  248. } else {
  249. loc.column += 1;
  250. this.generatedCodeColumn += 1;
  251. first = false;
  252. }
  253. originalCharIndex += 1;
  254. }
  255. this.pending = null;
  256. };
  257. Mappings.prototype.advance = function advance (str) {
  258. if (!str) { return; }
  259. var lines = str.split('\n');
  260. if (lines.length > 1) {
  261. for (var i = 0; i < lines.length - 1; i++) {
  262. this.generatedCodeLine++;
  263. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  264. }
  265. this.generatedCodeColumn = 0;
  266. }
  267. this.generatedCodeColumn += lines[lines.length - 1].length;
  268. };
  269. var n = '\n';
  270. var warned = {
  271. insertLeft: false,
  272. insertRight: false,
  273. storeName: false,
  274. };
  275. var MagicString = function MagicString(string, options) {
  276. if ( options === void 0 ) options = {};
  277. var chunk = new Chunk(0, string.length, string);
  278. Object.defineProperties(this, {
  279. original: { writable: true, value: string },
  280. outro: { writable: true, value: '' },
  281. intro: { writable: true, value: '' },
  282. firstChunk: { writable: true, value: chunk },
  283. lastChunk: { writable: true, value: chunk },
  284. lastSearchedChunk: { writable: true, value: chunk },
  285. byStart: { writable: true, value: {} },
  286. byEnd: { writable: true, value: {} },
  287. filename: { writable: true, value: options.filename },
  288. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  289. sourcemapLocations: { writable: true, value: new BitSet() },
  290. storedNames: { writable: true, value: {} },
  291. indentStr: { writable: true, value: guessIndent(string) },
  292. });
  293. this.byStart[0] = chunk;
  294. this.byEnd[string.length] = chunk;
  295. };
  296. MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
  297. this.sourcemapLocations.add(char);
  298. };
  299. MagicString.prototype.append = function append (content) {
  300. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  301. this.outro += content;
  302. return this;
  303. };
  304. MagicString.prototype.appendLeft = function appendLeft (index, content) {
  305. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  306. this._split(index);
  307. var chunk = this.byEnd[index];
  308. if (chunk) {
  309. chunk.appendLeft(content);
  310. } else {
  311. this.intro += content;
  312. }
  313. return this;
  314. };
  315. MagicString.prototype.appendRight = function appendRight (index, content) {
  316. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  317. this._split(index);
  318. var chunk = this.byStart[index];
  319. if (chunk) {
  320. chunk.appendRight(content);
  321. } else {
  322. this.outro += content;
  323. }
  324. return this;
  325. };
  326. MagicString.prototype.clone = function clone () {
  327. var cloned = new MagicString(this.original, { filename: this.filename });
  328. var originalChunk = this.firstChunk;
  329. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  330. while (originalChunk) {
  331. cloned.byStart[clonedChunk.start] = clonedChunk;
  332. cloned.byEnd[clonedChunk.end] = clonedChunk;
  333. var nextOriginalChunk = originalChunk.next;
  334. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  335. if (nextClonedChunk) {
  336. clonedChunk.next = nextClonedChunk;
  337. nextClonedChunk.previous = clonedChunk;
  338. clonedChunk = nextClonedChunk;
  339. }
  340. originalChunk = nextOriginalChunk;
  341. }
  342. cloned.lastChunk = clonedChunk;
  343. if (this.indentExclusionRanges) {
  344. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  345. }
  346. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  347. cloned.intro = this.intro;
  348. cloned.outro = this.outro;
  349. return cloned;
  350. };
  351. MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
  352. var this$1$1 = this;
  353. options = options || {};
  354. var sourceIndex = 0;
  355. var names = Object.keys(this.storedNames);
  356. var mappings = new Mappings(options.hires);
  357. var locate = getLocator(this.original);
  358. if (this.intro) {
  359. mappings.advance(this.intro);
  360. }
  361. this.firstChunk.eachNext(function (chunk) {
  362. var loc = locate(chunk.start);
  363. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  364. if (chunk.edited) {
  365. mappings.addEdit(
  366. sourceIndex,
  367. chunk.content,
  368. loc,
  369. chunk.storeName ? names.indexOf(chunk.original) : -1
  370. );
  371. } else {
  372. mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations);
  373. }
  374. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  375. });
  376. return {
  377. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  378. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  379. sourcesContent: options.includeContent ? [this.original] : [null],
  380. names: names,
  381. mappings: mappings.raw,
  382. };
  383. };
  384. MagicString.prototype.generateMap = function generateMap (options) {
  385. return new SourceMap(this.generateDecodedMap(options));
  386. };
  387. MagicString.prototype.getIndentString = function getIndentString () {
  388. return this.indentStr === null ? '\t' : this.indentStr;
  389. };
  390. MagicString.prototype.indent = function indent (indentStr, options) {
  391. var pattern = /^[^\r\n]/gm;
  392. if (isObject(indentStr)) {
  393. options = indentStr;
  394. indentStr = undefined;
  395. }
  396. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  397. if (indentStr === '') { return this; } // noop
  398. options = options || {};
  399. // Process exclusion ranges
  400. var isExcluded = {};
  401. if (options.exclude) {
  402. var exclusions =
  403. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  404. exclusions.forEach(function (exclusion) {
  405. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  406. isExcluded[i] = true;
  407. }
  408. });
  409. }
  410. var shouldIndentNextCharacter = options.indentStart !== false;
  411. var replacer = function (match) {
  412. if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
  413. shouldIndentNextCharacter = true;
  414. return match;
  415. };
  416. this.intro = this.intro.replace(pattern, replacer);
  417. var charIndex = 0;
  418. var chunk = this.firstChunk;
  419. while (chunk) {
  420. var end = chunk.end;
  421. if (chunk.edited) {
  422. if (!isExcluded[charIndex]) {
  423. chunk.content = chunk.content.replace(pattern, replacer);
  424. if (chunk.content.length) {
  425. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  426. }
  427. }
  428. } else {
  429. charIndex = chunk.start;
  430. while (charIndex < end) {
  431. if (!isExcluded[charIndex]) {
  432. var char = this.original[charIndex];
  433. if (char === '\n') {
  434. shouldIndentNextCharacter = true;
  435. } else if (char !== '\r' && shouldIndentNextCharacter) {
  436. shouldIndentNextCharacter = false;
  437. if (charIndex === chunk.start) {
  438. chunk.prependRight(indentStr);
  439. } else {
  440. this._splitChunk(chunk, charIndex);
  441. chunk = chunk.next;
  442. chunk.prependRight(indentStr);
  443. }
  444. }
  445. }
  446. charIndex += 1;
  447. }
  448. }
  449. charIndex = chunk.end;
  450. chunk = chunk.next;
  451. }
  452. this.outro = this.outro.replace(pattern, replacer);
  453. return this;
  454. };
  455. MagicString.prototype.insert = function insert () {
  456. throw new Error(
  457. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
  458. );
  459. };
  460. MagicString.prototype.insertLeft = function insertLeft (index, content) {
  461. if (!warned.insertLeft) {
  462. console.warn(
  463. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
  464. ); // eslint-disable-line no-console
  465. warned.insertLeft = true;
  466. }
  467. return this.appendLeft(index, content);
  468. };
  469. MagicString.prototype.insertRight = function insertRight (index, content) {
  470. if (!warned.insertRight) {
  471. console.warn(
  472. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
  473. ); // eslint-disable-line no-console
  474. warned.insertRight = true;
  475. }
  476. return this.prependRight(index, content);
  477. };
  478. MagicString.prototype.move = function move (start, end, index) {
  479. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  480. this._split(start);
  481. this._split(end);
  482. this._split(index);
  483. var first = this.byStart[start];
  484. var last = this.byEnd[end];
  485. var oldLeft = first.previous;
  486. var oldRight = last.next;
  487. var newRight = this.byStart[index];
  488. if (!newRight && last === this.lastChunk) { return this; }
  489. var newLeft = newRight ? newRight.previous : this.lastChunk;
  490. if (oldLeft) { oldLeft.next = oldRight; }
  491. if (oldRight) { oldRight.previous = oldLeft; }
  492. if (newLeft) { newLeft.next = first; }
  493. if (newRight) { newRight.previous = last; }
  494. if (!first.previous) { this.firstChunk = last.next; }
  495. if (!last.next) {
  496. this.lastChunk = first.previous;
  497. this.lastChunk.next = null;
  498. }
  499. first.previous = newLeft;
  500. last.next = newRight || null;
  501. if (!newLeft) { this.firstChunk = first; }
  502. if (!newRight) { this.lastChunk = last; }
  503. return this;
  504. };
  505. MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
  506. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  507. while (start < 0) { start += this.original.length; }
  508. while (end < 0) { end += this.original.length; }
  509. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  510. if (start === end)
  511. { throw new Error(
  512. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
  513. ); }
  514. this._split(start);
  515. this._split(end);
  516. if (options === true) {
  517. if (!warned.storeName) {
  518. console.warn(
  519. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
  520. ); // eslint-disable-line no-console
  521. warned.storeName = true;
  522. }
  523. options = { storeName: true };
  524. }
  525. var storeName = options !== undefined ? options.storeName : false;
  526. var contentOnly = options !== undefined ? options.contentOnly : false;
  527. if (storeName) {
  528. var original = this.original.slice(start, end);
  529. Object.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true });
  530. }
  531. var first = this.byStart[start];
  532. var last = this.byEnd[end];
  533. if (first) {
  534. var chunk = first;
  535. while (chunk !== last) {
  536. if (chunk.next !== this.byStart[chunk.end]) {
  537. throw new Error('Cannot overwrite across a split point');
  538. }
  539. chunk = chunk.next;
  540. chunk.edit('', false);
  541. }
  542. first.edit(content, storeName, contentOnly);
  543. } else {
  544. // must be inserting at the end
  545. var newChunk = new Chunk(start, end, '').edit(content, storeName);
  546. // TODO last chunk in the array may not be the last chunk, if it's moved...
  547. last.next = newChunk;
  548. newChunk.previous = last;
  549. }
  550. return this;
  551. };
  552. MagicString.prototype.prepend = function prepend (content) {
  553. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  554. this.intro = content + this.intro;
  555. return this;
  556. };
  557. MagicString.prototype.prependLeft = function prependLeft (index, content) {
  558. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  559. this._split(index);
  560. var chunk = this.byEnd[index];
  561. if (chunk) {
  562. chunk.prependLeft(content);
  563. } else {
  564. this.intro = content + this.intro;
  565. }
  566. return this;
  567. };
  568. MagicString.prototype.prependRight = function prependRight (index, content) {
  569. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  570. this._split(index);
  571. var chunk = this.byStart[index];
  572. if (chunk) {
  573. chunk.prependRight(content);
  574. } else {
  575. this.outro = content + this.outro;
  576. }
  577. return this;
  578. };
  579. MagicString.prototype.remove = function remove (start, end) {
  580. while (start < 0) { start += this.original.length; }
  581. while (end < 0) { end += this.original.length; }
  582. if (start === end) { return this; }
  583. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  584. if (start > end) { throw new Error('end must be greater than start'); }
  585. this._split(start);
  586. this._split(end);
  587. var chunk = this.byStart[start];
  588. while (chunk) {
  589. chunk.intro = '';
  590. chunk.outro = '';
  591. chunk.edit('');
  592. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  593. }
  594. return this;
  595. };
  596. MagicString.prototype.lastChar = function lastChar () {
  597. if (this.outro.length) { return this.outro[this.outro.length - 1]; }
  598. var chunk = this.lastChunk;
  599. do {
  600. if (chunk.outro.length) { return chunk.outro[chunk.outro.length - 1]; }
  601. if (chunk.content.length) { return chunk.content[chunk.content.length - 1]; }
  602. if (chunk.intro.length) { return chunk.intro[chunk.intro.length - 1]; }
  603. } while ((chunk = chunk.previous));
  604. if (this.intro.length) { return this.intro[this.intro.length - 1]; }
  605. return '';
  606. };
  607. MagicString.prototype.lastLine = function lastLine () {
  608. var lineIndex = this.outro.lastIndexOf(n);
  609. if (lineIndex !== -1) { return this.outro.substr(lineIndex + 1); }
  610. var lineStr = this.outro;
  611. var chunk = this.lastChunk;
  612. do {
  613. if (chunk.outro.length > 0) {
  614. lineIndex = chunk.outro.lastIndexOf(n);
  615. if (lineIndex !== -1) { return chunk.outro.substr(lineIndex + 1) + lineStr; }
  616. lineStr = chunk.outro + lineStr;
  617. }
  618. if (chunk.content.length > 0) {
  619. lineIndex = chunk.content.lastIndexOf(n);
  620. if (lineIndex !== -1) { return chunk.content.substr(lineIndex + 1) + lineStr; }
  621. lineStr = chunk.content + lineStr;
  622. }
  623. if (chunk.intro.length > 0) {
  624. lineIndex = chunk.intro.lastIndexOf(n);
  625. if (lineIndex !== -1) { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  626. lineStr = chunk.intro + lineStr;
  627. }
  628. } while ((chunk = chunk.previous));
  629. lineIndex = this.intro.lastIndexOf(n);
  630. if (lineIndex !== -1) { return this.intro.substr(lineIndex + 1) + lineStr; }
  631. return this.intro + lineStr;
  632. };
  633. MagicString.prototype.slice = function slice (start, end) {
  634. if ( start === void 0 ) start = 0;
  635. if ( end === void 0 ) end = this.original.length;
  636. while (start < 0) { start += this.original.length; }
  637. while (end < 0) { end += this.original.length; }
  638. var result = '';
  639. // find start chunk
  640. var chunk = this.firstChunk;
  641. while (chunk && (chunk.start > start || chunk.end <= start)) {
  642. // found end chunk before start
  643. if (chunk.start < end && chunk.end >= end) {
  644. return result;
  645. }
  646. chunk = chunk.next;
  647. }
  648. if (chunk && chunk.edited && chunk.start !== start)
  649. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  650. var startChunk = chunk;
  651. while (chunk) {
  652. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  653. result += chunk.intro;
  654. }
  655. var containsEnd = chunk.start < end && chunk.end >= end;
  656. if (containsEnd && chunk.edited && chunk.end !== end)
  657. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  658. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  659. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  660. result += chunk.content.slice(sliceStart, sliceEnd);
  661. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  662. result += chunk.outro;
  663. }
  664. if (containsEnd) {
  665. break;
  666. }
  667. chunk = chunk.next;
  668. }
  669. return result;
  670. };
  671. // TODO deprecate this? not really very useful
  672. MagicString.prototype.snip = function snip (start, end) {
  673. var clone = this.clone();
  674. clone.remove(0, start);
  675. clone.remove(end, clone.original.length);
  676. return clone;
  677. };
  678. MagicString.prototype._split = function _split (index) {
  679. if (this.byStart[index] || this.byEnd[index]) { return; }
  680. var chunk = this.lastSearchedChunk;
  681. var searchForward = index > chunk.end;
  682. while (chunk) {
  683. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  684. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  685. }
  686. };
  687. MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
  688. if (chunk.edited && chunk.content.length) {
  689. // zero-length edited chunks are a special case (overlapping replacements)
  690. var loc = getLocator(this.original)(index);
  691. throw new Error(
  692. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  693. );
  694. }
  695. var newChunk = chunk.split(index);
  696. this.byEnd[index] = chunk;
  697. this.byStart[index] = newChunk;
  698. this.byEnd[newChunk.end] = newChunk;
  699. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  700. this.lastSearchedChunk = chunk;
  701. return true;
  702. };
  703. MagicString.prototype.toString = function toString () {
  704. var str = this.intro;
  705. var chunk = this.firstChunk;
  706. while (chunk) {
  707. str += chunk.toString();
  708. chunk = chunk.next;
  709. }
  710. return str + this.outro;
  711. };
  712. MagicString.prototype.isEmpty = function isEmpty () {
  713. var chunk = this.firstChunk;
  714. do {
  715. if (
  716. (chunk.intro.length && chunk.intro.trim()) ||
  717. (chunk.content.length && chunk.content.trim()) ||
  718. (chunk.outro.length && chunk.outro.trim())
  719. )
  720. { return false; }
  721. } while ((chunk = chunk.next));
  722. return true;
  723. };
  724. MagicString.prototype.length = function length () {
  725. var chunk = this.firstChunk;
  726. var length = 0;
  727. do {
  728. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  729. } while ((chunk = chunk.next));
  730. return length;
  731. };
  732. MagicString.prototype.trimLines = function trimLines () {
  733. return this.trim('[\\r\\n]');
  734. };
  735. MagicString.prototype.trim = function trim (charType) {
  736. return this.trimStart(charType).trimEnd(charType);
  737. };
  738. MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
  739. var rx = new RegExp((charType || '\\s') + '+$');
  740. this.outro = this.outro.replace(rx, '');
  741. if (this.outro.length) { return true; }
  742. var chunk = this.lastChunk;
  743. do {
  744. var end = chunk.end;
  745. var aborted = chunk.trimEnd(rx);
  746. // if chunk was trimmed, we have a new lastChunk
  747. if (chunk.end !== end) {
  748. if (this.lastChunk === chunk) {
  749. this.lastChunk = chunk.next;
  750. }
  751. this.byEnd[chunk.end] = chunk;
  752. this.byStart[chunk.next.start] = chunk.next;
  753. this.byEnd[chunk.next.end] = chunk.next;
  754. }
  755. if (aborted) { return true; }
  756. chunk = chunk.previous;
  757. } while (chunk);
  758. return false;
  759. };
  760. MagicString.prototype.trimEnd = function trimEnd (charType) {
  761. this.trimEndAborted(charType);
  762. return this;
  763. };
  764. MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
  765. var rx = new RegExp('^' + (charType || '\\s') + '+');
  766. this.intro = this.intro.replace(rx, '');
  767. if (this.intro.length) { return true; }
  768. var chunk = this.firstChunk;
  769. do {
  770. var end = chunk.end;
  771. var aborted = chunk.trimStart(rx);
  772. if (chunk.end !== end) {
  773. // special case...
  774. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  775. this.byEnd[chunk.end] = chunk;
  776. this.byStart[chunk.next.start] = chunk.next;
  777. this.byEnd[chunk.next.end] = chunk.next;
  778. }
  779. if (aborted) { return true; }
  780. chunk = chunk.next;
  781. } while (chunk);
  782. return false;
  783. };
  784. MagicString.prototype.trimStart = function trimStart (charType) {
  785. this.trimStartAborted(charType);
  786. return this;
  787. };
  788. var hasOwnProp = Object.prototype.hasOwnProperty;
  789. var Bundle = function Bundle(options) {
  790. if ( options === void 0 ) options = {};
  791. this.intro = options.intro || '';
  792. this.separator = options.separator !== undefined ? options.separator : '\n';
  793. this.sources = [];
  794. this.uniqueSources = [];
  795. this.uniqueSourceIndexByFilename = {};
  796. };
  797. Bundle.prototype.addSource = function addSource (source) {
  798. if (source instanceof MagicString) {
  799. return this.addSource({
  800. content: source,
  801. filename: source.filename,
  802. separator: this.separator,
  803. });
  804. }
  805. if (!isObject(source) || !source.content) {
  806. throw new Error(
  807. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'
  808. );
  809. }
  810. ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
  811. if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; }
  812. });
  813. if (source.separator === undefined) {
  814. // TODO there's a bunch of this sort of thing, needs cleaning up
  815. source.separator = this.separator;
  816. }
  817. if (source.filename) {
  818. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  819. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  820. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  821. } else {
  822. var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  823. if (source.content.original !== uniqueSource.content) {
  824. throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
  825. }
  826. }
  827. }
  828. this.sources.push(source);
  829. return this;
  830. };
  831. Bundle.prototype.append = function append (str, options) {
  832. this.addSource({
  833. content: new MagicString(str),
  834. separator: (options && options.separator) || '',
  835. });
  836. return this;
  837. };
  838. Bundle.prototype.clone = function clone () {
  839. var bundle = new Bundle({
  840. intro: this.intro,
  841. separator: this.separator,
  842. });
  843. this.sources.forEach(function (source) {
  844. bundle.addSource({
  845. filename: source.filename,
  846. content: source.content.clone(),
  847. separator: source.separator,
  848. });
  849. });
  850. return bundle;
  851. };
  852. Bundle.prototype.generateDecodedMap = function generateDecodedMap (options) {
  853. var this$1$1 = this;
  854. if ( options === void 0 ) options = {};
  855. var names = [];
  856. this.sources.forEach(function (source) {
  857. Object.keys(source.content.storedNames).forEach(function (name) {
  858. if (!~names.indexOf(name)) { names.push(name); }
  859. });
  860. });
  861. var mappings = new Mappings(options.hires);
  862. if (this.intro) {
  863. mappings.advance(this.intro);
  864. }
  865. this.sources.forEach(function (source, i) {
  866. if (i > 0) {
  867. mappings.advance(this$1$1.separator);
  868. }
  869. var sourceIndex = source.filename ? this$1$1.uniqueSourceIndexByFilename[source.filename] : -1;
  870. var magicString = source.content;
  871. var locate = getLocator(magicString.original);
  872. if (magicString.intro) {
  873. mappings.advance(magicString.intro);
  874. }
  875. magicString.firstChunk.eachNext(function (chunk) {
  876. var loc = locate(chunk.start);
  877. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  878. if (source.filename) {
  879. if (chunk.edited) {
  880. mappings.addEdit(
  881. sourceIndex,
  882. chunk.content,
  883. loc,
  884. chunk.storeName ? names.indexOf(chunk.original) : -1
  885. );
  886. } else {
  887. mappings.addUneditedChunk(
  888. sourceIndex,
  889. chunk,
  890. magicString.original,
  891. loc,
  892. magicString.sourcemapLocations
  893. );
  894. }
  895. } else {
  896. mappings.advance(chunk.content);
  897. }
  898. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  899. });
  900. if (magicString.outro) {
  901. mappings.advance(magicString.outro);
  902. }
  903. });
  904. return {
  905. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  906. sources: this.uniqueSources.map(function (source) {
  907. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  908. }),
  909. sourcesContent: this.uniqueSources.map(function (source) {
  910. return options.includeContent ? source.content : null;
  911. }),
  912. names: names,
  913. mappings: mappings.raw,
  914. };
  915. };
  916. Bundle.prototype.generateMap = function generateMap (options) {
  917. return new SourceMap(this.generateDecodedMap(options));
  918. };
  919. Bundle.prototype.getIndentString = function getIndentString () {
  920. var indentStringCounts = {};
  921. this.sources.forEach(function (source) {
  922. var indentStr = source.content.indentStr;
  923. if (indentStr === null) { return; }
  924. if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; }
  925. indentStringCounts[indentStr] += 1;
  926. });
  927. return (
  928. Object.keys(indentStringCounts).sort(function (a, b) {
  929. return indentStringCounts[a] - indentStringCounts[b];
  930. })[0] || '\t'
  931. );
  932. };
  933. Bundle.prototype.indent = function indent (indentStr) {
  934. var this$1$1 = this;
  935. if (!arguments.length) {
  936. indentStr = this.getIndentString();
  937. }
  938. if (indentStr === '') { return this; } // noop
  939. var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  940. this.sources.forEach(function (source, i) {
  941. var separator = source.separator !== undefined ? source.separator : this$1$1.separator;
  942. var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  943. source.content.indent(indentStr, {
  944. exclude: source.indentExclusionRanges,
  945. indentStart: indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  946. });
  947. trailingNewline = source.content.lastChar() === '\n';
  948. });
  949. if (this.intro) {
  950. this.intro =
  951. indentStr +
  952. this.intro.replace(/^[^\n]/gm, function (match, index) {
  953. return index > 0 ? indentStr + match : match;
  954. });
  955. }
  956. return this;
  957. };
  958. Bundle.prototype.prepend = function prepend (str) {
  959. this.intro = str + this.intro;
  960. return this;
  961. };
  962. Bundle.prototype.toString = function toString () {
  963. var this$1$1 = this;
  964. var body = this.sources
  965. .map(function (source, i) {
  966. var separator = source.separator !== undefined ? source.separator : this$1$1.separator;
  967. var str = (i > 0 ? separator : '') + source.content.toString();
  968. return str;
  969. })
  970. .join('');
  971. return this.intro + body;
  972. };
  973. Bundle.prototype.isEmpty = function isEmpty () {
  974. if (this.intro.length && this.intro.trim()) { return false; }
  975. if (this.sources.some(function (source) { return !source.content.isEmpty(); })) { return false; }
  976. return true;
  977. };
  978. Bundle.prototype.length = function length () {
  979. return this.sources.reduce(
  980. function (length, source) { return length + source.content.length(); },
  981. this.intro.length
  982. );
  983. };
  984. Bundle.prototype.trimLines = function trimLines () {
  985. return this.trim('[\\r\\n]');
  986. };
  987. Bundle.prototype.trim = function trim (charType) {
  988. return this.trimStart(charType).trimEnd(charType);
  989. };
  990. Bundle.prototype.trimStart = function trimStart (charType) {
  991. var rx = new RegExp('^' + (charType || '\\s') + '+');
  992. this.intro = this.intro.replace(rx, '');
  993. if (!this.intro) {
  994. var source;
  995. var i = 0;
  996. do {
  997. source = this.sources[i++];
  998. if (!source) {
  999. break;
  1000. }
  1001. } while (!source.content.trimStartAborted(charType));
  1002. }
  1003. return this;
  1004. };
  1005. Bundle.prototype.trimEnd = function trimEnd (charType) {
  1006. var rx = new RegExp((charType || '\\s') + '+$');
  1007. var source;
  1008. var i = this.sources.length - 1;
  1009. do {
  1010. source = this.sources[i--];
  1011. if (!source) {
  1012. this.intro = this.intro.replace(rx, '');
  1013. break;
  1014. }
  1015. } while (!source.content.trimEndAborted(charType));
  1016. return this;
  1017. };
  1018. export { Bundle, SourceMap, MagicString as default };
  1019. //# sourceMappingURL=magic-string.es.js.map