magic-string.cjs.js 33 KB

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