magic-string.es.mjs 37 KB

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