magic-string.umd.js 36 KB

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