1
0

magic-string.cjs.js 37 KB

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