magic-string.umd.js 36 KB

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