a19dd32a6b4c25f693609fe317d629c6aa70ff62ede90a07d0d25e0b9275e12b50bffa31d805366fa92330fd38d260fd06554eeb9e2d672979d86856f283cd 33 KB

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