magic-string.es.mjs 37 KB

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