magic-string.es.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  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 = 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.original, loc, this$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('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  457. };
  458. MagicString.prototype.insertLeft = function insertLeft (index, content) {
  459. if (!warned.insertLeft) {
  460. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  461. warned.insertLeft = true;
  462. }
  463. return this.appendLeft(index, content);
  464. };
  465. MagicString.prototype.insertRight = function insertRight (index, content) {
  466. if (!warned.insertRight) {
  467. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  468. warned.insertRight = true;
  469. }
  470. return this.prependRight(index, content);
  471. };
  472. MagicString.prototype.move = function move (start, end, index) {
  473. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  474. this._split(start);
  475. this._split(end);
  476. this._split(index);
  477. var first = this.byStart[start];
  478. var last = this.byEnd[end];
  479. var oldLeft = first.previous;
  480. var oldRight = last.next;
  481. var newRight = this.byStart[index];
  482. if (!newRight && last === this.lastChunk) { return this; }
  483. var newLeft = newRight ? newRight.previous : this.lastChunk;
  484. if (oldLeft) { oldLeft.next = oldRight; }
  485. if (oldRight) { oldRight.previous = oldLeft; }
  486. if (newLeft) { newLeft.next = first; }
  487. if (newRight) { newRight.previous = last; }
  488. if (!first.previous) { this.firstChunk = last.next; }
  489. if (!last.next) {
  490. this.lastChunk = first.previous;
  491. this.lastChunk.next = null;
  492. }
  493. first.previous = newLeft;
  494. last.next = newRight || null;
  495. if (!newLeft) { this.firstChunk = first; }
  496. if (!newRight) { this.lastChunk = last; }
  497. return this;
  498. };
  499. MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
  500. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  501. while (start < 0) { start += this.original.length; }
  502. while (end < 0) { end += this.original.length; }
  503. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  504. if (start === end)
  505. { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
  506. this._split(start);
  507. this._split(end);
  508. if (options === true) {
  509. if (!warned.storeName) {
  510. console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
  511. warned.storeName = true;
  512. }
  513. options = { storeName: true };
  514. }
  515. var storeName = options !== undefined ? options.storeName : false;
  516. var contentOnly = options !== undefined ? options.contentOnly : false;
  517. if (storeName) {
  518. var original = this.original.slice(start, end);
  519. this.storedNames[original] = true;
  520. }
  521. var first = this.byStart[start];
  522. var last = this.byEnd[end];
  523. if (first) {
  524. if (end > first.end && first.next !== this.byStart[first.end]) {
  525. throw new Error('Cannot overwrite across a split point');
  526. }
  527. first.edit(content, storeName, contentOnly);
  528. if (first !== last) {
  529. var chunk = first.next;
  530. while (chunk !== last) {
  531. chunk.edit('', false);
  532. chunk = chunk.next;
  533. }
  534. chunk.edit('', false);
  535. }
  536. } else {
  537. // must be inserting at the end
  538. var newChunk = new Chunk(start, end, '').edit(content, storeName);
  539. // TODO last chunk in the array may not be the last chunk, if it's moved...
  540. last.next = newChunk;
  541. newChunk.previous = last;
  542. }
  543. return this;
  544. };
  545. MagicString.prototype.prepend = function prepend (content) {
  546. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  547. this.intro = content + this.intro;
  548. return this;
  549. };
  550. MagicString.prototype.prependLeft = function prependLeft (index, content) {
  551. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  552. this._split(index);
  553. var chunk = this.byEnd[index];
  554. if (chunk) {
  555. chunk.prependLeft(content);
  556. } else {
  557. this.intro = content + this.intro;
  558. }
  559. return this;
  560. };
  561. MagicString.prototype.prependRight = function prependRight (index, content) {
  562. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  563. this._split(index);
  564. var chunk = this.byStart[index];
  565. if (chunk) {
  566. chunk.prependRight(content);
  567. } else {
  568. this.outro = content + this.outro;
  569. }
  570. return this;
  571. };
  572. MagicString.prototype.remove = function remove (start, end) {
  573. while (start < 0) { start += this.original.length; }
  574. while (end < 0) { end += this.original.length; }
  575. if (start === end) { return this; }
  576. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  577. if (start > end) { throw new Error('end must be greater than start'); }
  578. this._split(start);
  579. this._split(end);
  580. var chunk = this.byStart[start];
  581. while (chunk) {
  582. chunk.intro = '';
  583. chunk.outro = '';
  584. chunk.edit('');
  585. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  586. }
  587. return this;
  588. };
  589. MagicString.prototype.lastChar = function lastChar () {
  590. if (this.outro.length)
  591. { return this.outro[this.outro.length - 1]; }
  592. var chunk = this.lastChunk;
  593. do {
  594. if (chunk.outro.length)
  595. { return chunk.outro[chunk.outro.length - 1]; }
  596. if (chunk.content.length)
  597. { return chunk.content[chunk.content.length - 1]; }
  598. if (chunk.intro.length)
  599. { return chunk.intro[chunk.intro.length - 1]; }
  600. } while (chunk = chunk.previous);
  601. if (this.intro.length)
  602. { return this.intro[this.intro.length - 1]; }
  603. return '';
  604. };
  605. MagicString.prototype.lastLine = function lastLine () {
  606. var lineIndex = this.outro.lastIndexOf(n);
  607. if (lineIndex !== -1)
  608. { return this.outro.substr(lineIndex + 1); }
  609. var lineStr = this.outro;
  610. var chunk = this.lastChunk;
  611. do {
  612. if (chunk.outro.length > 0) {
  613. lineIndex = chunk.outro.lastIndexOf(n);
  614. if (lineIndex !== -1)
  615. { 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)
  621. { return chunk.content.substr(lineIndex + 1) + lineStr; }
  622. lineStr = chunk.content + lineStr;
  623. }
  624. if (chunk.intro.length > 0) {
  625. lineIndex = chunk.intro.lastIndexOf(n);
  626. if (lineIndex !== -1)
  627. { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  628. lineStr = chunk.intro + lineStr;
  629. }
  630. } while (chunk = chunk.previous);
  631. lineIndex = this.intro.lastIndexOf(n);
  632. if (lineIndex !== -1)
  633. { return this.intro.substr(lineIndex + 1) + lineStr; }
  634. return this.intro + lineStr;
  635. };
  636. MagicString.prototype.slice = function slice (start, end) {
  637. if ( start === void 0 ) start = 0;
  638. if ( end === void 0 ) end = this.original.length;
  639. while (start < 0) { start += this.original.length; }
  640. while (end < 0) { end += this.original.length; }
  641. var result = '';
  642. // find start chunk
  643. var chunk = this.firstChunk;
  644. while (chunk && (chunk.start > start || chunk.end <= start)) {
  645. // found end chunk before start
  646. if (chunk.start < end && chunk.end >= end) {
  647. return result;
  648. }
  649. chunk = chunk.next;
  650. }
  651. if (chunk && chunk.edited && chunk.start !== start)
  652. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  653. var startChunk = chunk;
  654. while (chunk) {
  655. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  656. result += chunk.intro;
  657. }
  658. var containsEnd = chunk.start < end && chunk.end >= end;
  659. if (containsEnd && chunk.edited && chunk.end !== end)
  660. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  661. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  662. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  663. result += chunk.content.slice(sliceStart, sliceEnd);
  664. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  665. result += chunk.outro;
  666. }
  667. if (containsEnd) {
  668. break;
  669. }
  670. chunk = chunk.next;
  671. }
  672. return result;
  673. };
  674. // TODO deprecate this? not really very useful
  675. MagicString.prototype.snip = function snip (start, end) {
  676. var clone = this.clone();
  677. clone.remove(0, start);
  678. clone.remove(end, clone.original.length);
  679. return clone;
  680. };
  681. MagicString.prototype._split = function _split (index) {
  682. if (this.byStart[index] || this.byEnd[index]) { return; }
  683. var chunk = this.lastSearchedChunk;
  684. var searchForward = index > chunk.end;
  685. while (chunk) {
  686. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  687. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  688. }
  689. };
  690. MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
  691. if (chunk.edited && chunk.content.length) {
  692. // zero-length edited chunks are a special case (overlapping replacements)
  693. var loc = getLocator(this.original)(index);
  694. throw new Error(
  695. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  696. );
  697. }
  698. var newChunk = chunk.split(index);
  699. this.byEnd[index] = chunk;
  700. this.byStart[index] = newChunk;
  701. this.byEnd[newChunk.end] = newChunk;
  702. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  703. this.lastSearchedChunk = chunk;
  704. return true;
  705. };
  706. MagicString.prototype.toString = function toString () {
  707. var str = this.intro;
  708. var chunk = this.firstChunk;
  709. while (chunk) {
  710. str += chunk.toString();
  711. chunk = chunk.next;
  712. }
  713. return str + this.outro;
  714. };
  715. MagicString.prototype.isEmpty = function isEmpty () {
  716. var chunk = this.firstChunk;
  717. do {
  718. if (chunk.intro.length && chunk.intro.trim() ||
  719. chunk.content.length && chunk.content.trim() ||
  720. chunk.outro.length && chunk.outro.trim())
  721. { return false; }
  722. } while (chunk = chunk.next);
  723. return true;
  724. };
  725. MagicString.prototype.length = function length () {
  726. var chunk = this.firstChunk;
  727. var length = 0;
  728. do {
  729. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  730. } while (chunk = chunk.next);
  731. return length;
  732. };
  733. MagicString.prototype.trimLines = function trimLines () {
  734. return this.trim('[\\r\\n]');
  735. };
  736. MagicString.prototype.trim = function trim (charType) {
  737. return this.trimStart(charType).trimEnd(charType);
  738. };
  739. MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
  740. var rx = new RegExp((charType || '\\s') + '+$');
  741. this.outro = this.outro.replace(rx, '');
  742. if (this.outro.length) { return true; }
  743. var chunk = this.lastChunk;
  744. do {
  745. var end = chunk.end;
  746. var aborted = chunk.trimEnd(rx);
  747. // if chunk was trimmed, we have a new lastChunk
  748. if (chunk.end !== end) {
  749. if (this.lastChunk === chunk) {
  750. this.lastChunk = chunk.next;
  751. }
  752. this.byEnd[chunk.end] = chunk;
  753. this.byStart[chunk.next.start] = chunk.next;
  754. this.byEnd[chunk.next.end] = chunk.next;
  755. }
  756. if (aborted) { return true; }
  757. chunk = chunk.previous;
  758. } while (chunk);
  759. return false;
  760. };
  761. MagicString.prototype.trimEnd = function trimEnd (charType) {
  762. this.trimEndAborted(charType);
  763. return this;
  764. };
  765. MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
  766. var rx = new RegExp('^' + (charType || '\\s') + '+');
  767. this.intro = this.intro.replace(rx, '');
  768. if (this.intro.length) { return true; }
  769. var chunk = this.firstChunk;
  770. do {
  771. var end = chunk.end;
  772. var aborted = chunk.trimStart(rx);
  773. if (chunk.end !== end) {
  774. // special case...
  775. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  776. this.byEnd[chunk.end] = chunk;
  777. this.byStart[chunk.next.start] = chunk.next;
  778. this.byEnd[chunk.next.end] = chunk.next;
  779. }
  780. if (aborted) { return true; }
  781. chunk = chunk.next;
  782. } while (chunk);
  783. return false;
  784. };
  785. MagicString.prototype.trimStart = function trimStart (charType) {
  786. this.trimStartAborted(charType);
  787. return this;
  788. };
  789. var hasOwnProp = Object.prototype.hasOwnProperty;
  790. var Bundle = function Bundle(options) {
  791. if ( options === void 0 ) options = {};
  792. this.intro = options.intro || '';
  793. this.separator = options.separator !== undefined ? options.separator : '\n';
  794. this.sources = [];
  795. this.uniqueSources = [];
  796. this.uniqueSourceIndexByFilename = {};
  797. };
  798. Bundle.prototype.addSource = function addSource (source) {
  799. if (source instanceof MagicString) {
  800. return this.addSource({
  801. content: source,
  802. filename: source.filename,
  803. separator: this.separator
  804. });
  805. }
  806. if (!isObject(source) || !source.content) {
  807. throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
  808. }
  809. ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
  810. if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; }
  811. });
  812. if (source.separator === undefined) {
  813. // TODO there's a bunch of this sort of thing, needs cleaning up
  814. source.separator = this.separator;
  815. }
  816. if (source.filename) {
  817. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  818. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  819. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  820. } else {
  821. var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  822. if (source.content.original !== uniqueSource.content) {
  823. throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
  824. }
  825. }
  826. }
  827. this.sources.push(source);
  828. return this;
  829. };
  830. Bundle.prototype.append = function append (str, options) {
  831. this.addSource({
  832. content: new MagicString(str),
  833. separator: (options && options.separator) || ''
  834. });
  835. return this;
  836. };
  837. Bundle.prototype.clone = function clone () {
  838. var bundle = new Bundle({
  839. intro: this.intro,
  840. separator: this.separator
  841. });
  842. this.sources.forEach(function (source) {
  843. bundle.addSource({
  844. filename: source.filename,
  845. content: source.content.clone(),
  846. separator: source.separator
  847. });
  848. });
  849. return bundle;
  850. };
  851. Bundle.prototype.generateDecodedMap = function generateDecodedMap (options) {
  852. var this$1 = this;
  853. if ( options === void 0 ) options = {};
  854. var names = [];
  855. this.sources.forEach(function (source) {
  856. Object.keys(source.content.storedNames).forEach(function (name) {
  857. if (!~names.indexOf(name)) { names.push(name); }
  858. });
  859. });
  860. var mappings = new Mappings(options.hires);
  861. if (this.intro) {
  862. mappings.advance(this.intro);
  863. }
  864. this.sources.forEach(function (source, i) {
  865. if (i > 0) {
  866. mappings.advance(this$1.separator);
  867. }
  868. var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
  869. var magicString = source.content;
  870. var locate = getLocator(magicString.original);
  871. if (magicString.intro) {
  872. mappings.advance(magicString.intro);
  873. }
  874. magicString.firstChunk.eachNext(function (chunk) {
  875. var loc = locate(chunk.start);
  876. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  877. if (source.filename) {
  878. if (chunk.edited) {
  879. mappings.addEdit(
  880. sourceIndex,
  881. chunk.content,
  882. loc,
  883. chunk.storeName ? names.indexOf(chunk.original) : -1
  884. );
  885. } else {
  886. mappings.addUneditedChunk(
  887. sourceIndex,
  888. chunk,
  889. magicString.original,
  890. loc,
  891. magicString.sourcemapLocations
  892. );
  893. }
  894. } else {
  895. mappings.advance(chunk.content);
  896. }
  897. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  898. });
  899. if (magicString.outro) {
  900. mappings.advance(magicString.outro);
  901. }
  902. });
  903. return {
  904. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  905. sources: this.uniqueSources.map(function (source) {
  906. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  907. }),
  908. sourcesContent: this.uniqueSources.map(function (source) {
  909. return options.includeContent ? source.content : null;
  910. }),
  911. names: names,
  912. mappings: mappings.raw
  913. };
  914. };
  915. Bundle.prototype.generateMap = function generateMap (options) {
  916. return new SourceMap(this.generateDecodedMap(options));
  917. };
  918. Bundle.prototype.getIndentString = function getIndentString () {
  919. var indentStringCounts = {};
  920. this.sources.forEach(function (source) {
  921. var indentStr = source.content.indentStr;
  922. if (indentStr === null) { return; }
  923. if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; }
  924. indentStringCounts[indentStr] += 1;
  925. });
  926. return (
  927. Object.keys(indentStringCounts).sort(function (a, b) {
  928. return indentStringCounts[a] - indentStringCounts[b];
  929. })[0] || '\t'
  930. );
  931. };
  932. Bundle.prototype.indent = function indent (indentStr) {
  933. var this$1 = this;
  934. if (!arguments.length) {
  935. indentStr = this.getIndentString();
  936. }
  937. if (indentStr === '') { return this; } // noop
  938. var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  939. this.sources.forEach(function (source, i) {
  940. var separator = source.separator !== undefined ? source.separator : this$1.separator;
  941. var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  942. source.content.indent(indentStr, {
  943. exclude: source.indentExclusionRanges,
  944. indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  945. });
  946. trailingNewline = source.content.lastChar() === '\n';
  947. });
  948. if (this.intro) {
  949. this.intro =
  950. indentStr +
  951. this.intro.replace(/^[^\n]/gm, function (match, index) {
  952. return index > 0 ? indentStr + match : match;
  953. });
  954. }
  955. return this;
  956. };
  957. Bundle.prototype.prepend = function prepend (str) {
  958. this.intro = str + this.intro;
  959. return this;
  960. };
  961. Bundle.prototype.toString = function toString () {
  962. var this$1 = this;
  963. var body = this.sources
  964. .map(function (source, i) {
  965. var separator = source.separator !== undefined ? source.separator : this$1.separator;
  966. var str = (i > 0 ? separator : '') + source.content.toString();
  967. return str;
  968. })
  969. .join('');
  970. return this.intro + body;
  971. };
  972. Bundle.prototype.isEmpty = function isEmpty () {
  973. if (this.intro.length && this.intro.trim())
  974. { return false; }
  975. if (this.sources.some(function (source) { return !source.content.isEmpty(); }))
  976. { return false; }
  977. return true;
  978. };
  979. Bundle.prototype.length = function length () {
  980. return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
  981. };
  982. Bundle.prototype.trimLines = function trimLines () {
  983. return this.trim('[\\r\\n]');
  984. };
  985. Bundle.prototype.trim = function trim (charType) {
  986. return this.trimStart(charType).trimEnd(charType);
  987. };
  988. Bundle.prototype.trimStart = function trimStart (charType) {
  989. var rx = new RegExp('^' + (charType || '\\s') + '+');
  990. this.intro = this.intro.replace(rx, '');
  991. if (!this.intro) {
  992. var source;
  993. var i = 0;
  994. do {
  995. source = this.sources[i++];
  996. if (!source) {
  997. break;
  998. }
  999. } while (!source.content.trimStartAborted(charType));
  1000. }
  1001. return this;
  1002. };
  1003. Bundle.prototype.trimEnd = function trimEnd (charType) {
  1004. var rx = new RegExp((charType || '\\s') + '+$');
  1005. var source;
  1006. var i = this.sources.length - 1;
  1007. do {
  1008. source = this.sources[i--];
  1009. if (!source) {
  1010. this.intro = this.intro.replace(rx, '');
  1011. break;
  1012. }
  1013. } while (!source.content.trimEndAborted(charType));
  1014. return this;
  1015. };
  1016. export default MagicString;
  1017. export { Bundle, SourceMap };
  1018. //# sourceMappingURL=magic-string.es.js.map