e3f334f7c405889c5e9e9d518541ed1690cb19a2b188abaabacc57c1138e61b0deb61c99e1255bc5cd22a2d80bc421a0e40e05dd3c5c5d54ee5cf2956ec0d4 36 KB

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