magic-string.es.js 33 KB

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